[
  {
    "path": ".git-blame-ignore-revs",
    "content": "# List of revisions that can be ignored with git-blame(1).\n#\n# See `blame.ignoreRevsFile` in git-config(1) to enable it by default, or\n# use it with `--ignore-revs-file` manually with git-blame.\n#\n# To \"install\" it:\n#\n#   git config --local blame.ignoreRevsFile .git-blame-ignore-revs\n\n# run black\n703e4b11ba76171eccd3f13e723c47b810ded7ef\n# switched to src layout\neaa882f3d5340956beb176aa1753e07e3f3f2190\n# pre-commit run pyupgrade --all-files\na91fe1feddbded535a4322ab854429e3a3961fb4\n# move node base classes from main to nodes\nafc607cfd81458d4e4f3b1f3cf8cc931b933907e\n# [?] split most fixture related code into own plugin\n8c49561470708761f7321504f5e8343811be87ac\n# run pyupgrade\n9aacb4635e81edd6ecf281d4f6c0cfc8e94ab301\n# run blacken-docs\n5f95dce95602921a70bfbc7d8de2f7712c5e4505\n# ran pyupgrade-docs again\n75d0b899bbb56d6849e9d69d83a9426ed3f43f8b\n# move argument parser to own file\nc9df77cbd6a365dcb73c39618e4842711817e871\n# Replace reorder-python-imports by isort due to black incompatibility (#11896)\n8b54596639f41dfac070030ef20394b9001fe63c\n# Run blacken-docs with black's 2024's style\n4546d5445aaefe6a03957db028c263521dfb5c4b\n# Migration to ruff / ruff format\n4588653b2497ed25976b7aaff225b889fb476756\n# Use format specifiers instead of percent format\n4788165e69d08e10fc6b9c0124083fb358e2e9b0\n"
  },
  {
    "path": ".gitattributes",
    "content": "*.bat  text eol=crlf\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# info:\n# * https://help.github.com/en/articles/displaying-a-sponsor-button-in-your-repository\n# * https://tidelift.com/subscription/how-to-connect-tidelift-with-github\ngithub: pytest-dev\ntidelift: pypi/pytest\nopen_collective: pytest\nthanks_dev: u/gh/pytest-dev\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/1_bug_report.md",
    "content": "---\nname: 🐛 Bug Report\nabout: Report errors and problems\n\n---\n\n<!--\nThanks for submitting an issue!\n\nQuick check-list while reporting bugs:\n-->\n\n- [ ] a detailed description of the bug or problem you are having\n- [ ] output of `pip list` from the virtual environment you are using\n- [ ] pytest and operating system versions\n- [ ] minimal example if possible\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/2_feature_request.md",
    "content": "---\nname: 🚀 Feature Request\nabout: Ideas for new features and improvements\n\n---\n\n<!--\nThanks for suggesting a feature!\n\nQuick check-list while suggesting features:\n-->\n\n#### What's the problem this feature will solve?\n<!-- What are you trying to do, that you are unable to achieve with pytest as it currently stands? -->\n\n#### Describe the solution you'd like\n<!-- A clear and concise description of what you want to happen. -->\n\n<!-- Provide examples of real-world use cases that this would enable and how it solves the problem described above. -->\n\n#### Alternative Solutions\n<!-- Have you tried to workaround the problem using a pytest plugin or other tools? Or a different approach to solving this issue? Please elaborate here. -->\n\n#### Additional context\n<!-- Add any other context, links, etc. about the feature here. -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\ncontact_links:\n  - name: ❓ Support Question\n    url: https://github.com/pytest-dev/pytest/discussions\n    about: Use GitHub's new Discussions feature for questions\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "<!--\nThanks for submitting a PR, your contribution is really appreciated!\n\nHere is a quick checklist that should be present in PRs.\n\n- [ ] Include documentation when adding new features.\n- [ ] Include new tests or update existing tests when applicable.\n- [X] Allow maintainers to push and squash when merging my commits. Please uncheck this if you prefer to squash the commits yourself.\n\nIf this change fixes an issue, please:\n\n- [ ] Add text like ``closes #XYZW`` to the PR description and/or commits (where ``XYZW`` is the issue number). See the [github docs](https://help.github.com/en/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword) for more information.\n\n> [!IMPORTANT]\n> **Unsupervised agentic contributions are not accepted**. See our [AI/LLM-Assisted Contributions Policy](https://github.com/pytest-dev/pytest/blob/main/CONTRIBUTING.rst#aillm-assisted-contributions-policy).\n\n- [ ] If AI agents were used, they are credited in `Co-authored-by` commit trailers.\n\nUnless your change is trivial or a small documentation fix (e.g., a typo or reword of a small section) please:\n\n- [ ] Create a new changelog file in the `changelog` directory, with a name like `<ISSUE NUMBER>.<TYPE>.rst`. See [changelog/README.rst](https://github.com/pytest-dev/pytest/blob/main/changelog/README.rst) for details.\n\n  Write sentences in the **past or present tense**, examples:\n\n  * *Improved verbose diff output with sequences.*\n  * *Terminal summary statistics now use multiple colors.*\n\n  Also make sure to end the sentence with a `.`.\n\n- [ ] Add yourself to `AUTHORS` in alphabetical order.\n-->\n"
  },
  {
    "path": ".github/chronographer.yml",
    "content": "---\n\nbranch-protection-check-name: Changelog entry\naction-hints:\n  check-title-prefix: \"Chronographer: \"\n  external-docs-url: >-\n    https://docs.pytest.org/en/latest/contributing.html#preparing-pull-requests\n  inline-markdown: >-\n    See\n    https://docs.pytest.org/en/latest/contributing.html#preparing-pull-requests\n    for details.\nenforce-name:\n  suffix: .rst\nexclude:\n  humans:\n  - pyup-bot\nlabels:\n  skip-changelog: skip news\n\n...\n"
  },
  {
    "path": ".github/config.yml",
    "content": "rtd:\n  project: pytest\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n- package-ecosystem: pip\n  directory: \"/testing/plugins_integration\"\n  schedule:\n    interval: weekly\n    time: \"03:00\"\n  open-pull-requests-limit: 10\n  allow:\n  - dependency-type: direct\n  - dependency-type: indirect\n  cooldown:\n    default-days: 7\n- package-ecosystem: github-actions\n  directory: /\n  schedule:\n    interval: weekly\n    time: \"03:00\"\n  open-pull-requests-limit: 10\n  cooldown:\n    default-days: 7\n"
  },
  {
    "path": ".github/labels.toml",
    "content": "[\"os: cygwin\"]\ncolor = \"006b75\"\ndescription = \"cygwin platform-specific problem\"\nname = \"os: cygwin\"\n\n[\"os: linux\"]\ncolor = \"1d76db\"\ndescription = \"linux platform-specific problem\"\nname = \"os: linux\"\n\n[\"os: mac\"]\ncolor = \"bfdadc\"\ndescription = \"mac platform-specific problem\"\nname = \"os: mac\"\n\n[\"os: windows\"]\ncolor = \"fbca04\"\ndescription = \"windows platform-specific problem\"\nname = \"os: windows\"\n\n[\"plugin: argcomplete\"]\ncolor = \"d4c5f9\"\ndescription = \"related to the argcomplete builtin plugin\"\nname = \"plugin: argcomplete\"\n\n[\"plugin: cache\"]\ncolor = \"c7def8\"\ndescription = \"related to the cache builtin plugin\"\nname = \"plugin: cache\"\n\n[\"plugin: capture\"]\ncolor = \"1d76db\"\ndescription = \"related to the capture builtin plugin\"\nname = \"plugin: capture\"\n\n[\"plugin: debugging\"]\ncolor = \"dd52a8\"\ndescription = \"related to the debugging builtin plugin\"\nname = \"plugin: debugging\"\n\n[\"plugin: doctests\"]\ncolor = \"fad8c7\"\ndescription = \"related to the doctests builtin plugin\"\nname = \"plugin: doctests\"\n\n[\"plugin: junitxml\"]\ncolor = \"c5def5\"\ndescription = \"related to the junitxml builtin plugin\"\nname = \"plugin: junitxml\"\n\n[\"plugin: logging\"]\ncolor = \"ff5432\"\ndescription = \"related to the logging builtin plugin\"\nname = \"plugin: logging\"\n\n[\"plugin: monkeypatch\"]\ncolor = \"0e8a16\"\ndescription = \"related to the monkeypatch builtin plugin\"\nname = \"plugin: monkeypatch\"\n\n[\"plugin: nose\"]\ncolor = \"bfdadc\"\ndescription = \"related to the nose integration builtin plugin\"\nname = \"plugin: nose\"\n\n[\"plugin: pastebin\"]\ncolor = \"bfd4f2\"\ndescription = \"related to the pastebin builtin plugin\"\nname = \"plugin: pastebin\"\n\n[\"plugin: pytester\"]\ncolor = \"c5def5\"\ndescription = \"related to the pytester builtin plugin\"\nname = \"plugin: pytester\"\n\n[\"plugin: tmpdir\"]\ncolor = \"bfd4f2\"\ndescription = \"related to the tmpdir builtin plugin\"\nname = \"plugin: tmpdir\"\n\n[\"plugin: unittest\"]\ncolor = \"006b75\"\ndescription = \"related to the unittest integration builtin plugin\"\nname = \"plugin: unittest\"\n\n[\"plugin: warnings\"]\ncolor = \"fef2c0\"\ndescription = \"related to the warnings builtin plugin\"\nname = \"plugin: warnings\"\n\n[\"plugin: xdist\"]\ncolor = \"5319e7\"\ndescription = \"related to the xdist external plugin\"\nname = \"plugin: xdist\"\n\n[\"status: critical\"]\ncolor = \"e11d21\"\ndescription = \"grave problem or usability issue that affects lots of users\"\nname = \"status: critical\"\n\n[\"status: easy\"]\ncolor = \"bfe5bf\"\ndescription = \"easy issue that is friendly to new contributor\"\nname = \"status: easy\"\n\n[\"status: help wanted\"]\ncolor = \"159818\"\ndescription = \"developers would like help from experts on this topic\"\nname = \"status: help wanted\"\n\n[\"status: needs information\"]\ncolor = \"5319e7\"\ndescription = \"reporter needs to provide more information; can be closed after 2 or more weeks of inactivity\"\nname = \"status: needs information\"\n\n[\"topic: collection\"]\ncolor = \"006b75\"\ndescription = \"related to the collection phase\"\nname = \"topic: collection\"\n\n[\"topic: config\"]\ncolor = \"006b75\"\ndescription = \"related to config handling, argument parsing and config file\"\nname = \"topic: config\"\n\n[\"topic: fixtures\"]\ncolor = \"5319e7\"\ndescription = \"anything involving fixtures directly or indirectly\"\nname = \"topic: fixtures\"\n\n[\"topic: marks\"]\ncolor = \"b60205\"\ndescription = \"related to marks, either the general marks or builtin\"\nname = \"topic: marks\"\n\n[\"topic: parametrize\"]\ncolor = \"fbca04\"\ndescription = \"related to @pytest.mark.parametrize\"\nname = \"topic: parametrize\"\n\n[\"topic: reporting\"]\ncolor = \"fef2c0\"\ndescription = \"related to terminal output and user-facing messages and errors\"\nname = \"topic: reporting\"\n\n[\"topic: rewrite\"]\ncolor = \"0e8a16\"\ndescription = \"related to the assertion rewrite mechanism\"\nname = \"topic: rewrite\"\n"
  },
  {
    "path": ".github/patchback.yml",
    "content": "---\n\nbackport_branch_prefix: patchback/backports/\nbackport_label_prefix: 'backport '  # IMPORTANT: the labels are space-delimited\n# target_branch_prefix: ''  # The project's backport branches are non-prefixed\n\n...\n"
  },
  {
    "path": ".github/workflows/deploy.yml",
    "content": "name: deploy\n\non:\n  workflow_dispatch:\n    inputs:\n      version:\n        description: 'Release version'\n        required: true\n        default: '1.2.3'\n\n\n# Set permissions at the job level.\npermissions: {}\n\njobs:\n  package:\n    runs-on: ubuntu-latest\n    env:\n      SETUPTOOLS_SCM_PRETEND_VERSION_FOR_PYTEST: ${{ github.event.inputs.version }}\n    timeout-minutes: 10\n\n    # Required by attest-build-provenance-github.\n    permissions:\n      id-token: write\n      attestations: write\n\n    steps:\n    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      with:\n        fetch-depth: 0\n        persist-credentials: false\n\n    - name: Build and Check Package\n      uses: hynek/build-and-inspect-python-package@efb823f52190ad02594531168b7a2d5790e66516\n      with:\n        attest-build-provenance-github: 'true'\n\n  generate-gh-release-notes:\n    needs: [package]\n    runs-on: ubuntu-latest\n    timeout-minutes: 30\n    permissions:\n      contents: read\n    steps:\n    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      with:\n        fetch-depth: 0\n        persist-credentials: false\n\n    - name: Set up Python\n      uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0\n      with:\n        python-version: \"3.13\"\n\n    - name: Install tox\n      run: |\n        python -m pip install --upgrade pip\n        pip install tox\n\n    - name: Generate release notes\n      env:\n        VERSION: ${{ github.event.inputs.version }}\n      run: |\n        tox -e generate-gh-release-notes -- \"$VERSION\" gh-release-notes.md\n\n    - name: Upload release notes\n      uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0\n      with:\n        name: release-notes\n        path: gh-release-notes.md\n        retention-days: 1\n\n  publish-to-pypi:\n    if: github.repository == 'pytest-dev/pytest'\n    # Need generate-gh-release-notes only for ordering.\n    # Don't want to release to PyPI if generating GitHub release notes fails.\n    needs: [package, generate-gh-release-notes]\n    runs-on: ubuntu-latest\n    environment: deploy\n    timeout-minutes: 30\n    permissions:\n      id-token: write\n    steps:\n    - name: Download Package\n      uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0\n      with:\n        name: Packages\n        path: dist\n\n    - name: Publish package to PyPI\n      uses: pypa/gh-action-pypi-publish@ed0c53931b1dc9bd32cbe73a98c7f6766f8a527e\n      with:\n        attestations: true\n\n  push-tag:\n    needs: [publish-to-pypi]\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    permissions:\n      contents: write\n    steps:\n    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      with:\n        fetch-depth: 0\n        persist-credentials: true\n\n    - name: Push tag\n      env:\n          VERSION: ${{ github.event.inputs.version }}\n      run: |\n        git config user.name \"pytest bot\"\n        git config user.email \"pytestbot@gmail.com\"\n        git tag --annotate --message=v\"$VERSION\" \"$VERSION\" ${{ github.sha }}\n        git push origin \"$VERSION\"\n\n  create-github-release:\n    needs: [push-tag, generate-gh-release-notes]\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    permissions:\n      contents: write\n    steps:\n    - name: Download Package\n      uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0\n      with:\n        name: Packages\n        path: dist\n\n    - name: Download release notes\n      uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0\n      with:\n        name: release-notes\n        path: .\n\n    - name: Publish GitHub Release\n      env:\n        VERSION: ${{ github.event.inputs.version }}\n        GH_REPO: ${{ github.repository }}\n        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n      run: |\n        gh release create --notes-file gh-release-notes.md --verify-tag \"$VERSION\" dist/*\n"
  },
  {
    "path": ".github/workflows/doc-check-links.yml",
    "content": "name: Doc Check Links\n\non:\n  schedule:\n    # At 00:00 on Sunday.\n    # https://crontab.guru\n    - cron: '0 0 * * 0'\n  workflow_dispatch:\n\n# Set permissions at the job level.\npermissions: {}\n\njobs:\n  doc-check-links:\n    if: github.repository_owner == 'pytest-dev'\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          fetch-depth: 0\n          persist-credentials: false\n\n      - name: Setup Python\n        uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0\n        with:\n          python-version: \"3.13\"\n          cache: pip\n\n      - name: Install tox\n        run: |\n          python -m pip install --upgrade pip\n          pip install tox\n\n      - name: Run sphinx linkcheck via tox\n        run: tox -e docs-checklinks\n"
  },
  {
    "path": ".github/workflows/prepare-release-pr.yml",
    "content": "name: prepare release pr\n\non:\n  workflow_dispatch:\n    inputs:\n      branch:\n        description: 'Branch to base the release from'\n        required: true\n        default: ''\n      major:\n        description: 'Major release? (yes/no)'\n        required: true\n        default: 'no'\n      prerelease:\n        description: 'Prerelease (ex: rc1). Leave empty if not a pre-release.'\n        required: false\n        default: ''\n\n# Set permissions at the job level.\npermissions: {}\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n      pull-requests: write\n\n    steps:\n    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      with:\n        fetch-depth: 0\n        # persist-credentials is needed in order for us to push the release branch.\n        persist-credentials: true\n\n    - name: Set up Python\n      uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0\n      with:\n        python-version: \"3.13\"\n\n    - name: Install tox\n      run: |\n        python -m pip install --upgrade pip\n        pip install tox\n\n    - name: Prepare release PR (minor/patch release)\n      if: github.event.inputs.major == 'no'\n      env:\n        BRANCH: ${{ github.event.inputs.branch }}\n        PRERELEASE: ${{ github.event.inputs.prerelease }}\n        GH_TOKEN: ${{ github.token }}\n      run: |\n        tox -e prepare-release-pr -- \"$BRANCH\" --prerelease=\"$PRERELEASE\"\n\n    - name: Prepare release PR (major release)\n      if: github.event.inputs.major == 'yes'\n      env:\n        BRANCH: ${{ github.event.inputs.branch }}\n        PRERELEASE: ${{ github.event.inputs.prerelease }}\n        GH_TOKEN: ${{ github.token }}\n      run: |\n        tox -e prepare-release-pr -- \"$BRANCH\" --major --prerelease=\"$PRERELEASE\"\n"
  },
  {
    "path": ".github/workflows/stale.yml",
    "content": "name: close needs-information issues\non:\n  schedule:\n    - cron: \"30 1 * * *\"\n  workflow_dispatch:\n\njobs:\n  close-issues:\n    runs-on: ubuntu-latest\n    permissions:\n      issues: write\n    steps:\n      - uses: actions/stale@b5d41d4e1d5dceea10e7104786b73624c18a190f # v10.1.0\n        with:\n          debug-only: false\n          days-before-issue-stale: 14\n          days-before-issue-close: 7\n          only-labels: \"status: needs information\"\n          stale-issue-label: \"stale\"\n          stale-issue-message: \"This issue is stale because it has the `status: needs information` label and requested follow-up information was not provided for 14 days.\"\n          close-issue-message: \"This issue was closed because it has the `status: needs information` label and follow-up information has not been provided for 7 days since being marked as stale.\"\n          days-before-pr-stale: -1\n          days-before-pr-close: -1\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: test\n\non:\n  push:\n    branches:\n      - main\n      - \"[0-9]+.[0-9]+.x\"\n      - \"test-me-*\"\n    tags:\n      - \"[0-9]+.[0-9]+.[0-9]+\"\n      - \"[0-9]+.[0-9]+.[0-9]+rc[0-9]+\"\n\n  pull_request:\n    branches:\n      - main\n      - \"[0-9]+.[0-9]+.x\"\n    types:\n    - opened  # default\n    - synchronize  # default\n    - reopened  # default\n    - ready_for_review  # used in PRs created from the release workflow\n\n  workflow_dispatch:  # allows manual triggering of the workflow\n\nenv:\n  PYTEST_ADDOPTS: \"--color=yes\"\n\n# Cancel running jobs for the same workflow and branch.\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref }}\n  cancel-in-progress: true\n\n# Set permissions at the job level.\npermissions: {}\n\njobs:\n  package:\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      with:\n        fetch-depth: 0\n        persist-credentials: false\n    - name: Build and Check Package\n      uses: hynek/build-and-inspect-python-package@efb823f52190ad02594531168b7a2d5790e66516\n\n  build:\n    needs: [package]\n\n    runs-on: ${{ matrix.os }}\n    timeout-minutes: 45\n    permissions:\n      contents: read\n\n    strategy:\n      fail-fast: false\n      matrix:\n        name: [\n          \"windows-py310-unittest-asynctest\",\n          \"windows-py310-unittest-twisted24\",\n          \"windows-py310-unittest-twisted25\",\n          \"windows-py310-pluggy\",\n          \"windows-py310-xdist\",\n          \"windows-py311\",\n          \"windows-py312\",\n          \"windows-py313\",\n          \"windows-py314\",\n\n          \"ubuntu-py310-unittest-asynctest\",\n          \"ubuntu-py310-unittest-twisted24\",\n          \"ubuntu-py310-unittest-twisted25\",\n          \"ubuntu-py310-lsof-numpy-pexpect\",\n          \"ubuntu-py310-pluggy\",\n          \"ubuntu-py310-freeze\",\n          \"ubuntu-py310-xdist\",\n          \"ubuntu-py311\",\n          \"ubuntu-py312\",\n          \"ubuntu-py313-pexpect\",\n          \"ubuntu-py314\",\n          \"ubuntu-pypy3-xdist\",\n\n          \"macos-py310\",\n          \"macos-py312\",\n          \"macos-py313\",\n          \"macos-py314\",\n\n          \"doctesting\",\n          \"plugins\",\n        ]\n\n        include:\n          # Use separate jobs for different unittest flavors (twisted, asynctest) to ensure proper coverage.\n          - name: \"windows-py310-unittest-asynctest\"\n            python: \"3.10\"\n            os: windows-latest\n            tox_env: \"py310-asynctest\"\n            use_coverage: true\n\n          - name: \"windows-py310-unittest-twisted24\"\n            python: \"3.10\"\n            os: windows-latest\n            tox_env: \"py310-twisted24\"\n            use_coverage: true\n\n          - name: \"windows-py310-unittest-twisted25\"\n            python: \"3.10\"\n            os: windows-latest\n            tox_env: \"py310-twisted25\"\n            use_coverage: true\n\n          - name: \"windows-py310-pluggy\"\n            python: \"3.10\"\n            os: windows-latest\n            tox_env: \"py310-pluggymain-pylib-xdist\"\n            xfail: true\n\n          - name: \"windows-py310-xdist\"\n            python: \"3.10\"\n            os: windows-latest\n            tox_env: \"py310-xdist\"\n\n          - name: \"windows-py311\"\n            python: \"3.11\"\n            os: windows-latest\n            tox_env: \"py311\"\n\n          - name: \"windows-py312\"\n            python: \"3.12\"\n            os: windows-latest\n            tox_env: \"py312\"\n\n          - name: \"windows-py313\"\n            python: \"3.13\"\n            os: windows-latest\n            tox_env: \"py313\"\n            xfail: true\n\n          - name: \"windows-py314\"\n            python: \"3.14\"\n            os: windows-latest\n            tox_env: \"py314\"\n            use_coverage: true\n\n          # Use separate jobs for different unittest flavors (twisted, asynctest) to ensure proper coverage.\n          - name: \"ubuntu-py310-unittest-asynctest\"\n            python: \"3.10\"\n            os: ubuntu-latest\n            tox_env: \"py310-asynctest\"\n            use_coverage: true\n\n          - name: \"ubuntu-py310-unittest-twisted24\"\n            python: \"3.10\"\n            os: ubuntu-latest\n            tox_env: \"py310-twisted24\"\n            use_coverage: true\n\n          - name: \"ubuntu-py310-unittest-twisted25\"\n            python: \"3.10\"\n            os: ubuntu-latest\n            tox_env: \"py310-twisted25\"\n            use_coverage: true\n\n          - name: \"ubuntu-py310-lsof-numpy-pexpect\"\n            python: \"3.10\"\n            os: ubuntu-latest\n            tox_env: \"py310-lsof-numpy-pexpect\"\n            use_coverage: true\n\n          - name: \"ubuntu-py310-pluggy\"\n            python: \"3.10\"\n            os: ubuntu-latest\n            tox_env: \"py310-pluggymain-pylib-xdist\"\n            xfail: true\n\n          - name: \"ubuntu-py310-freeze\"\n            python: \"3.10\"\n            os: ubuntu-latest\n            tox_env: \"py310-freeze\"\n            xfail: true\n\n          - name: \"ubuntu-py310-xdist\"\n            python: \"3.10\"\n            os: ubuntu-latest\n            tox_env: \"py310-xdist\"\n\n          - name: \"ubuntu-py311\"\n            python: \"3.11\"\n            os: ubuntu-latest\n            tox_env: \"py311\"\n            use_coverage: true\n\n          - name: \"ubuntu-py312\"\n            python: \"3.12\"\n            os: ubuntu-latest\n            tox_env: \"py312\"\n            use_coverage: true\n\n          - name: \"ubuntu-py313-pexpect\"\n            python: \"3.13\"\n            os: ubuntu-latest\n            tox_env: \"py313-pexpect\"\n            use_coverage: true\n            xfail: true\n\n          - name: \"ubuntu-py314\"\n            python: \"3.14\"\n            os: ubuntu-latest\n            tox_env: \"py314\"\n            use_coverage: true\n\n          - name: \"ubuntu-pypy3-xdist\"\n            python: \"pypy-3.10\"\n            os: ubuntu-latest\n            tox_env: \"pypy3-xdist\"\n\n\n          - name: \"macos-py310\"\n            python: \"3.10\"\n            os: macos-latest\n            tox_env: \"py310-xdist\"\n            xfail: true\n\n          - name: \"macos-py312\"\n            python: \"3.12\"\n            os: macos-latest\n            tox_env: \"py312-xdist\"\n\n          - name: \"macos-py313\"\n            python: \"3.13\"\n            os: macos-latest\n            tox_env: \"py313-xdist\"\n            xfail: true\n\n          - name: \"macos-py314\"\n            python: \"3.14\"\n            os: macos-latest\n            tox_env: \"py314-xdist\"\n\n          - name: \"plugins\"\n            python: \"3.12\"\n            os: ubuntu-latest\n            tox_env: \"plugins\"\n\n\n          - name: \"doctesting\"\n            python: \"3.10\"\n            os: ubuntu-latest\n            tox_env: \"doctesting\"\n            use_coverage: true\n\n    continue-on-error: ${{ matrix.xfail && true || false }}\n\n    steps:\n    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      with:\n        fetch-depth: 0\n        persist-credentials: false\n\n    - name: Download Package\n      uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0\n      with:\n        name: Packages\n        path: dist\n\n    - name: Set up Python ${{ matrix.python }}\n      uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0\n      with:\n        python-version: ${{ matrix.python }}\n        check-latest: true\n        allow-prereleases: true\n\n    - name: Install tox\n      run: |\n        python -m pip install --upgrade pip\n        pip install tox\n\n    - name: Test without coverage\n      if: \"! matrix.use_coverage\"\n      shell: bash\n      env:\n        _PYTEST_TOX_POSARGS_JUNIT: --junitxml=junit.xml\n      run: tox run -e ${{ matrix.tox_env }} --installpkg `find dist/*.tar.gz`\n\n    - name: Test with coverage\n      if: \"matrix.use_coverage\"\n      shell: bash\n      env:\n        _PYTEST_TOX_POSARGS_JUNIT: --junitxml=junit.xml\n      run: tox run -e ${{ matrix.tox_env }}-coverage --installpkg `find dist/*.tar.gz`\n\n    - name: Upload coverage to Codecov\n      if: \"matrix.use_coverage\"\n      uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de\n      with:\n        fail_ci_if_error: false\n        files: ./coverage.xml\n        verbose: true\n\n    - name: Upload JUnit report to Codecov\n      uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de\n      with:\n        fail_ci_if_error: false\n        files: junit.xml\n        report_type: test_results\n        verbose: true\n\n  check:  # This job does nothing and is only used for the branch protection\n    if: always()\n\n    needs:\n    - build\n\n    runs-on: ubuntu-latest\n\n    steps:\n    - name: Decide whether the needed jobs succeeded or failed\n      uses: re-actors/alls-green@a638d6464689bbb24c325bb3fe9404d63a913030\n      with:\n        jobs: ${{ toJSON(needs) }}\n"
  },
  {
    "path": ".github/workflows/update-plugin-list.yml",
    "content": "name: Update Plugin List\n\non:\n  schedule:\n    # At 00:00 on Sunday.\n    # https://crontab.guru\n    - cron: '0 0 * * 0'\n  workflow_dispatch:\n\n# Set permissions at the job level.\npermissions: {}\n\njobs:\n  update-plugin-list:\n    if: github.repository_owner == 'pytest-dev'\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n      pull-requests: write\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          fetch-depth: 0\n          persist-credentials: false\n\n      - name: Setup Python\n        uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0\n        with:\n          python-version: \"3.13\"\n\n      - name: requests-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: ~/.cache/pytest-plugin-list/\n          key: plugins-http-cache-${{ github.run_id }} # Can use time based key as well\n          restore-keys: plugins-http-cache-\n\n      - name: Install tox\n        run: |\n          python -m pip install --upgrade pip\n          pip install tox\n\n      - name: Update Plugin List\n        run: tox -e update-plugin-list\n\n      - name: Create Pull Request\n        id: pr\n        uses: peter-evans/create-pull-request@c0f553fe549906ede9cf27b5156039d195d2ece0\n        with:\n          commit-message: '[automated] Update plugin list'\n          author: 'pytest bot <pytestbot@users.noreply.github.com>'\n          branch: update-plugin-list/patch\n          delete-branch: true\n          branch-suffix: short-commit-hash\n          title: '[automated] Update plugin list'\n          body: '[automated] Update plugin list'\n          draft: true\n\n      - name: Instruct the maintainers to trigger CI by undrafting the PR\n        env:\n          GITHUB_TOKEN: ${{ github.token }}\n          PULL_REQUEST_NUMBER: ${{ steps.pr.outputs.pull-request-number }}\n        run: >-\n          gh pr comment\n          --body 'Please mark the PR as ready for review to trigger PR checks.'\n          --repo '${{ github.repository }}'\n          \"$PULL_REQUEST_NUMBER\"\n"
  },
  {
    "path": ".gitignore",
    "content": "# Automatically generated by `hgimportsvn`\n.svn\n.hgsvn\n\n# Ignore local virtualenvs\nlib/\nbin/\ninclude/\n.Python/\n\n# These lines are suggested according to the svn:ignore property\n# Feel free to enable them by uncommenting them\n*.pyc\n*.pyo\n*.swp\n*.class\n*.orig\n*~\n.hypothesis/\n\n# autogenerated\nsrc/_pytest/_version.py\n# setuptools\n.eggs/\n\ndoc/*/_build\ndoc/*/.doctrees\nbuild/\ndist/\n*.egg-info\nhtmlcov/\nissue/\nenv/\n.env/\n.venv/\n/pythonenv*/\n3rdparty/\n.tox\n.cache\n.pytest_cache\n.mypy_cache\n.coverage\n.coverage.*\ncoverage.xml\n.ropeproject\n.idea\n.hypothesis\n.pydevproject\n.project\n.settings\n.vscode\n__pycache__/\n.python-version\n.claude/settings.local.json\n\n# generated by pip\npip-wheel-metadata/\n\n# pytest debug logs generated via --debug\npytestdebug.log\n"
  },
  {
    "path": ".mailmap",
    "content": "Freya Bruhin <git@the-compiler.org>\nFreya Bruhin <me@the-compiler.org>\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "minimum_pre_commit_version: \"4.4.0\"\nrepos:\n- repo: https://github.com/astral-sh/ruff-pre-commit\n  rev: \"v0.14.14\"\n  hooks:\n    - id: ruff-check\n      args: [\"--fix\"]\n    - id: ruff-format\n-   repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v6.0.0\n    hooks:\n    -   id: trailing-whitespace\n    -   id: end-of-file-fixer\n    -   id: check-yaml\n- repo: https://github.com/woodruffw/zizmor-pre-commit\n  rev: v1.22.0\n  hooks:\n    - id: zizmor\n      args: [\"--fix\", \"--no-progress\"]\n-   repo: https://github.com/adamchainz/blacken-docs\n    rev: 1.20.0\n    hooks:\n    -   id: blacken-docs\n        additional_dependencies: [black==24.1.1]\n-   repo: https://github.com/codespell-project/codespell\n    rev: v2.4.1\n    hooks:\n    -   id: codespell\n        args: [\"--toml=pyproject.toml\"]\n        additional_dependencies:\n          - tomli\n-   repo: https://github.com/pre-commit/pygrep-hooks\n    rev: v1.10.0\n    hooks:\n    -   id: python-use-type-annotations\n-   repo: https://github.com/pre-commit/mirrors-mypy\n    rev: v1.19.1\n    hooks:\n    -   id: mypy\n        files: ^(src/|testing/|scripts/)\n        additional_dependencies:\n          - iniconfig>=1.1.0\n          - attrs>=19.2.0\n          - pluggy>=1.5.0\n          - packaging\n          - tomli\n          - types-setuptools\n          - types-tabulate\n            # for mypy running on python>=3.11 since exceptiongroup is only a dependency\n            # on <3.11\n          - exceptiongroup>=1.0.0rc8\n-   repo: https://github.com/RobertCraigie/pyright-python\n    rev: v1.1.408\n    hooks:\n    -   id: pyright\n        files: ^(src/|scripts/)\n        additional_dependencies:\n          - iniconfig>=1.1.0\n          - attrs>=19.2.0\n          - pluggy>=1.5.0\n          - packaging\n          - tomli\n          - types-setuptools\n          - types-tabulate\n            # for mypy running on python>=3.11 since exceptiongroup is only a dependency\n            # on <3.11\n          - exceptiongroup>=1.0.0rc8\n        # Manual because passing pyright is a work in progress.\n        stages: [manual]\n- repo: https://github.com/tox-dev/pyproject-fmt\n  rev: \"v2.12.1\"\n  hooks:\n    - id: pyproject-fmt\n      # https://pyproject-fmt.readthedocs.io/en/latest/#calculating-max-supported-python-version\n      additional_dependencies: [\"tox>=4.9\"]\n-   repo: https://github.com/asottile/pyupgrade\n    rev: v3.21.2\n    hooks:\n    -   id: pyupgrade\n        args:\n          - \"--py310-plus\"\n        # Manual because ruff does what pyupgrade does and the two are not out of sync\n        # often enough to make launching pyupgrade everytime worth it\n        stages: [manual]\n-   repo: local\n    hooks:\n    -   id: pylint\n        name: pylint\n        entry: pylint\n        language: unsupported\n        types: [python]\n        args: [\"-rn\", \"-sn\", \"--fail-on=I\", \"--enable-all-extentions\"]\n        require_serial: true\n        stages: [manual]\n    -   id: rst\n        name: rst\n        entry: rst-lint\n        files: ^(RELEASING.rst|README.rst|TIDELIFT.rst)$\n        language: python\n        additional_dependencies: [pygments, restructuredtext_lint>=2.0.0]\n    -   id: changelogs-rst\n        name: changelog filenames\n        language: fail\n        entry: >-\n          changelog files must be named\n          ####.(\n          breaking\n          | deprecation\n          | feature\n          | improvement\n          | bugfix\n          | vendor\n          | doc\n          | packaging\n          | contrib\n          | misc\n          )(.#)?(.rst)?\n        exclude: >-\n          (?x)\n          ^\n            changelog/(\n              \\.gitignore\n              |\\d+\\.(\n                breaking\n                |deprecation\n                |feature\n                |improvement\n                |bugfix\n                |vendor\n                |doc\n                |packaging\n                |contrib\n                |misc\n              )(\\.\\d+)?(\\.rst)?\n              |README\\.rst\n              |_template\\.rst\n            )\n          $\n        files: ^changelog/\n    -   id: changelogs-user-role\n        name: Changelog files should use a non-broken :user:`name` role\n        language: pygrep\n        entry: :user:([^`]+`?|`[^`]+[\\s,])\n        pass_filenames: true\n        types:\n          - file\n          - rst\n    -   id: py-deprecated\n        name: py library is deprecated\n        language: pygrep\n        entry: >\n            (?x)\\bpy\\.(\n                _code\\.|\n                builtin\\.|\n                code\\.|\n                io\\.|\n                path\\.local\\.sysfind|\n                process\\.|\n                std\\.|\n                error\\.|\n                xml\\.\n            )\n        types: [python]\n    -   id: py-path-deprecated\n        name: py.path usage is deprecated\n        exclude: docs|src/_pytest/deprecated.py|testing/deprecated_test.py|src/_pytest/legacypath.py\n        language: pygrep\n        entry: \\bpy\\.path\\.local\n        types: [python]\n"
  },
  {
    "path": ".readthedocs.yaml",
    "content": "version: 2\n\npython:\n   install:\n     # Install pytest first, then doc/en/requirements.txt.\n     # This order is important to honor any pins in doc/en/requirements.txt\n     # when the pinned library is also a dependency of pytest.\n     - method: pip\n       path: .\n     - requirements: doc/en/requirements.txt\n\nsphinx:\n  configuration: doc/en/conf.py\n  fail_on_warning: true\n\nbuild:\n  os: ubuntu-24.04\n  tools:\n    python: >-\n      3.13\n  apt_packages:\n    - inkscape\n  jobs:\n    post_checkout:\n      - git fetch --unshallow || true\n      - git fetch --tags || true\n\nformats:\n  - epub\n  - pdf\n  - htmlzip\n"
  },
  {
    "path": "AUTHORS",
    "content": "Holger Krekel, holger at merlinux eu\nmerlinux GmbH, Germany, office at merlinux eu\n\nContributors include::\n\nAaron Coleman\nAbdeali JK\nAbdelrahman Elbehery\nAbhijeet Kasurde\nAdam Johnson\nAdam Stewart\nAdam Uhlir\nAhn Ki-Wook\nAkhilesh Ramakrishnan\nAkiomi Kamakura\nAlan Velasco\nAlejandro Villate\nAlessio Izzo\nAlex Jones\nAlex Lambson\nAlexander Johnson\nAlexander King\nAlexei Kozlenok\nAlice Purcell\nAllan Feldman\nAly Sivji\nAmir Elkess\nAmmar Askar\nAnatoly Bubenkoff\nAnders Hovmöller\nAndras Mitzki\nAndras Tim\nAndrea Cimatoribus\nAndreas Motl\nAndreas Zeidler\nAndrew Pikul\nAndrew Shapton\nAndrey Paramonov\nAndrzej Klajnert\nAndrzej Ostrowski\nAndy Freeland\nAnita Hammer\nAnna Tasiopoulou\nAnthon van der Neut\nAnthony Shaw\nAnthony Sottile\nAnton Grinevich\nAnton Lodder\nAnton Zhilin\nAntony Lee\nArel Cordero\nArias Emmanuel\nAriel Pillemer\nArmin Rigo\nAron Coyle\nAron Curzon\nArthur Richard\nAshish Kurmi\nAshley Whetter\nAviral Verma\nAviv Palivoda\nBabak Keyvani\nBahram Farahmand\nBarney Gale\nBen Brown\nBen Gartner\nBen Leith\nBen Webb\nBenjamin Peterson\nBenjamin Schubert\nBernard Pratz\nBo Wu\nBob Ippolito\nBrian Dorsey\nBrian Larsen\nBrian Maissy\nBrian Okken\nBrianna Laugher\nBruno Oliveira\nCal Jacobson\nCal Leeming\nCarl Friedrich Bolz\nCarlos Jenkins\nCeridwen\nCharles Cloud\nCharles Machalow\nCharles-Meldhine Madi Mnemoi (cmnemoi)\nCharnjit SiNGH (CCSJ)\nCheuk Ting Ho\nChris Mahoney\nChris Lamb\nChris NeJame\nChris Rose\nChris Wheeler\nChristian Boelsen\nChristian Clauss\nChristian Fetzer\nChristian Neumüller\nChristian Theunert\nChristian Tismer\nChristine Mecklenborg\nChristoph Buelter\nChristopher Dignam\nChristopher Gilling\nChristopher Head\nClaire Cecil\nClaudio Madotto\nClément M.T. Robert\nCornelius Riemenschneider\nCrazyMerlyn\nCristian Vera\nCyrus Maden\nDaara Shaw\nDamian Skrzypczak\nDaniel Grana\nDaniel Hahler\nDaniel Miller\nDaniel Nuri\nDaniel Sánchez Castelló\nDaniel Valenzuela Zenteno\nDaniel Wandschneider\nDaniele Procida\nDanielle Jenkins\nDaniil Galiev\nDave Hunt\nDavid Díaz-Barquero\nDavid Mohr\nDavid Paul Röthlisberger\nDavid Peled\nDavid Szotten\nDavid Vierra\nDaw-Ran Liou\nDebi Mishra\nDenis Cherednichenko\nDenis Kirisov\nDenivy Braiam Rück\nDeysha Rivera\nDheeraj C K\nDhiren Serai\nDiego Russo\nDima Gerasimov\nDmitry Dygalo\nDmitry Pribysh\nDominic Mortlock\nDuncan Betts\nEdison Gustavo Muenz\nEdoardo Batini\nEdson Tadeu M. Manoel\nEduardo Schettino\nEdward Haigh\nEero Vaher\nEli Boyarski\nElizaveta Shashkova\nÉloi Rivard\nEmil Hjelm\nEndre Galaczi\nEric Hunsberger\nEric Liu\nEric Siegerman\nEric Yuan\nErik Aronesty\nErik Hasse\nErik M. Bray\nEthan Wass\nEvan Kepner\nEvgeny Seliverstov\nFabian Sturm\nFabien Zarifian\nFabio Zadrozny\nFarbod Ahmadian\nfaph\nFelix Hofstätter\nFelix Nieuwenhuizen\nFeng Ma\nFlorian Dahlitz\nFloris Bruynooghe\nFrank Hoffmann\nFraser Stark\nFreya Bruhin\nGabriel Landau\nGabriel Reis\nGarvit Shubham\nGene Wood\nGeorge Kussumoto\nGeorgy Dyuldin\nGergely Kalmár\nGleb Nikonorov\nGraeme Smecher\nGraham Horler\nGreg Price\nGregory Lee\nGrig Gheorghiu\nGrigorii Eremeev (budulianin)\nGuido Wesdorp\nGuoqiang Zhang\nHarald Armin Massa\nHarshna\nHenk-Jaap Wagenaar\nHolger Kohr\nHugo van Kemenade\nHui Wang (coldnight)\nIan Bicking\nIan Lesperance\nIlya Konstantinov\nIonuț Turturică\nIsaac Virshup\nIsrael Fruchter\nIsraël Hallé\nItxaso Aizpurua\nIwan Briquemont\nJaap Broekhuizen\nJake VanderPlas\nJakob van Santen\nJakub Mitoraj\nJames Bourbeau\nJames Frost\nJan Balster\nJanne Vanhala\nJason R. Coombs\nJavier Domingo Cansino\nJavier Romero\nJeff Rackauckas\nJeff Widman\nJenni Rinker\nJens Tröger\nJiajun Xu\nJohn Eddie Ayson\nJohn Litborn\nJohn Towler\nJon Parise\nJon Sonesen\nJonas Obrist\nJordan Guymon\nJordan Macdonald\nJordan Moldow\nJordan Speicher\nJoseph Hunkeler\nJoseph Sawaya\nJosh Karpel\nJoshua Bronson\nJulian Valentin\nJunhao Liao\nJurko Gospodnetić\nJustice Ndou\nJustyna Janczyszyn\nKale Kundert\nKamran Ahmad\nKenny Y\nKarl O. Pinc\nKarthikeyan Singaravelan\nKatarzyna Jachim\nKatarzyna Król\nKaterina Koukiou\nKeri Volans\nKevin C\nKevin Cox\nKevin Hierro Carrasco\nKevin J. Foley\nKian Eliasi\nKian-Meng Ang\nKim Soo\nKodi B. Arfer\nKojo Idrissa\nKostis Anagnostopoulos\nKristoffer Nordström\nKyle Altendorf\nLawrence Mitchell\nLee Kamentsky\nLeonardus Chen\nLev Maximov\nLevon Saldamli\nLewis Cowles\nLiam DeVoe\nLlandy Riveron Del Risco\nLoic Esteve\nlovetheguitar\nLukas Bednar\nLuke Murphy\nMaciek Fijalkowski\nMaggie Chung\nMaho\nMaik Figura\nMandeep Bhutani\nManuel Krebber\nMarc Mueller\nMarc Schlaich\nMarcelo Duarte Trevisani\nMarcin Augustynów\nMarcin Bachry\nMarc Bresson\nMarco Gorelli\nMarcos Boger\nMark Abramowitz\nMark Dickinson\nMark Vong\nMarko Pacak\nMarkus Unterwaditzer\nMartijn Faassen\nMartin Altmayer\nMartin K. Scherer\nMartin Prusse\nMathieu Clabaut\nMatt Bachmann\nMatt Duck\nMatt Williams\nMatthias Hafner\nMaxim Filipenko\nMaximilian Cosmo Sitter\nmbyt\nMichael Aquilina\nMichael Birtwell\nMichael Droettboom\nMichael Goerz\nMichael Krebs\nMichael Seifert\nMichael Vogt\nMichael Reznik\nMichal Wajszczuk\nMichał Górny\nMichał Zięba\nMickey Pashov\nMihai Capotă\nMihail Milushev\nMike Hoyle (hoylemd)\nMike Lundy\nMilan Lesnek\nMiro Hrončok\nMulat Mekonen\nmrbean-bremen\nNathan Goldbaum\nNathan Rousseau\nNathaniel Compton\nNathaniel Waisbrot\nNauman Ahmed\nNed Batchelder\nNeil Martin\nNeven Mundar\nNicholas Devenish\nNicholas Murphy\nNiclas Olofsson\nNicolas Delaby\nNicolas Simonds\nNico Vidal\nNikesh Chavhan\nNikolay Kondratyev\nNipunn Koorapati\nOleg Pidsadnyi\nOleg Sushchenko\nOleksandr Zavertniev\nOlga Matoula\nOliver Bestwalter\nOlivier Grisel\nOmar Kohl\nOmer Hadari\nOmri Golan\nOndřej Súkup\nOscar Benjamin\nParth Patel\nPatrick Hayes\nPatrick Lannigan\nPaul Müller\nPaul Reece\nPauli Virtanen\nPavel Karateev\nPavel Zhukov\nPaweł Adamczak\nPedro Algarvio\nPeter Gessler\nPetter Strandmark\nPhilipp Loose\nPierre Sassoulas\nPieter Mulder\nPiotr Banaszkiewicz\nPiotr Helm\nPoulami Sau\nPrakhar Gurunani\nPrashant Anand\nPrashant Sharma\nPulkit Goyal\nPunyashloka Biswal\nQuentin Pradet\nq0w\nRalf Schmitt\nRalph Giles\nRam Rachum\nRan Benita\nRandy Döring\nRaphael Castaneda\nRaphael Pierzina\nRafal Semik\nReza Mousavi\nRaquel Alegre\nRavi Chandra\nReagan Lee\nReilly Brogan\nRob Arrow\nRobert Holt\nRoberto Aldera\nRoberto Polli\nRoland Puntaier\nRomain Dorgueil\nRoman Bolshakov\nRonny Pfannschmidt\nRoss Lawley\nRuaridh Williamson\nRussel Winder\nRussell Martin\nRyan Puddephatt\nRyan Wooden\nSadra Barikbin\nSaiprasad Kale\nSamuel Colvin\nSamuel Dion-Girardeau\nSamuel Gaist\nSamuel Jirovec\nSamuel Searles-Bryant\nSamuel Therrien (Avasam)\nSamuele Pedroni\nSanket Duthade\nSankt Petersbug\nSaravanan Padmanaban\nSean Malloy\nSegev Finer\nSerhii Mozghovyi\nSeth Junot\nShantanu Jain\nSharad Nair\nShaygan Hooshyari\nShubham Adep\nSimon Blanchard\nSimon Gomizelj\nSimon Holesch\nSimon Kerr\nSkylar Downes\nSrinivas Reddy Thatiparthy\nStefaan Lippens\nStefan Farmbauer\nStefan Scherfke\nStefan Zimmermann\nStefanie Molin\nStefano Taschini\nSteffen Allner\nStephan Obermann\nSven\nSven-Hendrik Haase\nSviatoslav Sydorenko\nSylvain Marié\nTadek Teleżyński\nTakafumi Arakaki\nTakumi Otani\nTaneli Hukkinen\nTanvi Mehta\nTanya Agarwal\nTarcisio Fischer\nTareq Alayan\nTatiana Ovary\nTed Xiao\nTerje Runde\nThomas Grainger\nThomas Hisch\nTianyu Dongfang\nTim Hoffmann\nTim Strazny\nTJ Bruno\nTobias Diez\nTobias Petersen\nTom Dalton\nTom Most\nTom Viner\nTomáš Gavenčiak\nTomer Keren\nTony Narlock\nTor Colvin\nTrevor Bekolay\nTushar Sadhwani\nTyler Goodlet\nTyler Smart\nTzu-ping Chung\nVasily Kuznetsov\nVictor Maryama\nVictor Rodriguez\nVictor Uriarte\nVidar T. Fauske\nVijay Arora\nVirendra Patil\nVirgil Dupras\nVitaly Lashmanov\nVivaan Verma\nVlad Dragos\nVlad Radziuk\nVladyslav Rachek\nVolodymyr Kochetkov\nVolodymyr Piskun\nWei Lin\nWil Cooley\nWill Riley\nWilliam Lee\nWim Glenn\nWouter van Ackooy\nXixi Zhao\nXuan Luong\nXuecong Liao\nYannick Péroux\nYao Xiao\nYoav Caspi\nYuliang Shao\nYusuke Kadowaki\nYutian Li\nYuval Shimon\nZac Hatfield-Dodds\nZac Palmer Laporte\nZach Snicker\nZachary Kneupper\nZachary OBrien\nZhouxin Qiu\nZoltán Máté\nZsolt Cserna\n"
  },
  {
    "path": "CHANGELOG.rst",
    "content": "=========\nChangelog\n=========\n\nThe pytest CHANGELOG is located `here <https://docs.pytest.org/en/stable/changelog.html>`__.\n\nThe source document can be found at: https://github.com/pytest-dev/pytest/blob/main/doc/en/changelog.rst\n"
  },
  {
    "path": "CITATION",
    "content": "NOTE: Change \"x.y\" by the version you use. If you are unsure about which version\nyou are using run: `pip show pytest`. Do not include the patch number (i.e., z in x.y.z)\n\nText:\n\n[pytest] pytest x.y, 2004\nKrekel et al., https://github.com/pytest-dev/pytest\n\nBibLaTeX:\n\n@software{pytest,\n  title        = {pytest x.y},\n  author       = {Holger Krekel and Bruno Oliveira and Ronny Pfannschmidt and Floris Bruynooghe and Brianna Laugher and Freya Bruhin},\n  year         = {2004},\n  version      = {x.y},\n  url          = {https://github.com/pytest-dev/pytest},\n  note         = {Contributors: Holger Krekel and Bruno Oliveira and Ronny Pfannschmidt and Floris Bruynooghe and Brianna Laugher and Freya Bruhin and others}\n}\n\nBibTeX:\n\n@misc{pytest,\n  author       = {Holger Krekel and Bruno Oliveira and Ronny Pfannschmidt and Floris Bruynooghe and Brianna Laugher and Freya Bruhin},\n  title        = {pytest x.y},\n  year         = {2004},\n  howpublished = {\\url{https://github.com/pytest-dev/pytest}},\n  note         = {Version x.y. Contributors include Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Freya Bruhin, and others.}\n}\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to making participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, sex characteristics, gender identity and expression,\nlevel of experience, education, socio-economic status, nationality, personal\nappearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or\n advances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic\n address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces\nwhen an individual is representing the project or its community. Examples of\nrepresenting a project or community include using an official project e-mail\naddress, posting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event. Representation of a project may be\nfurther defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at coc@pytest.org. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\nThe coc@pytest.org address is routed to the following people who can also be\ncontacted individually:\n\n- Brianna Laugher ([@pfctdayelise](https://github.com/pfctdayelise)): brianna@laugher.id.au\n- Bruno Oliveira ([@nicoddemus](https://github.com/nicoddemus)): nicoddemus@gmail.com\n- Freya Bruhin ([@the-compiler](https://github.com/the-compiler)): pytest@the-compiler.org\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see\nhttps://www.contributor-covenant.org/faq\n"
  },
  {
    "path": "CONTRIBUTING.rst",
    "content": "============================\nContributing\n============================\n\nContributions are highly welcomed and appreciated.  Every little bit of help counts,\nso do not hesitate!\n\n\n.. _submitfeedback:\n\nFeature requests and feedback\n-----------------------------\n\nDo you like pytest?  Share some love on Twitter or in your blog posts!\n\nWe'd also like to hear about your propositions and suggestions.  Feel free to\n`submit them as issues <https://github.com/pytest-dev/pytest/issues>`_ and:\n\n* Explain in detail how they should work.\n* Keep the scope as narrow as possible.  This will make it easier to implement.\n\n\n.. _reportbugs:\n\nReport bugs\n-----------\n\nReport bugs for pytest in the `issue tracker <https://github.com/pytest-dev/pytest/issues>`_.\n\nIf you are reporting a bug, please include:\n\n* Your operating system name and version.\n* Any details about your local setup that might be helpful in troubleshooting,\n  specifically the Python interpreter version, installed libraries, and pytest\n  version.\n* Detailed steps to reproduce the bug.\n\nIf you can write a demonstration test that currently fails but should pass\n(xfail), that is a very useful commit to make as well, even if you cannot\nfix the bug itself.\n\n\n.. _fixbugs:\n\nFix bugs\n--------\n\nLook through the `GitHub issues for bugs <https://github.com/pytest-dev/pytest/labels/type:%20bug>`_.\nSee also the `\"good first issue\" issues <https://github.com/pytest-dev/pytest/labels/good%20first%20issue>`_\nthat are friendly to new contributors.\n\n`Talk to developers <https://docs.pytest.org/en/stable/contact.html>`_ to find out how you can fix specific bugs. To indicate that you are going\nto work on a particular issue, add a comment to that effect on the specific issue.\n\nDon't forget to check the issue trackers of your favourite plugins, too!\n\n.. _writeplugins:\n\nImplement features\n------------------\n\nLook through the `GitHub issues for enhancements <https://github.com/pytest-dev/pytest/labels/type:%20enhancement>`_.\n\n`Talk to developers <https://docs.pytest.org/en/stable/contact.html>`_ to find out how you can implement specific\nfeatures.\n\nWrite documentation\n-------------------\n\nPytest could always use more documentation.  What exactly is needed?\n\n* More complementary documentation.  Have you perhaps found something unclear?\n* Documentation translations.  We currently have only English.\n* Docstrings.  There can never be too many of them.\n* Blog posts, articles and such -- they're all very appreciated.\n\nYou can also edit documentation files directly in the GitHub web interface,\nwithout using a local copy.  This can be convenient for small fixes.\n\n.. note::\n    Build the documentation locally with the following command:\n\n    .. code:: bash\n\n        $ tox -e docs\n\n    The built documentation should be available in ``doc/en/_build/html``,\n    where 'en' refers to the documentation language.\n\nPytest has an API reference which in large part is\n`generated automatically <https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html>`_\nfrom the docstrings of the documented items. Pytest uses the\n`Sphinx docstring format <https://sphinx-rtd-tutorial.readthedocs.io/en/latest/docstrings.html>`_.\nFor example:\n\n.. code-block:: python\n\n    def my_function(arg: ArgType) -> Foo:\n        \"\"\"Do important stuff.\n\n        More detailed info here, in separate paragraphs from the subject line.\n        Use proper sentences -- start sentences with capital letters and end\n        with periods.\n\n        Can include annotated documentation:\n\n        :param short_arg: An argument which determines stuff.\n        :param long_arg:\n            A long explanation which spans multiple lines, overflows\n            like this.\n        :returns: The result.\n        :raises ValueError:\n            Detailed information when this can happen.\n\n        .. versionadded:: 6.0\n\n        Including types into the annotations above is not necessary when\n        type-hinting is being used (as in this example).\n        \"\"\"\n\n\n.. _submitplugin:\n\nSubmitting Plugins to pytest-dev\n--------------------------------\n\nDevelopment of the pytest core, support code, and some plugins happens\nin repositories living under the ``pytest-dev`` organisations:\n\n- `pytest-dev on GitHub <https://github.com/pytest-dev>`_\n\nAll pytest-dev Contributors team members have write access to all contained\nrepositories.  Pytest core and plugins are generally developed\nusing `pull requests`_ to respective repositories.\n\nThe objectives of the ``pytest-dev`` organisation are:\n\n* Having a central location for popular pytest plugins\n* Sharing some of the maintenance responsibility (in case a maintainer no\n  longer wishes to maintain a plugin)\n\nYou can submit your plugin by posting a new topic in the `pytest-dev GitHub Discussions\n<https://github.com/pytest-dev/pytest/discussions>`_ pointing to your existing pytest plugin repository which must have\nthe following:\n\n- PyPI presence with packaging metadata that contains a ``pytest-``\n  prefixed name, version number, authors, short and long description.\n\n- a `tox configuration <https://tox.readthedocs.io/en/latest/config.html#configuration-discovery>`_\n  for running tests using `tox <https://tox.readthedocs.io>`_.\n\n- a ``README`` describing how to use the plugin and on which\n  platforms it runs.\n\n- a ``LICENSE`` file containing the licensing information, with\n  matching info in its packaging metadata.\n\n- an issue tracker for bug reports and enhancement requests.\n\n- a `changelog <https://keepachangelog.com/>`_.\n\nIf no contributor strongly objects and two agree, the repository can then be\ntransferred to the ``pytest-dev`` organisation.\n\nHere's a rundown of how a repository transfer usually proceeds\n(using a repository named ``joedoe/pytest-xyz`` as example):\n\n* ``joedoe`` transfers repository ownership to ``pytest-dev`` administrator ``calvin``.\n* ``calvin`` creates ``pytest-xyz-admin`` and ``pytest-xyz-developers`` teams, inviting ``joedoe`` to both as **maintainer**.\n* ``calvin`` transfers repository to ``pytest-dev`` and configures team access:\n\n  - ``pytest-xyz-admin`` **admin** access;\n  - ``pytest-xyz-developers`` **write** access;\n\nThe ``pytest-dev/Contributors`` team has write access to all projects, and\nevery project administrator is in it. We recommend that each plugin has at least three\npeople who have the right to release to PyPI.\n\nRepository owners can rest assured that no ``pytest-dev`` administrator will ever make\nreleases of your repository or take ownership in any way, except in rare cases\nwhere someone becomes unresponsive after months of contact attempts.\nAs stated, the objective is to share maintenance and avoid \"plugin-abandon\".\n\n\n.. _ai-contributions:\n\nAI/LLM-Assisted Contributions Policy\n-------------------------------------\n\nWe welcome contributions from all developers, including those who use AI/LLM tools\nas part of their workflow. However, we have requirements to protect the time\nand effort of our reviewers:\n\n**Purely agentic contributions are not accepted.** Pull requests that are entirely\ngenerated by AI agents, with no meaningful human review, understanding, or oversight,\nwill be closed. Every contribution must demonstrate that a human has reviewed,\nunderstood, and taken responsibility for the changes. If you submit it, you own it.\n\n**You are responsible for your contribution.** Regardless of how the code was\nproduced, the person submitting a pull request must understand the changes and be\nable to respond to review feedback. If a reviewer asks questions or requests changes,\nthey expect to interact with someone who can engage substantively, not an automated\nloop replaying prompts.\n\n**Credit AI tools via attribution.** If AI agents helped produce your code or\ncommits, consider adding ``Co-authored-by`` trailers to your commit messages to\ncredit them. This is not required, but helps reviewers set expectations and is\nappreciated.\n\n**Respect maintainer time.** Submitting low-effort AI-generated pull requests that\nwaste reviewer time may result in a ban from the project. Our maintainers are\nvolunteers, and contributions should reflect genuine engagement with the project.\n\n\nContext\n~~~~~~~\n\nWith the advent of unsupervised agentic tools like OpenClaw,\nthere has been a rise in low-quality contributions\nwhere an agent produces a large number of low-quality pull requests.\nOftentimes this can look similar to a human beginner with new access to tools\nand trying to learn, but in practice it is usually an unsupervised agentic tool\ngenerating changes without meaningful human review.\n\nWhen a human contributor is learning, we are glad to invest time to help,\ngive feedback, and guide them in the right direction. With fully agentic,\nunsupervised tools, that same review effort does not support anyone's learning\nor growth. Instead, it diverts limited maintainer time away from improving the\nproject and supporting engaged contributors.\n\nThere is also an asymmetry at play: someone is prioritizing what we review\nwithout making an equivalent investment of time or effort.\nWhen a contributor works on an issue themselves, they invest real time, effectively\nearning influence over what the project focuses on. Unsupervised agentic contributions\nexpect to set that priority at near-zero cost to the sender, while shifting the\nentire burden onto maintainers.\n\nFully agentic contributions invert the intended benefit of these tools: rather than\nsaving time, they create avoidable review and triage work. There is no accountable\nhuman author thoughtfully iterating on feedback, only automated output driven\nby prompts.\n\nFrom our own experience using coding agents, we know they must be carefully prompted,\nsupervised, and checked by humans. Even modern models can make serious mistakes when\noperating at framework or tooling level, and those mistakes can be subtle and\ntime-consuming to diagnose.\n\nRunning such tools unsupervised on open-source projects imposes this cost on\nmaintainers and other contributors without their consent. Our goal with this policy\nis to set clear expectations, protect reviewer time, and ensure that contributions\nremain collaborative, respectful, and sustainable.\n\n\n.. _`pull requests`:\n.. _pull-requests:\n\nPreparing Pull Requests\n-----------------------\n\nShort version\n~~~~~~~~~~~~~\n\n#. Fork the repository.\n#. Fetch tags from upstream if necessary (if you cloned only main `git fetch --tags https://github.com/pytest-dev/pytest`).\n#. Enable and install `pre-commit <https://pre-commit.com>`_ to ensure style-guides and code checks are followed.\n#. Follow `PEP-8 <https://www.python.org/dev/peps/pep-0008/>`_ for naming.\n#. Tests are run using ``tox``::\n\n    tox -e linting,py313\n\n   The test environments above are usually enough to cover most cases locally.\n\n#. Write a ``changelog`` entry: ``changelog/2574.bugfix.rst``, use issue id number\n   and one of ``feature``, ``improvement``, ``bugfix``, ``doc``, ``deprecation``,\n   ``breaking``, ``vendor``, ``packaging``, ``contrib``, or ``misc`` for the issue type.\n\n\n#. Unless your change is a trivial or a documentation fix (e.g., a typo or reword of a small section) please\n   add yourself to the ``AUTHORS`` file, in alphabetical order.\n\n\nLong version\n~~~~~~~~~~~~\n\nWhat is a \"pull request\"?  It informs the project's core developers about the\nchanges you want to review and merge.  Pull requests are stored on\n`GitHub servers <https://github.com/pytest-dev/pytest/pulls>`_.\nOnce you send a pull request, we can discuss its potential modifications and\neven add more commits to it later on. There's an excellent tutorial on how Pull\nRequests work in the\n`GitHub Help Center <https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests>`_.\n\nHere is a simple overview, with pytest-specific bits:\n\n#. Fork the\n   `pytest GitHub repository <https://github.com/pytest-dev/pytest>`__.  It's\n   fine to use ``pytest`` as your fork repository name because it will live\n   under your user.\n\n#. Clone your fork locally using `git <https://git-scm.com/>`_ and create a branch::\n\n    $ git clone git@github.com:YOUR_GITHUB_USERNAME/pytest.git\n    $ cd pytest\n    $ git fetch --tags https://github.com/pytest-dev/pytest\n    # now, create your own branch off \"main\":\n\n        $ git checkout -b your-bugfix-branch-name main\n\n   Given we have \"major.minor.micro\" version numbers, bug fixes will usually\n   be released in micro releases whereas features will be released in\n   minor releases and incompatible changes in major releases.\n\n   You will need the tags to test locally, so be sure you have the tags from the main repository. If you suspect you don't, set the main repository as upstream and fetch the tags::\n\n     $ git remote add upstream https://github.com/pytest-dev/pytest\n     $ git fetch upstream --tags\n\n   If you need some help with Git, follow this quick start\n   guide: https://git.wiki.kernel.org/index.php/QuickStart\n\n#. Install `pre-commit <https://pre-commit.com>`_ and its hook on the pytest repo::\n\n     $ pip install --user pre-commit\n     $ pre-commit install\n\n   Afterwards ``pre-commit`` will run whenever you commit.\n\n   https://pre-commit.com/ is a framework for managing and maintaining multi-language pre-commit hooks\n   to ensure code-style and code formatting is consistent.\n\n#. Install tox\n\n   Tox is used to run all the tests and will automatically setup virtualenvs\n   to run the tests in.\n   (will implicitly use https://virtualenv.pypa.io/en/latest/)::\n\n    $ pip install tox\n\n#. Run all the tests\n\n   You need to have a supported Python version available in your system.  Now\n   running tests is as simple as issuing this command::\n\n    $ tox -e linting,py\n\n   This command will run tests via the \"tox\" tool against your default Python\n   version and also perform \"lint\" coding-style checks.\n\n#. You can now edit your local working copy and run the tests again as necessary. Please follow `PEP-8 <https://www.python.org/dev/peps/pep-0008/>`_ for naming.\n\n   You can pass different options to ``tox``. For example, to run tests on Python 3.13 and pass options to pytest\n   (e.g. enter pdb on failure) you can do::\n\n    $ tox -e py313 -- --pdb\n\n   Or to only run tests in a particular test module on Python 3.12::\n\n    $ tox -e py312 -- testing/test_config.py\n\n\n   When committing, ``pre-commit`` will re-format the files if necessary.\n\n#. If instead of using ``tox`` you prefer to run the tests directly, then we suggest to create a virtual environment and use\n   an editable install with the ``dev`` extra::\n\n       $ python3 -m venv .venv\n       $ source .venv/bin/activate  # Linux\n       $ .venv/Scripts/activate.bat  # Windows\n       $ pip install -e \".[dev]\"\n\n   Afterwards, you can edit the files and run pytest normally::\n\n       $ pytest testing/test_config.py\n\n#. Create a new changelog entry in ``changelog``. The file should be named ``<issueid>.<type>.rst``,\n   where *issueid* is the number of the issue related to the change and *type* is one of\n   ``feature``, ``improvement``, ``bugfix``, ``doc``, ``deprecation``, ``breaking``, ``vendor``,\n   ``packaging``, ``contrib``, or ``misc``.\n   You may skip creating the changelog entry if the change doesn't affect the\n   documented behaviour of pytest.\n\n#. Add yourself to ``AUTHORS`` file if not there yet, in alphabetical order.\n\n#. Commit and push once your tests pass and you are happy with your change(s)::\n\n    $ git commit -a -m \"<commit message>\"\n    $ git push -u\n\n#. Finally, submit a pull request through the GitHub website using this data::\n\n    head-fork: YOUR_GITHUB_USERNAME/pytest\n    compare: your-branch-name\n\n    base-fork: pytest-dev/pytest\n    base: main\n\n\nWriting Tests\n~~~~~~~~~~~~~\n\nWriting tests for plugins or for pytest itself is often done using the `pytester fixture <https://docs.pytest.org/en/stable/reference/reference.html#pytester>`_, as a \"black-box\" test.\n\nFor example, to ensure a simple test passes you can write:\n\n.. code-block:: python\n\n    def test_true_assertion(pytester):\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert True\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(failed=0, passed=1)\n\n\nAlternatively, it is possible to make checks based on the actual output of the terminal using\n*glob-like* expressions:\n\n.. code-block:: python\n\n    def test_true_assertion(pytester):\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert False\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*assert False*\", \"*1 failed*\"])\n\nWhen choosing a file where to write a new test, take a look at the existing files and see if there's\none file which looks like a good fit. For example, a regression test about a bug in the ``--lf`` option\nshould go into ``test_cacheprovider.py``, given that this option is implemented in ``cacheprovider.py``.\nIf in doubt, go ahead and open a PR with your best guess and we can discuss this over the code.\n\nJoining the Development Team\n----------------------------\n\nAnyone who has successfully seen through a pull request which did not\nrequire any extra work from the development team to merge will\nthemselves gain commit access if they so wish (if we forget to ask please send a friendly\nreminder).  This does not mean there is any change in your contribution workflow:\neveryone goes through the same pull-request-and-review process and\nno-one merges their own pull requests unless already approved.  It does however mean you can\nparticipate in the development process more fully since you can merge\npull requests from other contributors yourself after having reviewed\nthem.\n\n\nMerge/squash guidelines\n-----------------------\n\nWhen a PR is approved and ready to be integrated to the ``main`` branch, one has the option to *merge* the commits unchanged, or *squash* all the commits into a single commit.\n\nHere are some guidelines on how to proceed, based on examples of a single PR commit history:\n\n1. Miscellaneous commits:\n\n   * ``Implement X``\n   * ``Fix test_a``\n   * ``Add myself to AUTHORS``\n   * ``fixup! Fix test_a``\n   * ``Update tests/test_integration.py``\n   * ``Merge origin/main into PR branch``\n   * ``Update tests/test_integration.py``\n\n   In this case, prefer to use the **Squash** merge strategy: the commit history is a bit messy (not in a derogatory way, often one just commits changes because they know the changes will eventually be squashed together), so squashing everything into a single commit is best. You must clean up the commit message, making sure it contains useful details.\n\n2. Separate commits related to the same topic:\n\n   * ``Implement X``\n   * ``Add myself to AUTHORS``\n   * ``Update CHANGELOG for X``\n\n   In this case, prefer to use the **Squash** merge strategy: while the commit history is not \"messy\" as in the example above, the individual commits do not bring much value overall, specially when looking at the changes a few months/years down the line.\n\n3. Separate commits, each with their own topic (refactorings, renames, etc), but still have a larger topic/purpose.\n\n   * ``Refactor class X in preparation for feature Y``\n   * ``Remove unused method``\n   * ``Implement feature Y``\n\n   In this case, prefer to use the **Merge** strategy: each commit is valuable on its own, even if they serve a common topic overall. Looking at the history later, it is useful to have the removal of the unused method separately on its own commit, along with more information (such as how it became unused in the first place).\n\n4. Separate commits, each with their own topic, but without a larger topic/purpose other than improve the code base (using more modern techniques, improve typing, removing clutter, etc).\n\n   * ``Improve internal names in X``\n   * ``Add type annotations to Y``\n   * ``Remove unnecessary dict access``\n   * ``Remove unreachable code due to EOL Python``\n\n   In this case, prefer to use the **Merge** strategy: each commit is valuable on its own, and the information on each is valuable in the long term.\n\n\nAs mentioned, those are overall guidelines, not rules cast in stone. This topic was discussed in `#12633 <https://github.com/pytest-dev/pytest/discussions/12633>`_.\n\n\n*Backport PRs* (as those created automatically from a ``backport`` label) should always be **squashed**, as they preserve the original PR author.\n\n\nBackporting bug fixes for the next patch release\n------------------------------------------------\n\nPytest makes a feature release every few weeks or months. In between, patch releases\nare made to the previous feature release, containing bug fixes only. The bug fixes\nusually fix regressions, but may be any change that should reach users before the\nnext feature release.\n\nSuppose for example that the latest release was 1.2.3, and you want to include\na bug fix in 1.2.4 (check https://github.com/pytest-dev/pytest/releases for the\nactual latest release). The procedure for this is:\n\n#. First, make sure the bug is fixed in the ``main`` branch, with a regular pull\n   request, as described above. An exception to this is if the bug fix is not\n   applicable to ``main`` anymore.\n\nAutomatic method:\n\nAdd a ``backport 1.2.x`` label to the PR you want to backport. This will create\na backport PR against the ``1.2.x`` branch.\n\nManual method:\n\n#. ``git checkout origin/1.2.x -b backport-XXXX`` # use the main PR number here\n\n#. Locate the merge commit on the PR, in the *merged* message, for example:\n\n    nicoddemus merged commit 0f8b462 into pytest-dev:main\n\n#. ``git cherry-pick -x -m1 REVISION`` # use the revision you found above (``0f8b462``).\n\n#. Open a PR targeting ``1.2.x``:\n\n   * Prefix the message with ``[1.2.x]``.\n   * Delete the PR body, it usually contains a duplicate commit message.\n\n\nWho does the backporting\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs mentioned above, bugs should first be fixed on ``main`` (except in rare occasions\nthat a bug only happens in a previous release). So, who should do the backport procedure described\nabove?\n\n1. If the bug was fixed by a core developer, it is the main responsibility of that core developer\n   to do the backport.\n2. However, often the merge is done by another maintainer, in which case it is nice of them to\n   do the backport procedure if they have the time.\n3. For bugs submitted by non-maintainers, it is expected that a core developer will do\n   the backport, normally the one that merged the PR on ``main``.\n4. If a non-maintainer notices a bug which is fixed on ``main`` but has not been backported\n   (due to maintainers forgetting to apply the *needs backport* or *backport x.x.x* labels, or just plain missing it),\n   they are also welcome to open a PR with the backport. The procedure is simple and really\n   helps with the maintenance of the project.\n\nAll the above are not rules, but merely some guidelines/suggestions on what we should expect\nabout backports.\n\nBackports should be **squashed** (rather than **merged**), as doing so preserves the original PR author correctly.\n\nHandling stale issues/PRs\n-------------------------\n\nStale issues/PRs are those where pytest contributors have asked for questions/changes\nand the authors didn't get around to answer/implement them yet after a somewhat long time, or\nthe discussion simply died because people seemed to lose interest.\n\nThere are many reasons why people don't answer questions or implement requested changes:\nthey might get busy, lose interest, or just forget about it,\nbut the fact is that this is very common in open source software.\n\nThe pytest team really appreciates every issue and pull request, but being a high-volume project\nwith many issues and pull requests being submitted daily, we try to reduce the number of stale\nissues and PRs by regularly closing them. When an issue/pull request is closed in this manner,\nit is by no means a dismissal of the topic being tackled by the issue/pull request, but it\nis just a way for us to clear up the queue and make the maintainers' work more manageable. Submitters\ncan always reopen the issue/pull request in their own time later if it makes sense.\n\nWhen to close\n~~~~~~~~~~~~~\n\nHere are a few general rules the maintainers use to decide when to close issues/PRs because\nof lack of inactivity:\n\n* Issues labeled ``question`` or ``needs information``: closed after 14 days inactive.\n* Issues labeled ``proposal``: closed after six months inactive.\n* Pull requests: after one month, consider pinging the author, update linked issue, or consider closing. For pull requests which are nearly finished, the team should consider finishing it up and merging it.\n\nThe above are **not hard rules**, but merely **guidelines**, and can be (and often are!) reviewed on a case-by-case basis.\n\nClosing pull requests\n~~~~~~~~~~~~~~~~~~~~~\n\nWhen closing a Pull Request, we should acknowledge the time, effort, and interest demonstrated by the person who submitted it. As mentioned previously, it is not the intent of the team to dismiss a stalled pull request entirely but to merely to clear up our queue, so a message like the one below is warranted when closing a pull request that went stale:\n\n    Hi <contributor>,\n\n    First of all, we would like to thank you for your time and effort on working on this, the pytest team deeply appreciates it.\n\n    We noticed it has been awhile since you have updated this PR, however. pytest is a high activity project, with many issues/PRs being opened daily, so it is hard for us maintainers to track which PRs are ready for merging, for review, or need more attention.\n\n    So for those reasons, we think it is best to close the PR for now, but with the only intention to clean up our queue, it is by no means a rejection of your changes. We still encourage you to re-open this PR (it is just a click of a button away) when you are ready to get back to it.\n\n    Again we appreciate your time for working on this, and hope you might get back to this at a later time!\n\n    <bye>\n\nClosing issues\n--------------\n\nWhen a pull request is submitted to fix an issue, add text like ``closes #XYZW`` to the PR description and/or commits (where ``XYZW`` is the issue number). See the `GitHub docs <https://help.github.com/en/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword>`_ for more information.\n\nWhen an issue is due to user error (e.g. misunderstanding of a functionality), please politely explain to the user why the issue raised is really a non-issue and ask them to close the issue if they have no further questions. If the original requester is unresponsive, the issue will be handled as described in the section `Handling stale issues/PRs`_ above.\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2004 Holger Krekel and others\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "OPENCOLLECTIVE.rst",
    "content": "==============\nOpenCollective\n==============\n\npytest has a collective setup at `OpenCollective`_. This document describes how the core team manages\nOpenCollective-related activities.\n\nWhat is it\n==========\n\nOpen Collective is an online funding platform for open and transparent communities.\nIt provides tools to raise money and share your finances in full transparency.\n\nIt is the platform of choice for individuals and companies that want to make one-time or\nmonthly donations directly to the project.\n\nFunds\n=====\n\nThe OpenCollective funds donated to pytest will be used to fund overall maintenance,\nlocal sprints, merchandising (stickers to distribute in conferences for example), and future\ngatherings of pytest developers (sprints).\n\n`Core contributors`_ which are contributing on a continuous basis are free to submit invoices\nto bill maintenance hours using the platform. How much each contributor should request is still an\nopen question, but we should use common sense and trust in the contributors, most of which know\nthemselves in-person. A good rule of thumb is to bill the same amount as monthly payments\ncontributors which participate in the `Tidelift`_ subscription. If in doubt, just ask.\n\nAdmins\n======\n\nA few people have admin access to the OpenCollective dashboard to make changes. Those people\nare part of the `@pytest-dev/opencollective-admins`_ team.\n\n`Core contributors`_ interested in helping out with OpenCollective maintenance are welcome! We don't\nexpect much work here other than the occasional approval of expenses from other core contributors.\nJust drop a line to one of the `@pytest-dev/opencollective-admins`_ or use the mailing list.\n\n\n.. _`OpenCollective`: https://opencollective.com/pytest\n.. _`Tidelift`: https://tidelift.com\n.. _`core contributors`: https://github.com/orgs/pytest-dev/teams/core/members\n.. _`@pytest-dev/opencollective-admins`: https://github.com/orgs/pytest-dev/teams/opencollective-admins/members\n"
  },
  {
    "path": "README.rst",
    "content": ".. image:: https://github.com/pytest-dev/pytest/raw/main/doc/en/img/pytest_logo_curves.svg\n   :target: https://docs.pytest.org/en/stable/\n   :align: center\n   :height: 200\n   :alt: pytest\n\n\n------\n\n.. image:: https://img.shields.io/pypi/v/pytest.svg\n    :target: https://pypi.org/project/pytest/\n\n.. image:: https://img.shields.io/conda/vn/conda-forge/pytest.svg\n    :target: https://anaconda.org/conda-forge/pytest\n\n.. image:: https://img.shields.io/pypi/pyversions/pytest.svg\n    :target: https://pypi.org/project/pytest/\n\n.. image:: https://codecov.io/gh/pytest-dev/pytest/branch/main/graph/badge.svg\n    :target: https://codecov.io/gh/pytest-dev/pytest\n    :alt: Code coverage Status\n\n.. image:: https://github.com/pytest-dev/pytest/actions/workflows/test.yml/badge.svg\n    :target: https://github.com/pytest-dev/pytest/actions?query=workflow%3Atest\n\n.. image:: https://results.pre-commit.ci/badge/github/pytest-dev/pytest/main.svg\n   :target: https://results.pre-commit.ci/latest/github/pytest-dev/pytest/main\n   :alt: pre-commit.ci status\n\n.. image:: https://www.codetriage.com/pytest-dev/pytest/badges/users.svg\n    :target: https://www.codetriage.com/pytest-dev/pytest\n\n.. image:: https://readthedocs.org/projects/pytest/badge/?version=latest\n    :target: https://pytest.readthedocs.io/en/latest/?badge=latest\n    :alt: Documentation Status\n\n.. image:: https://img.shields.io/badge/Discord-pytest--dev-blue\n    :target: https://discord.com/invite/pytest-dev\n    :alt: Discord\n\n.. image:: https://img.shields.io/badge/Libera%20chat-%23pytest-orange\n    :target: https://web.libera.chat/#pytest\n    :alt: Libera chat\n\n\nThe ``pytest`` framework makes it easy to write small tests, yet\nscales to support complex functional testing for applications and libraries.\n\nAn example of a simple test:\n\n.. code-block:: python\n\n    # content of test_sample.py\n    def inc(x):\n        return x + 1\n\n\n    def test_answer():\n        assert inc(3) == 5\n\n\nTo execute it::\n\n    $ pytest\n    ============================= test session starts =============================\n    collected 1 items\n\n    test_sample.py F\n\n    ================================== FAILURES ===================================\n    _________________________________ test_answer _________________________________\n\n        def test_answer():\n    >       assert inc(3) == 5\n    E       assert 4 == 5\n    E        +  where 4 = inc(3)\n\n    test_sample.py:5: AssertionError\n    ========================== 1 failed in 0.04 seconds ===========================\n\n\nThanks to ``pytest``'s detailed assertion introspection, you can simply use plain ``assert`` statements. See `getting-started <https://docs.pytest.org/en/stable/getting-started.html#our-first-test-run>`_ for more examples.\n\n\nFeatures\n--------\n\n- Detailed info on failing `assert statements <https://docs.pytest.org/en/stable/how-to/assert.html>`_ (no need to remember ``self.assert*`` names)\n\n- `Auto-discovery\n  <https://docs.pytest.org/en/stable/explanation/goodpractices.html#python-test-discovery>`_\n  of test modules and functions\n\n- `Modular fixtures <https://docs.pytest.org/en/stable/explanation/fixtures.html>`_ for\n  managing small or parametrized long-lived test resources\n\n- Can run `unittest <https://docs.pytest.org/en/stable/how-to/unittest.html>`_ (or trial)\n  test suites out of the box\n\n- Python 3.10+ or PyPy3\n\n- Rich plugin architecture, with over 1300+ `external plugins <https://docs.pytest.org/en/latest/reference/plugin_list.html>`_ and thriving community\n\n\nDocumentation\n-------------\n\nFor full documentation, including installation, tutorials and PDF documents, please see https://docs.pytest.org/en/stable/.\n\n\nBugs/Requests\n-------------\n\nPlease use the `GitHub issue tracker <https://github.com/pytest-dev/pytest/issues>`_ to submit bugs or request features.\n\n\nChangelog\n---------\n\nConsult the `Changelog <https://docs.pytest.org/en/stable/changelog.html>`__ page for fixes and enhancements of each version.\n\n\nSupport pytest\n--------------\n\n`Open Collective`_ is an online funding platform for open and transparent communities.\nIt provides tools to raise money and share your finances in full transparency.\n\nIt is the platform of choice for individuals and companies that want to make one-time or\nmonthly donations directly to the project.\n\nSee more details in the `pytest collective`_.\n\n.. _Open Collective: https://opencollective.com\n.. _pytest collective: https://opencollective.com/pytest\n\n\npytest for enterprise\n---------------------\n\nAvailable as part of the Tidelift Subscription.\n\nThe maintainers of pytest and thousands of other packages are working with Tidelift to deliver commercial support and\nmaintenance for the open source dependencies you use to build your applications.\nSave time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use.\n\n`Learn more. <https://tidelift.com/subscription/pkg/pypi-pytest?utm_source=pypi-pytest&utm_medium=referral&utm_campaign=enterprise&utm_term=repo>`_\n\nSecurity\n^^^^^^^^\n\npytest has never been associated with a security vulnerability, but in any case, to report a\nsecurity vulnerability please use the `Tidelift security contact <https://tidelift.com/security>`_.\nTidelift will coordinate the fix and disclosure.\n\n\nLicense\n-------\n\nCopyright Holger Krekel and others, 2004.\n\nDistributed under the terms of the `MIT`_ license, pytest is free and open source software.\n\n.. _`MIT`: https://github.com/pytest-dev/pytest/blob/main/LICENSE\n"
  },
  {
    "path": "RELEASING.rst",
    "content": "Release Procedure\n-----------------\n\nOur current policy for releasing is to aim for a bug-fix release every few weeks and a minor release every 2-3 months. The idea\nis to get fixes and new features out instead of trying to cram a ton of features into a release and by consequence\ntaking a lot of time to make a new one.\n\nThe git commands assume the following remotes are setup:\n\n* ``origin``: your own fork of the repository.\n* ``upstream``: the ``pytest-dev/pytest`` official repository.\n\nPreparing: Automatic Method\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWe have developed an automated workflow for releases, that uses GitHub workflows and is triggered\nby `manually running <https://docs.github.com/en/actions/managing-workflow-runs/manually-running-a-workflow>`__\nthe `prepare-release-pr workflow <https://github.com/pytest-dev/pytest/actions/workflows/prepare-release-pr.yml>`__\non GitHub Actions.\n\nThe automation will decide the new version number based on the following criteria:\n\n- If the \"major release\" input is set to \"yes\", release a new major release\n  (e.g. 7.0.0 -> 8.0.0)\n- If there are any ``.feature.rst`` or ``.breaking.rst`` files in the\n  ``changelog`` directory, release a new minor release (e.g. 7.0.0 -> 7.1.0)\n- Otherwise, release a bugfix release (e.g. 7.0.0 -> 7.0.1)\n- If the \"prerelease\" input is set, append the string to the version number\n  (e.g. 7.0.0 -> 8.0.0rc1), if \"major\" is set, and \"prerelease\" is set to `rc1`)\n\nBug-fix and minor releases\n^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nBug-fix and minor releases are always done from a maintenance branch. First,\nconsider double-checking the ``changelog`` directory to see if there are any\nbreaking changes or new features.\n\nFor a new minor release, first create a new maintenance branch from ``main``::\n\n     git fetch upstream\n     git branch 7.1.x upstream/main\n     git push upstream 7.1.x\n\nThen, trigger the workflow with the following inputs:\n\n- branch: **7.1.x**\n- major release: **no**\n- prerelease: empty\n\nOr via the commandline using `GitHub's cli <https://github.com/cli/cli>`__::\n\n    gh workflow run prepare-release-pr.yml -f branch=7.1.x -f major=no -f prerelease=\n\nWhere ``7.1.x`` is the maintenance branch for the ``7.1`` series. The automated\nworkflow will publish a PR for a branch ``release-7.1.0``.\n\nSimilarly, for a bug-fix release, use the existing maintenance branch and\ntrigger the workflow with e.g. ``branch: 7.0.x`` to get a new ``release-7.0.1``\nPR.\n\nMajor releases\n^^^^^^^^^^^^^^\n\n1. Create a new maintenance branch from ``main``::\n\n        git fetch upstream\n        git branch 8.0.x upstream/main\n        git push upstream 8.0.x\n\n2. Trigger the workflow with the following inputs:\n\n   - branch: **8.0.x**\n   - major release: **yes**\n   - prerelease: empty\n\nOr via the commandline::\n\n    gh workflow run prepare-release-pr.yml -f branch=8.0.x -f major=yes -f prerelease=\n\nThe automated workflow will publish a PR for a branch ``release-8.0.0``.\n\nAt this point on, this follows the same workflow as other maintenance branches: bug-fixes are merged\ninto ``main`` and ported back to the maintenance branch, even for release candidates.\n\nRelease candidates\n^^^^^^^^^^^^^^^^^^\n\nTo release a release candidate, set the \"prerelease\" input to the version number\nsuffix to use. To release a ``8.0.0rc1``, proceed like under \"major releases\", but set:\n\n- branch: 8.0.x\n- major release: yes\n- prerelease: **rc1**\n\nOr via the commandline::\n\n    gh workflow run prepare-release-pr.yml -f branch=8.0.x -f major=yes -f prerelease=rc1\n\nThe automated workflow will publish a PR for a branch ``release-8.0.0rc1``.\n\n**A note about release candidates**\n\nDuring release candidates we can merge small improvements into\nthe maintenance branch before releasing the final major version, however we must take care\nto avoid introducing big changes at this stage.\n\nPreparing: Manual Method\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n**Important**: pytest releases must be prepared on **Linux** because the docs and examples expect\nto be executed on that platform.\n\nTo release a version ``MAJOR.MINOR.PATCH``, follow these steps:\n\n#. For major and minor releases, create a new branch ``MAJOR.MINOR.x`` from\n   ``upstream/main`` and push it to ``upstream``.\n\n#. Create a branch ``release-MAJOR.MINOR.PATCH`` from the ``MAJOR.MINOR.x`` branch.\n\n   Ensure your local checkout is up to date and in a clean working tree.\n\n#. Using ``tox``, generate docs, changelog, announcements::\n\n    $ tox -e release -- MAJOR.MINOR.PATCH\n\n   This will generate a commit with all the changes ready for pushing.\n\n#. Open a PR for the ``release-MAJOR.MINOR.PATCH`` branch targeting ``MAJOR.MINOR.x``.\n\n\nReleasing\n~~~~~~~~~\n\nBoth automatic and manual processes described above follow the same steps from this point onward.\n\n#. After all tests pass and the PR has been approved, trigger the ``deploy`` workflow\n   in https://github.com/pytest-dev/pytest/actions/workflows/deploy.yml, using the ``release-MAJOR.MINOR.PATCH`` branch\n   as source.\n\n   Using the command-line::\n\n     $ gh workflow run deploy.yml -R pytest-dev/pytest --ref=release-{VERSION} -f version={VERSION}\n\n   This job will require approval from ``pytest-dev/core``, after which it will publish to PyPI\n   and tag the repository.\n\n#. Merge the PR. **Make sure it's not squash-merged**, so that the tagged commit ends up in the main branch.\n\n#. For major and minor releases (or the first prerelease of it),\n   in the `ReadTheDocs admin page <https://app.readthedocs.org/projects/pytest/>`__, click \"Add Version\" on the top right,\n   choose the new branch, then set the new version as active.\n\n#. Cherry-pick the CHANGELOG / announce files to the ``main`` branch::\n\n       git fetch upstream\n       git checkout upstream/main -b cherry-pick-release\n       git cherry-pick -x -m1 upstream/MAJOR.MINOR.x\n\n#. Open a PR for ``cherry-pick-release`` and merge it once CI passes. No need to wait for approvals if there were no conflicts on the previous step.\n\n#. For major and minor releases (or the first prerelease of it), tag the release cherry-pick merge commit in main with\n   a dev tag for the next feature release::\n\n       git checkout main\n       git pull\n       git tag MAJOR.{MINOR+1}.0.dev0\n       git push upstream MAJOR.{MINOR+1}.0.dev0\n\n#. Send an email announcement with the contents from::\n\n     doc/en/announce/release-<VERSION>.rst\n\n   To the following mailing lists:\n\n   * python-announce-list@python.org\n\n   And announce it with the ``#pytest`` hashtag on:\n\n   * `Bluesky <https://bsky.app>`_\n   * `Fosstodon <https://fosstodon.org>`_\n   * `Twitter/X <https://x.com>`_\n"
  },
  {
    "path": "TIDELIFT.rst",
    "content": "========\nTidelift\n========\n\npytest is a member of `Tidelift`_. This document describes how the core team manages\nTidelift-related activities.\n\nWhat is it\n==========\n\nTidelift aims to make Open Source sustainable by offering subscriptions to companies which rely\non Open Source packages. This subscription allows it to pay maintainers of those Open Source\npackages to aid sustainability of the work.\n\nIt is the perfect platform for companies that want to support Open Source packages and at the same\ntime obtain assurances regarding maintenance, quality and security.\n\nFunds\n=====\n\nIt was decided in the `mailing list`_ that the Tidelift contribution will be split evenly between\nmembers of the `contributors team`_ interested in receiving funding.\n\nThe current list of contributors receiving funding are:\n\n* `@nicoddemus`_\n* `@The-Compiler`_\n* `@RonnyPfannschmidt`_\n\nContributors interested in receiving a part of the funds just need to submit a PR adding their\nname to the list. Contributors that want to stop receiving the funds should also submit a PR\nin the same way.\n\nThe PR should mention `@pytest-dev/tidelift-admins`_ so appropriate changes\ncan be made in the Tidelift platform.\n\nAfter the PR has been accepted and merged, the contributor should register in the `Tidelift`_\nplatform and follow the instructions there, including signing an `agreement`_.\n\nAdmins\n======\n\nA few people have admin access to the Tidelift dashboard to make changes. Those people\nare part of the `@pytest-dev/tidelift-admins`_ team.\n\n`Core contributors`_ interested in helping out with Tidelift maintenance are welcome! We don't\nexpect much work here other than the occasional adding/removal of a contributor from receiving\nfunds. Just drop a line to one of the `@pytest-dev/tidelift-admins`_ or use the mailing list.\n\n\n.. _`Tidelift`: https://tidelift.com\n.. _`mailing list`: https://mail.python.org/pipermail/pytest-dev/2019-May/004716.html\n.. _`contributors team`: https://github.com/orgs/pytest-dev/teams/contributors\n.. _`core contributors`: https://github.com/orgs/pytest-dev/teams/core/members\n.. _`@pytest-dev/tidelift-admins`: https://github.com/orgs/pytest-dev/teams/tidelift-admins/members\n.. _`agreement`: https://tidelift.com/docs/lifting/agreement\n\n.. _`@nicoddemus`: https://github.com/nicoddemus\n.. _`@The-Compiler`: https://github.com/The-Compiler\n.. _`@RonnyPfannschmidt`: https://github.com/RonnyPfannschmidt\n"
  },
  {
    "path": "bench/bench.py",
    "content": "from __future__ import annotations\n\nimport sys\n\n\nif __name__ == \"__main__\":\n    import cProfile\n    import pstats\n\n    import pytest  # noqa: F401\n\n    script = sys.argv[1:] if len(sys.argv) > 1 else [\"empty.py\"]\n    cProfile.run(f\"pytest.cmdline.main({script!r})\", \"prof\")\n    p = pstats.Stats(\"prof\")\n    p.strip_dirs()\n    p.sort_stats(\"cumulative\")\n    print(p.print_stats(500))\n"
  },
  {
    "path": "bench/bench_argcomplete.py",
    "content": "# 10000 iterations, just for relative comparison\n#                      2.7.5     3.3.2\n# FilesCompleter       75.1109   69.2116\n# FastFilesCompleter    0.7383    1.0760\nfrom __future__ import annotations\n\nimport timeit\n\n\nimports = [\n    \"from argcomplete.completers import FilesCompleter as completer\",\n    \"from _pytest._argcomplete import FastFilesCompleter as completer\",\n]\n\ncount = 1000  # only a few seconds\nsetup = \"%s\\nfc = completer()\"\nrun = 'fc(\"/d\")'\n\n\nif __name__ == \"__main__\":\n    print(timeit.timeit(run, setup=setup % imports[0], number=count))\n    print(timeit.timeit(run, setup=setup % imports[1], number=count))\n"
  },
  {
    "path": "bench/empty.py",
    "content": "from __future__ import annotations\n\n\nfor i in range(1000):\n    exec(f\"def test_func_{i}(): pass\")\n"
  },
  {
    "path": "bench/manyparam.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture(scope=\"module\", params=range(966))\ndef foo(request):\n    return request.param\n\n\ndef test_it(foo):\n    pass\n\n\ndef test_it2(foo):\n    pass\n"
  },
  {
    "path": "bench/skip.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\n\nSKIP = True\n\n\n@pytest.mark.parametrize(\"x\", range(5000))\ndef test_foo(x):\n    if SKIP:\n        pytest.skip(\"heh\")\n"
  },
  {
    "path": "bench/unit_test.py",
    "content": "from __future__ import annotations\n\nfrom unittest import TestCase  # noqa: F401\n\n\nfor i in range(15000):\n    exec(\n        f\"\"\"\nclass Test{i}(TestCase):\n    @classmethod\n    def setUpClass(cls): pass\n    def test_1(self): pass\n    def test_2(self): pass\n    def test_3(self): pass\n\"\"\"\n    )\n"
  },
  {
    "path": "bench/xunit.py",
    "content": "from __future__ import annotations\n\n\nfor i in range(5000):\n    exec(\n        f\"\"\"\nclass Test{i}:\n    @classmethod\n    def setup_class(cls): pass\n    def test_1(self): pass\n    def test_2(self): pass\n    def test_3(self): pass\n\"\"\"\n    )\n"
  },
  {
    "path": "changelog/.gitignore",
    "content": "*\n!.gitignore\n!_template.rst\n!README.rst\n!*.bugfix\n!*.bugfix.rst\n!*.bugfix.*.rst\n!*.breaking\n!*.breaking.rst\n!*.breaking.*.rst\n!*.contrib\n!*.contrib.rst\n!*.contrib.*.rst\n!*.deprecation\n!*.deprecation.rst\n!*.deprecation.*.rst\n!*.doc\n!*.doc.rst\n!*.doc.*.rst\n!*.feature\n!*.feature.rst\n!*.feature.*.rst\n!*.improvement\n!*.improvement.rst\n!*.improvement.*.rst\n!*.misc\n!*.misc.rst\n!*.misc.*.rst\n!*.packaging\n!*.packaging.rst\n!*.packaging.*.rst\n!*.vendor\n!*.vendor.rst\n!*.vendor.*.rst\n"
  },
  {
    "path": "changelog/12444.bugfix.rst",
    "content": "Fixed :func:`pytest.approx` which now correctly takes into account :class:`~collections.abc.Mapping` keys order to compare them.\n"
  },
  {
    "path": "changelog/12689.contrib.rst",
    "content": "The test reports are now published to Codecov from GitHub Actions.\nThe test statistics is visible `on the web interface\n<https://app.codecov.io/gh/pytest-dev/pytest/tests>`__.\n\n-- by :user:`aleguy02`\n"
  },
  {
    "path": "changelog/12882.deprecation.rst",
    "content": "Calling :meth:`request.getfixturevalue() <pytest.FixtureRequest.getfixturevalue>` during teardown to request a fixture that was not already requested is now deprecated and will become an error in pytest 10.\n\nSee :ref:`dynamic-fixture-request-during-teardown` for details.\n"
  },
  {
    "path": "changelog/13192.bugfix.rst",
    "content": "Fixed `|` (pipe) not being treated as a regex meta-character that needs escaping in :func:`pytest.raises(match=...) <pytest.raises>`.\n"
  },
  {
    "path": "changelog/13388.doc.rst",
    "content": "Clarified documentation for ``-p`` vs ``PYTEST_PLUGINS`` plugin loading and fixed an incorrect ``-p`` example.\n"
  },
  {
    "path": "changelog/13409.deprecation.rst",
    "content": "Using non-:class:`~collections.abc.Collection` iterables (such as generators, iterators, or custom iterable objects) for the ``argvalues`` parameter in :ref:`@pytest.mark.parametrize <pytest.mark.parametrize ref>` and :meth:`metafunc.parametrize <pytest.Metafunc.parametrize>` is now deprecated.\n\nThese iterables get exhausted after the first iteration,\nleading to tests getting unexpectedly skipped in cases such as running :func:`pytest.main()` multiple times,\nusing class-level parametrize decorators,\nor collecting tests multiple times.\n\nSee :ref:`parametrize-iterators` for details and suggestions.\n"
  },
  {
    "path": "changelog/13634.bugfix.rst",
    "content": "Blocking a ``conftest.py`` file using the ``-p no:`` option is now explicitly disallowed.\n\nPreviously this resulted in an internal assertion failure during plugin loading.\n\nPytest now raises a clear ``UsageError`` explaining that conftest files are not plugins and cannot be disabled via ``-p``.\n"
  },
  {
    "path": "changelog/13731.doc.rst",
    "content": "Clarified that capture fixtures (e.g. ``capsys`` and ``capfd``) take precedence over the ``-s`` / ``--capture=no`` command-line options in :ref:`Accessing captured output from a test function <accessing-captured-output>`.\n"
  },
  {
    "path": "changelog/13734.bugfix.rst",
    "content": "Fixed crash when a test raises an exceptiongroup with ``__tracebackhide__ = True``.\n"
  },
  {
    "path": "changelog/13884.bugfix.rst",
    "content": "Fixed rare internal IndexError caused by `builtins.compile` being overridden in client code.\n"
  },
  {
    "path": "changelog/13917.bugfix.rst",
    "content": ":class:`unittest.SkipTest` is no longer considered an interactive exception, i.e. :hook:`pytest_exception_interact` is no longer called for it.\n"
  },
  {
    "path": "changelog/13946.deprecation.rst",
    "content": "The private ``config.inicfg`` attribute is now deprecated.\nUse :meth:`config.getini() <pytest.Config.getini>` to access configuration values instead.\n\nSee :ref:`config-inicfg` for more details.\n"
  },
  {
    "path": "changelog/13963.bugfix.rst",
    "content": "Fixed subtests running with :pypi:`pytest-xdist` when their contexts contain objects that are not JSON-serializable.\n\nFixes `pytest-dev/pytest-xdist#1273 <https://github.com/pytest-dev/pytest-xdist/issues/1273>`__.\n"
  },
  {
    "path": "changelog/14023.feature.rst",
    "content": "Added `--report-chars` long CLI option.\n"
  },
  {
    "path": "changelog/14026.improvement.rst",
    "content": "Added test coverage for compiled regex patterns in :func:`pytest.raises` match parameter.\n"
  },
  {
    "path": "changelog/14050.bugfix.rst",
    "content": "Display dictionary differences in assertion failures using the original key insertion order instead of sorted order.\n"
  },
  {
    "path": "changelog/14088.doc.rst",
    "content": "Clarified that the default :hook:`pytest_collection` hook sets ``session.items`` before it calls :hook:`pytest_collection_finish`, not after.\n"
  },
  {
    "path": "changelog/14114.bugfix.rst",
    "content": "An exception from :hook:`pytest_fixture_post_finalizer` no longer prevents fixtures from being torn down, causing additional errors in the following tests.\n"
  },
  {
    "path": "changelog/14195.bugfix.rst",
    "content": "Fixed an issue where non-string messages passed to `unittest.TestCase.subTest()` were not printed.\n"
  },
  {
    "path": "changelog/14255.doc.rst",
    "content": "TOML integer log levels must be quoted: Updating reference documentation.\n"
  },
  {
    "path": "changelog/14303.doc.rst",
    "content": "The documentation is now built with Sphinx >= 9.\n"
  },
  {
    "path": "changelog/5848.bugfix.rst",
    "content": ":hook:`pytest_fixture_post_finalizer` is no longer called extra times for the same fixture teardown in some cases.\n"
  },
  {
    "path": "changelog/719.bugfix.rst",
    "content": "Fixed :ref:`@pytest.mark.parametrize <pytest.mark.parametrize ref>` not unpacking single-element tuple values when using a string argnames with a trailing comma (e.g., ``\"arg,\"``).\n\nThe trailing comma form now correctly behaves like the tuple form ``(\"arg\",)``, treating argvalues as a list of tuples to unpack.\n"
  },
  {
    "path": "changelog/README.rst",
    "content": "This directory contains \"newsfragments\" which are short files that contain a small **ReST**-formatted\ntext that will be added to the next ``CHANGELOG``.\n\nThe ``CHANGELOG`` will be read by **users**, so this description should be aimed to pytest users\ninstead of describing internal changes which are only relevant to the developers.\n\nMake sure to use full sentences in the **past or present tense** and use punctuation, examples::\n\n    Improved verbose diff output with sequences.\n\n    Terminal summary statistics now use multiple colors.\n\nEach file should be named like ``<ISSUE>.<TYPE>.rst``, where\n``<ISSUE>`` is an issue number, and ``<TYPE>`` is one of:\n\n* ``feature``: new user facing features, like new command-line options and new behavior.\n* ``improvement``: improvement of existing functionality, usually without requiring user intervention (for example, new fields being written in ``--junit-xml``, improved colors in terminal, etc).\n* ``bugfix``: fixes a bug.\n* ``doc``: documentation improvement, like rewording an entire section or adding missing docs.\n* ``deprecation``: feature deprecation.\n* ``breaking``: a change which may break existing suites, such as feature removal or behavior change.\n* ``vendor``: changes in packages vendored in pytest.\n* ``packaging``: notes for downstreams about unobvious side effects\n  and tooling. Changes in the test invocation considerations and\n  runtime assumptions.\n* ``contrib``: stuff that affects the contributor experience. e.g.\n  Running tests, building the docs, setting up the development\n  environment.\n* ``misc``: changes that are hard to assign to any of the above\n  categories.\n\nSo for example: ``123.feature.rst``, ``456.bugfix.rst``.\n\n.. tip::\n\n   See :file:`pyproject.toml` for all available categories\n   (``tool.towncrier.type``).\n\nIf your PR fixes an issue, use that number here. If there is no issue,\nthen after you submit the PR and get the PR number you can add a\nchangelog using that instead.\n\nIf you are not sure what issue type to use, don't hesitate to ask in your PR.\n\n``towncrier`` preserves multiple paragraphs and formatting (code blocks, lists, and so on), but for entries\nother than ``features`` it is usually better to stick to a single paragraph to keep it concise.\n\nYou can also run ``tox -e docs`` to build the documentation\nwith the draft changelog (``doc/en/_build/html/changelog.html``) if you want to get a preview of how your change will look in the final release notes.\n"
  },
  {
    "path": "changelog/_template.rst",
    "content": "{% for section in sections %}\n{% set underline = \"-\" %}\n{% if section %}\n{{section}}\n{{ underline * section|length }}{% set underline = \"~\" %}\n\n{% endif %}\n{% if sections[section] %}\n{% for category, val in definitions.items() if category in sections[section] %}\n\n{{ definitions[category]['name'] }}\n{{ underline * definitions[category]['name']|length }}\n\n{% if definitions[category]['showcontent'] %}\n{% for text, values in sections[section][category]|dictsort(by='value') %}\n{% set issue_joiner = joiner(', ') %}\n- {% for value in values|sort %}{{ issue_joiner() }}`{{ value }} <https://github.com/pytest-dev/pytest/issues/{{ value[1:] }}>`_{% endfor %}: {{ text }}\n\n\n{% endfor %}\n{% else %}\n- {{ sections[section][category]['']|sort|join(', ') }}\n\n\n{% endif %}\n{% if sections[section][category]|length == 0 %}\n\nNo significant changes.\n\n\n{% else %}\n{% endif %}\n{% endfor %}\n{% else %}\n\nNo significant changes.\n\n\n{% endif %}\n{% endfor %}\n"
  },
  {
    "path": "codecov.yml",
    "content": "# reference: https://docs.codecov.io/docs/codecovyml-reference\n---\n\ncodecov:\n  token: 1eca3b1f-31a2-4fb8-a8c3-138b441b50a7 #repo token\n\ncoverage:\n  status:\n    patch:\n      default:\n        target: 100%  # require patches to be 100%\n    project: false\ncomment: false\n"
  },
  {
    "path": "doc/en/Makefile",
    "content": "# Minimal makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line, and also\n# from the environment for the first two.\nSPHINXOPTS    ?=\nSPHINXBUILD   ?= sphinx-build\nSOURCEDIR     = .\nBUILDDIR      = _build\n\n# Put it first so that \"make\" without argument is like \"make help\".\nhelp:\n\t@$(SPHINXBUILD) -M help \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)\n\n.PHONY: help Makefile\n\n# Catch-all target: route all unknown targets to Sphinx using the new\n# \"make mode\" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).\n%: Makefile\n\t@$(SPHINXBUILD) -M $@ \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)\n\n\nREGENDOC_ARGS := \\\n\t--normalize \"/[ \\t]+\\n/\\n/\" \\\n\t--normalize \"~\\$$REGENDOC_TMPDIR~/home/sweet/project~\" \\\n\t--normalize \"~/path/to/example~/home/sweet/project~\" \\\n\t--normalize \"/in \\d.\\d\\ds/in 0.12s/\" \\\n\t--normalize \"@/tmp/pytest-of-.*/pytest-\\d+@PYTEST_TMPDIR@\" \\\n\t--normalize \"@pytest-(\\d+)\\\\.[^ ,]+@pytest-\\1.x.y@\" \\\n\t--normalize \"@py-(\\d+)\\\\.[^ ,]+@py-\\1.x.y@\" \\\n\t--normalize \"@pluggy-(\\d+)\\\\.[.\\d,]+@pluggy-\\1.x.y@\" \\\n\t--normalize \"@hypothesis-(\\d+)\\\\.[.\\d,]+@hypothesis-\\1.x.y@\" \\\n\t--normalize \"@Python (\\d+)\\\\.[^ ,]+@Python \\1.x.y@\"\n\nregen: REGENDOC_FILES:=*.rst */*.rst\nregen:\n# need to reset cachedir to the non-tox default\n\tPYTHONDONTWRITEBYTECODE=1 \\\n\tPYTEST_ADDOPTS=\"-pno:hypothesis -p no:hypothesispytest -Wignore::pytest.PytestUnknownMarkWarning -o cache_dir=.pytest_cache\" \\\n\tCOLUMNS=76 \\\n\tregendoc --update ${REGENDOC_FILES} ${REGENDOC_ARGS}\n\n.PHONY: regen\n"
  },
  {
    "path": "doc/en/_static/pytest-custom.css",
    "content": "/* Tweak how the sidebar logo is presented */\n.sidebar-logo {\n  width: 70%;\n}\n.sidebar-brand {\n  padding: 0;\n}\n\n/* The landing pages' sidebar-in-content highlights */\n#features ul {\n  padding-left: 1rem;\n  list-style: none;\n}\n#features ul li {\n  margin-bottom: 0;\n}\n@media (min-width: 46em) {\n  #features {\n    width: 50%;\n  }\n}\n"
  },
  {
    "path": "doc/en/_templates/links.html",
    "content": "<h3>Useful Links</h3>\n<ul>\n  <li><a href=\"https://pypi.org/project/pytest/\">pytest @ PyPI</a></li>\n  <li><a href=\"https://github.com/pytest-dev/pytest/\">pytest @ GitHub</a></li>\n  <li><a href=\"https://github.com/pytest-dev/pytest/issues\">Issue Tracker</a></li>\n  <li><a href=\"https://media.readthedocs.org/pdf/pytest/latest/pytest.pdf\">PDF Documentation</a>\n</ul>\n"
  },
  {
    "path": "doc/en/adopt.rst",
    "content": ":orphan:\n\n.. warnings about this file not being included in any toctree will be suppressed by :orphan:\n\n\nApril 2015 is \"adopt pytest month\"\n=============================================\n\nAre you an enthusiastic pytest user, the local testing guru in your workplace? Or are you considering using pytest for your open source project, but not sure how to get started? Then you may be interested in \"adopt pytest month\"!\n\nWe will pair experienced pytest users with open source projects, for a month's effort of getting new development teams started with pytest.\n\nIn 2015 we are trying this for the first time. In February and March 2015 we will gather volunteers on both sides, in April we will do the work, and in May we will evaluate how it went. This effort is being coordinated by Brianna Laugher. If you have any questions or comments, you can raise them on the `@pytestdotorg twitter account <https://twitter.com/pytestdotorg>`_\\, the :issue:`issue tracker <676>` or the `pytest-dev mailing list`_.\n\n\n.. _`pytest-dev mailing list`: https://mail.python.org/mailman/listinfo/pytest-dev\n\n\nThe ideal pytest helper\n-----------------------------------------\n\n - will be able to commit 2-4 hours a week to working with their particular project (this might involve joining their mailing list, installing the software and exploring any existing tests, offering advice, writing some example tests)\n - feels confident in using pytest (e.g. has explored command line options, knows how to write parametrized tests, has an idea about conftest contents)\n - does not need to be an expert in every aspect!\n\nPytest helpers, sign up here! (preferably in February, hard deadline 22 March)\n\n\n\nThe ideal partner project\n-----------------------------------------\n\n - is open source, and predominantly written in Python\n - has an automated/documented install process for developers\n - has more than one core developer\n - has at least one official release (e.g. is available on pypi)\n - has the support of the core development team, in trying out pytest adoption\n - has no tests... or 100% test coverage... or somewhere in between!\n\nPartner projects, sign up here! (by 22 March)\n\n\n\nWhat does it mean to \"adopt pytest\"?\n-----------------------------------------\n\nThere can be many different definitions of \"success\". Pytest can run many unittest_ tests by default, so using pytest as your testrunner may be possible from day 1. Job done, right?\n\nProgressive success might look like:\n\n - tests can be run (by pytest) without errors (there may be failures)\n - tests can be run (by pytest) without failures\n - test runner is integrated into CI server\n - existing tests are rewritten to take advantage of pytest features - this can happen in several iterations, for example:\n    - changing to native assert_ statements (pycmd_ has a script to help with that, ``pyconvert_unittest.py``)\n    - changing `setUp/tearDown methods`_ to fixtures_\n    - adding markers_\n    - other changes to reduce boilerplate\n - assess needs for future tests to be written, e.g. new fixtures, distributed_ testing tweaks\n\n\"Success\" should also include that the development team feels comfortable with their knowledge of how to use pytest. In fact this is probably more important than anything else. So spending a lot of time on communication, giving examples, etc will probably be important - both in running the tests, and in writing them.\n\nIt may be after the month is up, the partner project decides that pytest is not right for it. That's okay - hopefully the pytest team will also learn something about its weaknesses or deficiencies.\n\n.. _unittest: unittest.html\n.. _assert: assert.html\n.. _pycmd: https://bitbucket.org/hpk42/pycmd/overview\n.. _`setUp/tearDown methods`: xunit_setup.html\n.. _fixtures: fixture.html\n.. _markers: mark.html\n.. _distributed: xdist.html\n\n\nOther ways to help\n-----------------------------------------\n\nPromote! Do your favourite open source Python projects use pytest? If not, why not tell them about this page?\n"
  },
  {
    "path": "doc/en/announce/index.rst",
    "content": "\nRelease announcements\n===========================================\n\n.. toctree::\n   :maxdepth: 2\n\n\n   release-9.0.2\n   release-9.0.1\n   release-9.0.0\n   release-8.4.2\n   release-8.4.1\n   release-8.4.0\n   release-8.3.5\n   release-8.3.4\n   release-8.3.3\n   release-8.3.2\n   release-8.3.1\n   release-8.3.0\n   release-8.2.2\n   release-8.2.1\n   release-8.2.0\n   release-8.1.2\n   release-8.1.1\n   release-8.1.0\n   release-8.0.2\n   release-8.0.1\n   release-8.0.0\n   release-8.0.0rc2\n   release-8.0.0rc1\n   release-7.4.4\n   release-7.4.3\n   release-7.4.2\n   release-7.4.1\n   release-7.4.0\n   release-7.3.2\n   release-7.3.1\n   release-7.3.0\n   release-7.2.2\n   release-7.2.1\n   release-7.2.0\n   release-7.1.3\n   release-7.1.2\n   release-7.1.1\n   release-7.1.0\n   release-7.0.1\n   release-7.0.0\n   release-7.0.0rc1\n   release-6.2.5\n   release-6.2.4\n   release-6.2.3\n   release-6.2.2\n   release-6.2.1\n   release-6.2.0\n   release-6.1.2\n   release-6.1.1\n   release-6.1.0\n   release-6.0.2\n   release-6.0.1\n   release-6.0.0\n   release-6.0.0rc1\n   release-5.4.3\n   release-5.4.2\n   release-5.4.1\n   release-5.4.0\n   release-5.3.5\n   release-5.3.4\n   release-5.3.3\n   release-5.3.2\n   release-5.3.1\n   release-5.3.0\n   release-5.2.4\n   release-5.2.3\n   release-5.2.2\n   release-5.2.1\n   release-5.2.0\n   release-5.1.3\n   release-5.1.2\n   release-5.1.1\n   release-5.1.0\n   release-5.0.1\n   release-5.0.0\n   release-4.6.9\n   release-4.6.8\n   release-4.6.7\n   release-4.6.6\n   release-4.6.5\n   release-4.6.4\n   release-4.6.3\n   release-4.6.2\n   release-4.6.1\n   release-4.6.0\n   release-4.5.0\n   release-4.4.2\n   release-4.4.1\n   release-4.4.0\n   release-4.3.1\n   release-4.3.0\n   release-4.2.1\n   release-4.2.0\n   release-4.1.1\n   release-4.1.0\n   release-4.0.2\n   release-4.0.1\n   release-4.0.0\n   release-3.10.1\n   release-3.10.0\n   release-3.9.3\n   release-3.9.2\n   release-3.9.1\n   release-3.9.0\n   release-3.8.2\n   release-3.8.1\n   release-3.8.0\n   release-3.7.4\n   release-3.7.3\n   release-3.7.2\n   release-3.7.1\n   release-3.7.0\n   release-3.6.4\n   release-3.6.3\n   release-3.6.2\n   release-3.6.1\n   release-3.6.0\n   release-3.5.1\n   release-3.5.0\n   release-3.4.2\n   release-3.4.1\n   release-3.4.0\n   release-3.3.2\n   release-3.3.1\n   release-3.3.0\n   release-3.2.5\n   release-3.2.4\n   release-3.2.3\n   release-3.2.2\n   release-3.2.1\n   release-3.2.0\n   release-3.1.3\n   release-3.1.2\n   release-3.1.1\n   release-3.1.0\n   release-3.0.7\n   release-3.0.6\n   release-3.0.5\n   release-3.0.4\n   release-3.0.3\n   release-3.0.2\n   release-3.0.1\n   release-3.0.0\n   sprint2016\n   release-2.9.2\n   release-2.9.1\n   release-2.9.0\n   release-2.8.7\n   release-2.8.6\n   release-2.8.5\n   release-2.8.4\n   release-2.8.3\n   release-2.8.2\n   release-2.7.2\n   release-2.7.1\n   release-2.7.0\n   release-2.6.3\n   release-2.6.2\n   release-2.6.1\n   release-2.6.0\n   release-2.5.2\n   release-2.5.1\n   release-2.5.0\n   release-2.4.2\n   release-2.4.1\n   release-2.4.0\n   release-2.3.5\n   release-2.3.4\n   release-2.3.3\n   release-2.3.2\n   release-2.3.1\n   release-2.3.0\n   release-2.2.4\n   release-2.2.2\n   release-2.2.1\n   release-2.2.0\n   release-2.1.3\n   release-2.1.2\n   release-2.1.1\n   release-2.1.0\n   release-2.0.3\n   release-2.0.2\n   release-2.0.1\n   release-2.0.0\n"
  },
  {
    "path": "doc/en/announce/release-2.0.0.rst",
    "content": "py.test 2.0.0: asserts++, unittest++, reporting++, config++, docs++\n===========================================================================\n\nWelcome to pytest-2.0.0, a major new release of \"py.test\", the rapid\neasy Python testing tool.  There are many new features and enhancements,\nsee below for summary and detailed lists.  A lot of long-deprecated code\nhas been removed, resulting in a much smaller and cleaner\nimplementation.  See the new docs with examples here:\n\n    http://pytest.org/en/stable/index.html\n\nA note on packaging: pytest used to part of the \"py\" distribution up\nuntil version py-1.3.4 but this has changed now:  pytest-2.0.0 only\ncontains py.test related code and is expected to be backward-compatible\nto existing test code. If you want to install pytest, just type one of::\n\n    pip install -U pytest\n    easy_install -U pytest\n\nMany thanks to all issue reporters and people asking questions or\ncomplaining.  Particular thanks to Floris Bruynooghe and Ronny Pfannschmidt\nfor their great coding contributions and many others for feedback and help.\n\nbest,\nholger krekel\n\n\nNew Features\n-----------------------\n\n- new invocations through Python interpreter and from Python::\n\n    python -m pytest      # on all pythons >= 2.5\n\n  or from a python program::\n\n    import pytest ; pytest.main(arglist, pluginlist)\n\n  see http://pytest.org/en/stable/how-to/usage.html for details.\n\n- new and better reporting information in assert expressions\n  if comparing lists, sequences or strings.\n\n  see http://pytest.org/en/stable/how-to/assert.html#newreport\n\n- new configuration through ini-files (setup.cfg or tox.ini recognized),\n  for example::\n\n    [pytest]\n    norecursedirs = .hg data*  # don't ever recurse in such dirs\n    addopts = -x --pyargs      # add these command line options by default\n\n  see http://pytest.org/en/stable/reference/customize.html\n\n- improved standard unittest support.  In general py.test should now\n  better be able to run custom unittest.TestCases like twisted trial\n  or Django based TestCases.  Also you can now run the tests of an\n  installed 'unittest' package with py.test::\n\n    py.test --pyargs unittest\n\n- new \"-q\" option which decreases verbosity and prints a more\n  nose/unittest-style \"dot\" output.\n\n- many, many, more detailed improvements details\n\nFixes\n-----------------------\n\n- fix issue126 - introduce py.test.set_trace() to trace execution via\n  PDB during the running of tests even if capturing is ongoing.\n- fix issue124 - make reporting more resilient against tests opening\n  files on filedescriptor 1 (stdout).\n- fix issue109 - sibling conftest.py files will not be loaded.\n  (and Directory collectors cannot be customized anymore from a Directory's\n  conftest.py - this needs to happen at least one level up).\n- fix issue88 (finding custom test nodes from command line arg)\n- fix issue93 stdout/stderr is captured while importing conftest.py\n- fix bug: unittest collected functions now also can have \"pytestmark\"\n  applied at class/module level\n\nImportant Notes\n--------------------\n\n* The usual way in pre-2.0 times to use py.test in python code was\n  to import \"py\" and then e.g. use \"py.test.raises\" for the helper.\n  This remains valid and is not planned to be deprecated.  However,\n  in most examples and internal code you'll find \"import pytest\"\n  and \"pytest.raises\" used as the recommended default way.\n\n* pytest now first performs collection of the complete test suite\n  before running any test. This changes for example the semantics of when\n  pytest_collectstart/pytest_collectreport are called.  Some plugins may\n  need upgrading.\n\n* The pytest package consists of a 400 LOC core.py and about 20 builtin plugins,\n  summing up to roughly 5000 LOCs, including docstrings. To be fair, it also\n  uses generic code from the \"pylib\", and the new \"py\" package to help\n  with filesystem and introspection/code manipulation.\n\n(Incompatible) Removals\n-----------------------------\n\n- py.test.config is now only available if you are in a test run.\n\n- the following (mostly already deprecated) functionality was removed:\n\n  - removed support for Module/Class/... collection node definitions\n    in conftest.py files.  They will cause nothing special.\n  - removed support for calling the pre-1.0 collection API of \"run()\" and \"join\"\n  - removed reading option values from conftest.py files or env variables.\n    This can now be done much, much, better and easier through the ini-file\n    mechanism and the \"addopts\" entry in particular.\n  - removed the \"disabled\" attribute in test classes.  Use the skipping\n    and pytestmark mechanism to skip or xfail a test class.\n\n- py.test.collect.Directory does not exist anymore and it\n  is not possible to provide an own \"Directory\" object.\n  If you have used this and don't know what to do, get\n  in contact.  We'll figure something out.\n\n  Note that pytest_collect_directory() is still called but\n  any return value will be ignored.  This allows to keep\n  old code working that performed for example \"py.test.skip()\"\n  in collect() to prevent recursion into directory trees\n  if a certain dependency or command line option is missing.\n\n\nsee :ref:`changelog` for more detailed changes.\n"
  },
  {
    "path": "doc/en/announce/release-2.0.1.rst",
    "content": "py.test 2.0.1: bug fixes\n===========================================================================\n\nWelcome to pytest-2.0.1, a maintenance and bug fix release of pytest,\na mature testing tool for Python, supporting CPython 2.4-3.2, Jython\nand latest PyPy interpreters.  See extensive docs with tested examples here:\n\n    http://pytest.org/\n\nIf you want to install or upgrade pytest, just type one of::\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nMany thanks to all issue reporters and people asking questions or\ncomplaining.  Particular thanks to Floris Bruynooghe and Ronny Pfannschmidt\nfor their great coding contributions and many others for feedback and help.\n\nbest,\nholger krekel\n\nChanges between 2.0.0 and 2.0.1\n----------------------------------------------\n\n- refine and unify initial capturing so that it works nicely\n  even if the logging module is used on an early-loaded conftest.py\n  file or plugin.\n- fix issue12 - show plugin versions with \"--version\" and\n  \"--traceconfig\" and also document how to add extra information\n  to reporting test header\n- fix issue17 (import-* reporting issue on python3) by\n  requiring py>1.4.0 (1.4.1 is going to include it)\n- fix issue10 (numpy arrays truth checking) by refining\n  assertion interpretation in py lib\n- fix issue15: make nose compatibility tests compatible\n  with python3 (now that nose-1.0 supports python3)\n- remove somewhat surprising \"same-conftest\" detection because\n  it ignores conftest.py when they appear in several subdirs.\n- improve assertions (\"not in\"), thanks Floris Bruynooghe\n- improve behaviour/warnings when running on top of \"python -OO\"\n  (assertions and docstrings are turned off, leading to potential\n  false positives)\n- introduce a pytest_cmdline_processargs(args) hook\n  to allow dynamic computation of command line arguments.\n  This fixes a regression because py.test prior to 2.0\n  allowed to set command line options from conftest.py\n  files which so far pytest-2.0 only allowed from ini-files now.\n- fix issue7: assert failures in doctest modules.\n  unexpected failures in doctests will not generally\n  show nicer, i.e. within the doctest failing context.\n- fix issue9: setup/teardown functions for an xfail-marked\n  test will report as xfail if they fail but report as normally\n  passing (not xpassing) if they succeed.  This only is true\n  for \"direct\" setup/teardown invocations because teardown_class/\n  teardown_module cannot closely relate to a single test.\n- fix issue14: no logging errors at process exit\n- refinements to \"collecting\" output on non-ttys\n- refine internal plugin registration and --traceconfig output\n- introduce a mechanism to prevent/unregister plugins from the\n  command line, see http://pytest.org/en/stable/how-to/plugins.html#cmdunregister\n- activate resultlog plugin by default\n- fix regression wrt yielded tests which due to the\n  collection-before-running semantics were not\n  setup as with pytest 1.3.4.  Note, however, that\n  the recommended and much cleaner way to do test\n  parametrization remains the \"pytest_generate_tests\"\n  mechanism, see the docs.\n"
  },
  {
    "path": "doc/en/announce/release-2.0.2.rst",
    "content": "py.test 2.0.2: bug fixes, improved xfail/skip expressions, speed ups\n===========================================================================\n\nWelcome to pytest-2.0.2, a maintenance and bug fix release of pytest,\na mature testing tool for Python, supporting CPython 2.4-3.2, Jython\nand latest PyPy interpreters.  See the extensive docs with tested examples here:\n\n    http://pytest.org/\n\nIf you want to install or upgrade pytest, just type one of::\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nMany thanks to all issue reporters and people asking questions\nor complaining, particularly Jurko for his insistence,\nLaura, Victor and Brianna for helping with improving\nand Ronny for his general advise.\n\nbest,\nholger krekel\n\nChanges between 2.0.1 and 2.0.2\n----------------------------------------------\n\n- tackle issue32 - speed up test runs of very quick test functions\n  by reducing the relative overhead\n\n- fix issue30 - extended xfail/skipif handling and improved reporting.\n  If you have a syntax error in your skip/xfail\n  expressions you now get nice error reports.\n\n  Also you can now access module globals from xfail/skipif\n  expressions so that this for example works now::\n\n    import pytest\n    import mymodule\n    @pytest.mark.skipif(\"mymodule.__version__[0] == \"1\")\n    def test_function():\n        pass\n\n  This will not run the test function if the module's version string\n  does not start with a \"1\".  Note that specifying a string instead\n  of a boolean expressions allows py.test to report meaningful information\n  when summarizing a test run as to what conditions lead to skipping\n  (or xfail-ing) tests.\n\n- fix issue28 - setup_method and pytest_generate_tests work together\n  The setup_method fixture method now gets called also for\n  test function invocations generated from the pytest_generate_tests\n  hook.\n\n- fix issue27 - collectonly and keyword-selection (-k) now work together\n  Also, if you do \"py.test --collectonly -q\" you now get a flat list\n  of test ids that you can use to paste to the py.test commandline\n  in order to execute a particular test.\n\n- fix issue25 avoid reported problems with --pdb and python3.2/encodings output\n\n- fix issue23 - tmpdir argument now works on Python3.2 and WindowsXP\n  Starting with Python3.2 os.symlink may be supported. By requiring\n  a newer py lib version the py.path.local() implementation acknowledges\n  this.\n\n- fixed typos in the docs (thanks Victor Garcia, Brianna Laugher) and particular\n  thanks to Laura Creighton who also reviewed parts of the documentation.\n\n- fix slightly wrong output of verbose progress reporting for classes\n  (thanks Amaury)\n\n- more precise (avoiding of) deprecation warnings for node.Class|Function accesses\n\n- avoid std unittest assertion helper code in tracebacks (thanks Ronny)\n"
  },
  {
    "path": "doc/en/announce/release-2.0.3.rst",
    "content": "py.test 2.0.3: bug fixes and speed ups\n===========================================================================\n\nWelcome to pytest-2.0.3, a maintenance and bug fix release of pytest,\na mature testing tool for Python, supporting CPython 2.4-3.2, Jython\nand latest PyPy interpreters.  See the extensive docs with tested examples here:\n\n    http://pytest.org/\n\nIf you want to install or upgrade pytest, just type one of::\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nThere also is a bugfix release 1.6 of pytest-xdist, the plugin\nthat enables seamless distributed and \"looponfail\" testing for Python.\n\nbest,\nholger krekel\n\nChanges between 2.0.2 and 2.0.3\n----------------------------------------------\n\n- fix issue38: nicer tracebacks on calls to hooks, particularly early\n  configure/sessionstart ones\n\n- fix missing skip reason/meta information in junitxml files, reported\n  via http://lists.idyll.org/pipermail/testing-in-python/2011-March/003928.html\n\n- fix issue34: avoid collection failure with \"test\" prefixed classes\n  deriving from object.\n\n- don't require zlib (and other libs) for genscript plugin without\n  --genscript actually being used.\n\n- speed up skips (by not doing a full traceback representation\n  internally)\n\n- fix issue37: avoid invalid characters in junitxml's output\n"
  },
  {
    "path": "doc/en/announce/release-2.1.0.rst",
    "content": "py.test 2.1.0: perfected assertions and bug fixes\n===========================================================================\n\nWelcome to the release of pytest-2.1, a mature testing tool for Python,\nsupporting CPython 2.4-3.2, Jython and latest PyPy interpreters.  See\nthe improved extensive docs (now also as PDF!) with tested examples here:\n\n     http://pytest.org/\n\nThe single biggest news about this release are **perfected assertions**\ncourtesy of Benjamin Peterson.  You can now safely use ``assert``\nstatements in test modules without having to worry about side effects\nor python optimization (\"-OO\") options.  This is achieved by rewriting\nassert statements in test modules upon import, using a PEP302 hook.\nSee https://docs.pytest.org/en/stable/how-to/assert.html for\ndetailed information.  The work has been partly sponsored by my company,\nmerlinux GmbH.\n\nFor further details on bug fixes and smaller enhancements see below.\n\nIf you want to install or upgrade pytest, just type one of::\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nbest,\nholger krekel / https://merlinux.eu/\n\nChanges between 2.0.3 and 2.1.0\n----------------------------------------------\n\n- fix issue53 call nosestyle setup functions with correct ordering\n- fix issue58 and issue59: new assertion code fixes\n- merge Benjamin's assertionrewrite branch: now assertions\n  for test modules on python 2.6 and above are done by rewriting\n  the AST and saving the pyc file before the test module is imported.\n  see doc/assert.txt for more info.\n- fix issue43: improve doctests with better traceback reporting on\n  unexpected exceptions\n- fix issue47: timing output in junitxml for test cases is now correct\n- fix issue48: typo in MarkInfo repr leading to exception\n- fix issue49: avoid confusing error when initialization partially fails\n- fix issue44: env/username expansion for junitxml file path\n- show releaselevel information in test runs for pypy\n- reworked doc pages for better navigation and PDF generation\n- report KeyboardInterrupt even if interrupted during session startup\n- fix issue 35 - provide PDF doc version and download link from index page\n"
  },
  {
    "path": "doc/en/announce/release-2.1.1.rst",
    "content": "py.test 2.1.1: assertion fixes and improved junitxml output\n===========================================================================\n\npytest-2.1.1 is a backward compatible maintenance release of the\npopular py.test testing tool.  See extensive docs with examples here:\n\n     http://pytest.org/\n\nMost bug fixes address remaining issues with the perfected assertions\nintroduced with 2.1.0 - many thanks to the bug reporters and to Benjamin\nPeterson for helping to fix them.  Also, junitxml output now produces\nsystem-out/err tags which lead to better displays of tracebacks with Jenkins.\n\nAlso a quick note to package maintainers and others interested: there now\nis a \"pytest\" man page which can be generated with \"make man\" in doc/.\n\nIf you want to install or upgrade pytest, just type one of::\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nbest,\nholger krekel / https://merlinux.eu/\n\nChanges between 2.1.0 and 2.1.1\n----------------------------------------------\n\n- fix issue64 / pytest.set_trace now works within pytest_generate_tests hooks\n- fix issue60 / fix error conditions involving the creation of __pycache__\n- fix issue63 / assertion rewriting on inserts involving strings containing '%'\n- fix assertion rewriting on calls with a ** arg\n- don't cache rewritten modules if bytecode generation is disabled\n- fix assertion rewriting in read-only directories\n- fix issue59: provide system-out/err tags for junitxml output\n- fix issue61: assertion rewriting on boolean operations with 3 or more operands\n- you can now build a man page with \"cd doc ; make man\"\n"
  },
  {
    "path": "doc/en/announce/release-2.1.2.rst",
    "content": "py.test 2.1.2: bug fixes and fixes for jython\n===========================================================================\n\npytest-2.1.2 is a minor backward compatible maintenance release of the\npopular py.test testing tool.  pytest is commonly used for unit,\nfunctional- and integration testing.  See extensive docs with examples\nhere:\n\n     http://pytest.org/\n\nMost bug fixes address remaining issues with the perfected assertions\nintroduced in the 2.1 series - many thanks to the bug reporters and to Benjamin\nPeterson for helping to fix them.  pytest should also work better with\nJython-2.5.1 (and Jython trunk).\n\nIf you want to install or upgrade pytest, just type one of::\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nbest,\nholger krekel / https://merlinux.eu/\n\nChanges between 2.1.1 and 2.1.2\n----------------------------------------\n\n- fix assertion rewriting on files with windows newlines on some Python versions\n- refine test discovery by package/module name (--pyargs), thanks Florian Mayer\n- fix issue69 / assertion rewriting fixed on some boolean operations\n- fix issue68 / packages now work with assertion rewriting\n- fix issue66: use different assertion rewriting caches when the -O option is passed\n- don't try assertion rewriting on Jython, use reinterp\n"
  },
  {
    "path": "doc/en/announce/release-2.1.3.rst",
    "content": "py.test 2.1.3: just some more fixes\n===========================================================================\n\npytest-2.1.3 is a minor backward compatible maintenance release of the\npopular py.test testing tool.  It is commonly used for unit, functional-\nand integration testing.  See extensive docs with examples here:\n\n     http://pytest.org/\n\nThe release contains another fix to the perfected assertions introduced\nwith the 2.1 series as well as the new possibility to customize reporting\nfor assertion expressions on a per-directory level.\n\nIf you want to install or upgrade pytest, just type one of::\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nThanks to the bug reporters and to Ronny Pfannschmidt, Benjamin Peterson\nand Floris Bruynooghe who implemented the fixes.\n\nbest,\nholger krekel\n\nChanges between 2.1.2 and 2.1.3\n----------------------------------------\n\n- fix issue79: assertion rewriting failed on some comparisons in boolops,\n- correctly handle zero length arguments (a la pytest '')\n- fix issue67 / junitxml now contains correct test durations\n- fix issue75 / skipping test failure on jython\n- fix issue77 / Allow assertrepr_compare hook to apply to a subset of tests\n"
  },
  {
    "path": "doc/en/announce/release-2.2.0.rst",
    "content": "py.test 2.2.0: test marking++, parametrization++ and duration profiling\n===========================================================================\n\npytest-2.2.0 is a test-suite compatible release of the popular\npy.test testing tool.  Plugins might need upgrades. It comes\nwith these improvements:\n\n* easier and more powerful parametrization of tests:\n\n  - new @pytest.mark.parametrize decorator to run tests with different arguments\n  - new metafunc.parametrize() API for parametrizing arguments independently\n  - see examples at http://pytest.org/en/stable/example/how-to/parametrize.html\n  - NOTE that parametrize() related APIs are still a bit experimental\n    and might change in future releases.\n\n* improved handling of test markers and refined marking mechanism:\n\n  - \"-m markexpr\" option for selecting tests according to their mark\n  - a new \"markers\" ini-variable for registering test markers for your project\n  - the new \"--strict\" bails out with an error if using unregistered markers.\n  - see examples at http://pytest.org/en/stable/example/markers.html\n\n* duration profiling: new \"--duration=N\" option showing the N slowest test\n  execution or setup/teardown calls. This is most useful if you want to\n  find out where your slowest test code is.\n\n* also 2.2.0 performs more eager calling of teardown/finalizers functions\n  resulting in better and more accurate reporting when they fail\n\nBesides there is the usual set of bug fixes along with a cleanup of\npytest's own test suite allowing it to run on a wider range of environments.\n\nFor general information, see extensive docs with examples here:\n\n     http://pytest.org/\n\nIf you want to install or upgrade pytest you might just type::\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nThanks to Ronny Pfannschmidt, David Burns, Jeff Donner, Daniel Nouri, Alfredo Deza and all who gave feedback or sent bug reports.\n\nbest,\nholger krekel\n\n\nnotes on incompatibility\n------------------------------\n\nWhile test suites should work unchanged you might need to upgrade plugins:\n\n* You need a new version of the pytest-xdist plugin (1.7) for distributing\n  test runs.\n\n* Other plugins might need an upgrade if they implement\n  the ``pytest_runtest_logreport`` hook which now is called unconditionally\n  for the setup/teardown fixture phases of a test. You may choose to\n  ignore setup/teardown failures by inserting \"if rep.when != 'call': return\"\n  or something similar. Note that most code probably \"just\" works because\n  the hook was already called for failing setup/teardown phases of a test\n  so a plugin should have been ready to grok such reports already.\n\n\nChanges between 2.1.3 and 2.2.0\n----------------------------------------\n\n- fix issue90: introduce eager tearing down of test items so that\n  teardown function are called earlier.\n- add an all-powerful metafunc.parametrize function which allows to\n  parametrize test function arguments in multiple steps and therefore\n  from independent plugins and places.\n- add a @pytest.mark.parametrize helper which allows to easily\n  call a test function with different argument values.\n- Add examples to the \"parametrize\" example page, including a quick port\n  of Test scenarios and the new parametrize function and decorator.\n- introduce registration for \"pytest.mark.*\" helpers via ini-files\n  or through plugin hooks.  Also introduce a \"--strict\" option which\n  will treat unregistered markers as errors\n  allowing to avoid typos and maintain a well described set of markers\n  for your test suite.  See examples at http://pytest.org/en/stable/how-to/mark.html\n  and its links.\n- issue50: introduce \"-m marker\" option to select tests based on markers\n  (this is a stricter and more predictable version of \"-k\" in that \"-m\"\n  only matches complete markers and has more obvious rules for and/or\n  semantics.\n- new feature to help optimizing the speed of your tests:\n  --durations=N option for displaying N slowest test calls\n  and setup/teardown methods.\n- fix issue87: --pastebin now works with python3\n- fix issue89: --pdb with unexpected exceptions in doctest work more sensibly\n- fix and cleanup pytest's own test suite to not leak FDs\n- fix issue83: link to generated funcarg list\n- fix issue74: pyarg module names are now checked against imp.find_module false positives\n- fix compatibility with twisted/trial-11.1.0 use cases\n"
  },
  {
    "path": "doc/en/announce/release-2.2.1.rst",
    "content": "pytest-2.2.1: bug fixes, perfect teardowns\n===========================================================================\n\n\npytest-2.2.1 is a minor backward-compatible release of the py.test\ntesting tool.   It contains bug fixes and little improvements, including\ndocumentation fixes.  If you are using the distributed testing\npluginmake sure to upgrade it to pytest-xdist-1.8.\n\nFor general information see here:\n\n     http://pytest.org/\n\nTo install or upgrade pytest:\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nSpecial thanks for helping on this release to Ronny Pfannschmidt, Jurko\nGospodnetic and Ralf Schmitt.\n\nbest,\nholger krekel\n\n\nChanges between 2.2.0 and 2.2.1\n----------------------------------------\n\n- fix issue99 (in pytest and py) internallerrors with resultlog now\n  produce better output - fixed by normalizing pytest_internalerror\n  input arguments.\n- fix issue97 / traceback issues (in pytest and py) improve traceback output\n  in conjunction with jinja2 and cython which hack tracebacks\n- fix issue93 (in pytest and pytest-xdist) avoid \"delayed teardowns\":\n  the final test in a test node will now run its teardown directly\n  instead of waiting for the end of the session. Thanks Dave Hunt for\n  the good reporting and feedback.  The pytest_runtest_protocol as well\n  as the pytest_runtest_teardown hooks now have \"nextitem\" available\n  which will be None indicating the end of the test run.\n- fix collection crash due to unknown-source collected items, thanks\n  to Ralf Schmitt (fixed by depending on a more recent pylib)\n"
  },
  {
    "path": "doc/en/announce/release-2.2.2.rst",
    "content": "pytest-2.2.2: bug fixes\n===========================================================================\n\npytest-2.2.2 (updated to 2.2.3 to fix packaging issues) is a minor\nbackward-compatible release of the versatile py.test testing tool.   It\ncontains bug fixes and a few refinements particularly to reporting with\n\"--collectonly\", see below for details.\n\nFor general information see here:\n\n     http://pytest.org/\n\nTo install or upgrade pytest:\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nSpecial thanks for helping on this release to Ronny Pfannschmidt\nand Ralf Schmitt and the contributors of issues.\n\nbest,\nholger krekel\n\n\nChanges between 2.2.1 and 2.2.2\n----------------------------------------\n\n- fix issue101: wrong args to unittest.TestCase test function now\n  produce better output\n- fix issue102: report more useful errors and hints for when a\n  test directory was renamed and some pyc/__pycache__ remain\n- fix issue106: allow parametrize to be applied multiple times\n  e.g. from module, class and at function level.\n- fix issue107: actually perform session scope finalization\n- don't check in parametrize if indirect parameters are funcarg names\n- add chdir method to monkeypatch funcarg\n- fix crash resulting from calling monkeypatch undo a second time\n- fix issue115: make --collectonly robust against early failure\n  (missing files/directories)\n- \"-qq --collectonly\" now shows only files and the number of tests in them\n- \"-q --collectonly\" now shows test ids\n- allow adding of attributes to test reports such that it also works\n  with distributed testing (no upgrade of pytest-xdist needed)\n"
  },
  {
    "path": "doc/en/announce/release-2.2.4.rst",
    "content": "pytest-2.2.4: bug fixes, better junitxml/unittest/python3 compat\n===========================================================================\n\npytest-2.2.4 is a minor backward-compatible release of the versatile\npy.test testing tool.   It contains bug fixes and a few refinements\nto junitxml reporting, better unittest- and python3 compatibility.\n\nFor general information see here:\n\n     http://pytest.org/\n\nTo install or upgrade pytest:\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nSpecial thanks for helping on this release to Ronny Pfannschmidt\nand Benjamin Peterson and the contributors of issues.\n\nbest,\nholger krekel\n\nChanges between 2.2.3 and 2.2.4\n-----------------------------------\n\n- fix error message for rewritten assertions involving the % operator\n- fix issue 126: correctly match all invalid xml characters for junitxml\n  binary escape\n- fix issue with unittest: now @unittest.expectedFailure markers should\n  be processed correctly (you can also use @pytest.mark markers)\n- document integration with the extended distribute/setuptools test commands\n- fix issue 140: properly get the real functions\n  of bound classmethods for setup/teardown_class\n- fix issue #141: switch from the deceased paste.pocoo.org to bpaste.net\n- fix issue #143: call unconfigure/sessionfinish always when\n  configure/sessionstart where called\n- fix issue #144: better mangle test ids to junitxml classnames\n- upgrade distribute_setup.py to 0.6.27\n"
  },
  {
    "path": "doc/en/announce/release-2.3.0.rst",
    "content": "pytest-2.3: improved fixtures / better unittest integration\n=============================================================================\n\npytest-2.3 comes with many major improvements for fixture/funcarg management\nand parametrized testing in Python.  It is now easier, more efficient and\nmore predictable to re-run the same tests with different fixture\ninstances.  Also, you can directly declare the caching \"scope\" of\nfixtures so that dependent tests throughout your whole test suite can\nreuse database or other expensive fixture objects with ease.  Lastly,\nit's possible for fixture functions (formerly known as funcarg\nfactories) to use other fixtures, allowing for a completely modular and\nreusable fixture design.\n\nFor detailed info and tutorial-style examples, see:\n\n    http://pytest.org/en/stable/explanation/fixtures.html\n\nMoreover, there is now support for using pytest fixtures/funcargs with\nunittest-style suites, see here for examples:\n\n    http://pytest.org/en/stable/how-to/unittest.html\n\nBesides, more unittest-test suites are now expected to \"simply work\"\nwith pytest.\n\nAll changes are backward compatible and you should be able to continue\nto run your test suites and 3rd party plugins that worked with\npytest-2.2.4.\n\nIf you are interested in the precise reasoning (including examples) of the\npytest-2.3 fixture evolution, please consult\nhttp://pytest.org/en/stable/funcarg_compare.html\n\nFor general info on installation and getting started:\n\n    http://pytest.org/en/stable/getting-started.html\n\nDocs and PDF access as usual at:\n\n    http://pytest.org\n\nand more details for those already in the knowing of pytest can be found\nin the CHANGELOG below.\n\nParticular thanks for this release go to Floris Bruynooghe, Alex Okrushko\nCarl Meyer, Ronny Pfannschmidt, Benjamin Peterson and Alex Gaynor for helping\nto get the new features right and well integrated.  Ronny and Floris\nalso helped to fix a number of bugs and yet more people helped by\nproviding bug reports.\n\nhave fun,\nholger krekel\n\n\nChanges between 2.2.4 and 2.3.0\n-----------------------------------\n\n- fix issue202 - better automatic names for parametrized test functions\n- fix issue139 - introduce @pytest.fixture which allows direct scoping\n  and parametrization of funcarg factories.  Introduce new @pytest.setup\n  marker to allow the writing of setup functions which accept funcargs.\n- fix issue198 - conftest fixtures were not found on windows32 in some\n  circumstances with nested directory structures due to path manipulation issues\n- fix issue193 skip test functions with were parametrized with empty\n  parameter sets\n- fix python3.3 compat, mostly reporting bits that previously depended\n  on dict ordering\n- introduce re-ordering of tests by resource and parametrization setup\n  which takes precedence to the usual file-ordering\n- fix issue185 monkeypatching time.time does not cause pytest to fail\n- fix issue172 duplicate call of pytest.setup-decoratored setup_module\n  functions\n- fix junitxml=path construction so that if tests change the\n  current working directory and the path is a relative path\n  it is constructed correctly from the original current working dir.\n- fix \"python setup.py test\" example to cause a proper \"errno\" return\n- fix issue165 - fix broken doc links and mention stackoverflow for FAQ\n- catch unicode-issues when writing failure representations\n  to terminal to prevent the whole session from crashing\n- fix xfail/skip confusion: a skip-mark or an imperative pytest.skip\n  will now take precedence before xfail-markers because we\n  can't determine xfail/xpass status in case of a skip. see also:\n  http://stackoverflow.com/questions/11105828/in-py-test-when-i-explicitly-skip-a-test-that-is-marked-as-xfail-how-can-i-get\n\n- always report installed 3rd party plugins in the header of a test run\n\n- fix issue160: a failing setup of an xfail-marked tests should\n  be reported as xfail (not xpass)\n\n- fix issue128: show captured output when capsys/capfd are used\n\n- fix issue179: properly show the dependency chain of factories\n\n- pluginmanager.register(...) now raises ValueError if the\n  plugin has been already registered or the name is taken\n\n- fix issue159: improve https://docs.pytest.org/en/6.0.1/faq.html\n  especially with respect to the \"magic\" history, also mention\n  pytest-django, trial and unittest integration.\n\n- make request.keywords and node.keywords writable.  All descendant\n  collection nodes will see keyword values.  Keywords are dictionaries\n  containing markers and other info.\n\n- fix issue 178: xml binary escapes are now wrapped in py.xml.raw\n\n- fix issue 176: correctly catch the builtin AssertionError\n  even when we replaced AssertionError with a subclass on the\n  python level\n\n- factory discovery no longer fails with magic global callables\n  that provide no sane __code__ object (mock.call for example)\n\n- fix issue 182: testdir.inprocess_run now considers passed plugins\n\n- fix issue 188: ensure sys.exc_info is clear on python2\n                 before calling into a test\n\n- fix issue 191: add unittest TestCase runTest method support\n- fix issue 156: monkeypatch correctly handles class level descriptors\n\n- reporting refinements:\n\n  - pytest_report_header now receives a \"startdir\" so that\n    you can use startdir.bestrelpath(yourpath) to show\n    nice relative path\n\n  - allow plugins to implement both pytest_report_header and\n    pytest_sessionstart (sessionstart is invoked first).\n\n  - don't show deselected reason line if there is none\n\n  - py.test -vv will show all of assert comparisons instead of truncating\n"
  },
  {
    "path": "doc/en/announce/release-2.3.1.rst",
    "content": "pytest-2.3.1: fix regression with factory functions\n===========================================================================\n\npytest-2.3.1 is a quick follow-up release:\n\n- fix issue202 - regression with fixture functions/funcarg factories:\n  using \"self\" is now safe again and works as in 2.2.4.  Thanks\n  to Eduard Schettino for the quick bug report.\n\n- disable pexpect pytest self tests on Freebsd - thanks Koob for the\n  quick reporting\n\n- fix/improve interactive docs with --markers\n\nSee\n\n     http://pytest.org/\n\nfor general information.  To install or upgrade pytest:\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nbest,\nholger krekel\n\n\nChanges between 2.3.0 and 2.3.1\n-----------------------------------\n\n- fix issue202 - fix regression: using \"self\" from fixture functions now\n  works as expected (it's the same \"self\" instance that a test method\n  which uses the fixture sees)\n\n- skip pexpect using tests (test_pdb.py mostly) on freebsd* systems\n  due to pexpect not supporting it properly (hanging)\n\n- link to web pages from --markers output which provides help for\n  pytest.mark.* usage.\n"
  },
  {
    "path": "doc/en/announce/release-2.3.2.rst",
    "content": "pytest-2.3.2: some fixes and more traceback-printing speed\n===========================================================================\n\npytest-2.3.2 is another stabilization release:\n\n- issue 205: fixes a regression with conftest detection\n- issue 208/29: fixes traceback-printing speed in some bad cases\n- fix teardown-ordering for parametrized setups\n- fix unittest and trial compat behaviour with respect  to runTest() methods\n- issue 206 and others: some improvements to packaging\n- fix issue127 and others: improve some docs\n\nSee\n\n     http://pytest.org/\n\nfor general information.  To install or upgrade pytest:\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nbest,\nholger krekel\n\n\nChanges between 2.3.1 and 2.3.2\n-----------------------------------\n\n- fix issue208 and fix issue29 use new py version to avoid long pauses\n  when printing tracebacks in long modules\n\n- fix issue205 - conftests in subdirs customizing\n  pytest_pycollect_makemodule and pytest_pycollect_makeitem\n  now work properly\n\n- fix teardown-ordering for parametrized setups\n\n- fix issue127 - better documentation for pytest_addoption\n  and related objects.\n\n- fix unittest behaviour: TestCase.runtest only called if there are\n  test methods defined\n\n- improve trial support: don't collect its empty\n  unittest.TestCase.runTest() method\n\n- \"python setup.py test\" now works with pytest itself\n\n- fix/improve internal/packaging related bits:\n\n  - exception message check of test_nose.py now passes on python33 as well\n\n  - issue206 - fix test_assertrewrite.py to work when a global\n    PYTHONDONTWRITEBYTECODE=1 is present\n\n  - add tox.ini to pytest distribution so that ignore-dirs and others config\n    bits are properly distributed for maintainers who run pytest-own tests\n"
  },
  {
    "path": "doc/en/announce/release-2.3.3.rst",
    "content": "pytest-2.3.3: integration fixes, py24 support, ``*/**`` shown in traceback\n===========================================================================\n\npytest-2.3.3 is another stabilization release of the py.test tool\nwhich offers uebersimple assertions, scalable fixture mechanisms\nand deep customization for testing with Python.  Particularly,\nthis release provides:\n\n- integration fixes and improvements related to flask, numpy, nose,\n  unittest, mock\n\n- makes pytest work on py24 again (yes, people sometimes still need to use it)\n\n- show ``*,**`` args in pytest tracebacks\n\nThanks to Manuel Jacob, Thomas Waldmann, Ronny Pfannschmidt, Pavel Repin\nand Andreas Taumoefolau for providing patches and all for the issues.\n\nSee\n\n     http://pytest.org/\n\nfor general information.  To install or upgrade pytest:\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nbest,\nholger krekel\n\nChanges between 2.3.2 and 2.3.3\n-----------------------------------\n\n- fix issue214 - parse modules that contain special objects like e. g.\n  flask's request object which blows up on getattr access if no request\n  is active. thanks Thomas Waldmann.\n\n- fix issue213 - allow to parametrize with values like numpy arrays that\n  do not support an __eq__ operator\n\n- fix issue215 - split test_python.org into multiple files\n\n- fix issue148 - @unittest.skip on classes is now recognized and avoids\n  calling setUpClass/tearDownClass, thanks Pavel Repin\n\n- fix issue209 - reintroduce python2.4 support by depending on newer\n  pylib which re-introduced statement-finding for pre-AST interpreters\n\n- nose support: only call setup if it's a callable, thanks Andrew\n  Taumoefolau\n\n- fix issue219 - add py2.4-3.3 classifiers to TROVE list\n\n- in tracebacks *,** arg values are now shown next to normal arguments\n  (thanks Manuel Jacob)\n\n- fix issue217 - support mock.patch with pytest's fixtures - note that\n  you need either mock-1.0.1 or the python3.3 builtin unittest.mock.\n\n- fix issue127 - improve documentation for pytest_addoption() and\n  add a ``config.getoption(name)`` helper function for consistency.\n"
  },
  {
    "path": "doc/en/announce/release-2.3.4.rst",
    "content": "pytest-2.3.4: stabilization, more flexible selection via \"-k expr\"\n===========================================================================\n\npytest-2.3.4 is a small stabilization release of the py.test tool\nwhich offers uebersimple assertions, scalable fixture mechanisms\nand deep customization for testing with Python.  This release\ncomes with the following fixes and features:\n\n- make \"-k\" option accept an expressions the same as with \"-m\" so that one\n  can write: -k \"name1 or name2\" etc.  This is a slight usage incompatibility\n  if you used special syntax like \"TestClass.test_method\" which you now\n  need to write as -k \"TestClass and test_method\" to match a certain\n  method in a certain test class.\n- allow to dynamically define markers via\n  item.keywords[...]=assignment integrating with \"-m\" option\n- yielded test functions will now have autouse-fixtures active but\n  cannot accept fixtures as funcargs - it's anyway recommended to\n  rather use the post-2.0 parametrize features instead of yield, see:\n  http://pytest.org/en/stable/example/how-to/parametrize.html\n- fix autouse-issue where autouse-fixtures would not be discovered\n  if defined in an a/conftest.py file and tests in a/tests/test_some.py\n- fix issue226 - LIFO ordering for fixture teardowns\n- fix issue224 - invocations with >256 char arguments now work\n- fix issue91 - add/discuss package/directory level setups in example\n- fixes related to autouse discovery and calling\n\nThanks in particular to Thomas Waldmann for spotting and reporting issues.\n\nSee\n\n     http://pytest.org/\n\nfor general information.  To install or upgrade pytest:\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nbest,\nholger krekel\n"
  },
  {
    "path": "doc/en/announce/release-2.3.5.rst",
    "content": "pytest-2.3.5: bug fixes and little improvements\n===========================================================================\n\npytest-2.3.5 is a maintenance release with many bug fixes and little\nimprovements.  See the changelog below for details.  No backward\ncompatibility issues are foreseen and all plugins which worked with the\nprior version are expected to work unmodified.   Speaking of which, a\nfew interesting new plugins saw the light last month:\n\n- pytest-instafail: show failure information while tests are running\n- pytest-qt: testing of GUI applications written with QT/Pyside\n- pytest-xprocess: managing external processes across test runs\n- pytest-random: randomize test ordering\n\nAnd several others like pytest-django saw maintenance releases.\nFor a more complete list, check out\nhttps://pypi.org/search/?q=pytest\n\nFor general information see:\n\n     http://pytest.org/\n\nTo install or upgrade pytest:\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\nParticular thanks to Floris, Ronny, Benjamin and the many bug reporters\nand fix providers.\n\nmay the fixtures be with you,\nholger krekel\n\n\nChanges between 2.3.4 and 2.3.5\n-----------------------------------\n\n- never consider a fixture function for test function collection\n\n- allow re-running of test items / helps to fix pytest-reruntests plugin\n  and also help to keep less fixture/resource references alive\n\n- put captured stdout/stderr into junitxml output even for passing tests\n  (thanks Adam Goucher)\n\n- Issue 265 - integrate nose setup/teardown with setupstate\n  so it doesn't try to teardown if it did not setup\n\n- issue 271 - don't write junitxml on worker nodes\n\n- Issue 274 - don't try to show full doctest example\n  when doctest does not know the example location\n\n- issue 280 - disable assertion rewriting on buggy CPython 2.6.0\n\n- inject \"getfixture()\" helper to retrieve fixtures from doctests,\n  thanks Andreas Zeidler\n\n- issue 259 - when assertion rewriting, be consistent with the default\n  source encoding of ASCII on Python 2\n\n- issue 251 - report a skip instead of ignoring classes with init\n\n- issue250 unicode/str mixes in parametrization names and values now works\n\n- issue257, assertion-triggered compilation of source ending in a\n  comment line doesn't blow up in python2.5 (fixed through py>=1.4.13.dev6)\n\n- fix --genscript option to generate standalone scripts that also\n  work with python3.3 (importer ordering)\n\n- issue171 - in assertion rewriting, show the repr of some\n  global variables\n\n- fix option help for \"-k\"\n\n- move long description of distribution into README.rst\n\n- improve docstring for metafunc.parametrize()\n\n- fix bug where using capsys with pytest.set_trace() in a test\n  function would break when looking at capsys.readouterr()\n\n- allow to specify prefixes starting with \"_\" when\n  customizing python_functions test discovery. (thanks Graham Horler)\n\n- improve PYTEST_DEBUG tracing output by putting\n  extra data on a new lines with additional indent\n\n- ensure OutcomeExceptions like skip/fail have initialized exception attributes\n\n- issue 260 - don't use nose special setup on plain unittest cases\n\n- fix issue134 - print the collect errors that prevent running specified test items\n\n- fix issue266 - accept unicode in MarkEvaluator expressions\n"
  },
  {
    "path": "doc/en/announce/release-2.4.0.rst",
    "content": "pytest-2.4.0: new fixture features/hooks and bug fixes\n===========================================================================\n\nThe just released pytest-2.4.0 brings many improvements and numerous\nbug fixes while remaining plugin- and test-suite compatible apart\nfrom a few supposedly very minor incompatibilities.  See below for\na full list of details.  A few feature highlights:\n\n- new yield-style fixtures `pytest.yield_fixture\n  <http://pytest.org/en/stable/yieldfixture.html>`_, allowing to use\n  existing with-style context managers in fixture functions.\n\n- improved pdb support: ``import pdb ; pdb.set_trace()`` now works\n  without requiring prior disabling of stdout/stderr capturing.\n  Also the ``--pdb`` options works now on collection and internal errors\n  and we introduced a new experimental hook for IDEs/plugins to\n  intercept debugging: ``pytest_exception_interact(node, call, report)``.\n\n- shorter monkeypatch variant to allow specifying an import path as\n  a target, for example: ``monkeypatch.setattr(\"requests.get\", myfunc)``\n\n- better unittest/nose compatibility: all teardown methods are now only\n  called if the corresponding setup method succeeded.\n\n- integrate tab-completion on command line options if you\n  have :pypi:`argcomplete` configured.\n\n- allow boolean expression directly with skipif/xfail\n  if a \"reason\" is also specified.\n\n- a new hook ``pytest_load_initial_conftests`` allows plugins like\n  :pypi:`pytest-django` to\n  influence the environment before conftest files import ``django``.\n\n- reporting: color the last line red or green depending if\n  failures/errors occurred or everything passed.\n\nThe documentation has been updated to accommodate the changes,\nsee `http://pytest.org <http://pytest.org>`_\n\nTo install or upgrade pytest::\n\n    pip install -U pytest # or\n    easy_install -U pytest\n\n\n**Many thanks to all who helped, including Floris Bruynooghe,\nBrianna Laugher, Andreas Pelme, Anthon van der Neut, Anatoly Bubenkoff,\nVladimir Keleshev, Mathieu Agopian, Ronny Pfannschmidt, Christian\nTheunert and many others.**\n\nmay passing tests be with you,\n\nholger krekel\n\nChanges between 2.3.5 and 2.4\n-----------------------------------\n\nknown incompatibilities:\n\n- if calling --genscript from python2.7 or above, you only get a\n  standalone script which works on python2.7 or above.  Use Python2.6\n  to also get a python2.5 compatible version.\n\n- all xunit-style teardown methods (nose-style, pytest-style,\n  unittest-style) will not be called if the corresponding setup method failed,\n  see issue322 below.\n\n- the pytest_plugin_unregister hook wasn't ever properly called\n  and there is no known implementation of the hook - so it got removed.\n\n- pytest.fixture-decorated functions cannot be generators (i.e. use\n  yield) anymore.  This change might be reversed in 2.4.1 if it causes\n  unforeseen real-life issues.  However, you can always write and return\n  an inner function/generator and change the fixture consumer to iterate\n  over the returned generator.  This change was done in lieu of the new\n  ``pytest.yield_fixture`` decorator, see below.\n\nnew features:\n\n- experimentally introduce a new ``pytest.yield_fixture`` decorator\n  which accepts exactly the same parameters as pytest.fixture but\n  mandates a ``yield`` statement instead of a ``return statement`` from\n  fixture functions.  This allows direct integration with \"with-style\"\n  context managers in fixture functions and generally avoids registering\n  of finalization callbacks in favour of treating the \"after-yield\" as\n  teardown code.  Thanks Andreas Pelme, Vladimir Keleshev, Floris\n  Bruynooghe, Ronny Pfannschmidt and many others for discussions.\n\n- allow boolean expression directly with skipif/xfail\n  if a \"reason\" is also specified.  Rework skipping documentation\n  to recommend \"condition as booleans\" because it prevents surprises\n  when importing markers between modules.  Specifying conditions\n  as strings will remain fully supported.\n\n- reporting: color the last line red or green depending if\n  failures/errors occurred or everything passed.  thanks Christian\n  Theunert.\n\n- make \"import pdb ; pdb.set_trace()\" work natively wrt capturing (no\n  \"-s\" needed anymore), making ``pytest.set_trace()`` a mere shortcut.\n\n- fix issue181: --pdb now also works on collect errors (and\n  on internal errors) .  This was implemented by a slight internal\n  refactoring and the introduction of a new hook\n  ``pytest_exception_interact`` hook (see next item).\n\n- fix issue341: introduce new experimental hook for IDEs/terminals to\n  intercept debugging: ``pytest_exception_interact(node, call, report)``.\n\n- new monkeypatch.setattr() variant to provide a shorter\n  invocation for patching out classes/functions from modules:\n\n     monkeypatch.setattr(\"requests.get\", myfunc)\n\n  will replace the \"get\" function of the \"requests\" module with ``myfunc``.\n\n- fix issue322: tearDownClass is not run if setUpClass failed. Thanks\n  Mathieu Agopian for the initial fix.  Also make all of pytest/nose\n  finalizer mimic the same generic behaviour: if a setupX exists and\n  fails, don't run teardownX.  This internally introduces a new method\n  \"node.addfinalizer()\" helper which can only be called during the setup\n  phase of a node.\n\n- simplify pytest.mark.parametrize() signature: allow to pass a\n  CSV-separated string to specify argnames.  For example:\n  ``pytest.mark.parametrize(\"input,expected\",  [(1,2), (2,3)])``\n  works as well as the previous:\n  ``pytest.mark.parametrize((\"input\", \"expected\"), ...)``.\n\n- add support for setUpModule/tearDownModule detection, thanks Brian Okken.\n\n- integrate tab-completion on options through use of \"argcomplete\".\n  Thanks Anthon van der Neut for the PR.\n\n- change option names to be hyphen-separated long options but keep the\n  old spelling backward compatible.  py.test -h will only show the\n  hyphenated version, for example \"--collect-only\" but \"--collectonly\"\n  will remain valid as well (for backward-compat reasons).  Many thanks to\n  Anthon van der Neut for the implementation and to Hynek Schlawack for\n  pushing us.\n\n- fix issue 308 - allow to mark/xfail/skip individual parameter sets\n  when parametrizing.  Thanks Brianna Laugher.\n\n- call new experimental pytest_load_initial_conftests hook to allow\n  3rd party plugins to do something before a conftest is loaded.\n\nBug fixes:\n\n- fix issue358 - capturing options are now parsed more properly\n  by using a new parser.parse_known_args method.\n\n- pytest now uses argparse instead of optparse (thanks Anthon) which\n  means that \"argparse\" is added as a dependency if installing into python2.6\n  environments or below.\n\n- fix issue333: fix a case of bad unittest/pytest hook interaction.\n\n- PR27: correctly handle nose.SkipTest during collection.  Thanks\n  Antonio Cuni, Ronny Pfannschmidt.\n\n- fix issue355: junitxml puts name=\"pytest\" attribute to testsuite tag.\n\n- fix issue336: autouse fixture in plugins should work again.\n\n- fix issue279: improve object comparisons on assertion failure\n  for standard datatypes and recognise collections.abc.  Thanks to\n  Brianna Laugher and Mathieu Agopian.\n\n- fix issue317: assertion rewriter support for the is_package method\n\n- fix issue335: document py.code.ExceptionInfo() object returned\n  from pytest.raises(), thanks Mathieu Agopian.\n\n- remove implicit distribute_setup support from setup.py.\n\n- fix issue305: ignore any problems when writing pyc files.\n\n- SO-17664702: call fixture finalizers even if the fixture function\n  partially failed (finalizers would not always be called before)\n\n- fix issue320 - fix class scope for fixtures when mixed with\n  module-level functions.  Thanks Anatoly Bubenkoff.\n\n- you can specify \"-q\" or \"-qq\" to get different levels of \"quieter\"\n  reporting (thanks Katarzyna Jachim)\n\n- fix issue300 - Fix order of conftest loading when starting py.test\n  in a subdirectory.\n\n- fix issue323 - sorting of many module-scoped arg parametrizations\n\n- make sessionfinish hooks execute with the same cwd-context as at\n  session start (helps fix plugin behaviour which write output files\n  with relative path such as pytest-cov)\n\n- fix issue316 - properly reference collection hooks in docs\n\n- fix issue 306 - cleanup of -k/-m options to only match markers/test\n  names/keywords respectively.  Thanks Wouter van Ackooy.\n\n- improved doctest counting for doctests in python modules --\n  files without any doctest items will not show up anymore\n  and doctest examples are counted as separate test items.\n  thanks Danilo Bellini.\n\n- fix issue245 by depending on the released py-1.4.14\n  which fixes py.io.dupfile to work with files with no\n  mode. Thanks Jason R. Coombs.\n\n- fix junitxml generation when test output contains control characters,\n  addressing issue267, thanks Jaap Broekhuizen\n\n- fix issue338: honor --tb style for setup/teardown errors as well.  Thanks Maho.\n\n- fix issue307 - use yaml.safe_load in example, thanks Mark Eichin.\n\n- better parametrize error messages, thanks Brianna Laugher\n\n- pytest_terminal_summary(terminalreporter) hooks can now use\n  \".section(title)\" and \".line(msg)\" methods to print extra\n  information at the end of a test run.\n"
  },
  {
    "path": "doc/en/announce/release-2.4.1.rst",
    "content": "pytest-2.4.1: fixing three regressions compared to 2.3.5\n===========================================================================\n\npytest-2.4.1 is a quick follow up release to fix three regressions\ncompared to 2.3.5 before they hit more people:\n\n- When using parser.addoption() unicode arguments to the\n  \"type\" keyword should also be converted to the respective types.\n  thanks Floris Bruynooghe, @dnozay. (fixes issue360 and issue362)\n\n- fix dotted filename completion when using argcomplete\n  thanks Anthon van der Neuth. (fixes issue361)\n\n- fix regression when a 1-tuple (\"arg\",) is used for specifying\n  parametrization (the values of the parametrization were passed\n  nested in a tuple).  Thanks Donald Stufft.\n\n- also merge doc typo fixes, thanks Andy Dirnberger\n\nas usual, docs at http://pytest.org and upgrades via::\n\n    pip install -U pytest\n\nhave fun,\nholger krekel\n"
  },
  {
    "path": "doc/en/announce/release-2.4.2.rst",
    "content": "pytest-2.4.2: colorama on windows, plugin/tmpdir fixes\n===========================================================================\n\npytest-2.4.2 is another bug-fixing release:\n\n- on Windows require colorama and a newer py lib so that py.io.TerminalWriter()\n  now uses colorama instead of its own ctypes hacks. (fixes issue365)\n  thanks Paul Moore for bringing it up.\n\n- fix \"-k\" matching of tests where \"repr\" and \"attr\" and other names would\n  cause wrong matches because of an internal implementation quirk\n  (don't ask) which is now properly implemented. fixes issue345.\n\n- avoid tmpdir fixture to create too long filenames especially\n  when parametrization is used (issue354)\n\n- fix pytest-pep8 and pytest-flakes / pytest interactions\n  (collection names in mark plugin was assuming an item always\n  has a function which is not true for those plugins etc.)\n  Thanks Andi Zeidler.\n\n- introduce node.get_marker/node.add_marker API for plugins\n  like pytest-pep8 and pytest-flakes to avoid the messy\n  details of the node.keywords  pseudo-dicts.  Adapted\n  docs.\n\n- remove attempt to \"dup\" stdout at startup as it's icky.\n  the normal capturing should catch enough possibilities\n  of tests messing up standard FDs.\n\n- add pluginmanager.do_configure(config) as a link to\n  config.do_configure() for plugin-compatibility\n\nas usual, docs at http://pytest.org and upgrades via::\n\n    pip install -U pytest\n\nhave fun,\nholger krekel\n"
  },
  {
    "path": "doc/en/announce/release-2.5.0.rst",
    "content": "pytest-2.5.0: now down to ZERO reported bugs!\n===========================================================================\n\npytest-2.5.0 is a big fixing release, the result of two community bug\nfixing days plus numerous additional works from many people and\nreporters.  The release should be fully compatible to 2.4.2, existing\nplugins and test suites.  We aim at maintaining this level of ZERO reported\nbugs because it's no fun if your testing tool has bugs, is it?  Under a\ncondition, though: when submitting a bug report please provide\nclear information about the circumstances and a simple example which\nreproduces the problem.\n\nThe issue tracker is of course not empty now.  We have many remaining\n\"enhancement\" issues which we'll hopefully can tackle in 2014 with your\nhelp.\n\nFor those who use older Python versions, please note that pytest is not\nautomatically tested on python2.5 due to virtualenv, setuptools and tox\nnot supporting it anymore.  Manual verification shows that it mostly\nworks fine but it's not going to be part of the automated release\nprocess and thus likely to break in the future.\n\nAs usual, current docs are at\n\n    http://pytest.org\n\nand you can upgrade from pypi via::\n\n    pip install -U pytest\n\nParticular thanks for helping with this release go to Anatoly Bubenkoff,\nFloris Bruynooghe, Marc Abramowitz, Ralph Schmitt, Ronny Pfannschmidt,\nDonald Stufft, James Lan, Rob Dennis, Jason R. Coombs, Mathieu Agopian,\nVirgil Dupras, Bruno Oliveira, Alex Gaynor and others.\n\nhave fun,\nholger krekel\n\n\n2.5.0\n-----------------------------------\n\n- dropped python2.5 from automated release testing of pytest itself\n  which means it's probably going to break soon (but still works\n  with this release we believe).\n\n- simplified and fixed implementation for calling finalizers when\n  parametrized fixtures or function arguments are involved.  finalization\n  is now performed lazily at setup time instead of in the \"teardown phase\".\n  While this might sound odd at first, it helps to ensure that we are\n  correctly handling setup/teardown even in complex code.  User-level code\n  should not be affected unless it's implementing the pytest_runtest_teardown\n  hook and expecting certain fixture instances are torn down within (very\n  unlikely and would have been unreliable anyway).\n\n- PR90: add --color=yes|no|auto option to force terminal coloring\n  mode (\"auto\" is default).  Thanks Marc Abramowitz.\n\n- fix issue319 - correctly show unicode in assertion errors.  Many\n  thanks to Floris Bruynooghe for the complete PR.  Also means\n  we depend on py>=1.4.19 now.\n\n- fix issue396 - correctly sort and finalize class-scoped parametrized\n  tests independently from number of methods on the class.\n\n- refix issue323 in a better way -- parametrization should now never\n  cause Runtime Recursion errors because the underlying algorithm\n  for re-ordering tests per-scope/per-fixture is not recursive\n  anymore (it was tail-call recursive before which could lead\n  to problems for more than >966 non-function scoped parameters).\n\n- fix issue290 - there is preliminary support now for parametrizing\n  with repeated same values (sometimes useful to test if calling\n  a second time works as with the first time).\n\n- close issue240 - document precisely how pytest module importing\n  works, discuss the two common test directory layouts, and how it\n  interacts with PEP420-namespace packages.\n\n- fix issue246 fix finalizer order to be LIFO on independent fixtures\n  depending on a parametrized higher-than-function scoped fixture.\n  (was quite some effort so please bear with the complexity of this sentence :)\n  Thanks Ralph Schmitt for the precise failure example.\n\n- fix issue244 by implementing special index for parameters to only use\n  indices for parametrized test ids\n\n- fix issue287 by running all finalizers but saving the exception\n  from the first failing finalizer and re-raising it so teardown will\n  still have failed.  We reraise the first failing exception because\n  it might be the cause for other finalizers to fail.\n\n- fix ordering when mock.patch or other standard decorator-wrappings\n  are used with test methods.  This fixes issue346 and should\n  help with random \"xdist\" collection failures.  Thanks to\n  Ronny Pfannschmidt and Donald Stufft for helping to isolate it.\n\n- fix issue357 - special case \"-k\" expressions to allow for\n  filtering with simple strings that are not valid python expressions.\n  Examples: \"-k 1.3\" matches all tests parametrized with 1.3.\n  \"-k None\" filters all tests that have \"None\" in their name\n  and conversely \"-k 'not None'\".\n  Previously these examples would raise syntax errors.\n\n- fix issue384 by removing the trial support code\n  since the unittest compat enhancements allow\n  trial to handle it on its own\n\n- don't hide an ImportError when importing a plugin produces one.\n  fixes issue375.\n\n- fix issue275 - allow usefixtures and autouse fixtures\n  for running doctest text files.\n\n- fix issue380 by making --resultlog only rely on longrepr instead\n  of the \"reprcrash\" attribute which only exists sometimes.\n\n- address issue122: allow @pytest.fixture(params=iterator) by exploding\n  into a list early on.\n\n- fix pexpect-3.0 compatibility for pytest's own tests.\n  (fixes issue386)\n\n- allow nested parametrize-value markers, thanks James Lan for the PR.\n\n- fix unicode handling with new monkeypatch.setattr(import_path, value)\n  API.  Thanks Rob Dennis.  Fixes issue371.\n\n- fix unicode handling with junitxml, fixes issue368.\n\n- In assertion rewriting mode on Python 2, fix the detection of coding\n  cookies. See issue #330.\n\n- make \"--runxfail\" turn imperative pytest.xfail calls into no ops\n  (it already did neutralize pytest.mark.xfail markers)\n\n- refine pytest / pkg_resources interactions: The AssertionRewritingHook\n  PEP302 compliant loader now registers itself with setuptools/pkg_resources\n  properly so that the pkg_resources.resource_stream method works properly.\n  Fixes issue366.  Thanks for the investigations and full PR to Jason R. Coombs.\n\n- pytestconfig fixture is now session-scoped as it is the same object during the\n  whole test run.  Fixes issue370.\n\n- avoid one surprising case of marker malfunction/confusion::\n\n      @pytest.mark.some(lambda arg: ...)\n      def test_function():\n\n  would not work correctly because pytest assumes @pytest.mark.some\n  gets a function to be decorated already.  We now at least detect if this\n  arg is a lambda and thus the example will work.  Thanks Alex Gaynor\n  for bringing it up.\n\n- xfail a test on pypy that checks wrong encoding/ascii (pypy does\n  not error out). fixes issue385.\n\n- internally make varnames() deal with classes's __init__,\n  although it's not needed by pytest itself atm.  Also\n  fix caching.  Fixes issue376.\n\n- fix issue221 - handle importing of namespace-package with no\n  __init__.py properly.\n\n- refactor internal FixtureRequest handling to avoid monkeypatching.\n  One of the positive user-facing effects is that the \"request\" object\n  can now be used in closures.\n\n- fixed version comparison in pytest.importskip(modname, minverstring)\n\n- fix issue377 by clarifying in the nose-compat docs that pytest\n  does not duplicate the unittest-API into the \"plain\" namespace.\n\n- fix verbose reporting for @mock'd test functions\n"
  },
  {
    "path": "doc/en/announce/release-2.5.1.rst",
    "content": "pytest-2.5.1: fixes and new home page styling\n===========================================================================\n\npytest is a mature Python testing tool with more than 1000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThe 2.5.1 release maintains the \"zero-reported-bugs\" promise by fixing\nthe three bugs reported since the last release a few days ago.  It also\nfeatures a new home page styling implemented by Tobias Bieniek, based on\nthe flask theme from Armin Ronacher:\n\n    http://pytest.org\n\nIf you have anything more to improve styling and docs,\nwe'd be very happy to merge further pull requests.\n\nOn the coding side, the release also contains a little enhancement to\nfixture decorators allowing to directly influence generation of test\nids, thanks to Floris Bruynooghe.  Other thanks for helping with\nthis release go to Anatoly Bubenkoff and Ronny Pfannschmidt.\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nhave fun and a nice remaining \"bug-free\" time of the year :)\nholger krekel\n\n2.5.1\n-----------------------------------\n\n- merge new documentation styling PR from Tobias Bieniek.\n\n- fix issue403: allow parametrize of multiple same-name functions within\n  a collection node.  Thanks Andreas Kloeckner and Alex Gaynor for reporting\n  and analysis.\n\n- Allow parameterized fixtures to specify the ID of the parameters by\n  adding an ids argument to pytest.fixture() and pytest.yield_fixture().\n  Thanks Floris Bruynooghe.\n\n- fix issue404 by always using the binary xml escape in the junitxml\n  plugin.  Thanks Ronny Pfannschmidt.\n\n- fix issue407: fix addoption docstring to point to argparse instead of\n  optparse. Thanks Daniel D. Wright.\n"
  },
  {
    "path": "doc/en/announce/release-2.5.2.rst",
    "content": "pytest-2.5.2: fixes\n===========================================================================\n\npytest is a mature Python testing tool with more than 1000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThe 2.5.2 release fixes a few bugs with two maybe-bugs remaining and\nactively being worked on (and waiting for the bug reporter's input).\nWe also have a new contribution guide thanks to Piotr Banaszkiewicz\nand others.\n\nSee docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to the following people who contributed to this release:\n\n    Anatoly Bubenkov\n    Ronny Pfannschmidt\n    Floris Bruynooghe\n    Bruno Oliveira\n    Andreas Pelme\n    Jurko Gospodnetić\n    Piotr Banaszkiewicz\n    Simon Liedtke\n    lakka\n    Lukasz Balcerzak\n    Philippe Muller\n    Daniel Hahler\n\nhave fun,\nholger krekel\n\n2.5.2\n-----------------------------------\n\n- fix issue409 -- better interoperate with cx_freeze by not\n  trying to import from collections.abc which causes problems\n  for py27/cx_freeze.  Thanks Wolfgang L. for reporting and tracking it down.\n\n- fixed docs and code to use \"pytest\" instead of \"py.test\" almost everywhere.\n  Thanks Jurko Gospodnetic for the complete PR.\n\n- fix issue425: mention at end of \"py.test -h\" that --markers\n  and --fixtures work according to specified test path (or current dir)\n\n- fix issue413: exceptions with unicode attributes are now printed\n  correctly also on python2 and with pytest-xdist runs. (the fix\n  requires py-1.4.20)\n\n- copy, cleanup and integrate py.io capture\n  from pylib 1.4.20.dev2 (rev 13d9af95547e)\n\n- address issue416: clarify docs as to conftest.py loading semantics\n\n- fix issue429: comparing byte strings with non-ascii chars in assert\n  expressions now work better.  Thanks Floris Bruynooghe.\n\n- make capfd/capsys.capture private, its unused and shouldn't be exposed\n"
  },
  {
    "path": "doc/en/announce/release-2.6.0.rst",
    "content": "pytest-2.6.0: shorter tracebacks, new warning system, test runner compat\n===========================================================================\n\npytest is a mature Python testing tool with more than 1000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThe 2.6.0 release should be drop-in backward compatible to 2.5.2 and\nfixes a number of bugs and brings some new features, mainly:\n\n- shorter tracebacks by default: only the first (test function) entry\n  and the last (failure location) entry are shown, the ones between\n  only in \"short\" format.  Use ``--tb=long`` to get back the old\n  behaviour of showing \"long\" entries everywhere.\n\n- a new warning system which reports oddities during collection\n  and execution.  For example, ignoring collecting Test* classes with an\n  ``__init__`` now produces a warning.\n\n- various improvements to nose/mock/unittest integration\n\nNote also that 2.6.0 departs with the \"zero reported bugs\" policy\nbecause it has been too hard to keep up with it, unfortunately.\nInstead we are for now rather bound to work on \"upvoted\" issues in\nthe https://bitbucket.org/pytest-dev/pytest/issues?status=new&status=open&sort=-votes\nissue tracker.\n\nSee docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed, among them:\n\n    Benjamin Peterson\n    Jurko Gospodnetić\n    Floris Bruynooghe\n    Marc Abramowitz\n    Marc Schlaich\n    Trevor Bekolay\n    Bruno Oliveira\n    Alex Groenholm\n\nhave fun,\nholger krekel\n\n2.6.0\n-----------------------------------\n\n- fix issue537: Avoid importing old assertion reinterpretation code by default.\n  Thanks Benjamin Peterson.\n\n- fix issue364: shorten and enhance tracebacks representation by default.\n  The new \"--tb=auto\" option (default) will only display long tracebacks\n  for the first and last entry.  You can get the old behaviour of printing\n  all entries as long entries with \"--tb=long\".  Also short entries by\n  default are now printed very similarly to \"--tb=native\" ones.\n\n- fix issue514: teach assertion reinterpretation about private class attributes\n  Thanks Benjamin Peterson.\n\n- change -v output to include full node IDs of tests.  Users can copy\n  a node ID from a test run, including line number, and use it as a\n  positional argument in order to run only a single test.\n\n- fix issue 475: fail early and comprehensible if calling\n  pytest.raises with wrong exception type.\n\n- fix issue516: tell in getting-started about current dependencies.\n\n- cleanup setup.py a bit and specify supported versions. Thanks Jurko\n  Gospodnetic for the PR.\n\n- change XPASS colour to yellow rather than red when tests are run\n  with -v.\n\n- fix issue473: work around mock putting an unbound method into a class\n  dict when double-patching.\n\n- fix issue498: if a fixture finalizer fails, make sure that\n  the fixture is still invalidated.\n\n- fix issue453: the result of the pytest_assertrepr_compare hook now gets\n  it's newlines escaped so that format_exception does not blow up.\n\n- internal new warning system: pytest will now produce warnings when\n  it detects oddities in your test collection or execution.\n  Warnings are ultimately sent to a new pytest_logwarning hook which is\n  currently only implemented by the terminal plugin which displays\n  warnings in the summary line and shows more details when -rw (report on\n  warnings) is specified.\n\n- change skips into warnings for test classes with an __init__ and\n  callables in test modules which look like a test but are not functions.\n\n- fix issue436: improved finding of initial conftest files from command\n  line arguments by using the result of parse_known_args rather than\n  the previous flaky heuristics.  Thanks Marc Abramowitz for tests\n  and initial fixing approaches in this area.\n\n- fix issue #479: properly handle nose/unittest(2) SkipTest exceptions\n  during collection/loading of test modules.  Thanks to Marc Schlaich\n  for the complete PR.\n\n- fix issue490: include pytest_load_initial_conftests in documentation\n  and improve docstring.\n\n- fix issue472: clarify that ``pytest.config.getvalue()`` cannot work\n  if it's triggered ahead of command line parsing.\n\n- merge PR123: improved integration with mock.patch decorator on tests.\n\n- fix issue412: messing with stdout/stderr FD-level streams is now\n  captured without crashes.\n\n- fix issue483: trial/py33 works now properly.  Thanks Daniel Grana for PR.\n\n- improve example for pytest integration with \"python setup.py test\"\n  which now has a generic \"-a\" or \"--pytest-args\" option where you\n  can pass additional options as a quoted string.  Thanks Trevor Bekolay.\n\n- simplified internal capturing mechanism and made it more robust\n  against tests or setups changing FD1/FD2, also better integrated\n  now with pytest.pdb() in single tests.\n\n- improvements to pytest's own test-suite leakage detection, courtesy of PRs\n  from Marc Abramowitz\n\n- fix issue492: avoid leak in test_writeorg.  Thanks Marc Abramowitz.\n\n- fix issue493: don't run tests in doc directory with ``python setup.py test``\n  (use tox -e doctesting for that)\n\n- fix issue486: better reporting and handling of early conftest loading failures\n\n- some cleanup and simplification of internal conftest handling.\n\n- work a bit harder to break reference cycles when catching exceptions.\n  Thanks Jurko Gospodnetic.\n\n- fix issue443: fix skip examples to use proper comparison.  Thanks Alex\n  Groenholm.\n\n- support nose-style ``__test__`` attribute on modules, classes and\n  functions, including unittest-style Classes.  If set to False, the\n  test will not be collected.\n\n- fix issue512: show \"<notset>\" for arguments which might not be set\n  in monkeypatch plugin.  Improves output in documentation.\n\n- avoid importing \"py.test\" (an old alias module for \"pytest\")\n"
  },
  {
    "path": "doc/en/announce/release-2.6.1.rst",
    "content": "pytest-2.6.1: fixes and new xfail feature\n===========================================================================\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThe 2.6.1 release is drop-in compatible to 2.5.2 and actually fixes some\nregressions introduced with 2.6.0.  It also brings a little feature\nto the xfail marker which now recognizes expected exceptions,\nsee the CHANGELOG below.\n\nSee docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed, among them:\n\n    Floris Bruynooghe\n    Bruno Oliveira\n    Nicolas Delaby\n\nhave fun,\nholger krekel\n\nChanges 2.6.1\n=================\n\n- No longer show line numbers in the --verbose output, the output is now\n  purely the nodeid.  The line number is still shown in failure reports.\n  Thanks Floris Bruynooghe.\n\n- fix issue437 where assertion rewriting could cause pytest-xdist worker nodes\n  to collect different tests. Thanks Bruno Oliveira.\n\n- fix issue555: add \"errors\" attribute to capture-streams to satisfy\n  some distutils and possibly other code accessing sys.stdout.errors.\n\n- fix issue547 capsys/capfd also work when output capturing (\"-s\") is disabled.\n\n- address issue170: allow pytest.mark.xfail(...) to specify expected exceptions via\n  an optional \"raises=EXC\" argument where EXC can be a single exception\n  or a tuple of exception classes.  Thanks David Mohr for the complete\n  PR.\n\n- fix integration of pytest with unittest.mock.patch decorator when\n  it uses the \"new\" argument.  Thanks Nicolas Delaby for test and PR.\n\n- fix issue with detecting conftest files if the arguments contain\n  \"::\" node id specifications (copy pasted from \"-v\" output)\n\n- fix issue544 by only removing \"@NUM\" at the end of \"::\" separated parts\n  and if the part has a \".py\" extension\n\n- don't use py.std import helper, rather import things directly.\n  Thanks Bruno Oliveira.\n"
  },
  {
    "path": "doc/en/announce/release-2.6.2.rst",
    "content": "pytest-2.6.2: few fixes and cx_freeze support\n===========================================================================\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is drop-in compatible to 2.5.2 and 2.6.X.  It also\nbrings support for including pytest with cx_freeze or similar\nfreezing tools into your single-file app distribution.  For details\nsee the CHANGELOG below.\n\nSee docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed, among them:\n\n    Floris Bruynooghe\n    Benjamin Peterson\n    Bruno Oliveira\n\nhave fun,\nholger krekel\n\n2.6.2\n-----------\n\n- Added function pytest.freeze_includes(), which makes it easy to embed\n  pytest into executables using tools like cx_freeze.\n  See docs for examples and rationale. Thanks Bruno Oliveira.\n\n- Improve assertion rewriting cache invalidation precision.\n\n- fixed issue561: adapt autouse fixture example for python3.\n\n- fixed issue453: assertion rewriting issue with __repr__ containing\n  \"\\n{\", \"\\n}\" and \"\\n~\".\n\n- fix issue560: correctly display code if an \"else:\" or \"finally:\" is\n  followed by statements on the same line.\n\n- Fix example in monkeypatch documentation, thanks t-8ch.\n\n- fix issue572: correct tmpdir doc example for python3.\n\n- Do not mark as universal wheel because Python 2.6 is different from\n  other builds due to the extra argparse dependency.  Fixes issue566.\n  Thanks sontek.\n"
  },
  {
    "path": "doc/en/announce/release-2.6.3.rst",
    "content": "pytest-2.6.3: fixes and little improvements\n===========================================================================\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is drop-in compatible to 2.5.2 and 2.6.X.\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed, among them:\n\n    Floris Bruynooghe\n    Oleg Sinyavskiy\n    Uwe Schmitt\n    Charles Cloud\n    Wolfgang Schnerring\n\nhave fun,\nholger krekel\n\nChanges 2.6.3\n======================\n\n- fix issue575: xunit-xml was reporting collection errors as failures\n  instead of errors, thanks Oleg Sinyavskiy.\n\n- fix issue582: fix setuptools example, thanks Laszlo Papp and Ronny\n  Pfannschmidt.\n\n- Fix infinite recursion bug when pickling capture.EncodedFile, thanks\n  Uwe Schmitt.\n\n- fix issue589: fix bad interaction with numpy and others when showing\n  exceptions.  Check for precise \"maximum recursion depth exceed\" exception\n  instead of presuming any RuntimeError is that one (implemented in py\n  dep).  Thanks Charles Cloud for analysing the issue.\n\n- fix conftest related fixture visibility issue: when running with a\n  CWD outside of a test package pytest would get fixture discovery wrong.\n  Thanks to Wolfgang Schnerring for figuring out a reproducible example.\n\n- Introduce pytest_enter_pdb hook (needed e.g. by pytest_timeout to cancel the\n  timeout when interactively entering pdb).  Thanks Wolfgang Schnerring.\n\n- check xfail/skip also with non-python function test items. Thanks\n  Floris Bruynooghe.\n"
  },
  {
    "path": "doc/en/announce/release-2.7.0.rst",
    "content": "pytest-2.7.0: fixes, features, speed improvements\n===========================================================================\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.6.X.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed, among them:\n\n    Anatoly Bubenkoff\n    Floris Bruynooghe\n    Brianna Laugher\n    Eric Siegerman\n    Daniel Hahler\n    Charles Cloud\n    Tom Viner\n    Holger Peters\n    Ldiary Translations\n    almarklein\n\nhave fun,\nholger krekel\n\n2.7.0 (compared to 2.6.4)\n-----------------------------\n\n- fix issue435: make reload() work when assert rewriting is active.\n  Thanks Daniel Hahler.\n\n- fix issue616: conftest.py files and their contained fixtures are now\n  properly considered for visibility, independently from the exact\n  current working directory and test arguments that are used.\n  Many thanks to Eric Siegerman and his PR235 which contains\n  systematic tests for conftest visibility and now passes.\n  This change also introduces the concept of a ``rootdir`` which\n  is printed as a new pytest header and documented in the pytest\n  customize web page.\n\n- change reporting of \"diverted\" tests, i.e. tests that are collected\n  in one file but actually come from another (e.g. when tests in a test class\n  come from a base class in a different file).  We now show the nodeid\n  and indicate via a postfix the other file.\n\n- add ability to set command line options by environment variable PYTEST_ADDOPTS.\n\n- added documentation on the new pytest-dev teams on bitbucket and\n  github.  See https://pytest.org/en/stable/contributing.html .\n  Thanks to Anatoly for pushing and initial work on this.\n\n- fix issue650: new option ``--doctest-ignore-import-errors`` which\n  will turn import errors in doctests into skips.  Thanks Charles Cloud\n  for the complete PR.\n\n- fix issue655: work around different ways that cause python2/3\n  to leak sys.exc_info into fixtures/tests causing failures in 3rd party code\n\n- fix issue615: assertion rewriting did not correctly escape % signs\n  when formatting boolean operations, which tripped over mixing\n  booleans with modulo operators.  Thanks to Tom Viner for the report,\n  triaging and fix.\n\n- implement issue351: add ability to specify parametrize ids as a callable\n  to generate custom test ids.  Thanks Brianna Laugher for the idea and\n  implementation.\n\n- introduce and document new hookwrapper mechanism useful for plugins\n  which want to wrap the execution of certain hooks for their purposes.\n  This supersedes the undocumented ``__multicall__`` protocol which\n  pytest itself and some external plugins use.  Note that pytest-2.8\n  is scheduled to drop supporting the old ``__multicall__``\n  and only support the hookwrapper protocol.\n\n- majorly speed up invocation of plugin hooks\n\n- use hookwrapper mechanism in builtin pytest plugins.\n\n- add a doctest ini option for doctest flags, thanks Holger Peters.\n\n- add note to docs that if you want to mark a parameter and the\n  parameter is a callable, you also need to pass in a reason to disambiguate\n  it from the \"decorator\" case.  Thanks Tom Viner.\n\n- \"python_classes\" and \"python_functions\" options now support glob-patterns\n  for test discovery, as discussed in issue600. Thanks Ldiary Translations.\n\n- allow to override parametrized fixtures with non-parametrized ones and vice versa (bubenkoff).\n\n- fix issue463: raise specific error for 'parameterize' misspelling (pfctdayelise).\n\n- On failure, the ``sys.last_value``, ``sys.last_type`` and\n  ``sys.last_traceback`` are set, so that a user can inspect the error\n  via postmortem debugging (almarklein).\n"
  },
  {
    "path": "doc/en/announce/release-2.7.1.rst",
    "content": "pytest-2.7.1: bug fixes\n=======================\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.7.0.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n    Bruno Oliveira\n    Holger Krekel\n    Ionel Maries Cristian\n    Floris Bruynooghe\n\nHappy testing,\nThe py.test Development Team\n\n\n2.7.1 (compared to 2.7.0)\n-------------------------\n\n- fix issue731: do not get confused by the braces which may be present\n  and unbalanced in an object's repr while collapsing False\n  explanations.  Thanks Carl Meyer for the report and test case.\n\n- fix issue553: properly handling inspect.getsourcelines failures in\n  FixtureLookupError which would lead to an internal error,\n  obfuscating the original problem. Thanks talljosh for initial\n  diagnose/patch and Bruno Oliveira for final patch.\n\n- fix issue660: properly report scope-mismatch-access errors\n  independently from ordering of fixture arguments.  Also\n  avoid the pytest internal traceback which does not provide\n  information to the user. Thanks Holger Krekel.\n\n- streamlined and documented release process.  Also all versions\n  (in setup.py and documentation generation) are now read\n  from _pytest/__init__.py. Thanks Holger Krekel.\n\n- fixed docs to remove the notion that yield-fixtures are experimental.\n  They are here to stay :)  Thanks Bruno Oliveira.\n\n- Support building wheels by using environment markers for the\n  requirements.  Thanks Ionel Maries Cristian.\n\n- fixed regression to 2.6.4 which surfaced e.g. in lost stdout capture printing\n  when tests raised SystemExit. Thanks Holger Krekel.\n\n- reintroduced _pytest fixture of the pytester plugin which is used\n  at least by pytest-xdist.\n"
  },
  {
    "path": "doc/en/announce/release-2.7.2.rst",
    "content": "pytest-2.7.2: bug fixes\n=======================\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.7.1.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n    Bruno Oliveira\n    Floris Bruynooghe\n    Punyashloka Biswal\n    Aron Curzon\n    Benjamin Peterson\n    Thomas De Schampheleire\n    Edison Gustavo Muenz\n    Holger Krekel\n\nHappy testing,\nThe py.test Development Team\n\n\n2.7.2 (compared to 2.7.1)\n-----------------------------\n\n- fix issue767: pytest.raises value attribute does not contain the exception\n  instance on Python 2.6. Thanks Eric Siegerman for providing the test\n  case and Bruno Oliveira for PR.\n\n- Automatically create directory for junitxml and results log.\n  Thanks Aron Curzon.\n\n- fix issue713: JUnit XML reports for doctest failures.\n  Thanks Punyashloka Biswal.\n\n- fix issue735: assertion failures on debug versions of Python 3.4+\n  Thanks Benjamin Peterson.\n\n- fix issue114: skipif marker reports to internal skipping plugin;\n  Thanks Floris Bruynooghe for reporting and Bruno Oliveira for the PR.\n\n- fix issue748: unittest.SkipTest reports to internal pytest unittest plugin.\n  Thanks Thomas De Schampheleire for reporting and Bruno Oliveira for the PR.\n\n- fix issue718: failed to create representation of sets containing unsortable\n  elements in python 2. Thanks Edison Gustavo Muenz\n\n- fix issue756, fix issue752 (and similar issues): depend on py-1.4.29\n  which has a refined algorithm for traceback generation.\n"
  },
  {
    "path": "doc/en/announce/release-2.8.2.rst",
    "content": "pytest-2.8.2: bug fixes\n=======================\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.1.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n    Bruno Oliveira\n    Demian Brecht\n    Freya Bruhin\n    Ionel Cristian Mărieș\n    Raphael Pierzina\n    Ronny Pfannschmidt\n    holger krekel\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.2 (compared to 2.7.2)\n-----------------------------\n\n- fix #1085: proper handling of encoding errors when passing encoded byte\n  strings to pytest.parametrize in Python 2.\n  Thanks Themanwithoutaplan for the report and Bruno Oliveira for the PR.\n\n- fix #1087: handling SystemError when passing empty byte strings to\n  pytest.parametrize in Python 3.\n  Thanks Paul Kehrer for the report and Bruno Oliveira for the PR.\n\n- fix #995: fixed internal error when filtering tracebacks where one entry\n  was generated by an exec() statement.\n  Thanks Daniel Hahler, Ashley C Straw, Philippe Gauthier and Pavel Savchenko\n  for contributing and Bruno Oliveira for the PR.\n"
  },
  {
    "path": "doc/en/announce/release-2.8.3.rst",
    "content": "pytest-2.8.3: bug fixes\n=======================\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.2.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n        Bruno Oliveira\n        Freya Bruhin\n        Gabe Hollombe\n        Gabriel Reis\n        Hartmut Goebel\n        John Vandenberg\n        Lee Kamentsky\n        Michael Birtwell\n        Raphael Pierzina\n        Ronny Pfannschmidt\n        William Martin Stewart\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.3 (compared to 2.8.2)\n-----------------------------\n\n- fix #1169: add __name__ attribute to testcases in TestCaseFunction to\n  support the @unittest.skip decorator on functions and methods.\n  Thanks Lee Kamentsky for the PR.\n\n- fix #1035: collecting tests if test module level obj has __getattr__().\n  Thanks Suor for the report and Bruno Oliveira / Tom Viner for the PR.\n\n- fix #331: don't collect tests if their failure cannot be reported correctly\n  e.g. they are a callable instance of a class.\n\n- fix #1133: fixed internal error when filtering tracebacks where one entry\n  belongs to a file which is no longer available.\n  Thanks Bruno Oliveira for the PR.\n\n- enhancement made to highlight in red the name of the failing tests so\n  they stand out in the output.\n  Thanks Gabriel Reis for the PR.\n\n- add more talks to the documentation\n- extend documentation on the --ignore cli option\n- use pytest-runner for setuptools integration\n- minor fixes for interaction with OS X El Capitan system integrity protection (thanks Florian)\n"
  },
  {
    "path": "doc/en/announce/release-2.8.4.rst",
    "content": "pytest-2.8.4\n============\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.2.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n  Bruno Oliveira\n  Freya Bruhin\n  Jeff Widman\n  Mehdy Khoshnoody\n  Nicholas Chammas\n  Ronny Pfannschmidt\n  Tim Chan\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.4 (compared to 2.8.3)\n-----------------------------\n\n- fix #1190: ``deprecated_call()`` now works when the deprecated\n  function has been already called by another test in the same\n  module. Thanks Mikhail Chernykh for the report and Bruno Oliveira for the\n  PR.\n\n- fix #1198: ``--pastebin`` option now works on Python 3. Thanks\n  Mehdy Khoshnoody for the PR.\n\n- fix #1219: ``--pastebin`` now works correctly when captured output contains\n  non-ascii characters. Thanks Bruno Oliveira for the PR.\n\n- fix #1204: another error when collecting with a nasty __getattr__().\n  Thanks Freya Bruhin for the PR.\n\n- fix the summary printed when no tests did run.\n  Thanks Freya Bruhin for the PR.\n\n- a number of documentation modernizations wrt good practices.\n  Thanks Bruno Oliveira for the PR.\n"
  },
  {
    "path": "doc/en/announce/release-2.8.5.rst",
    "content": "pytest-2.8.5\n============\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.4.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n  Alex Gaynor\n  aselus-hub\n  Bruno Oliveira\n  Ronny Pfannschmidt\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.5 (compared to 2.8.4)\n-------------------------\n\n- fix #1243: fixed issue where class attributes injected during collection could break pytest.\n  PR by Alexei Kozlenok, thanks Ronny Pfannschmidt and Bruno Oliveira for the review and help.\n\n- fix #1074: precompute junitxml chunks instead of storing the whole tree in objects\n  Thanks Bruno Oliveira for the report and Ronny Pfannschmidt for the PR\n\n- fix #1238: fix ``pytest.deprecated_call()`` receiving multiple arguments\n  (Regression introduced in 2.8.4). Thanks Alex Gaynor for the report and\n  Bruno Oliveira for the PR.\n"
  },
  {
    "path": "doc/en/announce/release-2.8.6.rst",
    "content": "pytest-2.8.6\n============\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.5.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n    AMiT Kumar\n    Bruno Oliveira\n    Erik M. Bray\n    Freya Bruhin\n    Georgy Dyuldin\n    Jeff Widman\n    Kartik Singhal\n    Loïc Estève\n    Manu Phatak\n    Peter Demin\n    Rick van Hattem\n    Ronny Pfannschmidt\n    Ulrich Petri\n    foxx\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.6 (compared to 2.8.5)\n-------------------------\n\n- fix #1259: allow for double nodeids in junitxml,\n  this was a regression failing plugins combinations\n  like pytest-pep8 + pytest-flakes\n\n- Workaround for exception that occurs in pyreadline when using\n  ``--pdb`` with standard I/O capture enabled.\n  Thanks Erik M. Bray for the PR.\n\n- fix #900: Better error message in case the target of a ``monkeypatch`` call\n  raises an ``ImportError``.\n\n- fix #1292: monkeypatch calls (setattr, setenv, etc.) are now O(1).\n  Thanks David R. MacIver for the report and Bruno Oliveira for the PR.\n\n- fix #1223: captured stdout and stderr are now properly displayed before\n  entering pdb when ``--pdb`` is used instead of being thrown away.\n  Thanks Cal Leeming for the PR.\n\n- fix #1305: pytest warnings emitted during ``pytest_terminal_summary`` are now\n  properly displayed.\n  Thanks Ionel Maries Cristian for the report and Bruno Oliveira for the PR.\n\n- fix #628: fixed internal UnicodeDecodeError when doctests contain unicode.\n  Thanks Jason R. Coombs for the report and Bruno Oliveira for the PR.\n\n- fix #1334: Add captured stdout to jUnit XML report on setup error.\n  Thanks Georgy Dyuldin for the PR.\n"
  },
  {
    "path": "doc/en/announce/release-2.8.7.rst",
    "content": "pytest-2.8.7\n============\n\nThis is a hotfix release to solve a regression\nin the builtin monkeypatch plugin that got introduced in 2.8.6.\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\nThis release is supposed to be drop-in compatible to 2.8.5.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n    Ronny Pfannschmidt\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.8.7 (compared to 2.8.6)\n-------------------------\n\n- fix #1338: use predictable object resolution for monkeypatch\n"
  },
  {
    "path": "doc/en/announce/release-2.9.0.rst",
    "content": "pytest-2.9.0\n============\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n    Anatoly Bubenkov\n    Bruno Oliveira\n    Buck Golemon\n    David Vierra\n    Freya Bruhin\n    Galaczi Endre\n    Georgy Dyuldin\n    Lukas Bednar\n    Luke Murphy\n    Marcin Biernat\n    Matt Williams\n    Michael Aquilina\n    Raphael Pierzina\n    Ronny Pfannschmidt\n    Ryan Wooden\n    Tiemo Kieft\n    TomV\n    holger krekel\n    jab\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.9.0 (compared to 2.8.7)\n-------------------------\n\n**New Features**\n\n* New ``pytest.mark.skip`` mark, which unconditionally skips marked tests.\n  Thanks :user:`MichaelAquilina` for the complete PR (:pr:`1040`).\n\n* ``--doctest-glob`` may now be passed multiple times in the command-line.\n  Thanks :user:`jab` and :user:`nicoddemus` for the PR.\n\n* New ``-rp`` and ``-rP`` reporting options give the summary and full output\n  of passing tests, respectively. Thanks to :user:`codewarrior0` for the PR.\n\n* ``pytest.mark.xfail`` now has a ``strict`` option which makes ``XPASS``\n  tests to fail the test suite, defaulting to ``False``. There's also a\n  ``xfail_strict`` ini option that can be used to configure it project-wise.\n  Thanks :user:`rabbbit` for the request and :user:`nicoddemus` for the PR (:issue:`1355`).\n\n* ``Parser.addini`` now supports options of type ``bool``. Thanks\n  :user:`nicoddemus` for the PR.\n\n* New ``ALLOW_BYTES`` doctest option strips ``b`` prefixes from byte strings\n  in doctest output (similar to ``ALLOW_UNICODE``).\n  Thanks :user:`jaraco` for the request and :user:`nicoddemus` for the PR (:issue:`1287`).\n\n* give a hint on KeyboardInterrupt to use the --fulltrace option to show the errors,\n  this fixes :issue:`1366`.\n  Thanks to :user:`hpk42` for the report and :user:`RonnyPfannschmidt` for the PR.\n\n* catch IndexError exceptions when getting exception source location. This fixes\n  pytest internal error for dynamically generated code (fixtures and tests)\n  where source lines are fake by intention\n\n**Changes**\n\n* **Important**: `py.code <https://pylib.readthedocs.io/en/stable/code.html>`_ has been\n  merged into the ``pytest`` repository as ``pytest._code``. This decision\n  was made because ``py.code`` had very few uses outside ``pytest`` and the\n  fact that it was in a different repository made it difficult to fix bugs on\n  its code in a timely manner. The team hopes with this to be able to better\n  refactor out and improve that code.\n  This change shouldn't affect users, but it is useful to let users aware\n  if they encounter any strange behavior.\n\n  Keep in mind that the code for ``pytest._code`` is **private** and\n  **experimental**, so you definitely should not import it explicitly!\n\n  Please note that the original ``py.code`` is still available in\n  `pylib <https://pylib.readthedocs.io/en/stable/>`_.\n\n* ``pytest_enter_pdb`` now optionally receives the pytest config object.\n  Thanks :user:`nicoddemus` for the PR.\n\n* Removed code and documentation for Python 2.5 or lower versions,\n  including removal of the obsolete ``_pytest.assertion.oldinterpret`` module.\n  Thanks :user:`nicoddemus` for the PR (:issue:`1226`).\n\n* Comparisons now always show up in full when ``CI`` or ``BUILD_NUMBER`` is\n  found in the environment, even when -vv isn't used.\n  Thanks :user:`The-Compiler` for the PR.\n\n* ``--lf`` and ``--ff`` now support long names: ``--last-failed`` and\n  ``--failed-first`` respectively.\n  Thanks :user:`MichaelAquilina` for the PR.\n\n* Added expected exceptions to pytest.raises fail message\n\n* Collection only displays progress (\"collecting X items\") when in a terminal.\n  This avoids cluttering the output when using ``--color=yes`` to obtain\n  colors in CI integrations systems (:issue:`1397`).\n\n**Bug Fixes**\n\n* The ``-s`` and ``-c`` options should now work under ``xdist``;\n  ``Config.fromdictargs`` now represents its input much more faithfully.\n  Thanks to :user:`bukzor` for the complete PR (:issue:`680`).\n\n* Fix (:issue:`1290`): support Python 3.5's ``@`` operator in assertion rewriting.\n  Thanks :user:`Shinkenjoe` for report with test case and :user:`tomviner` for the PR.\n\n* Fix formatting utf-8 explanation messages (:issue:`1379`).\n  Thanks :user:`biern` for the PR.\n\n* Fix `traceback style docs`_ to describe all of the available options\n  (auto/long/short/line/native/no), with ``auto`` being the default since v2.6.\n  Thanks :user:`hackebrot` for the PR.\n\n* Fix (:issue:`1422`): junit record_xml_property doesn't allow multiple records\n  with same name.\n\n\n.. _`traceback style docs`: https://pytest.org/en/stable/how-to/output.html#modifying-python-traceback-printing\n"
  },
  {
    "path": "doc/en/announce/release-2.9.1.rst",
    "content": "pytest-2.9.1\n============\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n    Bruno Oliveira\n    Daniel Hahler\n    Dmitry Malinovsky\n    Freya Bruhin\n    Floris Bruynooghe\n    Matt Bachmann\n    Ronny Pfannschmidt\n    TomV\n    Vladimir Bolshakov\n    Zearin\n    palaviv\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.9.1 (compared to 2.9.0)\n-------------------------\n\n**Bug Fixes**\n\n* Improve error message when a plugin fails to load.\n  Thanks :user:`nicoddemus` for the PR.\n\n* Fix (:issue:`1178`):\n  ``pytest.fail`` with non-ascii characters raises an internal pytest error.\n  Thanks :user:`nicoddemus` for the PR.\n\n* Fix (:issue:`469`): junit parses report.nodeid incorrectly, when params IDs\n  contain ``::``. Thanks :user:`tomviner` for the PR (:pr:`1431`).\n\n* Fix (:issue:`578`): SyntaxErrors\n  containing non-ascii lines at the point of failure generated an internal\n  py.test error.\n  Thanks :user:`asottile` for the report and :user:`nicoddemus` for the PR.\n\n* Fix (:issue:`1437`): When passing in a bytestring regex pattern to parameterize\n  attempt to decode it as utf-8 ignoring errors.\n\n* Fix (:issue:`649`): parametrized test nodes cannot be specified to run on the command line.\n"
  },
  {
    "path": "doc/en/announce/release-2.9.2.rst",
    "content": "pytest-2.9.2\n============\n\npytest is a mature Python testing tool with more than 1100 tests\nagainst itself, passing on many different interpreters and platforms.\n\nSee below for the changes and see docs at:\n\n    http://pytest.org\n\nAs usual, you can upgrade from pypi via::\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n      Adam Chainz\n      Benjamin Dopplinger\n      Bruno Oliveira\n      Freya Bruhin\n      John Towler\n      Martin Prusse\n      Meng Jue\n      MengJueM\n      Omar Kohl\n      Quentin Pradet\n      Ronny Pfannschmidt\n      Thomas Güttler\n      TomV\n      Tyler Goodlet\n\n\nHappy testing,\nThe py.test Development Team\n\n\n2.9.2 (compared to 2.9.1)\n---------------------------\n\n**Bug Fixes**\n\n* fix :issue:`510`: skip tests where one parameterize dimension was empty\n  thanks Alex Stapleton for the Report and :user:`RonnyPfannschmidt` for the PR\n\n* Fix Xfail does not work with condition keyword argument.\n  Thanks :user:`astraw38` for reporting the issue (:issue:`1496`) and :user:`tomviner`\n  for PR the (:pr:`1524`).\n\n* Fix win32 path issue when putting custom config file with absolute path\n  in ``pytest.main(\"-c your_absolute_path\")``.\n\n* Fix maximum recursion depth detection when raised error class is not aware\n  of unicode/encoded bytes.\n  Thanks :user:`prusse-martin` for the PR (:pr:`1506`).\n\n* Fix ``pytest.mark.skip`` mark when used in strict mode.\n  Thanks :user:`pquentin` for the PR and :user:`RonnyPfannschmidt` for\n  showing how to fix the bug.\n\n* Minor improvements and fixes to the documentation.\n  Thanks :user:`omarkohl` for the PR.\n\n* Fix ``--fixtures`` to show all fixture definitions as opposed to just\n  one per fixture name.\n  Thanks to :user:`hackebrot` for the PR.\n"
  },
  {
    "path": "doc/en/announce/release-3.0.0.rst",
    "content": "pytest-3.0.0\n============\n\nThe pytest team is proud to announce the 3.0.0 release!\n\npytest is a mature Python testing tool with more than 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a lot of bugs fixes and improvements, and much of\nthe work done on it was possible because of the 2016 Sprint[1], which\nwas funded by an indiegogo campaign which raised over US$12,000 with\nnearly 100 backers.\n\nThere's a \"What's new in pytest 3.0\" [2] blog post highlighting the\nmajor features in this release.\n\nTo see the complete changelog and documentation, please visit:\n\n    http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n    AbdealiJK\n    Ana Ribeiro\n    Antony Lee\n    Brandon W Maister\n    Brianna Laugher\n    Bruno Oliveira\n    Ceridwen\n    Christian Boelsen\n    Daniel Hahler\n    Danielle Jenkins\n    Dave Hunt\n    Diego Russo\n    Dmitry Dygalo\n    Edoardo Batini\n    Eli Boyarski\n    Freya Bruhin\n    Floris Bruynooghe\n    Greg Price\n    Guyzmo\n    HEAD KANGAROO\n    JJ\n    Javi Romero\n    Javier Domingo Cansino\n    Kale Kundert\n    Kalle Bronsen\n    Marius Gedminas\n    Matt Williams\n    Mike Lundy\n    Oliver Bestwalter\n    Omar Kohl\n    Raphael Pierzina\n    RedBeardCode\n    Roberto Polli\n    Romain Dorgueil\n    Roman Bolshakov\n    Ronny Pfannschmidt\n    Stefan Zimmermann\n    Steffen Allner\n    Tareq Alayan\n    Ted Xiao\n    Thomas Grainger\n    Tom Viner\n    TomV\n    Vasily Kuznetsov\n    aostr\n    marscher\n    palaviv\n    satoru\n    taschini\n\n\nHappy testing,\nThe Pytest Development Team\n\n[1] http://blog.pytest.org/2016/pytest-development-sprint/\n[2] http://blog.pytest.org/2016/whats-new-in-pytest-30/\n"
  },
  {
    "path": "doc/en/announce/release-3.0.1.rst",
    "content": "pytest-3.0.1\n============\n\npytest 3.0.1 has just been released to PyPI.\n\nThis release fixes some regressions reported in version 3.0.0, being a\ndrop-in replacement. To upgrade:\n\n  pip install --upgrade pytest\n\nThe changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n      Adam Chainz\n      Andrew Svetlov\n      Bruno Oliveira\n      Daniel Hahler\n      Dmitry Dygalo\n      Freya Bruhin\n      Marcin Bachry\n      Ronny Pfannschmidt\n      matthiasha\n\nHappy testing,\nThe py.test Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.0.2.rst",
    "content": "pytest-3.0.2\n============\n\npytest 3.0.2 has just been released to PyPI.\n\nThis release fixes some regressions and bugs reported in version 3.0.1, being a\ndrop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Ahn Ki-Wook\n* Bruno Oliveira\n* Freya Bruhin\n* Jordan Guymon\n* Raphael Pierzina\n* Ronny Pfannschmidt\n* mbyt\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.0.3.rst",
    "content": "pytest-3.0.3\n============\n\npytest 3.0.3 has just been released to PyPI.\n\nThis release fixes some regressions and bugs reported in the last version,\nbeing a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Freya Bruhin\n* Floris Bruynooghe\n* Huayi Zhang\n* Lev Maximov\n* Raquel Alegre\n* Ronny Pfannschmidt\n* Roy Williams\n* Tyler Goodlet\n* mbyt\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.0.4.rst",
    "content": "pytest-3.0.4\n============\n\npytest 3.0.4 has just been released to PyPI.\n\nThis release fixes some regressions and bugs reported in the last version,\nbeing a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Dan Wandschneider\n* Freya Bruhin\n* Georgy Dyuldin\n* Grigorii Eremeev\n* Jason R. Coombs\n* Manuel Jacob\n* Mathieu Clabaut\n* Michael Seifert\n* Nikolaus Rath\n* Ronny Pfannschmidt\n* Tom V\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.0.5.rst",
    "content": "pytest-3.0.5\n============\n\npytest 3.0.5 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Ana Vojnovic\n* Bruno Oliveira\n* Daniel Hahler\n* Duncan Betts\n* Igor Starikov\n* Ismail\n* Luke Murphy\n* Ned Batchelder\n* Ronny Pfannschmidt\n* Sebastian Ramacher\n* nmundar\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.0.6.rst",
    "content": "pytest-3.0.6\n============\n\npytest 3.0.6 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\n\nThanks to all who contributed to this release, among them:\n\n* Andreas Pelme\n* Bruno Oliveira\n* Dmitry Malinovsky\n* Eli Boyarski\n* Jakub Wilk\n* Jeff Widman\n* Loïc Estève\n* Luke Murphy\n* Miro Hrončok\n* Oscar Hellström\n* Peter Heatwole\n* Philippe Ombredanne\n* Ronny Pfannschmidt\n* Rutger Prins\n* Stefan Scherfke\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.0.7.rst",
    "content": "pytest-3.0.7\n============\n\npytest 3.0.7 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Barney Gale\n* Bruno Oliveira\n* Freya Bruhin\n* Floris Bruynooghe\n* Ionel Cristian Mărieș\n* Katerina Koukiou\n* NODA, Kai\n* Omer Hadari\n* Patrick Hayes\n* Ran Benita\n* Ronny Pfannschmidt\n* Victor Uriarte\n* Vidar Tonaas Fauske\n* Ville Skyttä\n* fbjorn\n* mbyt\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.1.0.rst",
    "content": "pytest-3.1.0\n=======================================\n\nThe pytest team is proud to announce the 3.1.0 release!\n\npytest is a mature Python testing tool with more than 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\nhttp://doc.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Ben Lloyd\n* Bruno Oliveira\n* David Giese\n* David Szotten\n* Dmitri Pribysh\n* Freya Bruhin\n* Florian Schulze\n* Floris Bruynooghe\n* John Towler\n* Jonas Obrist\n* Katerina Koukiou\n* Kodi Arfer\n* Krzysztof Szularz\n* Lev Maximov\n* Loïc Estève\n* Luke Murphy\n* Manuel Krebber\n* Matthew Duck\n* Matthias Bussonnier\n* Michael Howitz\n* Michal Wajszczuk\n* Paweł Adamczak\n* Rafael Bertoldi\n* Ravi Chandra\n* Ronny Pfannschmidt\n* Skylar Downes\n* Thomas Kriechbaumer\n* Vitaly Lashmanov\n* Vlad Dragos\n* Wheerd\n* Xander Johnson\n* mandeep\n* reut\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.1.1.rst",
    "content": "pytest-3.1.1\n=======================================\n\npytest 3.1.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Freya Bruhin\n* Floris Bruynooghe\n* Jason R. Coombs\n* Ronny Pfannschmidt\n* wanghui\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.1.2.rst",
    "content": "pytest-3.1.2\n=======================================\n\npytest 3.1.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andreas Pelme\n* ApaDoctor\n* Bruno Oliveira\n* Freya Bruhin\n* Ronny Pfannschmidt\n* Segev Finer\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.1.3.rst",
    "content": "pytest-3.1.3\n=======================================\n\npytest 3.1.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Antoine Legrand\n* Bruno Oliveira\n* Max Moroz\n* Raphael Pierzina\n* Ronny Pfannschmidt\n* Ryan Fitzpatrick\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.10.0.rst",
    "content": "pytest-3.10.0\n=======================================\n\nThe pytest team is proud to announce the 3.10.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anders Hovmöller\n* Andreu Vallbona Plazas\n* Ankit Goel\n* Anthony Sottile\n* Bernardo Gomes\n* Brianna Laugher\n* Bruno Oliveira\n* Daniel Hahler\n* David Szotten\n* Mick Koch\n* Niclas Olofsson\n* Palash Chatterjee\n* Ronny Pfannschmidt\n* Sven-Hendrik Haase\n* Ville Skyttä\n* William Jamir Silva\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.10.1.rst",
    "content": "pytest-3.10.1\n=======================================\n\npytest 3.10.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Boris Feld\n* Bruno Oliveira\n* Daniel Hahler\n* Fabien ZARIFIAN\n* Jon Dufresne\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.2.0.rst",
    "content": "pytest-3.2.0\n=======================================\n\nThe pytest team is proud to announce the 3.2.0 release!\n\npytest is a mature Python testing tool with more than 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    http://doc.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Alex Hartoto\n* Andras Tim\n* Bruno Oliveira\n* Daniel Hahler\n* Freya Bruhin\n* Floris Bruynooghe\n* John Still\n* Jordan Moldow\n* Kale Kundert\n* Lawrence Mitchell\n* Llandy Riveron Del Risco\n* Maik Figura\n* Martin Altmayer\n* Mihai Capotă\n* Nathaniel Waisbrot\n* Nguyễn Hồng Quân\n* Pauli Virtanen\n* Raphael Pierzina\n* Ronny Pfannschmidt\n* Segev Finer\n* V.Kuznetsov\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.2.1.rst",
    "content": "pytest-3.2.1\n=======================================\n\npytest 3.2.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Alex Gaynor\n* Bruno Oliveira\n* Freya Bruhin\n* Ronny Pfannschmidt\n* Srinivas Reddy Thatiparthy\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.2.2.rst",
    "content": "pytest-3.2.2\n=======================================\n\npytest 3.2.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andreas Pelme\n* Antonio Hidalgo\n* Bruno Oliveira\n* Felipe Dau\n* Fernando Macedo\n* Jesús Espino\n* Joan Massich\n* Joe Talbott\n* Kirill Pinchuk\n* Ronny Pfannschmidt\n* Xuan Luong\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.2.3.rst",
    "content": "pytest-3.2.3\n=======================================\n\npytest 3.2.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Evan\n* Joe Hamman\n* Oliver Bestwalter\n* Ronny Pfannschmidt\n* Xuan Luong\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.2.4.rst",
    "content": "pytest-3.2.4\n=======================================\n\npytest 3.2.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Christian Boelsen\n* Christoph Buchner\n* Daw-Ran Liou\n* Freya Bruhin\n* Franck Michea\n* Leonard Lausen\n* Matty G\n* Owen Tuz\n* Pavel Karateev\n* Pierre GIRAUD\n* Ronny Pfannschmidt\n* Stephen Finucane\n* Sviatoslav Abakumov\n* Thomas Hisch\n* Tom Dalton\n* Xuan Luong\n* Yorgos Pagles\n* Семён Марьясин\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.2.5.rst",
    "content": "pytest-3.2.5\n=======================================\n\npytest 3.2.5 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.3.0.rst",
    "content": "pytest-3.3.0\n=======================================\n\nThe pytest team is proud to announce the 3.3.0 release!\n\npytest is a mature Python testing tool with more than 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    http://doc.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Ceridwen\n* Daniel Hahler\n* Dirk Thomas\n* Dmitry Malinovsky\n* Freya Bruhin\n* George Y. Kussumoto\n* Hugo\n* Jesús Espino\n* Joan Massich\n* Ofir\n* OfirOshir\n* Ronny Pfannschmidt\n* Samuel Dion-Girardeau\n* Srinivas Reddy Thatiparthy\n* Sviatoslav Abakumov\n* Tarcisio Fischer\n* Thomas Hisch\n* Tyler Goodlet\n* hugovk\n* je\n* prokaktus\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.3.1.rst",
    "content": "pytest-3.3.1\n=======================================\n\npytest 3.3.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Daniel Hahler\n* Eugene Prikazchikov\n* Freya Bruhin\n* Roland Puntaier\n* Ronny Pfannschmidt\n* Sebastian Rahlf\n* Tom Viner\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.3.2.rst",
    "content": "pytest-3.3.2\n=======================================\n\npytest 3.3.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Antony Lee\n* Austin\n* Bruno Oliveira\n* Freya Bruhin\n* Floris Bruynooghe\n* Henk-Jaap Wagenaar\n* Jurko Gospodnetić\n* Ronny Pfannschmidt\n* Srinivas Reddy Thatiparthy\n* Thomas Hisch\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.4.0.rst",
    "content": "pytest-3.4.0\n=======================================\n\nThe pytest team is proud to announce the 3.4.0 release!\n\npytest is a mature Python testing tool with more than 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    http://doc.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Aaron\n* Alan Velasco\n* Anders Hovmöller\n* Andrew Toolan\n* Anthony Sottile\n* Aron Coyle\n* Brian Maissy\n* Bruno Oliveira\n* Cyrus Maden\n* Freya Bruhin\n* Henk-Jaap Wagenaar\n* Ian Lesperance\n* Jon Dufresne\n* Jurko Gospodnetić\n* Kate\n* Kimberly\n* Per A. Brodtkorb\n* Pierre-Alexandre Fonta\n* Raphael Castaneda\n* Ronny Pfannschmidt\n* ST John\n* Segev Finer\n* Thomas Hisch\n* Tzu-ping Chung\n* feuillemorte\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.4.1.rst",
    "content": "pytest-3.4.1\n=======================================\n\npytest 3.4.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Aaron\n* Alan Velasco\n* Andy Freeland\n* Brian Maissy\n* Bruno Oliveira\n* Freya Bruhin\n* Jason R. Coombs\n* Marcin Bachry\n* Pedro Algarvio\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.4.2.rst",
    "content": "pytest-3.4.2\n=======================================\n\npytest 3.4.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Allan Feldman\n* Bruno Oliveira\n* Freya Bruhin\n* Jason R. Coombs\n* Kyle Altendorf\n* Maik Figura\n* Ronny Pfannschmidt\n* codetriage-readme-bot\n* feuillemorte\n* joshm91\n* mike\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.5.0.rst",
    "content": "pytest-3.5.0\n=======================================\n\nThe pytest team is proud to announce the 3.5.0 release!\n\npytest is a mature Python testing tool with more than 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    http://doc.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Allan Feldman\n* Brian Maissy\n* Bruno Oliveira\n* Carlos Jenkins\n* Daniel Hahler\n* Freya Bruhin\n* Jason R. Coombs\n* Jeffrey Rackauckas\n* Jordan Speicher\n* Julien Palard\n* Kale Kundert\n* Kostis Anagnostopoulos\n* Kyle Altendorf\n* Maik Figura\n* Pedro Algarvio\n* Ronny Pfannschmidt\n* Tadeu Manoel\n* Tareq Alayan\n* Thomas Hisch\n* William Lee\n* codetriage-readme-bot\n* feuillemorte\n* joshm91\n* mike\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.5.1.rst",
    "content": "pytest-3.5.1\n=======================================\n\npytest 3.5.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Brian Maissy\n* Bruno Oliveira\n* Darren Burns\n* David Chudzicki\n* Floris Bruynooghe\n* Holger Kohr\n* Irmen de Jong\n* Jeffrey Rackauckas\n* Rachel Kogan\n* Ronny Pfannschmidt\n* Stefan Scherfke\n* Tim Strazny\n* Семён Марьясин\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.6.0.rst",
    "content": "pytest-3.6.0\n=======================================\n\nThe pytest team is proud to announce the 3.6.0 release!\n\npytest is a mature Python testing tool with more than 1600 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    http://doc.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Shaw\n* ApaDoctor\n* Brian Maissy\n* Bruno Oliveira\n* Jon Dufresne\n* Katerina Koukiou\n* Miro Hrončok\n* Rachel Kogan\n* Ronny Pfannschmidt\n* Tim Hughes\n* Tyler Goodlet\n* Ville Skyttä\n* aviral1701\n* feuillemorte\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.6.1.rst",
    "content": "pytest-3.6.1\n=======================================\n\npytest 3.6.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Jeffrey Rackauckas\n* Miro Hrončok\n* Niklas Meinzer\n* Oliver Bestwalter\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.6.2.rst",
    "content": "pytest-3.6.2\n=======================================\n\npytest 3.6.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Alan Velasco\n* Alex Barbato\n* Anthony Sottile\n* Bartosz Cierocki\n* Bruno Oliveira\n* Daniel Hahler\n* Guoqiang Zhang\n* Hynek Schlawack\n* John T. Wodder II\n* Michael Käufl\n* Ronny Pfannschmidt\n* Samuel Dion-Girardeau\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.6.3.rst",
    "content": "pytest-3.6.3\n=======================================\n\npytest 3.6.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* AdamEr8\n* Anthony Sottile\n* Bruno Oliveira\n* Jean-Paul Calderone\n* Jon Dufresne\n* Marcelo Duarte Trevisani\n* Ondřej Súkup\n* Ronny Pfannschmidt\n* T.E.A de Souza\n* Victor Maryama\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.6.4.rst",
    "content": "pytest-3.6.4\n=======================================\n\npytest 3.6.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bernhard M. Wiedemann\n* Bruno Oliveira\n* Drew\n* E Hershey\n* Hugo Martins\n* Vlad Shcherbina\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.7.0.rst",
    "content": "pytest-3.7.0\n=======================================\n\nThe pytest team is proud to announce the 3.7.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    http://doc.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    http://docs.pytest.org\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Alan\n* Alan Brammer\n* Ammar Najjar\n* Anthony Sottile\n* Bruno Oliveira\n* Jeffrey Rackauckas\n* Kale Kundert\n* Ronny Pfannschmidt\n* Serhii Mozghovyi\n* Tadek Teleżyński\n* Wil Cooley\n* abrammer\n* avirlrma\n* turturica\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.7.1.rst",
    "content": "pytest-3.7.1\n=======================================\n\npytest 3.7.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Kale Kundert\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.7.2.rst",
    "content": "pytest-3.7.2\n=======================================\n\npytest 3.7.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Josh Holland\n* Ronny Pfannschmidt\n* Sankt Petersbug\n* Wes Thomas\n* turturica\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.7.3.rst",
    "content": "pytest-3.7.3\n=======================================\n\npytest 3.7.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at http://doc.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andrew Champion\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Gandalf Saxe\n* Jennifer Rinker\n* Natan Lao\n* Ondřej Súkup\n* Ronny Pfannschmidt\n* Sankt Petersbug\n* Tyler Richard\n* Victor Maryama\n* Vlad Shcherbina\n* turturica\n* wim glenn\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.7.4.rst",
    "content": "pytest-3.7.4\n=======================================\n\npytest 3.7.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Jiri Kuncar\n* Steve Piercy\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.8.0.rst",
    "content": "pytest-3.8.0\n=======================================\n\nThe pytest team is proud to announce the 3.8.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* CrazyMerlyn\n* Daniel Hahler\n* Fabio Zadrozny\n* Jeffrey Rackauckas\n* Ronny Pfannschmidt\n* Virgil Dupras\n* dhirensr\n* hoefling\n* wim glenn\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.8.1.rst",
    "content": "pytest-3.8.1\n=======================================\n\npytest 3.8.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Ankit Goel\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Maximilian Albert\n* Ronny Pfannschmidt\n* William Jamir Silva\n* wim glenn\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.8.2.rst",
    "content": "pytest-3.8.2\n=======================================\n\npytest 3.8.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Ankit Goel\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Denis Otkidach\n* Harry Percival\n* Jeffrey Rackauckas\n* Jose Carlos Menezes\n* Ronny Pfannschmidt\n* Zac Hatfield-Dodds\n* iwanb\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.9.0.rst",
    "content": "pytest-3.9.0\n=======================================\n\nThe pytest team is proud to announce the 3.9.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Andrea Cimatoribus\n* Ankit Goel\n* Anthony Sottile\n* Ben Eyal\n* Bruno Oliveira\n* Daniel Hahler\n* Jeffrey Rackauckas\n* Jose Carlos Menezes\n* Kyle Altendorf\n* Niklas JQ\n* Palash Chatterjee\n* Ronny Pfannschmidt\n* Thomas Hess\n* Thomas Hisch\n* Tomer Keren\n* Victor Maryama\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.9.1.rst",
    "content": "pytest-3.9.1\n=======================================\n\npytest 3.9.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Ronny Pfannschmidt\n* Thomas Hisch\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.9.2.rst",
    "content": "pytest-3.9.2\n=======================================\n\npytest 3.9.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Ankit Goel\n* Anthony Sottile\n* Bruno Oliveira\n* Ronny Pfannschmidt\n* Vincent Barbaresi\n* ykantor\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-3.9.3.rst",
    "content": "pytest-3.9.3\n=======================================\n\npytest 3.9.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andreas Profous\n* Ankit Goel\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Jon Dufresne\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.0.0.rst",
    "content": "pytest-4.0.0\n=======================================\n\nThe pytest team is proud to announce the 4.0.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Daniel Hahler\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.0.1.rst",
    "content": "pytest-4.0.1\n=======================================\n\npytest 4.0.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Michael D. Hoyle\n* Ronny Pfannschmidt\n* Slam\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.0.2.rst",
    "content": "pytest-4.0.2\n=======================================\n\npytest 4.0.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Pedro Algarvio\n* Ronny Pfannschmidt\n* Tomer Keren\n* Yash Todi\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.1.0.rst",
    "content": "pytest-4.1.0\n=======================================\n\nThe pytest team is proud to announce the 4.1.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Adam Johnson\n* Aly Sivji\n* Andrey Paramonov\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* David Vo\n* Hyunchel Kim\n* Jeffrey Rackauckas\n* Kanguros\n* Nicholas Devenish\n* Pedro Algarvio\n* Randy Barlow\n* Ronny Pfannschmidt\n* Tomer Keren\n* feuillemorte\n* wim glenn\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.1.1.rst",
    "content": "pytest-4.1.1\n=======================================\n\npytest 4.1.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Anton Lodder\n* Bruno Oliveira\n* Daniel Hahler\n* David Vo\n* Oscar Benjamin\n* Ronny Pfannschmidt\n* Victor Maryama\n* Yoav Caspi\n* dmitry.dygalo\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.2.0.rst",
    "content": "pytest-4.2.0\n=======================================\n\nThe pytest team is proud to announce the 4.2.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Adam Uhlir\n* Anthony Sottile\n* Bruno Oliveira\n* Christopher Dignam\n* Daniel Hahler\n* Joseph Hunkeler\n* Kristoffer Nordstroem\n* Ronny Pfannschmidt\n* Thomas Hisch\n* wim glenn\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.2.1.rst",
    "content": "pytest-4.2.1\n=======================================\n\npytest 4.2.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Arel Cordero\n* Bruno Oliveira\n* Daniel Hahler\n* Holger Kohr\n* Kevin J. Foley\n* Nick Murphy\n* Paweł Stradomski\n* Raphael Pierzina\n* Ronny Pfannschmidt\n* Sam Brightman\n* Thomas Hisch\n* Zac Hatfield-Dodds\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.3.0.rst",
    "content": "pytest-4.3.0\n=======================================\n\nThe pytest team is proud to announce the 4.3.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Andras Mitzki\n* Anthony Sottile\n* Bruno Oliveira\n* Christian Fetzer\n* Daniel Hahler\n* Grygorii Iermolenko\n* R. Alex Matevish\n* Ronny Pfannschmidt\n* cclauss\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.3.1.rst",
    "content": "pytest-4.3.1\n=======================================\n\npytest 4.3.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andras Mitzki\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Danilo Horta\n* Grygorii Iermolenko\n* Jeff Hale\n* Kyle Altendorf\n* Stephan Hoyer\n* Zac Hatfield-Dodds\n* songbowen\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.4.0.rst",
    "content": "pytest-4.4.0\n=======================================\n\nThe pytest team is proud to announce the 4.4.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* ApaDoctor\n* Bernhard M. Wiedemann\n* Brian Skinn\n* Bruno Oliveira\n* Daniel Hahler\n* Gary Tyler\n* Jeong YunWon\n* Miro Hrončok\n* Takafumi Arakaki\n* henrykironde\n* smheidrich\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.4.1.rst",
    "content": "pytest-4.4.1\n=======================================\n\npytest 4.4.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.4.2.rst",
    "content": "pytest-4.4.2\n=======================================\n\npytest 4.4.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Allan Lewis\n* Anthony Sottile\n* Bruno Oliveira\n* DamianSkrzypczak\n* Daniel Hahler\n* Don Kirkby\n* Douglas Thor\n* Hugo\n* Ilya Konstantinov\n* Jon Dufresne\n* Matt Cooper\n* Nikolay Kondratyev\n* Ondřej Súkup\n* Peter Schutt\n* Romain Chossart\n* Sitaktif\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.5.0.rst",
    "content": "pytest-4.5.0\n=======================================\n\nThe pytest team is proud to announce the 4.5.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Floris Bruynooghe\n* Pulkit Goyal\n* Samuel Searles-Bryant\n* Zac Hatfield-Dodds\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.6.0.rst",
    "content": "pytest-4.6.0\n=======================================\n\nThe pytest team is proud to announce the 4.6.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Akiomi Kamakura\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* David Röthlisberger\n* Evan Kepner\n* Jeffrey Rackauckas\n* MyComputer\n* Nikita Krokosh\n* Raul Tambre\n* Thomas Hisch\n* Tim Hoffmann\n* Tomer Keren\n* Victor Maryama\n* danielx123\n* oleg-yegorov\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.6.1.rst",
    "content": "pytest-4.6.1\n=======================================\n\npytest 4.6.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.6.2.rst",
    "content": "pytest-4.6.2\n=======================================\n\npytest 4.6.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.6.3.rst",
    "content": "pytest-4.6.3\n=======================================\n\npytest 4.6.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Dirk Thomas\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.6.4.rst",
    "content": "pytest-4.6.4\n=======================================\n\npytest 4.6.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Thomas Grainger\n* Zac Hatfield-Dodds\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.6.5.rst",
    "content": "pytest-4.6.5\n=======================================\n\npytest 4.6.5 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Thomas Grainger\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.6.6.rst",
    "content": "pytest-4.6.6\n=======================================\n\npytest 4.6.6 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Michael Goerz\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.6.7.rst",
    "content": "pytest-4.6.7\n=======================================\n\npytest 4.6.7 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Daniel Hahler\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.6.8.rst",
    "content": "pytest-4.6.8\n=======================================\n\npytest 4.6.8 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Ryan Mast\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-4.6.9.rst",
    "content": "pytest-4.6.9\n=======================================\n\npytest 4.6.9 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Felix Yan\n* Hugo\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.0.0.rst",
    "content": "pytest-5.0.0\n=======================================\n\nThe pytest team is proud to announce the 5.0.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Dirk Thomas\n* Evan Kepner\n* Freya Bruhin\n* Hugo\n* Kevin J. Foley\n* Pulkit Goyal\n* Ralph Giles\n* Ronny Pfannschmidt\n* Thomas Grainger\n* Thomas Hisch\n* Tim Gates\n* Victor Maryama\n* Yuri Apollov\n* Zac Hatfield-Dodds\n* curiousjazz77\n* patriksevallius\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.0.1.rst",
    "content": "pytest-5.0.1\n=======================================\n\npytest 5.0.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* AmirElkess\n* Andreu Vallbona Plazas\n* Anthony Sottile\n* Bruno Oliveira\n* Freya Bruhin\n* Michael Moore\n* Niklas Meinzer\n* Thomas Grainger\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.1.0.rst",
    "content": "pytest-5.1.0\n=======================================\n\nThe pytest team is proud to announce the 5.1.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Albert Tugushev\n* Alexey Zankevich\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* David Röthlisberger\n* Freya Bruhin\n* Ilya Stepin\n* Jon Dufresne\n* Kaiqi\n* Max R\n* Miro Hrončok\n* Oliver Bestwalter\n* Ran Benita\n* Ronny Pfannschmidt\n* Samuel Searles-Bryant\n* Semen Zhydenko\n* Steffen Schroeder\n* Thomas Grainger\n* Tim Hoffmann\n* William Woodall\n* Wojtek Erbetowski\n* Xixi Zhao\n* Yash Todi\n* boris\n* dmitry.dygalo\n* helloocc\n* martbln\n* mei-li\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.1.1.rst",
    "content": "pytest-5.1.1\n=======================================\n\npytest 5.1.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Freya Bruhin\n* Hugo van Kemenade\n* Ran Benita\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.1.2.rst",
    "content": "pytest-5.1.2\n=======================================\n\npytest 5.1.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Andrzej Klajnert\n* Anthony Sottile\n* Bruno Oliveira\n* Christian Neumüller\n* Robert Holt\n* linchiwei123\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.1.3.rst",
    "content": "pytest-5.1.3\n=======================================\n\npytest 5.1.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Christian Neumüller\n* Daniel Hahler\n* Gene Wood\n* Hugo\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.2.0.rst",
    "content": "pytest-5.2.0\n=======================================\n\nThe pytest team is proud to announce the 5.2.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Andrzej Klajnert\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* James Cooke\n* Michael Goerz\n* Ran Benita\n* Tomáš Chvátal\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.2.1.rst",
    "content": "pytest-5.2.1\n=======================================\n\npytest 5.2.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Freya Bruhin\n* Hynek Schlawack\n* Kevin J. Foley\n* tadashigaki\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.2.2.rst",
    "content": "pytest-5.2.2\n=======================================\n\npytest 5.2.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Albert Tugushev\n* Andrzej Klajnert\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Freya Bruhin\n* Nattaphoom Chaipreecha\n* Oliver Bestwalter\n* Philipp Loose\n* Ran Benita\n* Victor Maryama\n* Yoav Caspi\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.2.3.rst",
    "content": "pytest-5.2.3\n=======================================\n\npytest 5.2.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Brett Cannon\n* Bruno Oliveira\n* Daniel Hahler\n* Daniil Galiev\n* David Szotten\n* Freya Bruhin\n* Patrick Harmon\n* Ran Benita\n* Zac Hatfield-Dodds\n* Zak Hassan\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.2.4.rst",
    "content": "pytest-5.2.4\n=======================================\n\npytest 5.2.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Hugo\n* Michael Shields\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.3.0.rst",
    "content": "pytest-5.3.0\n=======================================\n\nThe pytest team is proud to announce the 5.3.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bugs fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from pypi via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* AnjoMan\n* Anthony Sottile\n* Anton Lodder\n* Bruno Oliveira\n* Daniel Hahler\n* Gregory Lee\n* Josh Karpel\n* JoshKarpel\n* Joshua Storck\n* Kale Kundert\n* MarcoGorelli\n* Michael Krebs\n* NNRepos\n* Ran Benita\n* TH3CHARLie\n* Tibor Arpas\n* Zac Hatfield-Dodds\n* 林玮\n\n\nHappy testing,\nThe Pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.3.1.rst",
    "content": "pytest-5.3.1\n=======================================\n\npytest 5.3.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Felix Yan\n* Freya Bruhin\n* Mark Dickinson\n* Nikolay Kondratyev\n* Steffen Schroeder\n* Zac Hatfield-Dodds\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.3.2.rst",
    "content": "pytest-5.3.2\n=======================================\n\npytest 5.3.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Claudio Madotto\n* Daniel Hahler\n* Jared Vasquez\n* Michael Rose\n* Ran Benita\n* Ronny Pfannschmidt\n* Zac Hatfield-Dodds\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.3.3.rst",
    "content": "pytest-5.3.3\n=======================================\n\npytest 5.3.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Adam Johnson\n* Alexandre Mulatinho\n* Anthony Sottile\n* Bruno Oliveira\n* Chris NeJame\n* Daniel Hahler\n* Hugo van Kemenade\n* Marcelo Duarte Trevisani\n* PaulC\n* Ran Benita\n* Ryan Barner\n* Seth Junot\n* marc\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.3.4.rst",
    "content": "pytest-5.3.4\n=======================================\n\npytest 5.3.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Daniel Hahler\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.3.5.rst",
    "content": "pytest-5.3.5\n=======================================\n\npytest 5.3.5 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Daniel Hahler\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.4.0.rst",
    "content": "pytest-5.4.0\n=======================================\n\nThe pytest team is proud to announce the 5.4.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bug fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Christoph Buelter\n* Christoph Bülter\n* Daniel Arndt\n* Daniel Hahler\n* Holger Kohr\n* Hugo\n* Hugo van Kemenade\n* Jakub Mitoraj\n* Kyle Altendorf\n* Minuddin Ahmed Rana\n* Nathaniel Compton\n* ParetoLife\n* Pauli Virtanen\n* Philipp Loose\n* Ran Benita\n* Ronny Pfannschmidt\n* Stefan Scherfke\n* Stefano Mazzucco\n* TWood67\n* Tobias Schmidt\n* Tomáš Gavenčiak\n* Vinay Calastry\n* Vladyslav Rachek\n* Zac Hatfield-Dodds\n* captainCapitalism\n* cmachalo\n* gftea\n* kpinc\n* rebecca-palmer\n* sdementen\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.4.1.rst",
    "content": "pytest-5.4.1\n=======================================\n\npytest 5.4.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.4.2.rst",
    "content": "pytest-5.4.2\n=======================================\n\npytest 5.4.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Hahler\n* Ran Benita\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-5.4.3.rst",
    "content": "pytest-5.4.3\n=======================================\n\npytest 5.4.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Ran Benita\n* Tor Colvin\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.0.0.rst",
    "content": "pytest-6.0.0\n=======================================\n\nThe pytest team is proud to announce the 6.0.0 release!\n\npytest is a mature Python testing tool with more than 2000 tests\nagainst itself, passing on many different interpreters and platforms.\n\nThis release contains a number of bug fixes and improvements, so users are encouraged\nto take a look at the CHANGELOG:\n\n    https://docs.pytest.org/en/latest/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/latest/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all who contributed to this release, among them:\n\n* Anthony Sottile\n* Arvin Firouzi\n* Bruno Oliveira\n* Debi Mishra\n* Garrett Thomas\n* Hugo van Kemenade\n* Kelton Bassingthwaite\n* Kostis Anagnostopoulos\n* Lewis Cowles\n* Miro Hrončok\n* Ran Benita\n* Simon K\n* Zac Hatfield-Dodds\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.0.0rc1.rst",
    "content": "pytest-6.0.0rc1\n=======================================\n\npytest 6.0.0rc1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Alfredo Deza\n* Andreas Maier\n* Andrew\n* Anthony Sottile\n* ArtyomKaltovich\n* Bruno Oliveira\n* Claire Cecil\n* Curt J. Sampson\n* Daniel\n* Daniel Hahler\n* Danny Sepler\n* David Diaz Barquero\n* Fabio Zadrozny\n* Felix Nieuwenhuizen\n* Freya Bruhin\n* Florian Dahlitz\n* Gleb Nikonorov\n* Hugo van Kemenade\n* Hunter Richards\n* Katarzyna Król\n* Katrin Leinweber\n* Keri Volans\n* Lewis Belcher\n* Lukas Geiger\n* Martin Michlmayr\n* Mattwmaster58\n* Maximilian Cosmo Sitter\n* Nikolay Kondratyev\n* Pavel Karateev\n* Paweł Wilczyński\n* Prashant Anand\n* Ram Rachum\n* Ran Benita\n* Ronny Pfannschmidt\n* Ruaridh Williamson\n* Simon K\n* Tim Hoffmann\n* Tor Colvin\n* Vlad-Radz\n* Xinbin Huang\n* Zac Hatfield-Dodds\n* earonesty\n* gaurav dhameeja\n* gdhameeja\n* ibriquem\n* mcsitter\n* piotrhm\n* smarie\n* symonk\n* xuiqzy\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.0.1.rst",
    "content": "pytest-6.0.1\n=======================================\n\npytest 6.0.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/latest/changelog.html.\n\nThanks to all who contributed to this release, among them:\n\n* Bruno Oliveira\n* Mattreex\n* Ran Benita\n* hp310780\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.0.2.rst",
    "content": "pytest-6.0.2\n=======================================\n\npytest 6.0.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.1.0.rst",
    "content": "pytest-6.1.0\n=======================================\n\nThe pytest team is proud to announce the 6.1.0 release!\n\nThis release contains new features, improvements, bug fixes, and breaking changes, so users\nare encouraged to take a look at the CHANGELOG carefully:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Anthony Sottile\n* Bruno Oliveira\n* C. Titus Brown\n* Drew Devereux\n* Faris A Chugthai\n* Freya Bruhin\n* Hugo van Kemenade\n* Hynek Schlawack\n* Joseph Lucas\n* Kamran Ahmad\n* Mattreex\n* Maximilian Cosmo Sitter\n* Ran Benita\n* Rüdiger Busche\n* Sam Estep\n* Sorin Sbarnea\n* Thomas Grainger\n* Vipul Kumar\n* Yutaro Ikeda\n* hp310780\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.1.1.rst",
    "content": "pytest-6.1.1\n=======================================\n\npytest 6.1.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.1.2.rst",
    "content": "pytest-6.1.2\n=======================================\n\npytest 6.1.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Manuel Mariñez\n* Ran Benita\n* Vasilis Gerakaris\n* William Jamir Silva\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.2.0.rst",
    "content": "pytest-6.2.0\n=======================================\n\nThe pytest team is proud to announce the 6.2.0 release!\n\nThis release contains new features, improvements, bug fixes, and breaking changes, so users\nare encouraged to take a look at the CHANGELOG carefully:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Adam Johnson\n* Albert Villanova del Moral\n* Anthony Sottile\n* Anton\n* Ariel Pillemer\n* Bruno Oliveira\n* Charles Aracil\n* Christine M\n* Christine Mecklenborg\n* Cserna Zsolt\n* Dominic Mortlock\n* Emiel van de Laar\n* Freya Bruhin\n* Garvit Shubham\n* Gustavo Camargo\n* Hugo Martins\n* Hugo van Kemenade\n* Jakob van Santen\n* Josias Aurel\n* Jürgen Gmach\n* Karthikeyan Singaravelan\n* Katarzyna\n* Kyle Altendorf\n* Manuel Mariñez\n* Matthew Hughes\n* Matthias Gabriel\n* Max Voitko\n* Maximilian Cosmo Sitter\n* Mikhail Fesenko\n* Nimesh Vashistha\n* Pedro Algarvio\n* Petter Strandmark\n* Prakhar Gurunani\n* Prashant Sharma\n* Ran Benita\n* Ronny Pfannschmidt\n* Sanket Duthade\n* Shubham Adep\n* Simon K\n* Tanvi Mehta\n* Thomas Grainger\n* Tim Hoffmann\n* Vasilis Gerakaris\n* William Jamir Silva\n* Zac Hatfield-Dodds\n* crricks\n* dependabot[bot]\n* duthades\n* frankgerhardt\n* kwgchi\n* mickeypash\n* symonk\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.2.1.rst",
    "content": "pytest-6.2.1\n=======================================\n\npytest 6.2.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Jakob van Santen\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.2.2.rst",
    "content": "pytest-6.2.2\n=======================================\n\npytest 6.2.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Adam Johnson\n* Bruno Oliveira\n* Chris NeJame\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.2.3.rst",
    "content": "pytest-6.2.3\n=======================================\n\npytest 6.2.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.2.4.rst",
    "content": "pytest-6.2.4\n=======================================\n\npytest 6.2.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Christian Maurer\n* Freya Bruhin\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-6.2.5.rst",
    "content": "pytest-6.2.5\n=======================================\n\npytest 6.2.5 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Brylie Christopher Oxley\n* Daniel Asztalos\n* Freya Bruhin\n* Jason Haugen\n* MapleCCC\n* Michał Górny\n* Miro Hrončok\n* Ran Benita\n* Ronny Pfannschmidt\n* Sylvain Bellemare\n* Thomas Güttler\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.0.0.rst",
    "content": "pytest-7.0.0\n=======================================\n\nThe pytest team is proud to announce the 7.0.0 release!\n\nThis release contains new features, improvements, bug fixes, and breaking changes, so users\nare encouraged to take a look at the CHANGELOG carefully:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Adam J. Stewart\n* Alexander King\n* Amin Alaee\n* Andrew Neitsch\n* Anthony Sottile\n* Ben Davies\n* Bernát Gábor\n* Brian Okken\n* Bruno Oliveira\n* Cristian Vera\n* Dan Alvizu\n* David Szotten\n* Eddie\n* Emmanuel Arias\n* Emmanuel Meric de Bellefon\n* Eric Liu\n* Freya Bruhin\n* GergelyKalmar\n* Graeme Smecher\n* Harshna\n* Hugo van Kemenade\n* Jakub Kulík\n* James Myatt\n* Jeff Rasley\n* Kale Kundert\n* Kian Meng, Ang\n* Miro Hrončok\n* Naveen-Pratap\n* Oleg Höfling\n* Olga Matoula\n* Ran Benita\n* Ronny Pfannschmidt\n* Simon K\n* Srip\n* Sören Wegener\n* Taneli Hukkinen\n* Terje Runde\n* Thomas Grainger\n* Thomas Hisch\n* William Jamir Silva\n* Yuval Shimon\n* Zac Hatfield-Dodds\n* andrewdotn\n* denivyruck\n* ericluoliu\n* oleg.hoefling\n* symonk\n* ziebam\n* Éloi Rivard\n* Éric\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.0.0rc1.rst",
    "content": "pytest-7.0.0rc1\n=======================================\n\nThe pytest team is proud to announce the 7.0.0rc1 prerelease!\n\nThis is a prerelease, not intended for production use, but to test the upcoming features and improvements\nin order to catch any major problems before the final version is released to the major public.\n\nWe appreciate your help testing this out before the final release, making sure to report any\nregressions to our issue tracker:\n\nhttps://github.com/pytest-dev/pytest/issues\n\nWhen doing so, please include the string ``[prerelease]`` in the title.\n\nYou can upgrade from PyPI via:\n\n    pip install pytest==7.0.0rc1\n\nUsers are encouraged to take a look at the CHANGELOG carefully:\n\n    https://docs.pytest.org/en/7.0.x/changelog.html\n\nThanks to all the contributors to this release:\n\n* Adam J. Stewart\n* Alexander King\n* Amin Alaee\n* Andrew Neitsch\n* Anthony Sottile\n* Ben Davies\n* Bernát Gábor\n* Brian Okken\n* Bruno Oliveira\n* Cristian Vera\n* David Szotten\n* Eddie\n* Emmanuel Arias\n* Emmanuel Meric de Bellefon\n* Eric Liu\n* Freya Bruhin\n* GergelyKalmar\n* Graeme Smecher\n* Harshna\n* Hugo van Kemenade\n* Jakub Kulík\n* James Myatt\n* Jeff Rasley\n* Kale Kundert\n* Miro Hrončok\n* Naveen-Pratap\n* Oleg Höfling\n* Ran Benita\n* Ronny Pfannschmidt\n* Simon K\n* Srip\n* Sören Wegener\n* Taneli Hukkinen\n* Terje Runde\n* Thomas Grainger\n* Thomas Hisch\n* William Jamir Silva\n* Zac Hatfield-Dodds\n* andrewdotn\n* denivyruck\n* ericluoliu\n* oleg.hoefling\n* symonk\n* ziebam\n* Éloi Rivard\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.0.1.rst",
    "content": "pytest-7.0.1\n=======================================\n\npytest 7.0.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.1.0.rst",
    "content": "pytest-7.1.0\n=======================================\n\nThe pytest team is proud to announce the 7.1.0 release!\n\nThis release contains new features, improvements, and bug fixes,\nthe full list of changes is available in the changelog:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Akuli\n* Andrew Svetlov\n* Anthony Sottile\n* Brett Holman\n* Bruno Oliveira\n* Chris NeJame\n* Dan Alvizu\n* Elijah DeLee\n* Emmanuel Arias\n* Fabian Egli\n* Freya Bruhin\n* Gabor Szabo\n* Hasan Ramezani\n* Hugo van Kemenade\n* Kian Meng, Ang\n* Kojo Idrissa\n* Masaru Tsuchiyama\n* Olga Matoula\n* P. L. Lim\n* Ran Benita\n* Tobias Deiminger\n* Yuval Shimon\n* eduardo naufel schettino\n* Éric\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.1.1.rst",
    "content": "pytest-7.1.1\n=======================================\n\npytest 7.1.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.1.2.rst",
    "content": "pytest-7.1.2\n=======================================\n\npytest 7.1.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Hugo van Kemenade\n* Kian Eliasi\n* Ran Benita\n* Zac Hatfield-Dodds\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.1.3.rst",
    "content": "pytest-7.1.3\n=======================================\n\npytest 7.1.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Gergely Kalmár\n* Nipunn Koorapati\n* Pax\n* Sviatoslav Sydorenko\n* Tim Hoffmann\n* Tony Narlock\n* Wolfremium\n* Zach OBrien\n* aizpurua23a\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.2.0.rst",
    "content": "pytest-7.2.0\n=======================================\n\nThe pytest team is proud to announce the 7.2.0 release!\n\nThis release contains new features, improvements, and bug fixes,\nthe full list of changes is available in the changelog:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Aaron Berdy\n* Adam Turner\n* Albert Villanova del Moral\n* Alice Purcell\n* Anthony Sottile\n* Anton Yakutovich\n* Babak Keyvani\n* Brandon Chinn\n* Bruno Oliveira\n* Chanvin Xiao\n* Cheuk Ting Ho\n* Chris Wheeler\n* EmptyRabbit\n* Ezio Melotti\n* Florian Best\n* Freya Bruhin\n* Fredrik Berndtsson\n* Gabriel Landau\n* Gergely Kalmár\n* Hugo van Kemenade\n* James Gerity\n* John Litborn\n* Jon Parise\n* Kevin C\n* Kian Eliasi\n* MatthewFlamm\n* Miro Hrončok\n* Nate Meyvis\n* Neil Girdhar\n* Nhieuvu1802\n* Nipunn Koorapati\n* Ofek Lev\n* Paul Müller\n* Paul Reece\n* Pax\n* Pete Baughman\n* Peyman Salehi\n* Philipp A\n* Ran Benita\n* Robert O'Shea\n* Ronny Pfannschmidt\n* Rowin\n* Ruth Comer\n* Samuel Colvin\n* Samuel Gaist\n* Sandro Tosi\n* Shantanu\n* Simon K\n* Stephen Rosen\n* Sviatoslav Sydorenko\n* Tatiana Ovary\n* Thierry Moisan\n* Thomas Grainger\n* Tim Hoffmann\n* Tobias Diez\n* Tony Narlock\n* Vivaan Verma\n* Wolfremium\n* Zac Hatfield-Dodds\n* Zach OBrien\n* aizpurua23a\n* gresm\n* holesch\n* itxasos23\n* johnkangw\n* skhomuti\n* sommersoft\n* wodny\n* zx.qiu\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.2.1.rst",
    "content": "pytest-7.2.1\n=======================================\n\npytest 7.2.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Anthony Sottile\n* Bruno Oliveira\n* Daniel Valenzuela\n* Kadino\n* Prerak Patel\n* Ronny Pfannschmidt\n* Santiago Castro\n* s-padmanaban\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.2.2.rst",
    "content": "pytest-7.2.2\n=======================================\n\npytest 7.2.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Garvit Shubham\n* Mahesh Vashishtha\n* Ramsey\n* Ronny Pfannschmidt\n* Teejay\n* q0w\n* vin01\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.3.0.rst",
    "content": "pytest-7.3.0\n=======================================\n\nThe pytest team is proud to announce the 7.3.0 release!\n\nThis release contains new features, improvements, and bug fixes,\nthe full list of changes is available in the changelog:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Aaron Berdy\n* Adam Turner\n* Albert Villanova del Moral\n* Alessio Izzo\n* Alex Hadley\n* Alice Purcell\n* Anthony Sottile\n* Anton Yakutovich\n* Ashish Kurmi\n* Babak Keyvani\n* Billy\n* Brandon Chinn\n* Bruno Oliveira\n* Cal Jacobson\n* Chanvin Xiao\n* Cheuk Ting Ho\n* Chris Wheeler\n* Daniel Garcia Moreno\n* Daniel Scheffler\n* Daniel Valenzuela\n* EmptyRabbit\n* Ezio Melotti\n* Felix Hofstätter\n* Florian Best\n* Freya Bruhin\n* Fredrik Berndtsson\n* Gabriel Landau\n* Garvit Shubham\n* Gergely Kalmár\n* HTRafal\n* Hugo van Kemenade\n* Ilya Konstantinov\n* Itxaso Aizpurua\n* James Gerity\n* Jay\n* John Litborn\n* Jon Parise\n* Jouke Witteveen\n* Kadino\n* Kevin C\n* Kian Eliasi\n* Klaus Rettinghaus\n* Kodi Arfer\n* Mahesh Vashishtha\n* Manuel Jacob\n* Marko Pacak\n* MatthewFlamm\n* Miro Hrončok\n* Nate Meyvis\n* Neil Girdhar\n* Nhieuvu1802\n* Nipunn Koorapati\n* Ofek Lev\n* Paul Kehrer\n* Paul Müller\n* Paul Reece\n* Pax\n* Pete Baughman\n* Peyman Salehi\n* Philipp A\n* Pierre Sassoulas\n* Prerak Patel\n* Ramsey\n* Ran Benita\n* Robert O'Shea\n* Ronny Pfannschmidt\n* Rowin\n* Ruth Comer\n* Samuel Colvin\n* Samuel Gaist\n* Sandro Tosi\n* Santiago Castro\n* Shantanu\n* Simon K\n* Stefanie Molin\n* Stephen Rosen\n* Sviatoslav Sydorenko\n* Tatiana Ovary\n* Teejay\n* Thierry Moisan\n* Thomas Grainger\n* Tim Hoffmann\n* Tobias Diez\n* Tony Narlock\n* Vivaan Verma\n* Wolfremium\n* Yannick PÉROUX\n* Yusuke Kadowaki\n* Zac Hatfield-Dodds\n* Zach OBrien\n* aizpurua23a\n* bitzge\n* bluthej\n* gresm\n* holesch\n* itxasos23\n* johnkangw\n* q0w\n* rdb\n* s-padmanaban\n* skhomuti\n* sommersoft\n* vin01\n* wim glenn\n* wodny\n* zx.qiu\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.3.1.rst",
    "content": "pytest-7.3.1\n=======================================\n\npytest 7.3.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.3.2.rst",
    "content": "pytest-7.3.2\n=======================================\n\npytest 7.3.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Adam J. Stewart\n* Alessio Izzo\n* Bruno Oliveira\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.4.0.rst",
    "content": "pytest-7.4.0\n=======================================\n\nThe pytest team is proud to announce the 7.4.0 release!\n\nThis release contains new features, improvements, and bug fixes,\nthe full list of changes is available in the changelog:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Adam J. Stewart\n* Alessio Izzo\n* Alex\n* Alex Lambson\n* Brian Larsen\n* Bruno Oliveira\n* Bryan Ricker\n* Chris Mahoney\n* Facundo Batista\n* Freya Bruhin\n* Jarrett Keifer\n* Kenny Y\n* Miro Hrončok\n* Ran Benita\n* Roberto Aldera\n* Ronny Pfannschmidt\n* Sergey Kim\n* Stefanie Molin\n* Vijay Arora\n* Ville Skyttä\n* Zac Hatfield-Dodds\n* bzoracler\n* leeyueh\n* nondescryptid\n* theirix\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.4.1.rst",
    "content": "pytest-7.4.1\n=======================================\n\npytest 7.4.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Freya Bruhin\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.4.2.rst",
    "content": "pytest-7.4.2\n=======================================\n\npytest 7.4.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.4.3.rst",
    "content": "pytest-7.4.3\n=======================================\n\npytest 7.4.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Marc Mueller\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-7.4.4.rst",
    "content": "pytest-7.4.4\n=======================================\n\npytest 7.4.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Ran Benita\n* Zac Hatfield-Dodds\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.0.0.rst",
    "content": "pytest-8.0.0\n=======================================\n\nThe pytest team is proud to announce the 8.0.0 release!\n\nThis release contains new features, improvements, bug fixes, and breaking changes, so users\nare encouraged to take a look at the CHANGELOG carefully:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.0.0rc1.rst",
    "content": "pytest-8.0.0rc1\n=======================================\n\nThe pytest team is proud to announce the 8.0.0rc1 release!\n\nThis release contains new features, improvements, bug fixes, and breaking changes, so users\nare encouraged to take a look at the CHANGELOG carefully:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Akhilesh Ramakrishnan\n* Aleksandr Brodin\n* Anthony Sottile\n* Arthur Richard\n* Avasam\n* Benjamin Schubert\n* Bruno Oliveira\n* Carsten Grohmann\n* Cheukting\n* Chris Mahoney\n* Christoph Anton Mitterer\n* DetachHead\n* Erik Hasse\n* Freya Bruhin\n* Fraser Stark\n* Ha Pam\n* Hugo van Kemenade\n* Isaac Virshup\n* Israel Fruchter\n* Jens Tröger\n* Jon Parise\n* Kenny Y\n* Lesnek\n* Marc Mueller\n* Michał Górny\n* Mihail Milushev\n* Milan Lesnek\n* Miro Hrončok\n* Patrick Lannigan\n* Ran Benita\n* Reagan Lee\n* Ronny Pfannschmidt\n* Sadra Barikbin\n* Sean Malloy\n* Sean Patrick Malloy\n* Sharad Nair\n* Simon Blanchard\n* Sourabh Beniwal\n* Stefaan Lippens\n* Tanya Agarwal\n* Thomas Grainger\n* Tom Mortimer-Jones\n* Tushar Sadhwani\n* Tyler Smart\n* Uday Kumar\n* Warren Markham\n* WarrenTheRabbit\n* Zac Hatfield-Dodds\n* Ziad Kermadi\n* akhilramkee\n* antosikv\n* bowugit\n* mickeypash\n* neilmartin2000\n* pomponchik\n* ryanpudd\n* touilleWoman\n* ubaumann\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.0.0rc2.rst",
    "content": "pytest-8.0.0rc2\n=======================================\n\nThe pytest team is proud to announce the 8.0.0rc2 prerelease!\n\nThis is a prerelease, not intended for production use, but to test the upcoming features and improvements\nin order to catch any major problems before the final version is released to the major public.\n\nWe appreciate your help testing this out before the final release, making sure to report any\nregressions to our issue tracker:\n\nhttps://github.com/pytest-dev/pytest/issues\n\nWhen doing so, please include the string ``[prerelease]`` in the title.\n\nYou can upgrade from PyPI via:\n\n    pip install pytest==8.0.0rc2\n\nUsers are encouraged to take a look at the CHANGELOG carefully:\n\n    https://docs.pytest.org/en/release-8.0.0rc2/changelog.html\n\nThanks to all the contributors to this release:\n\n* Ben Brown\n* Bruno Oliveira\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.0.1.rst",
    "content": "pytest-8.0.1\n=======================================\n\npytest 8.0.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Clément Robert\n* Pierre Sassoulas\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.0.2.rst",
    "content": "pytest-8.0.2\n=======================================\n\npytest 8.0.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.1.0.rst",
    "content": "pytest-8.1.0\n=======================================\n\nThe pytest team is proud to announce the 8.1.0 release!\n\nThis release contains new features, improvements, and bug fixes,\nthe full list of changes is available in the changelog:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Ben Brown\n* Ben Leith\n* Bruno Oliveira\n* Clément Robert\n* Dave Hall\n* Dương Quốc Khánh\n* Eero Vaher\n* Eric Larson\n* Fabian Sturm\n* Faisal Fawad\n* Freya Bruhin\n* Franck Charras\n* Joachim B Haga\n* John Litborn\n* Loïc Estève\n* Marc Bresson\n* Patrick Lannigan\n* Pierre Sassoulas\n* Ran Benita\n* Reagan Lee\n* Ronny Pfannschmidt\n* Russell Martin\n* clee2000\n* donghui\n* faph\n* jakkdl\n* mrbean-bremen\n* robotherapist\n* whysage\n* woutdenolf\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.1.1.rst",
    "content": "pytest-8.1.1\n=======================================\n\npytest 8.1.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.1.2.rst",
    "content": "pytest-8.1.2\n=======================================\n\npytest 8.1.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.2.0.rst",
    "content": "pytest-8.2.0\n=======================================\n\nThe pytest team is proud to announce the 8.2.0 release!\n\nThis release contains new features, improvements, and bug fixes,\nthe full list of changes is available in the changelog:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Daniel Miller\n* Freya Bruhin\n* HolyMagician03-UMich\n* John Litborn\n* Levon Saldamli\n* Linghao Zhang\n* Manuel López-Ibáñez\n* Pierre Sassoulas\n* Ran Benita\n* Ronny Pfannschmidt\n* Sebastian Meyer\n* Shekhar verma\n* Tamir Duberstein\n* Tobias Stoeckmann\n* dj\n* jakkdl\n* poulami-sau\n* tserg\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.2.1.rst",
    "content": "pytest-8.2.1\n=======================================\n\npytest 8.2.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.2.2.rst",
    "content": "pytest-8.2.2\n=======================================\n\npytest 8.2.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.3.0.rst",
    "content": "pytest-8.3.0\n=======================================\n\nThe pytest team is proud to announce the 8.3.0 release!\n\nThis release contains new features, improvements, and bug fixes,\nthe full list of changes is available in the changelog:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Anita Hammer\n* Ben Brown\n* Brian Okken\n* Bruno Oliveira\n* Cornelius Riemenschneider\n* Farbod Ahmadian\n* Freya Bruhin\n* Hynek Schlawack\n* James Frost\n* Jason R. Coombs\n* Jelle Zijlstra\n* Josh Soref\n* Marc Bresson\n* Michael Vogt\n* Nathan Goldbaum\n* Nicolas Simonds\n* Oliver Bestwalter\n* Pavel Březina\n* Pierre Sassoulas\n* Pradyun Gedam\n* Ran Benita\n* Ronny Pfannschmidt\n* SOUBHIK KUMAR MITRA\n* Sam Jirovec\n* Stavros Ntentos\n* Sviatoslav Sydorenko\n* Sviatoslav Sydorenko (Святослав Сидоренко)\n* Tomasz Kłoczko\n* Virendra Patil\n* Yutian Li\n* Zach Snicker\n* dj\n* holger krekel\n* joseph-sentry\n* lovetheguitar\n* neutraljump\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.3.1.rst",
    "content": "pytest-8.3.1\n=======================================\n\npytest 8.3.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Ran Benita\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.3.2.rst",
    "content": "pytest-8.3.2\n=======================================\n\npytest 8.3.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Ran Benita\n* Ronny Pfannschmidt\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.3.3.rst",
    "content": "pytest-8.3.3\n=======================================\n\npytest 8.3.3 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Anthony Sottile\n* Avasam\n* Bruno Oliveira\n* Christian Clauss\n* Eugene Mwangi\n* Freya Bruhin\n* GTowers1\n* Nauman Ahmed\n* Pierre Sassoulas\n* Reagan Lee\n* Ronny Pfannschmidt\n* Stefaan Lippens\n* Sviatoslav Sydorenko (Святослав Сидоренко)\n* dongfangtianyu\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.3.4.rst",
    "content": "pytest-8.3.4\n=======================================\n\npytest 8.3.4 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement. To upgrade::\n\n  pip install --upgrade pytest\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Freya Bruhin\n* Frank Hoffmann\n* Jakob van Santen\n* Leonardus Chen\n* Pierre Sassoulas\n* Pradeep Kumar\n* Ran Benita\n* Serge Smertin\n* Stefaan Lippens\n* Sviatoslav Sydorenko (Святослав Сидоренко)\n* dongfangtianyu\n* suspe\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.3.5.rst",
    "content": "pytest-8.3.5\n=======================================\n\npytest 8.3.5 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement.\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Freya Bruhin\n* John Litborn\n* Kenny Y\n* Ran Benita\n* Sadra Barikbin\n* Vincent (Wen Yu) Ge\n* delta87\n* dongfangtianyu\n* mwychung\n* 🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко)\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.4.0.rst",
    "content": "pytest-8.4.0\n=======================================\n\nThe pytest team is proud to announce the 8.4.0 release!\n\nThis release contains new features, improvements, and bug fixes,\nthe full list of changes is available in the changelog:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* Adam Johnson\n* Ammar Askar\n* Andrew Pikul\n* Andy Freeland\n* Anthony Sottile\n* Anton Zhilin\n* Arpit Gupta\n* Ashley Whetter\n* Avasam\n* Bahram Farahmand\n* Brigitta Sipőcz\n* Bruno Oliveira\n* Callum Scott\n* Christian Clauss\n* Christopher Head\n* Daara\n* Daniel Miller\n* Deysha Rivera\n* Emil Hjelm\n* Eugene Mwangi\n* Freya Bruhin\n* Frank Hoffmann\n* GTowers1\n* Guillaume Gauvrit\n* Gupta Arpit\n* Harmin Parra Rueda\n* Jakob van Santen\n* Jason N. White\n* Jiajun Xu\n* John Litborn\n* Julian Valentin\n* JulianJvn\n* Kenny Y\n* Leonardus Chen\n* Marcelo Duarte Trevisani\n* Marcin Augustynów\n* Natalia Mokeeva\n* Nathan Rousseau\n* Nauman Ahmed\n* Nick Murphy\n* Oleksandr Zavertniev\n* Pavel Zhukov\n* Peter Gessler\n* Pierre Sassoulas\n* Pradeep Kumar\n* Ran Benita\n* Reagan Lee\n* Rob Arrow\n* Ronny Pfannschmidt\n* Sadra Barikbin\n* Sam Bull\n* Samuel Bronson\n* Sashko\n* Serge Smertin\n* Shaygan Hooshyari\n* Stefaan Lippens\n* Stefan Zimmermann\n* Stephen McDowell\n* Sviatoslav Sydorenko\n* Sviatoslav Sydorenko (Святослав Сидоренко)\n* Thomas Grainger\n* TobiMcNamobi\n* Tobias Alex-Petersen\n* Tony Narlock\n* Vincent (Wen Yu) Ge\n* Virendra Patil\n* Will Riley\n* Yann Dirson\n* Zac Hatfield-Dodds\n* delta87\n* dongfangtianyu\n* eitanwass\n* fazeelghafoor\n* ikappaki\n* jakkdl\n* maugu\n* moajo\n* mwychung\n* polkapolka\n* suspe\n* sven\n* 🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко)\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.4.1.rst",
    "content": "pytest-8.4.1\n=======================================\n\npytest 8.4.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement.\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Iwithyou2025\n* John Litborn\n* Martin Fischer\n* Ran Benita\n* SarahPythonista\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-8.4.2.rst",
    "content": "pytest-8.4.2\n=======================================\n\npytest 8.4.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement.\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* AD\n* Aditi De\n* Bruno Oliveira\n* Freya Bruhin\n* John Litborn\n* Liam DeVoe\n* Marc Mueller\n* NayeemJohn\n* Olivier Grisel\n* Ran Benita\n* bengartner\n* 🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко)\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-9.0.0.rst",
    "content": "pytest-9.0.0\n=======================================\n\nThe pytest team is proud to announce the 9.0.0 release!\n\nThis release contains new features, improvements, bug fixes, and breaking changes, so users\nare encouraged to take a look at the CHANGELOG carefully:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n* AD\n* Aditi De\n* Ali Nazzal\n* Bruno Oliveira\n* Charles-Meldhine Madi Mnemoi\n* Clément Robert\n* CoretexShadow\n* Cornelius Roemer\n* Eero Vaher\n* Freya Bruhin\n* Harsha Sai\n* Hossein\n* Israël Hallé\n* Iwithyou2025\n* James Addison\n* John Litborn\n* Jordan Macdonald\n* Kieran Ryan\n* Liam DeVoe\n* Marc Mueller\n* Marcos Boger\n* Michał Górny\n* Mulat Mekonen\n* NayeemJohn\n* Olivier Grisel\n* Omri Golan\n* Pierre Sassoulas\n* Praise Tompane\n* Ran Benita\n* Reilly Brogan\n* Samuel Gaist\n* SarahPythonista\n* Sorin Sbarnea\n* Stu-ops\n* Tanuj Rai\n* bengartner\n* dariomesic\n* jakkdl\n* karlicoss\n* popododo0720\n* sazsu\n* slackline\n* vyuroshchin\n* zapl\n* 🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко)\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-9.0.1.rst",
    "content": "pytest-9.0.1\n=======================================\n\npytest 9.0.1 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement.\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Bruno Oliveira\n* Ran Benita\n* 🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко)\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/release-9.0.2.rst",
    "content": "pytest-9.0.2\n=======================================\n\npytest 9.0.2 has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement.\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n* Alex Waygood\n* Bruno Oliveira\n* Fazeel Usmani\n* Freya Bruhin\n* Ran Benita\n* Tom Most\n* 🇺🇦 Sviatoslav Sydorenko (Святослав Сидоренко)\n\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "doc/en/announce/sprint2016.rst",
    "content": "python testing sprint June 20th-26th 2016\n======================================================\n\n.. image:: ../img/freiburg2.jpg\n   :width: 400\n\nThe pytest core group held the biggest sprint\nin its history in June 2016, taking place in the black forest town Freiburg\nin Germany.  In February 2016 we started a `funding\ncampaign on Indiegogo to cover expenses\n<http://igg.me/at/pytest-sprint/x/4034848>`_ The page also mentions\nsome preliminary topics:\n\n- improving pytest-xdist test scheduling to take into account\n  fixture setups and explicit user hints.\n\n- provide info on fixture dependencies during --collect-only\n\n- tying pytest-xdist to tox so that you can do \"py.test -e py34\"\n  to run tests in a particular tox-managed virtualenv.  Also\n  look into making pytest-xdist use tox environments on\n  remote ssh-sides so that remote dependency management becomes\n  easier.\n\n- refactoring the fixture system so more people understand it :)\n\n- integrating PyUnit setup methods as autouse fixtures.\n  possibly adding ways to influence ordering of same-scoped\n  fixtures (so you can make a choice of which fixtures come\n  before others)\n\n- fixing bugs and issues from the tracker, really an endless source :)\n\n\nParticipants\n--------------\n\nOver 20 participants took part from 4 continents, including employees\nfrom Splunk, Personalkollen, Cobe.io, FanDuel and Dolby. Some newcomers\nmixed with developers who have worked on pytest since its beginning, and\nof course everyone in between.\n\n\nSprint organisation, schedule\n-------------------------------\n\nPeople arrived in Freiburg on the 19th, with sprint development taking\nplace on 20th, 21st, 22nd, 24th and 25th. On the 23rd we took a break\nday for some hot hiking in the Black Forest.\n\nSprint activity was organised heavily around pairing, with plenty of group\ndiscussions to take advantage of the high bandwidth, and lightning talks\nas well.\n\n\nMoney / funding\n---------------\n\n\nThe Indiegogo campaign aimed for 11000 USD and in the end raised over\n12000, to reimburse travel costs, pay for a sprint venue and catering.\n\nExcess money is reserved for further sprint/travel funding for pytest/tox\ncontributors.\n"
  },
  {
    "path": "doc/en/backwards-compatibility.rst",
    "content": ".. _backwards-compatibility:\n\nBackwards Compatibility Policy\n==============================\n\n.. versionadded: 6.0\n\nPytest is an actively evolving project that has been decades in the making.\nWe keep learning about new and better structures to express different details about testing.\n\nWhile we implement those modifications, we try to ensure an easy transition and don't want to impose unnecessary churn on our users and community/plugin authors.\n\nAs of now, pytest considers multiple types of backward compatibility transitions:\n\na) trivial: APIs that trivially translate to the new mechanism and do not cause problematic changes.\n\n   We try to support those indefinitely while encouraging users to switch to newer or better mechanisms through documentation.\n\nb) transitional: the old and new APIs don't conflict, and we can help users transition by using warnings while supporting both for a prolonged period of time.\n\n   We will only start the removal of deprecated functionality in major releases (e.g., if we deprecate something in 3.0, we will start to remove it in 4.0), and keep it around for at least two minor releases (e.g., if we deprecate something in 3.9 and 4.0 is the next release, we start to remove it in 5.0, not in 4.0).\n\n   A deprecated feature scheduled to be removed in major version X will use the warning class `PytestRemovedInXWarning` (a subclass of :class:`~pytest.PytestDeprecationWarning`).\n\n   When the deprecation expires (e.g., 4.0 is released), we won't remove the deprecated functionality immediately but will use the standard warning filters to turn `PytestRemovedInXWarning` (e.g., `PytestRemovedIn4Warning`) into **errors** by default. This approach makes it explicit that removal is imminent and still gives you time to turn the deprecated feature into a warning instead of an error so it can be dealt with in your own time. In the next minor release (e.g., 4.1), the feature will be effectively removed.\n\nc) True breakage should only be considered when a normal transition is unreasonably unsustainable and would offset important developments or features by years. In addition, they should be limited to APIs where the number of actual users is very small (for example, only impacting some plugins) and can be coordinated with the community in advance.\n\n   Examples for such upcoming changes:\n\n   * removal of ``pytest_runtest_protocol/nextitem`` - :issue:`895`\n   * rearranging of the node tree to include ``FunctionDefinition``\n   * rearranging of ``SetupState`` :issue:`895`\n\n   True breakages must be announced first in an issue containing:\n\n   * Detailed description of the change\n   * Rationale\n   * Expected impact on users and plugin authors (example in :issue:`895`)\n\n   After there's no hard *-1* on the issue it should be followed up by an initial proof-of-concept Pull Request.\n\n   This POC serves as both a coordination point to assess impact and potential inspiration to come up with a transitional solution after all.\n\n   After a reasonable amount of time the PR can be merged to base a new major release.\n\n   For the PR to mature from POC to acceptance, it must contain:\n   * Setup of deprecation errors/warnings that help users fix and port their code. If it is possible to introduce a deprecation period under the current series, before the true breakage, it should be introduced in a separate PR and be part of the current release stream.\n   * Detailed description of the rationale and examples on how to port code in ``doc/en/deprecations.rst``.\n\n\nHistory\n=========\n\n\nFocus primarily on smooth transition - stance (pre 6.0)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nKeeping backwards compatibility has a very high priority in the pytest project. Although we have deprecated functionality over the years, most of it is still supported. All deprecations in pytest were done because simpler or more efficient ways of accomplishing the same tasks have emerged, making the old way of doing things unnecessary.\n\nWith the pytest 3.0 release, we introduced a clear communication scheme for when we will actually remove the old busted joint and politely ask you to use the new hotness instead, while giving you enough time to adjust your tests or raise concerns if there are valid reasons to keep deprecated functionality around.\n\nTo communicate changes, we issue deprecation warnings using a custom warning hierarchy (see :ref:`internal-warnings`). These warnings may be suppressed using the standard means: :option:`-W` command-line flag or :confval:`filterwarnings` configuration option (see :ref:`warnings`), but we suggest to use these sparingly and temporarily, and heed the warnings when possible.\n\nWe will only start the removal of deprecated functionality in major releases (e.g. if we deprecate something in 3.0, we will start to remove it in 4.0), and keep it around for at least two minor releases (e.g. if we deprecate something in 3.9 and 4.0 is the next release, we start to remove it in 5.0, not in 4.0).\n\nWhen the deprecation expires (e.g. 4.0 is released), we won't remove the deprecated functionality immediately, but will use the standard warning filters to turn them into **errors** by default. This approach makes it explicit that removal is imminent, and still gives you time to turn the deprecated feature into a warning instead of an error so it can be dealt with in your own time. In the next minor release (e.g. 4.1), the feature will be effectively removed.\n\n\nDeprecation Roadmap\n-------------------\n\nFeatures currently deprecated and removed in previous releases can be found in :ref:`deprecations`.\n\nWe track future deprecation and removal of features using milestones and the `deprecation <https://github.com/pytest-dev/pytest/issues?q=label%3A%22type%3A+deprecation%22>`_ and `removal <https://github.com/pytest-dev/pytest/labels/type%3A%20removal>`_ labels on GitHub.\n\n\nPython version support\n======================\n\nReleased pytest versions support all Python versions that are actively maintained at the time of the release:\n\n==============  ===================\npytest version  min. Python version\n==============  ===================\n9.0+            3.10+\n8.4             3.9+\n8.0 - 8.3       3.8+\n7.1 - 7.4       3.7+\n6.2 - 7.0       3.6+\n5.0 - 6.1       3.5+\n3.3 - 4.6       2.7, 3.4+\n==============  ===================\n\n`Status of Python Versions <https://devguide.python.org/versions/>`__.\n"
  },
  {
    "path": "doc/en/broken-dep-constraints.txt",
    "content": "# This file contains transitive dependencies that need to be pinned for some reason.\n# Eventually this file will be empty, but in this case keep it around for future use.\n"
  },
  {
    "path": "doc/en/builtin.rst",
    "content": ":orphan:\n\n.. _`pytest helpers`:\n\nPytest API and builtin fixtures\n================================================\n\n\nMost of the information of this page has been moved over to :ref:`api-reference`.\n\nFor information on plugin hooks and objects, see :ref:`plugins`.\n\nFor information on the ``pytest.mark`` mechanism, see :ref:`mark`.\n\nFor information about fixtures, see :ref:`fixtures`. To see a complete list of available fixtures (add :option:`-v` to also see fixtures with leading ``_``), type :\n\n.. code-block:: pytest\n\n    $ pytest  --fixtures -v\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collected 0 items\n    cache -- .../_pytest/cacheprovider.py:566\n        Return a cache object that can persist state between testing sessions.\n\n        cache.get(key, default)\n        cache.set(key, value)\n\n        Keys must be ``/`` separated strings, where the first part is usually the\n        name of your plugin or application to avoid clashes with other cache users.\n\n        Values can be any object handled by the json stdlib module.\n\n    capsys -- .../_pytest/capture.py:1000\n        Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n        The captured output is made available via ``capsys.readouterr()`` method\n        calls, which return a ``(out, err)`` namedtuple.\n        ``out`` and ``err`` will be ``text`` objects.\n\n        Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.\n\n        Example:\n\n        .. code-block:: python\n\n            def test_output(capsys):\n                print(\"hello\")\n                captured = capsys.readouterr()\n                assert captured.out == \"hello\\n\"\n\n    capteesys -- .../_pytest/capture.py:1028\n        Enable simultaneous text capturing and pass-through of writes\n        to ``sys.stdout`` and ``sys.stderr`` as defined by ``--capture=``.\n\n\n        The captured output is made available via ``capteesys.readouterr()`` method\n        calls, which return a ``(out, err)`` namedtuple.\n        ``out`` and ``err`` will be ``text`` objects.\n\n        The output is also passed-through, allowing it to be \"live-printed\",\n        reported, or both as defined by ``--capture=``.\n\n        Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.\n\n        Example:\n\n        .. code-block:: python\n\n            def test_output(capteesys):\n                print(\"hello\")\n                captured = capteesys.readouterr()\n                assert captured.out == \"hello\\n\"\n\n    capsysbinary -- .../_pytest/capture.py:1063\n        Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n        The captured output is made available via ``capsysbinary.readouterr()``\n        method calls, which return a ``(out, err)`` namedtuple.\n        ``out`` and ``err`` will be ``bytes`` objects.\n\n        Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.\n\n        Example:\n\n        .. code-block:: python\n\n            def test_output(capsysbinary):\n                print(\"hello\")\n                captured = capsysbinary.readouterr()\n                assert captured.out == b\"hello\\n\"\n\n    capfd -- .../_pytest/capture.py:1091\n        Enable text capturing of writes to file descriptors ``1`` and ``2``.\n\n        The captured output is made available via ``capfd.readouterr()`` method\n        calls, which return a ``(out, err)`` namedtuple.\n        ``out`` and ``err`` will be ``text`` objects.\n\n        Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.\n\n        Example:\n\n        .. code-block:: python\n\n            def test_system_echo(capfd):\n                os.system('echo \"hello\"')\n                captured = capfd.readouterr()\n                assert captured.out == \"hello\\n\"\n\n    capfdbinary -- .../_pytest/capture.py:1119\n        Enable bytes capturing of writes to file descriptors ``1`` and ``2``.\n\n        The captured output is made available via ``capfd.readouterr()`` method\n        calls, which return a ``(out, err)`` namedtuple.\n        ``out`` and ``err`` will be ``byte`` objects.\n\n        Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.\n\n        Example:\n\n        .. code-block:: python\n\n            def test_system_echo(capfdbinary):\n                os.system('echo \"hello\"')\n                captured = capfdbinary.readouterr()\n                assert captured.out == b\"hello\\n\"\n\n    doctest_namespace [session scope] -- .../_pytest/doctest.py:722\n        Fixture that returns a :py:class:`dict` that will be injected into the\n        namespace of doctests.\n\n        Usually this fixture is used in conjunction with another ``autouse`` fixture:\n\n        .. code-block:: python\n\n            @pytest.fixture(autouse=True)\n            def add_np(doctest_namespace):\n                doctest_namespace[\"np\"] = numpy\n\n        For more details: :ref:`doctest_namespace`.\n\n    pytestconfig [session scope] -- .../_pytest/fixtures.py:1431\n        Session-scoped fixture that returns the session's :class:`pytest.Config`\n        object.\n\n        Example::\n\n            def test_foo(pytestconfig):\n                if pytestconfig.get_verbosity() > 0:\n                    ...\n\n    record_property -- .../_pytest/junitxml.py:277\n        Add extra properties to the calling test.\n\n        User properties become part of the test report and are available to the\n        configured reporters, like JUnit XML.\n\n        The fixture is callable with ``name, value``. The value is automatically\n        XML-encoded.\n\n        Example::\n\n            def test_function(record_property):\n                record_property(\"example_key\", 1)\n\n    record_xml_attribute -- .../_pytest/junitxml.py:300\n        Add extra xml attributes to the tag for the calling test.\n\n        The fixture is callable with ``name, value``. The value is\n        automatically XML-encoded.\n\n    record_testsuite_property [session scope] -- .../_pytest/junitxml.py:338\n        Record a new ``<property>`` tag as child of the root ``<testsuite>``.\n\n        This is suitable to writing global information regarding the entire test\n        suite, and is compatible with ``xunit2`` JUnit family.\n\n        This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:\n\n        .. code-block:: python\n\n            def test_foo(record_testsuite_property):\n                record_testsuite_property(\"ARCH\", \"PPC\")\n                record_testsuite_property(\"STORAGE_TYPE\", \"CEPH\")\n\n        :param name:\n            The property name.\n        :param value:\n            The property value. Will be converted to a string.\n\n        .. warning::\n\n            Currently this fixture **does not work** with the\n            `pytest-xdist <https://github.com/pytest-dev/pytest-xdist>`__ plugin. See\n            :issue:`7767` for details.\n\n    tmpdir_factory [session scope] -- .../_pytest/legacypath.py:298\n        Return a :class:`pytest.TempdirFactory` instance for the test session.\n\n    tmpdir -- .../_pytest/legacypath.py:305\n        Return a temporary directory (as `legacy_path`_ object)\n        which is unique to each test function invocation.\n        The temporary directory is created as a subdirectory\n        of the base temporary directory, with configurable retention,\n        as discussed in :ref:`temporary directory location and retention`.\n\n        .. note::\n            These days, it is preferred to use ``tmp_path``.\n\n            :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.\n\n        .. _legacy_path: https://py.readthedocs.io/en/latest/path.html\n\n    caplog -- .../_pytest/logging.py:596\n        Access and control log capturing.\n\n        Captured logs are available through the following properties/methods::\n\n        * caplog.messages        -> list of format-interpolated log messages\n        * caplog.text            -> string containing formatted log output\n        * caplog.records         -> list of logging.LogRecord instances\n        * caplog.record_tuples   -> list of (logger_name, level, message) tuples\n        * caplog.clear()         -> clear captured records and formatted log output string\n\n    monkeypatch -- .../_pytest/monkeypatch.py:33\n        A convenient fixture for monkey-patching.\n\n        The fixture provides these methods to modify objects, dictionaries, or\n        :data:`os.environ`:\n\n        * :meth:`monkeypatch.setattr(obj, name, value, raising=True) <pytest.MonkeyPatch.setattr>`\n        * :meth:`monkeypatch.delattr(obj, name, raising=True) <pytest.MonkeyPatch.delattr>`\n        * :meth:`monkeypatch.setitem(mapping, name, value) <pytest.MonkeyPatch.setitem>`\n        * :meth:`monkeypatch.delitem(obj, name, raising=True) <pytest.MonkeyPatch.delitem>`\n        * :meth:`monkeypatch.setenv(name, value, prepend=None) <pytest.MonkeyPatch.setenv>`\n        * :meth:`monkeypatch.delenv(name, raising=True) <pytest.MonkeyPatch.delenv>`\n        * :meth:`monkeypatch.syspath_prepend(path) <pytest.MonkeyPatch.syspath_prepend>`\n        * :meth:`monkeypatch.chdir(path) <pytest.MonkeyPatch.chdir>`\n        * :meth:`monkeypatch.context() <pytest.MonkeyPatch.context>`\n\n        All modifications will be undone after the requesting test function or\n        fixture has finished. The ``raising`` parameter determines if a :class:`KeyError`\n        or :class:`AttributeError` will be raised if the set/deletion operation does not have the\n        specified target.\n\n        To undo modifications done by the fixture in a contained scope,\n        use :meth:`context() <pytest.MonkeyPatch.context>`.\n\n    recwarn -- .../_pytest/recwarn.py:34\n        Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.\n\n        See :ref:`warnings` for information on warning categories.\n\n    subtests -- .../_pytest/subtests.py:129\n        Provides subtests functionality.\n\n    tmp_path_factory [session scope] -- .../_pytest/tmpdir.py:243\n        Return a :class:`pytest.TempPathFactory` instance for the test session.\n\n    tmp_path -- .../_pytest/tmpdir.py:258\n        Return a temporary directory (as :class:`pathlib.Path` object)\n        which is unique to each test function invocation.\n        The temporary directory is created as a subdirectory\n        of the base temporary directory, with configurable retention,\n        as discussed in :ref:`temporary directory location and retention`.\n\n\n    ========================== no tests ran in 0.12s ===========================\n\nYou can also interactively ask for help, e.g. by typing on the Python interactive prompt something like:\n\n.. code-block:: python\n\n    import pytest\n\n    help(pytest)\n"
  },
  {
    "path": "doc/en/changelog.rst",
    "content": ".. _`changelog`:\n\n=========\nChangelog\n=========\n\nVersions follow `Semantic Versioning <https://semver.org/>`_ (``<major>.<minor>.<patch>``).\n\nBackward incompatible (breaking) changes will only be introduced in major versions\nwith advance notice in the **Deprecations** section of releases.\n\n\n..\n    You should *NOT* be adding new change log entries to this file, this\n    file is managed by towncrier. You *may* edit previous change logs to\n    fix problems like typo corrections or such.\n    To add a new change log entry, please see\n    https://pip.pypa.io/en/latest/development/contributing/#news-entries\n    but note that in pytest the \"news/\" directory is named \"changelog/\".\n\n\n.. only:: not is_release\n\n   To be included in v\\ |release| (if present)\n   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n   .. towncrier-draft-entries:: |release| [UNRELEASED DRAFT]\n\n   Released versions\n   ^^^^^^^^^^^^^^^^^\n\n.. towncrier release notes start\n\npytest 9.0.2 (2025-12-06)\n=========================\n\nBug fixes\n---------\n\n- `#13896 <https://github.com/pytest-dev/pytest/issues/13896>`_: The terminal progress feature added in pytest 9.0.0 has been disabled by default, except on Windows, due to compatibility issues with some terminal emulators.\n\n  You may enable it again by passing ``-p terminalprogress``. We may enable it by default again once compatibility improves in the future.\n\n  Additionally, when the environment variable ``TERM`` is ``dumb``, the escape codes are no longer emitted, even if the plugin is enabled.\n\n\n- `#13904 <https://github.com/pytest-dev/pytest/issues/13904>`_: Fixed the TOML type of the :confval:`tmp_path_retention_count` settings in the API reference from number to string.\n\n\n- `#13946 <https://github.com/pytest-dev/pytest/issues/13946>`_: The private ``config.inicfg`` attribute was changed in a breaking manner in pytest 9.0.0.\n  Due to its usage in the ecosystem, it is now restored to working order using a compatibility shim.\n  It will be deprecated in pytest 9.1 and removed in pytest 10.\n\n\n- `#13965 <https://github.com/pytest-dev/pytest/issues/13965>`_: Fixed quadratic-time behavior when handling ``unittest`` subtests in Python 3.10.\n\n\n\nImproved documentation\n----------------------\n\n- `#4492 <https://github.com/pytest-dev/pytest/issues/4492>`_: The API Reference now contains cross-reference-able documentation of :ref:`pytest's command-line flags <command-line-flags>`.\n\n\npytest 9.0.1 (2025-11-12)\n=========================\n\nBug fixes\n---------\n\n- `#13895 <https://github.com/pytest-dev/pytest/issues/13895>`_: Restore support for skipping tests via ``raise unittest.SkipTest``.\n\n\n- `#13896 <https://github.com/pytest-dev/pytest/issues/13896>`_: The terminal progress plugin added in pytest 9.0 is now automatically disabled when iTerm2 is detected, it generated desktop notifications instead of the desired functionality.\n\n\n- `#13904 <https://github.com/pytest-dev/pytest/issues/13904>`_: Fixed the TOML type of the verbosity settings in the API reference from number to string.\n\n\n- `#13910 <https://github.com/pytest-dev/pytest/issues/13910>`_: Fixed `UserWarning: Do not expect file_or_dir` on some earlier Python 3.12 and 3.13 point versions.\n\n\n\nPackaging updates and notes for downstreams\n-------------------------------------------\n\n- `#13933 <https://github.com/pytest-dev/pytest/issues/13933>`_: The tox configuration has been adjusted to make sure the desired\n  version string can be passed into its :ref:`package_env` through\n  the ``SETUPTOOLS_SCM_PRETEND_VERSION_FOR_PYTEST`` environment\n  variable as a part of the release process -- by :user:`webknjaz`.\n\n\n\nContributor-facing changes\n--------------------------\n\n- `#13891 <https://github.com/pytest-dev/pytest/issues/13891>`_, `#13942 <https://github.com/pytest-dev/pytest/issues/13942>`_: The CI/CD part of the release automation is now capable of\n  creating GitHub Releases without having a Git checkout on\n  disk -- by :user:`bluetech` and :user:`webknjaz`.\n\n\n- `#13933 <https://github.com/pytest-dev/pytest/issues/13933>`_: The tox configuration has been adjusted to make sure the desired\n  version string can be passed into its :ref:`package_env` through\n  the ``SETUPTOOLS_SCM_PRETEND_VERSION_FOR_PYTEST`` environment\n  variable as a part of the release process -- by :user:`webknjaz`.\n\n\npytest 9.0.0 (2025-11-05)\n=========================\n\nNew features\n------------\n\n\n- `#1367 <https://github.com/pytest-dev/pytest/issues/1367>`_: **Support for subtests** has been added.\n\n  :ref:`subtests <subtests>` are an alternative to parametrization, useful in situations where the parametrization values are not all known at collection time.\n\n  Example:\n\n  .. code-block:: python\n\n      def contains_docstring(p: Path) -> bool:\n          \"\"\"Return True if the given Python file contains a top-level docstring.\"\"\"\n          ...\n\n\n      def test_py_files_contain_docstring(subtests: pytest.Subtests) -> None:\n          for path in Path.cwd().glob(\"*.py\"):\n              with subtests.test(path=str(path)):\n                  assert contains_docstring(path)\n\n\n  Each assert failure or error is caught by the context manager and reported individually, giving a clear picture of all files that are missing a docstring.\n\n  In addition, :meth:`unittest.TestCase.subTest` is now also supported.\n\n  This feature was originally implemented as a separate plugin in `pytest-subtests <https://github.com/pytest-dev/pytest-subtests>`__, but since then has been merged into the core.\n\n  .. note::\n\n      This feature is experimental and will likely evolve in future releases. By that we mean that we might change how subtests are reported on failure, but the functionality and how to use it are stable.\n\n\n- `#13743 <https://github.com/pytest-dev/pytest/issues/13743>`_: Added support for **native TOML configuration files**.\n\n  While pytest, since version 6, supports configuration in ``pyproject.toml`` files under ``[tool.pytest.ini_options]``,\n  it does so in an \"INI compatibility mode\", where all configuration values are treated as strings or list of strings.\n  Now, pytest supports the native TOML data model.\n\n  In ``pyproject.toml``, the native TOML configuration is under the ``[tool.pytest]`` table.\n\n  .. code-block:: toml\n\n      # pyproject.toml\n      [tool.pytest]\n      minversion = \"9.0\"\n      addopts = [\"-ra\", \"-q\"]\n      testpaths = [\n          \"tests\",\n          \"integration\",\n      ]\n\n  The ``[tool.pytest.ini_options]`` table remains supported, but both tables cannot be used at the same time.\n\n  If you prefer to use a separate configuration file, or don't use ``pyproject.toml``, you can use ``pytest.toml`` or ``.pytest.toml``:\n\n  .. code-block:: toml\n\n      # pytest.toml or .pytest.toml\n      [pytest]\n      minversion = \"9.0\"\n      addopts = [\"-ra\", \"-q\"]\n      testpaths = [\n          \"tests\",\n          \"integration\",\n      ]\n\n  The documentation now (sometimes) shows configuration snippets in both TOML and INI formats, in a tabbed interface.\n\n  See :ref:`config file formats` for full details.\n\n\n- `#13823 <https://github.com/pytest-dev/pytest/issues/13823>`_: Added a **\"strict mode\"** enabled by the :confval:`strict` configuration option.\n\n  When set to ``true``, the :confval:`strict` option currently enables\n\n  * :confval:`strict_config`\n  * :confval:`strict_markers`\n  * :confval:`strict_parametrization_ids`\n  * :confval:`strict_xfail`\n\n  The individual strictness options can be explicitly set to override the global :confval:`strict` setting.\n\n  The previously-deprecated ``--strict`` command-line flag now enables strict mode.\n\n  If pytest adds new strictness options in the future, they will also be enabled in strict mode.\n  Therefore, you should only enable strict mode if you use a pinned/locked version of pytest,\n  or if you want to proactively adopt new strictness options as they are added.\n\n  See :ref:`strict mode` for more details.\n\n\n- `#13737 <https://github.com/pytest-dev/pytest/issues/13737>`_: Added the :confval:`strict_parametrization_ids` configuration option.\n\n  When set, pytest emits an error if it detects non-unique parameter set IDs,\n  rather than automatically making the IDs unique by adding `0`, `1`, ... to them.\n  This can be particularly useful for catching unintended duplicates.\n\n\n- `#13072 <https://github.com/pytest-dev/pytest/issues/13072>`_: Added support for displaying test session **progress in the terminal tab** using the `OSC 9;4; <https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC>`_ ANSI sequence.\n\n  **Note**: *This feature has been disabled by default in version 9.0.2, except on Windows, due to compatibility issues with some terminal emulators.\n  You may enable it again by passing* ``-p terminalprogress``. *We may enable it by default again once compatibility improves in the future.*\n\n  When pytest runs in a supported terminal emulator like ConEmu, Gnome Terminal, Ptyxis, Windows Terminal, Kitty or Ghostty,\n  you'll see the progress in the terminal tab or window,\n  allowing you to monitor pytest's progress at a glance.\n\n  This feature is automatically enabled when running in a TTY. It is implemented as an internal plugin. If needed, it can be disabled as follows:\n  - On a user level, using ``-p no:terminalprogress`` on the command line or via an environment variable ``PYTEST_ADDOPTS='-p no:terminalprogress'``.\n  - On a project configuration level, using ``addopts = \"-p no:terminalprogress\"``.\n\n\n- `#478 <https://github.com/pytest-dev/pytest/issues/478>`_: Support PEP420 (implicit namespace packages) as `--pyargs` target when :confval:`consider_namespace_packages` is `true` in the config.\n\n  Previously, this option only impacted package imports, now it also impacts tests discovery.\n\n\n- `#13678 <https://github.com/pytest-dev/pytest/issues/13678>`_: Added a new :confval:`faulthandler_exit_on_timeout` configuration option set to \"false\" by default to let `faulthandler` interrupt the `pytest` process after a timeout in case of deadlock.\n\n  Previously, a `faulthandler` timeout would only dump the traceback of all threads to stderr, but would not interrupt the `pytest` process.\n\n  -- by :user:`ogrisel`.\n\n\n- `#13829 <https://github.com/pytest-dev/pytest/issues/13829>`_: Added support for configuration option aliases via the ``aliases`` parameter in :meth:`Parser.addini() <pytest.Parser.addini>`.\n\n  Plugins can now register alternative names for configuration options,\n  allowing for more flexibility in configuration naming and supporting backward compatibility when renaming options.\n  The canonical name always takes precedence if both the canonical name and an alias are specified in the configuration file.\n\n\n\nImprovements in existing functionality\n--------------------------------------\n\n- `#13330 <https://github.com/pytest-dev/pytest/issues/13330>`_: Having pytest configuration spread over more than one file (for example having both a ``pytest.ini`` file and ``pyproject.toml`` with a ``[tool.pytest.ini_options]`` table) will now print a warning to make it clearer to the user that only one of them is actually used.\n\n  -- by :user:`sgaist`\n\n\n- `#13574 <https://github.com/pytest-dev/pytest/issues/13574>`_: The single argument ``--version`` no longer loads the entire plugin infrastructure, making it faster and more reliable when displaying only the pytest version.\n\n  Passing ``--version`` twice (e.g., ``pytest --version --version``) retains the original behavior, showing both the pytest version and plugin information.\n\n  .. note::\n\n      Since ``--version`` is now processed early, it only takes effect when passed directly via the command line. It will not work if set through other mechanisms, such as :envvar:`PYTEST_ADDOPTS` or :confval:`addopts`.\n\n\n- `#13823 <https://github.com/pytest-dev/pytest/issues/13823>`_: Added :confval:`strict_xfail` as an alias to the ``xfail_strict`` option,\n  :confval:`strict_config` as an alias to the ``--strict-config`` flag,\n  and :confval:`strict_markers` as an alias to the ``--strict-markers`` flag.\n  This makes all strictness options consistently have configuration options with the prefix ``strict_``.\n\n- `#13700 <https://github.com/pytest-dev/pytest/issues/13700>`_: `--junitxml`  no longer prints the `generated xml file` summary at the end of the pytest session when `--quiet` is given.\n\n\n- `#13732 <https://github.com/pytest-dev/pytest/issues/13732>`_: Previously, when filtering warnings, pytest would fail if the filter referenced a class that could not be imported. Now, this only outputs a message indicating the problem.\n\n\n- `#13859 <https://github.com/pytest-dev/pytest/issues/13859>`_: Clarify the error message for `pytest.raises()` when a regex `match` fails.\n\n\n- `#13861 <https://github.com/pytest-dev/pytest/issues/13861>`_: Better sentence structure in a test's expected error message. Previously, the error message would be \"expected exception must be <expected>, but got <actual>\". Now, it is \"Expected <expected>, but got <actual>\".\n\n\nRemovals and backward incompatible breaking changes\n---------------------------------------------------\n\n- `#12083 <https://github.com/pytest-dev/pytest/issues/12083>`_: Fixed a bug where an invocation such as `pytest a/ a/b` would cause only tests from `a/b` to run, and not other tests under `a/`.\n\n  The fix entails a few breaking changes to how such overlapping arguments and duplicates are handled:\n\n  1. `pytest a/b a/` or `pytest a/ a/b` are equivalent to `pytest a`; if an argument overlaps another arguments, only the prefix remains.\n\n  2. `pytest x.py x.py` is equivalent to `pytest x.py`; previously such an invocation was taken as an explicit request to run the tests from the file twice.\n\n  If you rely on these behaviors, consider using :ref:`--keep-duplicates <duplicate-paths>`, which retains its existing behavior (including the bug).\n\n\n- `#13719 <https://github.com/pytest-dev/pytest/issues/13719>`_: Support for Python 3.9 is dropped following its end of life.\n\n\n- `#13766 <https://github.com/pytest-dev/pytest/issues/13766>`_: Previously, pytest would assume it was running in a CI/CD environment if either of the environment variables `$CI` or `$BUILD_NUMBER` was defined;\n  now, CI mode is only activated if at least one of those variables is defined and set to a *non-empty* value.\n\n\n- The non-public ``config.args`` attribute used to be able to contain ``pathlib.Path`` instances; now it can only contain strings.\n\n\n- `#13779 <https://github.com/pytest-dev/pytest/issues/13779>`_: **PytestRemovedIn9Warning deprecation warnings are now errors by default.**\n\n  Following our plan to remove deprecated features with as little disruption as\n  possible, all warnings of type ``PytestRemovedIn9Warning`` now generate errors\n  instead of warning messages by default.\n\n  **The affected features will be effectively removed in pytest 9.1**, so please consult the\n  :ref:`deprecations` section in the docs for directions on how to update existing code.\n\n  In the pytest ``9.0.X`` series, it is possible to change the errors back into warnings as a\n  stopgap measure by adding this to your ``pytest.ini`` file:\n\n  .. code-block:: ini\n\n      [pytest]\n      filterwarnings =\n          ignore::pytest.PytestRemovedIn9Warning\n\n  But this will stop working when pytest ``9.1`` is released.\n\n  **If you have concerns** about the removal of a specific feature, please add a\n  comment to :issue:`13779`.\n\n\n\nDeprecations (removal in next major release)\n--------------------------------------------\n\n- `#13807 <https://github.com/pytest-dev/pytest/issues/13807>`_: :meth:`monkeypatch.syspath_prepend() <pytest.MonkeyPatch.syspath_prepend>` now issues a deprecation warning when the prepended path contains legacy namespace packages (those using ``pkg_resources.declare_namespace()``).\n  Users should migrate to native namespace packages (:pep:`420`).\n  See :ref:`monkeypatch-fixup-namespace-packages` for details.\n\n\nBug fixes\n---------\n\n- `#13445 <https://github.com/pytest-dev/pytest/issues/13445>`_: Made the type annotations of :func:`pytest.skip` and friends more spec-complaint to have them work across more type checkers.\n\n\n- `#13537 <https://github.com/pytest-dev/pytest/issues/13537>`_: Fixed a bug in which :class:`ExceptionGroup` with only ``Skipped`` exceptions in teardown was not handled correctly and showed as error.\n\n\n- `#13598 <https://github.com/pytest-dev/pytest/issues/13598>`_: Fixed possible collection confusion on Windows when short paths and symlinks are involved.\n\n\n- `#13716 <https://github.com/pytest-dev/pytest/issues/13716>`_: Fixed a bug where a nonsensical invocation like ``pytest x.py[a]`` (a file cannot be parametrized) was silently treated as ``pytest x.py``. This is now a usage error.\n\n\n- `#13722 <https://github.com/pytest-dev/pytest/issues/13722>`_: Fixed a misleading assertion failure message when using :func:`pytest.approx` on mappings with differing lengths.\n\n\n- `#13773 <https://github.com/pytest-dev/pytest/issues/13773>`_: Fixed the static fixture closure calculation to properly consider transitive dependencies requested by overridden fixtures.\n\n\n- `#13816 <https://github.com/pytest-dev/pytest/issues/13816>`_: Fixed :func:`pytest.approx` which now returns a clearer error message when comparing mappings with different keys.\n\n\n- `#13849 <https://github.com/pytest-dev/pytest/issues/13849>`_: Hidden ``.pytest.ini`` files are now picked up as the config file even if empty.\n  This was an inconsistency with non-hidden ``pytest.ini``.\n\n\n- `#13865 <https://github.com/pytest-dev/pytest/issues/13865>`_: Fixed `--show-capture` with `--tb=line`.\n\n\n- `#13522 <https://github.com/pytest-dev/pytest/issues/13522>`_: Fixed :fixture:`pytester` in subprocess mode ignored all :attr:`pytester.plugins <pytest.Pytester.plugins>` except the first.\n\n  Fixed :fixture:`pytester` in subprocess mode silently ignored non-str :attr:`pytester.plugins <pytest.Pytester.plugins>`.\n  Now it errors instead.\n  If you are affected by this, specify the plugin by name, or switch the affected tests to use :func:`pytester.runpytest_inprocess <pytest.Pytester.runpytest_inprocess>` explicitly instead.\n\n\n\nPackaging updates and notes for downstreams\n-------------------------------------------\n\n- `#13791 <https://github.com/pytest-dev/pytest/issues/13791>`_: Minimum requirements on ``iniconfig`` and ``packaging`` were bumped to ``1.0.1`` and ``22.0.0``, respectively.\n\n\n\nContributor-facing changes\n--------------------------\n\n- `#12244 <https://github.com/pytest-dev/pytest/issues/12244>`_: Fixed self-test failures when `TERM=dumb`.\n\n\n- `#12474 <https://github.com/pytest-dev/pytest/issues/12474>`_: Added scheduled GitHub Action Workflow to run Sphinx linkchecks in repo documentation.\n\n\n- `#13621 <https://github.com/pytest-dev/pytest/issues/13621>`_: pytest's own testsuite now handles the ``lsof`` command hanging (e.g. due to unreachable network filesystems), with the affected selftests being skipped after 10 seconds.\n\n\n- `#13638 <https://github.com/pytest-dev/pytest/issues/13638>`_: Fixed deprecated :command:`gh pr new` command in :file:`scripts/prepare-release-pr.py`.\n  The script now uses :command:`gh pr create` which is compatible with GitHub CLI v2.0+.\n\n\n- `#13695 <https://github.com/pytest-dev/pytest/issues/13695>`_: Flush `stdout` and `stderr` in `Pytester.run` to avoid truncated outputs in `test_faulthandler.py::test_timeout` on CI -- by :user:`ogrisel`.\n\n\n- `#13771 <https://github.com/pytest-dev/pytest/issues/13771>`_: Skip `test_do_not_collect_symlink_siblings` on Windows environments without symlink support to avoid false negatives.\n\n\n- `#13841 <https://github.com/pytest-dev/pytest/issues/13841>`_: ``tox>=4`` is now required when contributing to pytest.\n\n- `#13625 <https://github.com/pytest-dev/pytest/issues/13625>`_: Added missing docstrings to ``pytest_addoption()``, ``pytest_configure()``, and ``cacheshow()`` functions in ``cacheprovider.py``.\n\n\n\nMiscellaneous internal changes\n------------------------------\n\n- `#13830 <https://github.com/pytest-dev/pytest/issues/13830>`_: Configuration overrides (``-o``/``--override-ini``) are now processed during startup rather than during :func:`config.getini() <pytest.Config.getini>`.\n\n\npytest 8.4.2 (2025-09-03)\n=========================\n\nBug fixes\n---------\n\n- `#13478 <https://github.com/pytest-dev/pytest/issues/13478>`_: Fixed a crash when using :confval:`console_output_style` with ``times`` and a module is skipped.\n\n\n- `#13530 <https://github.com/pytest-dev/pytest/issues/13530>`_: Fixed a crash when using :func:`pytest.approx` and :class:`decimal.Decimal` instances with the :class:`decimal.FloatOperation` trap set.\n\n\n- `#13549 <https://github.com/pytest-dev/pytest/issues/13549>`_: No longer evaluate type annotations in Python ``3.14`` when inspecting function signatures.\n\n  This prevents crashes during module collection when modules do not explicitly use ``from __future__ import annotations`` and import types for annotations within a ``if TYPE_CHECKING:`` block.\n\n\n- `#13559 <https://github.com/pytest-dev/pytest/issues/13559>`_: Added missing `int` and `float` variants to the `Literal` type annotation of the `type` parameter in :meth:`pytest.Parser.addini`.\n\n\n- `#13563 <https://github.com/pytest-dev/pytest/issues/13563>`_: :func:`pytest.approx` now only imports ``numpy`` if NumPy is already in ``sys.modules``. This fixes unconditional import behavior introduced in `8.4.0`.\n\n\n\nImproved documentation\n----------------------\n\n- `#13577 <https://github.com/pytest-dev/pytest/issues/13577>`_: Clarify that ``pytest_generate_tests`` is discovered in test modules/classes; other hooks must be in ``conftest.py`` or plugins.\n\n\n\nContributor-facing changes\n--------------------------\n\n- `#13480 <https://github.com/pytest-dev/pytest/issues/13480>`_: Self-testing: fixed a few test failures when run with ``-Wdefault`` or a similar override.\n\n\n- `#13547 <https://github.com/pytest-dev/pytest/issues/13547>`_: Self-testing: corrected expected message for ``test_doctest_unexpected_exception`` in Python ``3.14``.\n\n\n- `#13684 <https://github.com/pytest-dev/pytest/issues/13684>`_: Make pytest's own testsuite insensitive to the presence of the ``CI`` environment variable -- by :user:`ogrisel`.\n\n\npytest 8.4.1 (2025-06-17)\n=========================\n\nBug fixes\n---------\n\n- `#13461 <https://github.com/pytest-dev/pytest/issues/13461>`_: Corrected ``_pytest.terminal.TerminalReporter.isatty`` to support\n  being called as a method. Before it was just a boolean which could\n  break correct code when using ``-o log_cli=true``).\n\n\n- `#13477 <https://github.com/pytest-dev/pytest/issues/13477>`_: Reintroduced :class:`pytest.PytestReturnNotNoneWarning` which was removed by accident in pytest `8.4`.\n\n  This warning is raised when a test functions returns a value other than ``None``, which is often a mistake made by beginners.\n\n  See :ref:`return-not-none` for more information.\n\n\n- `#13497 <https://github.com/pytest-dev/pytest/issues/13497>`_: Fixed compatibility with ``Twisted 25+``.\n\n\n\nImproved documentation\n----------------------\n\n- `#13492 <https://github.com/pytest-dev/pytest/issues/13492>`_: Fixed outdated warning about ``faulthandler`` not working on Windows.\n\n\npytest 8.4.0 (2025-06-02)\n=========================\n\nRemovals and backward incompatible breaking changes\n---------------------------------------------------\n\n- `#11372 <https://github.com/pytest-dev/pytest/issues/11372>`_: Async tests will now fail, instead of warning+skipping, if you don't have any suitable plugin installed.\n\n\n- `#12346 <https://github.com/pytest-dev/pytest/issues/12346>`_: Tests will now fail, instead of raising a warning, if they return any value other than None.\n\n\n- `#12874 <https://github.com/pytest-dev/pytest/issues/12874>`_: We dropped support for Python 3.8 following its end of life (2024-10-07).\n\n\n- `#12960 <https://github.com/pytest-dev/pytest/issues/12960>`_: Test functions containing a yield now cause an explicit error. They have not been run since pytest 4.0, and were previously marked as an expected failure and deprecation warning.\n\n  See :ref:`the docs <yield tests deprecated>` for more information.\n\n\n\nDeprecations (removal in next major release)\n--------------------------------------------\n\n- `#10839 <https://github.com/pytest-dev/pytest/issues/10839>`_: Requesting an asynchronous fixture without a `pytest_fixture_setup` hook that resolves it will now give a DeprecationWarning. This most commonly happens if a sync test requests an async fixture. This should have no effect on a majority of users with async tests or fixtures using async pytest plugins, but may affect non-standard hook setups or ``autouse=True``. For guidance on how to work around this warning see :ref:`sync-test-async-fixture`.\n\n\n\nNew features\n------------\n\n- `#11538 <https://github.com/pytest-dev/pytest/issues/11538>`_: Added :class:`pytest.RaisesGroup` as an equivalent to :func:`pytest.raises` for expecting :exc:`ExceptionGroup`. Also adds :class:`pytest.RaisesExc` which is now the logic behind :func:`pytest.raises` and used as parameter to :class:`pytest.RaisesGroup`. ``RaisesGroup`` includes the ability to specify multiple different expected exceptions, the structure of nested exception groups, and flags for emulating :ref:`except* <except_star>`. See :ref:`assert-matching-exception-groups` and docstrings for more information.\n\n\n- `#12081 <https://github.com/pytest-dev/pytest/issues/12081>`_: Added :fixture:`capteesys` to capture AND pass output to next handler set by ``--capture=``.\n\n\n- `#12504 <https://github.com/pytest-dev/pytest/issues/12504>`_: :func:`pytest.mark.xfail` now accepts :class:`pytest.RaisesGroup` for the ``raises`` parameter when you expect an exception group. You can also pass a :class:`pytest.RaisesExc` if you e.g. want to make use of the ``check`` parameter.\n\n\n- `#12713 <https://github.com/pytest-dev/pytest/issues/12713>`_: New `--force-short-summary` option to force condensed summary output regardless of verbosity level.\n\n  This lets users still see condensed summary output of failures for quick reference in log files from job outputs, being especially useful if non-condensed output is very verbose.\n\n\n- `#12749 <https://github.com/pytest-dev/pytest/issues/12749>`_: pytest traditionally collects classes/functions in the test module namespace even if they are imported from another file.\n\n  For example:\n\n  .. code-block:: python\n\n      # contents of src/domain.py\n      class Testament: ...\n\n\n      # contents of tests/test_testament.py\n      from domain import Testament\n\n\n      def test_testament(): ...\n\n  In this scenario with the default options, pytest will collect the class `Testament` from `tests/test_testament.py` because it starts with `Test`, even though in this case it is a production class being imported in the test module namespace.\n\n  This behavior can now be prevented by setting the new :confval:`collect_imported_tests` configuration option to ``false``, which will make pytest collect classes/functions from test files **only** if they are defined in that file.\n\n  -- by :user:`FreerGit`\n\n\n- `#12765 <https://github.com/pytest-dev/pytest/issues/12765>`_: Thresholds to trigger snippet truncation can now be set with :confval:`truncation_limit_lines` and :confval:`truncation_limit_chars`.\n\n  See :ref:`truncation-params` for more information.\n\n\n- `#13125 <https://github.com/pytest-dev/pytest/issues/13125>`_: :confval:`console_output_style` now supports ``times`` to show execution time of each test.\n\n\n- `#13192 <https://github.com/pytest-dev/pytest/issues/13192>`_: :func:`pytest.raises` will now raise a warning when passing an empty string to ``match``, as this will match against any value. Use ``match=\"^$\"`` if you want to check that an exception has no message.\n\n\n- `#13192 <https://github.com/pytest-dev/pytest/issues/13192>`_: :func:`pytest.raises` will now print a helpful string diff if matching fails and the match parameter has ``^`` and ``$`` and is otherwise escaped.\n\n\n- `#13192 <https://github.com/pytest-dev/pytest/issues/13192>`_: You can now pass :func:`with pytest.raises(check=fn): <pytest.raises>`, where ``fn`` is a function which takes a raised exception and returns a boolean. The ``raises`` fails if no exception was raised (as usual), passes if an exception is raised and ``fn`` returns ``True`` (as well as ``match`` and the type matching, if specified, which are checked before), and propagates the exception if ``fn`` returns ``False`` (which likely also fails the test).\n\n\n- `#13228 <https://github.com/pytest-dev/pytest/issues/13228>`_: :ref:`hidden-param` can now be used in ``id`` of :func:`pytest.param` or in\n  ``ids`` of :py:func:`Metafunc.parametrize <pytest.Metafunc.parametrize>`.\n  It hides the parameter set from the test name.\n\n\n- `#13253 <https://github.com/pytest-dev/pytest/issues/13253>`_: New flag: :ref:`--disable-plugin-autoload <disable_plugin_autoload>` which works as an alternative to :envvar:`PYTEST_DISABLE_PLUGIN_AUTOLOAD` when setting environment variables is inconvenient; and allows setting it in config files with :confval:`addopts`.\n\n\n\nImprovements in existing functionality\n--------------------------------------\n\n- `#10224 <https://github.com/pytest-dev/pytest/issues/10224>`_: pytest's ``short`` and ``long`` traceback styles (:ref:`how-to-modifying-python-tb-printing`)\n  now have partial :pep:`657` support and will show specific code segments in the\n  traceback.\n\n  .. code-block:: pytest\n\n      ================================= FAILURES =================================\n      _______________________ test_gets_correct_tracebacks _______________________\n\n      test_tracebacks.py:12: in test_gets_correct_tracebacks\n          assert manhattan_distance(p1, p2) == 1\n                 ^^^^^^^^^^^^^^^^^^^^^^^^^^\n      test_tracebacks.py:6: in manhattan_distance\n          return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)\n                                 ^^^^^^^^^\n      E   AttributeError: 'NoneType' object has no attribute 'x'\n\n  -- by :user:`ammaraskar`\n\n\n- `#11118 <https://github.com/pytest-dev/pytest/issues/11118>`_: Now :confval:`pythonpath` configures `$PYTHONPATH` earlier than before during the initialization process, which now also affects plugins loaded via the `-p` command-line option.\n\n  -- by :user:`millerdev`\n\n\n- `#11381 <https://github.com/pytest-dev/pytest/issues/11381>`_: The ``type`` parameter of the ``parser.addini`` method now accepts `\"int\"` and ``\"float\"`` parameters, facilitating the parsing of configuration values in the configuration file.\n\n  Example:\n\n  .. code-block:: python\n\n    def pytest_addoption(parser):\n        parser.addini(\"int_value\", type=\"int\", default=2, help=\"my int value\")\n        parser.addini(\"float_value\", type=\"float\", default=4.2, help=\"my float value\")\n\n  The `pytest.ini` file:\n\n  .. code-block:: ini\n\n    [pytest]\n    int_value = 3\n    float_value = 5.4\n\n\n- `#11525 <https://github.com/pytest-dev/pytest/issues/11525>`_: Fixtures are now clearly represented in the output as a \"fixture object\", not as a normal function as before, making it easy for beginners to catch mistakes such as referencing a fixture declared in the same module but not requested in the test function.\n\n  -- by :user:`the-compiler` and :user:`glyphack`\n\n\n- `#12426 <https://github.com/pytest-dev/pytest/issues/12426>`_: A warning is now issued when :ref:`pytest.mark.usefixtures ref` is used without specifying any fixtures. Previously, empty usefixtures markers were silently ignored.\n\n\n- `#12707 <https://github.com/pytest-dev/pytest/issues/12707>`_: Exception chains can be navigated when dropped into Pdb in Python 3.13+.\n\n\n- `#12736 <https://github.com/pytest-dev/pytest/issues/12736>`_: Added a new attribute `name` with the fixed value `\"pytest tests\"` to the root tag `testsuites` of the junit-xml generated by pytest.\n\n  This attribute is part of many junit-xml specifications and is even part of the `junit-10.xsd` specification that pytest's implementation is based on.\n\n\n- `#12943 <https://github.com/pytest-dev/pytest/issues/12943>`_: If a test fails with an exceptiongroup with a single exception, the contained exception will now be displayed in the short test summary info.\n\n\n- `#12958 <https://github.com/pytest-dev/pytest/issues/12958>`_: A number of :ref:`unraisable <unraisable>` enhancements:\n\n  * Set the unraisable hook as early as possible and unset it as late as possible, to collect the most possible number of unraisable exceptions.\n  * Call the garbage collector just before unsetting the unraisable hook, to collect any straggling exceptions.\n  * Collect multiple unraisable exceptions per test phase.\n  * Report the :mod:`tracemalloc` allocation traceback (if available).\n  * Avoid using a generator based hook to allow handling :class:`StopIteration` in test failures.\n  * Report the unraisable exception as the cause of the :class:`pytest.PytestUnraisableExceptionWarning` exception if raised.\n  * Compute the ``repr`` of the unraisable object in the unraisable hook so you get the latest information if available, and should help with resurrection of the object.\n\n\n- `#13010 <https://github.com/pytest-dev/pytest/issues/13010>`_: :func:`pytest.approx` now can compare collections that contain numbers and non-numbers mixed.\n\n\n- `#13016 <https://github.com/pytest-dev/pytest/issues/13016>`_: A number of :ref:`threadexception <unraisable>` enhancements:\n\n  * Set the excepthook as early as possible and unset it as late as possible, to collect the most possible number of unhandled exceptions from threads.\n  * Collect multiple thread exceptions per test phase.\n  * Report the :mod:`tracemalloc` allocation traceback (if available).\n  * Avoid using a generator based hook to allow handling :class:`StopIteration` in test failures.\n  * Report the thread exception as the cause of the :class:`pytest.PytestUnhandledThreadExceptionWarning` exception if raised.\n  * Extract the ``name`` of the thread object in the excepthook which should help with resurrection of the thread.\n\n\n- `#13031 <https://github.com/pytest-dev/pytest/issues/13031>`_: An empty parameter set as in ``pytest.mark.parametrize([], ids=idfunc)`` will no longer trigger a call to ``idfunc`` with internal objects.\n\n\n- `#13115 <https://github.com/pytest-dev/pytest/issues/13115>`_: Allows supplying ``ExceptionGroup[Exception]`` and ``BaseExceptionGroup[BaseException]`` to ``pytest.raises`` to keep full typing on :class:`ExceptionInfo <pytest.ExceptionInfo>`:\n\n  .. code-block:: python\n\n      with pytest.raises(ExceptionGroup[Exception]) as exc_info:\n          some_function()\n\n  Parametrizing with other exception types remains an error - we do not check the types of child exceptions and thus do not permit code that might look like we do.\n\n\n- `#13122 <https://github.com/pytest-dev/pytest/issues/13122>`_: The ``--stepwise`` mode received a number of improvements:\n\n  * It no longer forgets the last failed test in case pytest is executed later without the flag.\n\n    This enables the following workflow:\n\n    1. Execute pytest with ``--stepwise``, pytest then stops at the first failing test;\n    2. Iteratively update the code and run the test in isolation, without the ``--stepwise`` flag (for example in an IDE), until it is fixed.\n    3. Execute pytest with ``--stepwise`` again and pytest will continue from the previously failed test, and if it passes, continue on to the next tests.\n\n    Previously, at step 3, pytest would start from the beginning, forgetting the previously failed test.\n\n    This change however might cause issues if the ``--stepwise`` mode is used far apart in time, as the state might get stale, so the internal state will be reset automatically in case the test suite changes (for now only the number of tests are considered for this, we might change/improve this on the future).\n\n  * New ``--stepwise-reset``/``--sw-reset`` flag, allowing the user to explicitly reset the stepwise state and restart the workflow from the beginning.\n\n\n- `#13308 <https://github.com/pytest-dev/pytest/issues/13308>`_: Added official support for Python 3.14.\n\n\n- `#13380 <https://github.com/pytest-dev/pytest/issues/13380>`_: Fix :class:`ExceptionGroup` traceback filtering to exclude pytest internals.\n\n\n- `#13415 <https://github.com/pytest-dev/pytest/issues/13415>`_: The author metadata of the BibTex example is now correctly formatted with last names following first names.\n  An example of BibLaTex has been added.\n  BibTex and BibLaTex examples now clearly indicate that what is cited is software.\n\n  -- by :user:`willynilly`\n\n\n- `#13420 <https://github.com/pytest-dev/pytest/issues/13420>`_: Improved test collection performance by optimizing path resolution used in ``FSCollector``.\n\n\n- `#13457 <https://github.com/pytest-dev/pytest/issues/13457>`_: The error message about duplicate parametrization no longer displays an internal stack trace.\n\n\n- `#4112 <https://github.com/pytest-dev/pytest/issues/4112>`_: Using :ref:`pytest.mark.usefixtures <pytest.mark.usefixtures ref>` on :func:`pytest.param` now produces an error instead of silently doing nothing.\n\n\n- `#5473 <https://github.com/pytest-dev/pytest/issues/5473>`_: Replace `:` with `;` in the assertion rewrite warning message so it can be filtered using standard Python warning filters before calling :func:`pytest.main`.\n\n\n- `#6985 <https://github.com/pytest-dev/pytest/issues/6985>`_: Improved :func:`pytest.approx` to enhance the readability of value ranges and tolerances between 0.001 and 1000.\n    * The `repr` method now provides clearer output for values within those ranges, making it easier to interpret the results.\n    * Previously, the output for those ranges of values and tolerances was displayed in scientific notation (e.g., `42 ± 1.0e+00`). The updated method now presents the tolerance as a decimal for better readability (e.g., `42 ± 1`).\n\n      Example:\n\n      **Previous Output:**\n\n      .. code-block:: console\n\n          >>> pytest.approx(42, abs=1)\n          42 ± 1.0e+00\n\n      **Current Output:**\n\n      .. code-block:: console\n\n          >>> pytest.approx(42, abs=1)\n          42 ± 1\n\n    -- by :user:`fazeelghafoor`\n\n\n- `#7683 <https://github.com/pytest-dev/pytest/issues/7683>`_: The formerly optional ``pygments`` dependency is now required, causing output always to be source-highlighted (unless disabled via the ``--code-highlight=no`` CLI option).\n\n\n\nBug fixes\n---------\n\n- `#10404 <https://github.com/pytest-dev/pytest/issues/10404>`_: Apply filterwarnings from config/cli as soon as possible, and revert them as late as possible\n  so that warnings as errors are collected throughout the pytest run and before the\n  unraisable and threadexcept hooks are removed.\n\n  This allows very late warnings and unraisable/threadexcept exceptions to fail the test suite.\n\n  This also changes the warning that the lsof plugin issues from PytestWarning to the new warning PytestFDWarning so it can be more easily filtered.\n\n\n- `#11067 <https://github.com/pytest-dev/pytest/issues/11067>`_: The test report is now consistent regardless if the test xfailed via :ref:`pytest.mark.xfail <pytest.mark.xfail ref>` or :func:`pytest.fail`.\n\n  Previously, *xfailed* tests via the marker would have the string ``\"reason: \"`` prefixed to the message, while those *xfailed* via the function did not. The prefix has been removed.\n\n\n- `#12008 <https://github.com/pytest-dev/pytest/issues/12008>`_: In :pr:`11220`, an unintended change in reordering was introduced by changing the way indices were assigned to direct params. More specifically, before that change, the indices of direct params to metafunc's callspecs were assigned after all parametrizations took place. Now, that change is reverted.\n\n\n- `#12863 <https://github.com/pytest-dev/pytest/issues/12863>`_: Fix applying markers, including :ref:`pytest.mark.parametrize <pytest.mark.parametrize ref>` when placed above `@staticmethod` or `@classmethod`.\n\n\n- `#12929 <https://github.com/pytest-dev/pytest/issues/12929>`_: Handle StopIteration from test cases, setup and teardown correctly.\n\n\n- `#12938 <https://github.com/pytest-dev/pytest/issues/12938>`_: Fixed ``--durations-min`` argument not respected if ``-vv`` is used.\n\n\n- `#12946 <https://github.com/pytest-dev/pytest/issues/12946>`_: Fixed missing help for :mod:`pdb` commands wrapped by pytest -- by :user:`adamchainz`.\n\n\n- `#12981 <https://github.com/pytest-dev/pytest/issues/12981>`_: Prevent exceptions in :func:`pytest.Config.add_cleanup` callbacks preventing further cleanups.\n\n\n- `#13047 <https://github.com/pytest-dev/pytest/issues/13047>`_: Restore :func:`pytest.approx` handling of equality checks between `bool` and `numpy.bool_` types.\n\n  Comparing `bool` and `numpy.bool_` using :func:`pytest.approx` accidentally changed in version `8.3.4` and `8.3.5` to no longer match:\n\n  .. code-block:: pycon\n\n      >>> import numpy as np\n      >>> from pytest import approx\n      >>> [np.True_, np.True_] == pytest.approx([True, True])\n      False\n\n  This has now been fixed:\n\n  .. code-block:: pycon\n\n      >>> [np.True_, np.True_] == pytest.approx([True, True])\n      True\n\n\n- `#13119 <https://github.com/pytest-dev/pytest/issues/13119>`_: Improved handling of invalid regex patterns for filter warnings by providing a clear error message.\n\n\n- `#13175 <https://github.com/pytest-dev/pytest/issues/13175>`_: The diff is now also highlighted correctly when comparing two strings.\n\n\n- `#13248 <https://github.com/pytest-dev/pytest/issues/13248>`_: Fixed an issue where passing a ``scope`` in :py:func:`Metafunc.parametrize <pytest.Metafunc.parametrize>` with ``indirect=True``\n  could result in other fixtures being unable to depend on the parametrized fixture.\n\n\n- `#13291 <https://github.com/pytest-dev/pytest/issues/13291>`_: Fixed ``repr`` of ``attrs`` objects in assertion failure messages when using ``attrs>=25.2``.\n\n\n- `#13312 <https://github.com/pytest-dev/pytest/issues/13312>`_: Fixed a possible ``KeyError`` crash on PyPy during collection of tests involving higher-scoped parameters.\n\n\n- `#13345 <https://github.com/pytest-dev/pytest/issues/13345>`_: Fix type hints for :attr:`pytest.TestReport.when` and :attr:`pytest.TestReport.location`.\n\n\n- `#13377 <https://github.com/pytest-dev/pytest/issues/13377>`_: Fixed handling of test methods with positional-only parameter syntax.\n\n  Now, methods are supported that formally define ``self`` as positional-only\n  and/or fixture parameters as keyword-only, e.g.:\n\n  .. code-block:: python\n\n      class TestClass:\n\n          def test_method(self, /, *, fixture): ...\n\n  Before, this caused an internal error in pytest.\n\n\n- `#13384 <https://github.com/pytest-dev/pytest/issues/13384>`_: Fixed an issue where pytest could report negative durations.\n\n\n- `#13420 <https://github.com/pytest-dev/pytest/issues/13420>`_: Added ``lru_cache`` to ``nodes._check_initialpaths_for_relpath``.\n\n\n- `#9037 <https://github.com/pytest-dev/pytest/issues/9037>`_: Honor :confval:`disable_test_id_escaping_and_forfeit_all_rights_to_community_support` when escaping ids in parametrized tests.\n\n\n\nImproved documentation\n----------------------\n\n- `#12535 <https://github.com/pytest-dev/pytest/issues/12535>`_: `This\n  example`<https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures>\n  showed ``print`` statements that do not exactly reflect what the\n  different branches actually do.  The fix makes the example more precise.\n\n\n- `#13218 <https://github.com/pytest-dev/pytest/issues/13218>`_: Pointed out in the :func:`pytest.approx` documentation that it considers booleans unequal to numeric zero or one.\n\n\n- `#13221 <https://github.com/pytest-dev/pytest/issues/13221>`_: Improved grouping of CLI options in the ``--help`` output.\n\n\n- `#6649 <https://github.com/pytest-dev/pytest/issues/6649>`_: Added :class:`~pytest.TerminalReporter` to the :ref:`api-reference` documentation page.\n\n\n- `#8612 <https://github.com/pytest-dev/pytest/issues/8612>`_: Add a recipe for handling abstract test classes in the documentation.\n\n  A new example has been added to the documentation to demonstrate how to use a mixin class to handle abstract\n  test classes without manually setting the ``__test__`` attribute for subclasses.\n  This ensures that subclasses of abstract test classes are automatically collected by pytest.\n\n\n\nPackaging updates and notes for downstreams\n-------------------------------------------\n\n- `#13317 <https://github.com/pytest-dev/pytest/issues/13317>`_: Specified minimum allowed versions of ``colorama``, ``iniconfig``,\n  and ``packaging``; and bumped the minimum allowed version\n  of ``exceptiongroup`` for ``python_version<'3.11'`` from a release\n  candidate to a full release.\n\n\n\nContributor-facing changes\n--------------------------\n\n- `#12017 <https://github.com/pytest-dev/pytest/issues/12017>`_: Mixed internal improvements:\n\n  * Migrate formatting to f-strings in some tests.\n  * Use type-safe constructs in JUnitXML tests.\n  * Moved`` MockTiming`` into ``_pytest.timing``.\n\n  -- by :user:`RonnyPfannschmidt`\n\n\n- `#12647 <https://github.com/pytest-dev/pytest/issues/12647>`_: Fixed running the test suite with the ``hypothesis`` pytest plugin.\n\n\n\nMiscellaneous internal changes\n------------------------------\n\n- `#6649 <https://github.com/pytest-dev/pytest/issues/6649>`_: Added :class:`~pytest.TerminalReporter` to the public pytest API, as it is part of the signature of the :hook:`pytest_terminal_summary` hook.\n\n\npytest 8.3.5 (2025-03-02)\n=========================\n\nBug fixes\n---------\n\n- `#11777 <https://github.com/pytest-dev/pytest/issues/11777>`_: Fixed issue where sequences were still being shortened even with ``-vv`` verbosity.\n\n\n- `#12888 <https://github.com/pytest-dev/pytest/issues/12888>`_: Fixed broken input when using Python 3.13+ and a ``libedit`` build of Python, such as on macOS or with uv-managed Python binaries from the ``python-build-standalone`` project. This could manifest e.g. by a broken prompt when using ``Pdb``, or seeing empty inputs with manual usage of ``input()`` and suspended capturing.\n\n\n- `#13026 <https://github.com/pytest-dev/pytest/issues/13026>`_: Fixed :class:`AttributeError`  crash when using ``--import-mode=importlib`` when top-level directory same name as another module of the standard library.\n\n\n- `#13053 <https://github.com/pytest-dev/pytest/issues/13053>`_: Fixed a regression in pytest 8.3.4 where, when using ``--import-mode=importlib``, a directory containing py file with the same name would cause an ``ImportError``\n\n\n- `#13083 <https://github.com/pytest-dev/pytest/issues/13083>`_: Fixed issue where pytest could crash if one of the collected directories got removed during collection.\n\n\n\nImproved documentation\n----------------------\n\n- `#12842 <https://github.com/pytest-dev/pytest/issues/12842>`_: Added dedicated page about using types with pytest.\n\n  See :ref:`types` for detailed usage.\n\n\n\nContributor-facing changes\n--------------------------\n\n- `#13112 <https://github.com/pytest-dev/pytest/issues/13112>`_: Fixed selftest failures in ``test_terminal.py`` with Pygments >= 2.19.0\n\n\n- `#13256 <https://github.com/pytest-dev/pytest/issues/13256>`_: Support for Towncrier versions released in 2024 has been re-enabled\n  when building Sphinx docs -- by :user:`webknjaz`.\n\n\npytest 8.3.4 (2024-12-01)\n=========================\n\nBug fixes\n---------\n\n- `#12592 <https://github.com/pytest-dev/pytest/issues/12592>`_: Fixed :class:`KeyError` crash when using ``--import-mode=importlib`` in a directory layout where a directory contains a child directory with the same name.\n\n\n- `#12818 <https://github.com/pytest-dev/pytest/issues/12818>`_: Assertion rewriting now preserves the source ranges of the original instructions, making it play well with tools that deal with the ``AST``, like `executing <https://github.com/alexmojaki/executing>`__.\n\n\n- `#12849 <https://github.com/pytest-dev/pytest/issues/12849>`_: ANSI escape codes for colored output now handled correctly in :func:`pytest.fail` with `pytrace=False`.\n\n\n- `#9353 <https://github.com/pytest-dev/pytest/issues/9353>`_: :func:`pytest.approx` now uses strict equality when given booleans.\n\n\n\nImproved documentation\n----------------------\n\n- `#10558 <https://github.com/pytest-dev/pytest/issues/10558>`_: Fix ambiguous docstring of :func:`pytest.Config.getoption`.\n\n\n- `#10829 <https://github.com/pytest-dev/pytest/issues/10829>`_: Improve documentation on the current handling of the ``--basetemp`` option and its lack of retention functionality (:ref:`temporary directory location and retention`).\n\n\n- `#12866 <https://github.com/pytest-dev/pytest/issues/12866>`_: Improved cross-references concerning the :fixture:`recwarn` fixture.\n\n\n- `#12966 <https://github.com/pytest-dev/pytest/issues/12966>`_: Clarify :ref:`filterwarnings` docs on filter precedence/order when using multiple :ref:`@pytest.mark.filterwarnings <pytest.mark.filterwarnings ref>` marks.\n\n\n\nContributor-facing changes\n--------------------------\n\n- `#12497 <https://github.com/pytest-dev/pytest/issues/12497>`_: Fixed two failing pdb-related tests on Python 3.13.\n\n\npytest 8.3.3 (2024-09-09)\n=========================\n\nBug fixes\n---------\n\n- `#12446 <https://github.com/pytest-dev/pytest/issues/12446>`_: Avoid calling ``@property`` (and other instance descriptors) during fixture discovery -- by :user:`asottile`\n\n\n- `#12659 <https://github.com/pytest-dev/pytest/issues/12659>`_: Fixed the issue of not displaying assertion failure differences when using the parameter ``--import-mode=importlib`` in pytest>=8.1.\n\n\n- `#12667 <https://github.com/pytest-dev/pytest/issues/12667>`_: Fixed a regression where type change in `ExceptionInfo.errisinstance` caused `mypy` to fail.\n\n\n- `#12744 <https://github.com/pytest-dev/pytest/issues/12744>`_: Fixed typing compatibility with Python 3.9 or less -- replaced `typing.Self` with `typing_extensions.Self` -- by :user:`Avasam`\n\n\n- `#12745 <https://github.com/pytest-dev/pytest/issues/12745>`_: Fixed an issue with backslashes being incorrectly converted in nodeid paths on Windows, ensuring consistent path handling across environments.\n\n\n- `#6682 <https://github.com/pytest-dev/pytest/issues/6682>`_: Fixed bug where the verbosity levels where not being respected when printing the \"msg\" part of failed assertion (as in ``assert condition, msg``).\n\n\n- `#9422 <https://github.com/pytest-dev/pytest/issues/9422>`_: Fix bug where disabling the terminal plugin via ``-p no:terminal`` would cause crashes related to missing the ``verbose`` option.\n\n  -- by :user:`GTowers1`\n\n\n\nImproved documentation\n----------------------\n\n- `#12663 <https://github.com/pytest-dev/pytest/issues/12663>`_: Clarify that the `pytest_deselected` hook should be called from `pytest_collection_modifyitems` hook implementations when items are deselected.\n\n\n- `#12678 <https://github.com/pytest-dev/pytest/issues/12678>`_: Remove erroneous quotes from `tmp_path_retention_policy` example in docs.\n\n\n\nMiscellaneous internal changes\n------------------------------\n\n- `#12769 <https://github.com/pytest-dev/pytest/issues/12769>`_: Fix typos discovered by codespell and add codespell to pre-commit hooks.\n\n\npytest 8.3.2 (2024-07-24)\n=========================\n\nBug fixes\n---------\n\n- `#12652 <https://github.com/pytest-dev/pytest/issues/12652>`_: Resolve regression `conda` environments where no longer being automatically detected.\n\n  -- by :user:`RonnyPfannschmidt`\n\n\npytest 8.3.1 (2024-07-20)\n=========================\n\nThe 8.3.0 release failed to include the change notes and docs for the release. This patch release remedies this. There are no other changes.\n\n\npytest 8.3.0 (2024-07-20)\n=========================\n\nNew features\n------------\n\n- `#12231 <https://github.com/pytest-dev/pytest/issues/12231>`_: Added `--xfail-tb` flag, which turns on traceback output for XFAIL results.\n\n  * If the `--xfail-tb` flag is not given, tracebacks for XFAIL results are NOT shown.\n  * The style of traceback for XFAIL is set with `--tb`, and can be `auto|long|short|line|native|no`.\n  * Note: Even if you have `--xfail-tb` set, you won't see them if `--tb=no`.\n\n  Some history:\n\n  With pytest 8.0, `-rx` or `-ra` would not only turn on summary reports for xfail, but also report the tracebacks for xfail results. This caused issues with some projects that utilize xfail, but don't want to see all of the xfail tracebacks.\n\n  This change detaches xfail tracebacks from `-rx`, and now we turn on xfail tracebacks with `--xfail-tb`. With this, the default `-rx`/ `-ra` behavior is identical to pre-8.0 with respect to xfail tracebacks. While this is a behavior change, it brings default behavior back to pre-8.0.0 behavior, which ultimately was considered the better course of action.\n\n  -- by :user:`okken`\n\n\n- `#12281 <https://github.com/pytest-dev/pytest/issues/12281>`_: Added support for keyword matching in marker expressions.\n\n  Now tests can be selected by marker keyword arguments.\n  Supported values are :class:`int`, (unescaped) :class:`str`, :class:`bool` & :data:`None`.\n\n  See :ref:`marker examples <marker_keyword_expression_example>` for more information.\n\n  -- by :user:`lovetheguitar`\n\n\n- `#12567 <https://github.com/pytest-dev/pytest/issues/12567>`_: Added ``--no-fold-skipped`` command line option.\n\n  If this option is set, then skipped tests in short summary are no longer grouped\n  by reason but all tests are printed individually with their nodeid in the same\n  way as other statuses.\n\n  -- by :user:`pbrezina`\n\n\n\nImprovements in existing functionality\n--------------------------------------\n\n- `#12469 <https://github.com/pytest-dev/pytest/issues/12469>`_: The console output now uses the \"third-party plugins\" terminology,\n  replacing the previously established but confusing and outdated\n  reference to :std:doc:`setuptools <setuptools:index>`\n  -- by :user:`webknjaz`.\n\n\n- `#12544 <https://github.com/pytest-dev/pytest/issues/12544>`_, `#12545 <https://github.com/pytest-dev/pytest/issues/12545>`_: Python virtual environment detection was improved by\n  checking for a :file:`pyvenv.cfg` file, ensuring reliable detection on\n  various platforms -- by :user:`zachsnickers`.\n\n\n- `#2871 <https://github.com/pytest-dev/pytest/issues/2871>`_: Do not truncate arguments to functions in output when running with `-vvv`.\n\n\n- `#389 <https://github.com/pytest-dev/pytest/issues/389>`_: The readability of assertion introspection of bound methods has been enhanced\n  -- by :user:`farbodahm`, :user:`webknjaz`, :user:`obestwalter`, :user:`flub`\n  and :user:`glyphack`.\n\n  Earlier, it was like:\n\n  .. code-block:: console\n\n      =================================== FAILURES ===================================\n      _____________________________________ test _____________________________________\n\n          def test():\n      >       assert Help().fun() == 2\n      E       assert 1 == 2\n      E        +  where 1 = <bound method Help.fun of <example.Help instance at 0x256a830>>()\n      E        +    where <bound method Help.fun of <example.Help instance at 0x256a830>> = <example.Help instance at 0x256a830>.fun\n      E        +      where <example.Help instance at 0x256a830> = Help()\n\n      example.py:7: AssertionError\n      =========================== 1 failed in 0.03 seconds ===========================\n\n\n  And now it's like:\n\n  .. code-block:: console\n\n      =================================== FAILURES ===================================\n      _____________________________________ test _____________________________________\n\n          def test():\n      >       assert Help().fun() == 2\n      E       assert 1 == 2\n      E        +  where 1 = fun()\n      E        +    where fun = <test_local.Help object at 0x1074be230>.fun\n      E        +      where <test_local.Help object at 0x1074be230> = Help()\n\n      test_local.py:13: AssertionError\n      =========================== 1 failed in 0.03 seconds ===========================\n\n\n- `#7662 <https://github.com/pytest-dev/pytest/issues/7662>`_: Added timezone information to the testsuite timestamp in the JUnit XML report.\n\n\n\nBug fixes\n---------\n\n- `#11706 <https://github.com/pytest-dev/pytest/issues/11706>`_: Fixed reporting of teardown errors in higher-scoped fixtures when using `--maxfail` or `--stepwise`.\n\n  Originally added in pytest 8.0.0, but reverted in 8.0.2 due to a regression in pytest-xdist.\n  This regression was fixed in pytest-xdist 3.6.1.\n\n\n- `#11797 <https://github.com/pytest-dev/pytest/issues/11797>`_: :func:`pytest.approx` now correctly handles :class:`Sequence <collections.abc.Sequence>`-like objects.\n\n\n- `#12204 <https://github.com/pytest-dev/pytest/issues/12204>`_, `#12264 <https://github.com/pytest-dev/pytest/issues/12264>`_: Fixed a regression in pytest 8.0 where tracebacks get longer and longer when multiple\n  tests fail due to a shared higher-scope fixture which raised -- by :user:`bluetech`.\n\n  Also fixed a similar regression in pytest 5.4 for collectors which raise during setup.\n\n  The fix necessitated internal changes which may affect some plugins:\n\n  * ``FixtureDef.cached_result[2]`` is now a tuple ``(exc, tb)``\n    instead of ``exc``.\n  * ``SetupState.stack`` failures are now a tuple ``(exc, tb)``\n    instead of ``exc``.\n\n\n- `#12275 <https://github.com/pytest-dev/pytest/issues/12275>`_: Fixed collection error upon encountering an :mod:`abstract <abc>` class, including abstract `unittest.TestCase` subclasses.\n\n\n- `#12328 <https://github.com/pytest-dev/pytest/issues/12328>`_: Fixed a regression in pytest 8.0.0 where package-scoped parameterized items were not correctly reordered to minimize setups/teardowns in some cases.\n\n\n- `#12424 <https://github.com/pytest-dev/pytest/issues/12424>`_: Fixed crash with `assert testcase is not None` assertion failure when re-running unittest tests using plugins like pytest-rerunfailures. Regressed in 8.2.2.\n\n\n- `#12472 <https://github.com/pytest-dev/pytest/issues/12472>`_: Fixed a crash when returning category ``\"error\"`` or ``\"failed\"`` with a custom test status from :hook:`pytest_report_teststatus` hook -- :user:`pbrezina`.\n\n\n- `#12505 <https://github.com/pytest-dev/pytest/issues/12505>`_: Improved handling of invalid regex patterns in :func:`pytest.raises(match=r'...') <pytest.raises>` by providing a clear error message.\n\n\n- `#12580 <https://github.com/pytest-dev/pytest/issues/12580>`_: Fixed a crash when using the cache class on Windows and the cache directory was created concurrently.\n\n\n- `#6962 <https://github.com/pytest-dev/pytest/issues/6962>`_: Parametrization parameters are now compared using `==` instead of `is` (`is` is still used as a fallback if the parameter does not support `==`).\n  This fixes use of parameters such as lists, which have a different `id` but compare equal, causing fixtures to be re-computed instead of being cached.\n\n\n- `#7166 <https://github.com/pytest-dev/pytest/issues/7166>`_: Fixed progress percentages (the ``[ 87%]`` at the edge of the screen) sometimes not aligning correctly when running with pytest-xdist ``-n``.\n\n\n\nImproved documentation\n----------------------\n\n- `#12153 <https://github.com/pytest-dev/pytest/issues/12153>`_: Documented using :envvar:`PYTEST_VERSION` to detect if code is running from within a pytest run.\n\n\n- `#12469 <https://github.com/pytest-dev/pytest/issues/12469>`_: The external plugin mentions in the documentation now avoid mentioning\n  :std:doc:`setuptools entry-points <setuptools:index>` as the concept is\n  much more generic nowadays. Instead, the terminology of \"external\",\n  \"installed\", or \"third-party\" plugins (or packages) replaces that.\n\n  -- by :user:`webknjaz`\n\n\n- `#12577 <https://github.com/pytest-dev/pytest/issues/12577>`_: `CI` and `BUILD_NUMBER` environment variables role is described in\n  the reference doc. They now also appear when doing `pytest -h`\n  -- by :user:`MarcBresson`.\n\n\n\nContributor-facing changes\n--------------------------\n\n- `#12467 <https://github.com/pytest-dev/pytest/issues/12467>`_: Migrated all internal type-annotations to the python3.10+ style by using the `annotations` future import.\n\n  -- by :user:`RonnyPfannschmidt`\n\n\n- `#11771 <https://github.com/pytest-dev/pytest/issues/11771>`_, `#12557 <https://github.com/pytest-dev/pytest/issues/12557>`_: The PyPy runtime version has been updated to 3.9 from 3.8 that introduced\n  a flaky bug at the garbage collector which was not expected to fix there\n  as the 3.8 is EoL.\n\n  -- by :user:`x612skm`\n\n\n- `#12493 <https://github.com/pytest-dev/pytest/issues/12493>`_: The change log draft preview integration has been refactored to use a\n  third party extension ``sphinxcontib-towncrier``. The previous in-repo\n  script was putting the change log preview file at\n  :file:`doc/en/_changelog_towncrier_draft.rst`. Said file is no longer\n  ignored in Git and might show up among untracked files in the\n  development environments of the contributors. To address that, the\n  contributors can run the following command that will clean it up:\n\n  .. code-block:: console\n\n     $ git clean -x -i -- doc/en/_changelog_towncrier_draft.rst\n\n  -- by :user:`webknjaz`\n\n\n- `#12498 <https://github.com/pytest-dev/pytest/issues/12498>`_: All the undocumented ``tox`` environments now have descriptions.\n  They can be listed in one's development environment by invoking\n  ``tox -av`` in a terminal.\n\n  -- by :user:`webknjaz`\n\n\n- `#12501 <https://github.com/pytest-dev/pytest/issues/12501>`_: The changelog configuration has been updated to introduce more accurate\n  audience-tailored categories. Previously, there was a ``trivial``\n  change log fragment type with an unclear and broad meaning. It was\n  removed and we now have ``contrib``, ``misc`` and ``packaging`` in\n  place of it.\n\n  The new change note types target the readers who are downstream\n  packagers and project contributors. Additionally, the miscellaneous\n  section is kept for unspecified updates that do not fit anywhere else.\n\n  -- by :user:`webknjaz`\n\n\n- `#12502 <https://github.com/pytest-dev/pytest/issues/12502>`_: The UX of the GitHub automation making pull requests to update the\n  plugin list has been updated. Previously, the maintainers had to close\n  the automatically created pull requests and re-open them to trigger the\n  CI runs. From now on, they only need to click the `Ready for review`\n  button instead.\n\n  -- by :user:`webknjaz`\n\n\n- `#12522 <https://github.com/pytest-dev/pytest/issues/12522>`_: The ``:pull:`` RST role has been replaced with a shorter\n  ``:pr:`` due to starting to use the implementation from\n  the third-party :pypi:`sphinx-issues` Sphinx extension\n  -- by :user:`webknjaz`.\n\n\n- `#12531 <https://github.com/pytest-dev/pytest/issues/12531>`_: The coverage reporting configuration has been updated to exclude\n  pytest's own tests marked as expected to fail from the coverage\n  report. This has an effect of reducing the influence of flaky\n  tests on the resulting number.\n\n  -- by :user:`webknjaz`\n\n\n- `#12533 <https://github.com/pytest-dev/pytest/issues/12533>`_: The ``extlinks`` Sphinx extension is no longer enabled. The ``:bpo:``\n  role it used to declare has been removed with that. BPO itself has\n  migrated to GitHub some years ago and it is possible to link the\n  respective issues by using their GitHub issue numbers and the\n  ``:issue:`` role that the ``sphinx-issues`` extension implements.\n\n  -- by :user:`webknjaz`\n\n\n- `#12562 <https://github.com/pytest-dev/pytest/issues/12562>`_: Possible typos in using the ``:user:`` RST role is now being linted\n  through the pre-commit tool integration -- by :user:`webknjaz`.\n\n\npytest 8.2.2 (2024-06-04)\n=========================\n\nBug Fixes\n---------\n\n- `#12355 <https://github.com/pytest-dev/pytest/issues/12355>`_: Fix possible catastrophic performance slowdown on a certain parametrization pattern involving many higher-scoped parameters.\n\n\n- `#12367 <https://github.com/pytest-dev/pytest/issues/12367>`_: Fix a regression in pytest 8.2.0 where unittest class instances (a fresh one is created for each test) were not released promptly on test teardown but only on session teardown.\n\n\n- `#12381 <https://github.com/pytest-dev/pytest/issues/12381>`_: Fix possible \"Directory not empty\" crashes arising from concurrent cache dir (``.pytest_cache``) creation. Regressed in pytest 8.2.0.\n\n\n\nImproved Documentation\n----------------------\n\n- `#12290 <https://github.com/pytest-dev/pytest/issues/12290>`_: Updated Sphinx theme to use Furo instead of Flask, enabling Dark mode theme.\n\n\n- `#12356 <https://github.com/pytest-dev/pytest/issues/12356>`_: Added a subsection to the documentation for debugging flaky tests to mention\n  lack of thread safety in pytest as a possible source of flakiness.\n\n\n- `#12363 <https://github.com/pytest-dev/pytest/issues/12363>`_: The documentation webpages now links to a canonical version to reduce outdated documentation in search engine results.\n\n\npytest 8.2.1 (2024-05-19)\n=========================\n\nImprovements\n------------\n\n- `#12334 <https://github.com/pytest-dev/pytest/issues/12334>`_: Support for Python 3.13 (beta1 at the time of writing).\n\n\n\nBug Fixes\n---------\n\n- `#12120 <https://github.com/pytest-dev/pytest/issues/12120>`_: Fix `PermissionError` crashes arising from directories which are not selected on the command-line.\n\n\n- `#12191 <https://github.com/pytest-dev/pytest/issues/12191>`_: Keyboard interrupts and system exits are now properly handled during the test collection.\n\n\n- `#12300 <https://github.com/pytest-dev/pytest/issues/12300>`_: Fixed handling of 'Function not implemented' error under squashfuse_ll, which is a different way to say that the mountpoint is read-only.\n\n\n- `#12308 <https://github.com/pytest-dev/pytest/issues/12308>`_: Fix a regression in pytest 8.2.0 where the permissions of automatically-created ``.pytest_cache`` directories became ``rwx------`` instead of the expected ``rwxr-xr-x``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#12333 <https://github.com/pytest-dev/pytest/issues/12333>`_: pytest releases are now attested using the recent `Artifact Attestation <https://github.blog/2024-05-02-introducing-artifact-attestations-now-in-public-beta/>`_ support from GitHub, allowing users to verify the provenance of pytest's sdist and wheel artifacts.\n\n\npytest 8.2.0 (2024-04-27)\n=========================\n\nBreaking Changes\n----------------\n\n- `#12089 <https://github.com/pytest-dev/pytest/pull/12089>`_: pytest now requires that :class:`unittest.TestCase` subclasses can be instantiated freely using ``MyTestCase('runTest')``.\n\n  If the class doesn't allow this, you may see an error during collection such as ``AttributeError: 'MyTestCase' object has no attribute 'runTest'``.\n\n  Classes which do not override ``__init__``, or do not access the test method in ``__init__`` using ``getattr`` or similar, are unaffected.\n\n  Classes which do should take care to not crash when ``\"runTest\"`` is given, as is shown in `unittest.TestCases's implementation <https://github.com/python/cpython/blob/51aefc5bf907ddffaaf083ded0de773adcdf08c8/Lib/unittest/case.py#L419-L426>`_.\n  Alternatively, consider using :meth:`setUp <unittest.TestCase.setUp>` instead of ``__init__``.\n\n  If you run into this issue using ``tornado.AsyncTestCase``, please see `issue 12263 <https://github.com/pytest-dev/pytest/issues/12263>`_.\n\n  If you run into this issue using an abstract ``TestCase`` subclass, please see `issue 12275 <https://github.com/pytest-dev/pytest/issues/12275>`_.\n\n  Historical note: the effect of this change on custom TestCase implementations was not properly considered initially, this is why it was done in a minor release. We apologize for the inconvenience.\n\nDeprecations\n------------\n\n- `#12069 <https://github.com/pytest-dev/pytest/issues/12069>`_: A deprecation warning is now raised when implementations of one of the following hooks request a deprecated ``py.path.local`` parameter instead of the ``pathlib.Path`` parameter which replaced it:\n\n  - :hook:`pytest_ignore_collect` - the ``path`` parameter - use ``collection_path`` instead.\n  - :hook:`pytest_collect_file` - the ``path`` parameter - use ``file_path`` instead.\n  - :hook:`pytest_pycollect_makemodule` - the ``path`` parameter - use ``module_path`` instead.\n  - :hook:`pytest_report_header` - the ``startdir`` parameter - use ``start_path`` instead.\n  - :hook:`pytest_report_collectionfinish` - the ``startdir`` parameter - use ``start_path`` instead.\n\n  The replacement parameters are available since pytest 7.0.0.\n  The old parameters will be removed in pytest 9.0.0.\n\n  See :ref:`legacy-path-hooks-deprecated` for more details.\n\n\n\nFeatures\n--------\n\n- `#11871 <https://github.com/pytest-dev/pytest/issues/11871>`_: Added support for reading command line arguments from a file using the prefix character ``@``, like e.g.: ``pytest @tests.txt``. The file must have one argument per line.\n\n  See :ref:`Read arguments from file <args-from-file>` for details.\n\n\n\nImprovements\n------------\n\n- `#11523 <https://github.com/pytest-dev/pytest/issues/11523>`_: :func:`pytest.importorskip` will now issue a warning if the module could be found, but raised :class:`ImportError` instead of :class:`ModuleNotFoundError`.\n\n  The warning can be suppressed by passing ``exc_type=ImportError`` to :func:`pytest.importorskip`.\n\n  See :ref:`import-or-skip-import-error` for details.\n\n\n- `#11728 <https://github.com/pytest-dev/pytest/issues/11728>`_: For ``unittest``-based tests, exceptions during class cleanup (as raised by functions registered with :meth:`TestCase.addClassCleanup <unittest.TestCase.addClassCleanup>`) are now reported instead of silently failing.\n\n\n- `#11777 <https://github.com/pytest-dev/pytest/issues/11777>`_: Text is no longer truncated in the ``short test summary info`` section when ``-vv`` is given.\n\n\n- `#12112 <https://github.com/pytest-dev/pytest/issues/12112>`_: Improved namespace packages detection when :confval:`consider_namespace_packages` is enabled, covering more situations (like editable installs).\n\n\n- `#9502 <https://github.com/pytest-dev/pytest/issues/9502>`_: Added :envvar:`PYTEST_VERSION` environment variable which is defined at the start of the pytest session and undefined afterwards. It contains the value of ``pytest.__version__``, and among other things can be used to easily check if code is running from within a pytest run.\n\n\n\nBug Fixes\n---------\n\n- `#12065 <https://github.com/pytest-dev/pytest/issues/12065>`_: Fixed a regression in pytest 8.0.0 where test classes containing ``setup_method`` and tests using ``@staticmethod`` or ``@classmethod`` would crash with ``AttributeError: 'NoneType' object has no attribute 'setup_method'``.\n\n  Now the :attr:`request.instance <pytest.FixtureRequest.instance>` attribute of tests using ``@staticmethod`` and ``@classmethod`` is no longer ``None``, but a fresh instance of the class, like in non-static methods.\n  Previously it was ``None``, and all fixtures of such tests would share a single ``self``.\n\n\n- `#12135 <https://github.com/pytest-dev/pytest/issues/12135>`_: Fixed issue where fixtures adding their finalizer multiple times to fixtures they request would cause unreliable and non-intuitive teardown ordering in some instances.\n\n\n- `#12194 <https://github.com/pytest-dev/pytest/issues/12194>`_: Fixed a bug with ``--importmode=importlib`` and ``--doctest-modules`` where child modules did not appear as attributes in parent modules.\n\n\n- `#1489 <https://github.com/pytest-dev/pytest/issues/1489>`_: Fixed some instances where teardown of higher-scoped fixtures was not happening in the reverse order they were initialized in.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#12069 <https://github.com/pytest-dev/pytest/issues/12069>`_: ``pluggy>=1.5.0`` is now required.\n\n\n- `#12167 <https://github.com/pytest-dev/pytest/issues/12167>`_: :ref:`cache <cache>`: create supporting files (``CACHEDIR.TAG``, ``.gitignore``, etc.) in a temporary directory to provide atomic semantics.\n\n\npytest 8.1.2 (2024-04-26)\n=========================\n\nBug Fixes\n---------\n\n- `#12114 <https://github.com/pytest-dev/pytest/issues/12114>`_: Fixed error in :func:`pytest.approx` when used with `numpy` arrays and comparing with other types.\n\n\npytest 8.1.1 (2024-03-08)\n=========================\n\n.. note::\n\n       This release is not a usual bug fix release -- it contains features and improvements, being a follow up\n       to ``8.1.0``, which has been yanked from PyPI.\n\nFeatures\n--------\n\n- `#11475 <https://github.com/pytest-dev/pytest/issues/11475>`_: Added the new :confval:`consider_namespace_packages` configuration option, defaulting to ``False``.\n\n  If set to ``True``, pytest will attempt to identify modules that are part of `namespace packages <https://packaging.python.org/en/latest/guides/packaging-namespace-packages>`__ when importing modules.\n\n\n- `#11653 <https://github.com/pytest-dev/pytest/issues/11653>`_: Added the new :confval:`verbosity_test_cases` configuration option for fine-grained control of test execution verbosity.\n  See :ref:`Fine-grained verbosity <pytest.fine_grained_verbosity>` for more details.\n\n\n\nImprovements\n------------\n\n- `#10865 <https://github.com/pytest-dev/pytest/issues/10865>`_: :func:`pytest.warns` now validates that :func:`warnings.warn` was called with a `str` or a `Warning`.\n  Currently in Python it is possible to use other types, however this causes an exception when :func:`warnings.filterwarnings` is used to filter those warnings (see `CPython #103577 <https://github.com/python/cpython/issues/103577>`__ for a discussion).\n  While this can be considered a bug in CPython, we decided to put guards in pytest as the error message produced without this check in place is confusing.\n\n\n- `#11311 <https://github.com/pytest-dev/pytest/issues/11311>`_: When using ``--override-ini`` for paths in invocations without a configuration file defined, the current working directory is used\n  as the relative directory.\n\n  Previously this would raise an :class:`AssertionError`.\n\n\n- `#11475 <https://github.com/pytest-dev/pytest/issues/11475>`_: :ref:`--import-mode=importlib <import-mode-importlib>` now tries to import modules using the standard import mechanism (but still without changing :py:data:`sys.path`), falling back to importing modules directly only if that fails.\n\n  This means that installed packages will be imported under their canonical name if possible first, for example ``app.core.models``, instead of having the module name always be derived from their path (for example ``.env310.lib.site_packages.app.core.models``).\n\n\n- `#11801 <https://github.com/pytest-dev/pytest/issues/11801>`_: Added the :func:`iter_parents() <_pytest.nodes.Node.iter_parents>` helper method on nodes.\n  It is similar to :func:`listchain <_pytest.nodes.Node.listchain>`, but goes from bottom to top, and returns an iterator, not a list.\n\n\n- `#11850 <https://github.com/pytest-dev/pytest/issues/11850>`_: Added support for :data:`sys.last_exc` for post-mortem debugging on Python>=3.12.\n\n\n- `#11962 <https://github.com/pytest-dev/pytest/issues/11962>`_: In case no other suitable candidates for configuration file are found, a ``pyproject.toml`` (even without a ``[tool.pytest.ini_options]`` table) will be considered as the configuration file and define the ``rootdir``.\n\n\n- `#11978 <https://github.com/pytest-dev/pytest/issues/11978>`_: Add ``--log-file-mode`` option to the logging plugin, enabling appending to log-files. This option accepts either ``\"w\"`` or ``\"a\"`` and defaults to ``\"w\"``.\n\n  Previously, the mode was hard-coded to be ``\"w\"`` which truncates the file before logging.\n\n\n- `#12047 <https://github.com/pytest-dev/pytest/issues/12047>`_: When multiple finalizers of a fixture raise an exception, now all exceptions are reported as an exception group.\n  Previously, only the first exception was reported.\n\n\n\nBug Fixes\n---------\n\n- `#11475 <https://github.com/pytest-dev/pytest/issues/11475>`_: Fixed regression where ``--importmode=importlib`` would import non-test modules more than once.\n\n\n- `#11904 <https://github.com/pytest-dev/pytest/issues/11904>`_: Fixed a regression in pytest 8.0.0 that would cause test collection to fail due to permission errors when using ``--pyargs``.\n\n  This change improves the collection tree for tests specified using ``--pyargs``, see :pr:`12043` for a comparison with pytest 8.0 and <8.\n\n\n- `#12011 <https://github.com/pytest-dev/pytest/issues/12011>`_: Fixed a regression in 8.0.1 whereby ``setup_module`` xunit-style fixtures are not executed when ``--doctest-modules`` is passed.\n\n\n- `#12014 <https://github.com/pytest-dev/pytest/issues/12014>`_: Fix the ``stacklevel`` used when warning about marks used on fixtures.\n\n\n- `#12039 <https://github.com/pytest-dev/pytest/issues/12039>`_: Fixed a regression in ``8.0.2`` where tests created using :fixture:`tmp_path` have been collected multiple times in CI under Windows.\n\n\nImproved Documentation\n----------------------\n\n- `#11790 <https://github.com/pytest-dev/pytest/issues/11790>`_: Documented the retention of temporary directories created using the ``tmp_path`` fixture in more detail.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#11785 <https://github.com/pytest-dev/pytest/issues/11785>`_: Some changes were made to private functions which may affect plugins which access them:\n\n  - ``FixtureManager._getautousenames()`` now takes a ``Node`` itself instead of the nodeid.\n  - ``FixtureManager.getfixturedefs()`` now takes the ``Node`` itself instead of the nodeid.\n  - The ``_pytest.nodes.iterparentnodeids()`` function is removed without replacement.\n    Prefer to traverse the node hierarchy itself instead.\n    If you really need to, copy the function from the previous pytest release.\n\n\n- `#12069 <https://github.com/pytest-dev/pytest/issues/12069>`_: Delayed the deprecation of the following features to ``9.0.0``:\n\n  * :ref:`node-ctor-fspath-deprecation`.\n  * :ref:`legacy-path-hooks-deprecated`.\n\n  It was discovered after ``8.1.0`` was released that the warnings about the impeding removal were not being displayed, so the team decided to revert the removal.\n\n  This is the reason for ``8.1.0`` being yanked.\n\n\npytest 8.1.0 (YANKED)\n=====================\n\n\n.. note::\n\n       This release has been **yanked**: it broke some plugins without the proper warning period, due to\n       some warnings not showing up as expected.\n\n       See `#12069 <https://github.com/pytest-dev/pytest/issues/12069>`__.\n\n\npytest 8.0.2 (2024-02-24)\n=========================\n\nBug Fixes\n---------\n\n- `#11895 <https://github.com/pytest-dev/pytest/issues/11895>`_: Fix collection on Windows where initial paths contain the short version of a path (for example ``c:\\PROGRA~1\\tests``).\n\n\n- `#11953 <https://github.com/pytest-dev/pytest/issues/11953>`_: Fix an ``IndexError`` crash raising from ``getstatementrange_ast``.\n\n\n- `#12021 <https://github.com/pytest-dev/pytest/issues/12021>`_: Reverted a fix to `--maxfail` handling in pytest 8.0.0 because it caused a regression in pytest-xdist whereby session fixture teardowns may get executed multiple times when the max-fails is reached.\n\n\npytest 8.0.1 (2024-02-16)\n=========================\n\nBug Fixes\n---------\n\n- `#11875 <https://github.com/pytest-dev/pytest/issues/11875>`_: Correctly handle errors from :func:`getpass.getuser` in Python 3.13.\n\n\n- `#11879 <https://github.com/pytest-dev/pytest/issues/11879>`_: Fix an edge case where ``ExceptionInfo._stringify_exception`` could crash :func:`pytest.raises`.\n\n\n- `#11906 <https://github.com/pytest-dev/pytest/issues/11906>`_: Fix regression with :func:`pytest.warns` using custom warning subclasses which have more than one parameter in their `__init__`.\n\n\n- `#11907 <https://github.com/pytest-dev/pytest/issues/11907>`_: Fix a regression in pytest 8.0.0 whereby calling :func:`pytest.skip` and similar control-flow exceptions within a :func:`pytest.warns()` block would get suppressed instead of propagating.\n\n\n- `#11929 <https://github.com/pytest-dev/pytest/issues/11929>`_: Fix a regression in pytest 8.0.0 whereby autouse fixtures defined in a module get ignored by the doctests in the module.\n\n\n- `#11937 <https://github.com/pytest-dev/pytest/issues/11937>`_: Fix a regression in pytest 8.0.0 whereby items would be collected in reverse order in some circumstances.\n\n\npytest 8.0.0 (2024-01-27)\n=========================\n\nBug Fixes\n---------\n\n- `#11842 <https://github.com/pytest-dev/pytest/issues/11842>`_: Properly escape the ``reason`` of a :ref:`skip <pytest.mark.skip ref>` mark when writing JUnit XML files.\n\n\n- `#11861 <https://github.com/pytest-dev/pytest/issues/11861>`_: Avoid microsecond exceeds ``1_000_000`` when using ``log-date-format`` with ``%f`` specifier, which might cause the test suite to crash.\n\n\npytest 8.0.0rc2 (2024-01-17)\n============================\n\n\nImprovements\n------------\n\n- `#11233 <https://github.com/pytest-dev/pytest/issues/11233>`_: Improvements to ``-r`` for xfailures and xpasses:\n\n  * Report tracebacks for xfailures when ``-rx`` is set.\n  * Report captured output for xpasses when ``-rX`` is set.\n  * For xpasses, add ``-`` in summary between test name and reason, to match how xfail is displayed.\n\n- `#11825 <https://github.com/pytest-dev/pytest/issues/11825>`_: The :hook:`pytest_plugin_registered` hook has a new ``plugin_name`` parameter containing the name by which ``plugin`` is registered.\n\n\nBug Fixes\n---------\n\n- `#11706 <https://github.com/pytest-dev/pytest/issues/11706>`_: Fix reporting of teardown errors in higher-scoped fixtures when using `--maxfail` or `--stepwise`.\n\n  NOTE: This change was reverted in pytest 8.0.2 to fix a `regression <https://github.com/pytest-dev/pytest-xdist/issues/1024>`_ it caused in pytest-xdist.\n\n\n- `#11758 <https://github.com/pytest-dev/pytest/issues/11758>`_: Fixed ``IndexError: string index out of range`` crash in ``if highlighted[-1] == \"\\n\" and source[-1] != \"\\n\"``.\n  This bug was introduced in pytest 8.0.0rc1.\n\n\n- `#9765 <https://github.com/pytest-dev/pytest/issues/9765>`_, `#11816 <https://github.com/pytest-dev/pytest/issues/11816>`_: Fixed a frustrating bug that afflicted some users with the only error being ``assert mod not in mods``. The issue was caused by the fact that ``str(Path(mod))`` and ``mod.__file__`` don't necessarily produce the same string, and was being erroneously used interchangeably in some places in the code.\n\n  This fix also broke the internal API of ``PytestPluginManager.consider_conftest`` by introducing a new parameter -- we mention this in case it is being used by external code, even if marked as *private*.\n\n\npytest 8.0.0rc1 (2023-12-30)\n============================\n\nBreaking Changes\n----------------\n\nOld Deprecations Are Now Errors\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n- `#7363 <https://github.com/pytest-dev/pytest/issues/7363>`_: **PytestRemovedIn8Warning deprecation warnings are now errors by default.**\n\n  Following our plan to remove deprecated features with as little disruption as\n  possible, all warnings of type ``PytestRemovedIn8Warning`` now generate errors\n  instead of warning messages by default.\n\n  **The affected features will be effectively removed in pytest 8.1**, so please consult the\n  :ref:`deprecations` section in the docs for directions on how to update existing code.\n\n  In the pytest ``8.0.X`` series, it is possible to change the errors back into warnings as a\n  stopgap measure by adding this to your ``pytest.ini`` file:\n\n  .. code-block:: ini\n\n      [pytest]\n      filterwarnings =\n          ignore::pytest.PytestRemovedIn8Warning\n\n  But this will stop working when pytest ``8.1`` is released.\n\n  **If you have concerns** about the removal of a specific feature, please add a\n  comment to :issue:`7363`.\n\n\nVersion Compatibility\n^^^^^^^^^^^^^^^^^^^^^\n\n- `#11151 <https://github.com/pytest-dev/pytest/issues/11151>`_: Dropped support for Python 3.7, which `reached end-of-life on 2023-06-27 <https://devguide.python.org/versions/>`__.\n\n\n- ``pluggy>=1.3.0`` is now required.\n\n\nCollection Changes\n^^^^^^^^^^^^^^^^^^\n\nIn this version we've made several breaking changes to pytest's collection phase,\nparticularly around how filesystem directories and Python packages are collected,\nfixing deficiencies and allowing for cleanups and improvements to pytest's internals.\nA deprecation period for these changes was not possible.\n\n\n- `#7777 <https://github.com/pytest-dev/pytest/issues/7777>`_: Files and directories are now collected in alphabetical order jointly, unless changed by a plugin.\n  Previously, files were collected before directories.\n  See below for an example.\n\n\n- `#8976 <https://github.com/pytest-dev/pytest/issues/8976>`_: Running `pytest pkg/__init__.py` now collects the `pkg/__init__.py` file (module) only.\n  Previously, it collected the entire `pkg` package, including other test files in the directory, but excluding tests in the `__init__.py` file itself\n  (unless :confval:`python_files` was changed to allow `__init__.py` file).\n\n  To collect the entire package, specify just the directory: `pytest pkg`.\n\n\n- `#11137 <https://github.com/pytest-dev/pytest/issues/11137>`_: :class:`pytest.Package` is no longer a :class:`pytest.Module` or :class:`pytest.File`.\n\n  The ``Package`` collector node designates a Python package, that is, a directory with an `__init__.py` file.\n  Previously ``Package`` was a subtype of ``pytest.Module`` (which represents a single Python module),\n  the module being the `__init__.py` file.\n  This has been deemed a design mistake (see :issue:`11137` and :issue:`7777` for details).\n\n  The ``path`` property of ``Package`` nodes now points to the package directory instead of the ``__init__.py`` file.\n\n  Note that a ``Module`` node for ``__init__.py`` (which is not a ``Package``) may still exist,\n  if it is picked up during collection (e.g. if you configured :confval:`python_files` to include ``__init__.py`` files).\n\n\n- `#7777 <https://github.com/pytest-dev/pytest/issues/7777>`_: Added a new :class:`pytest.Directory` base collection node, which all collector nodes for filesystem directories are expected to subclass.\n  This is analogous to the existing :class:`pytest.File` for file nodes.\n\n  Changed :class:`pytest.Package` to be a subclass of :class:`pytest.Directory`.\n  A ``Package`` represents a filesystem directory which is a Python package,\n  i.e. contains an ``__init__.py`` file.\n\n  :class:`pytest.Package` now only collects files in its own directory; previously it collected recursively.\n  Sub-directories are collected as their own collector nodes, which then collect themselves, thus creating a collection tree which mirrors the filesystem hierarchy.\n\n  Added a new :class:`pytest.Dir` concrete collection node, a subclass of :class:`pytest.Directory`.\n  This node represents a filesystem directory, which is not a :class:`pytest.Package`,\n  that is, does not contain an ``__init__.py`` file.\n  Similarly to ``Package``, it only collects the files in its own directory.\n\n  :class:`pytest.Session` now only collects the initial arguments, without recursing into directories.\n  This work is now done by the :func:`recursive expansion process <pytest.Collector.collect>` of directory collector nodes.\n\n  :attr:`session.name <pytest.Session.name>` is now ``\"\"``; previously it was the rootdir directory name.\n  This matches :attr:`session.nodeid <_pytest.nodes.Node.nodeid>` which has always been `\"\"`.\n\n  The collection tree now contains directories/packages up to the :ref:`rootdir <rootdir>`,\n  for initial arguments that are found within the rootdir.\n  For files outside the rootdir, only the immediate directory/package is collected --\n  note however that collecting from outside the rootdir is discouraged.\n\n  As an example, given the following filesystem tree::\n\n      myroot/\n          pytest.ini\n          top/\n          ├── aaa\n          │   └── test_aaa.py\n          ├── test_a.py\n          ├── test_b\n          │   ├── __init__.py\n          │   └── test_b.py\n          ├── test_c.py\n          └── zzz\n              ├── __init__.py\n              └── test_zzz.py\n\n  the collection tree, as shown by `pytest --collect-only top/` but with the otherwise-hidden :class:`~pytest.Session` node added for clarity,\n  is now the following::\n\n      <Session>\n        <Dir myroot>\n          <Dir top>\n            <Dir aaa>\n              <Module test_aaa.py>\n                <Function test_it>\n            <Module test_a.py>\n              <Function test_it>\n            <Package test_b>\n              <Module test_b.py>\n                <Function test_it>\n            <Module test_c.py>\n              <Function test_it>\n            <Package zzz>\n              <Module test_zzz.py>\n                <Function test_it>\n\n  Previously, it was::\n\n      <Session>\n        <Module top/test_a.py>\n          <Function test_it>\n        <Module top/test_c.py>\n          <Function test_it>\n        <Module top/aaa/test_aaa.py>\n          <Function test_it>\n        <Package test_b>\n          <Module test_b.py>\n            <Function test_it>\n        <Package zzz>\n          <Module test_zzz.py>\n            <Function test_it>\n\n  Code/plugins which rely on a specific shape of the collection tree might need to update.\n\n\n- `#11676 <https://github.com/pytest-dev/pytest/issues/11676>`_: The classes :class:`~_pytest.nodes.Node`, :class:`~pytest.Collector`, :class:`~pytest.Item`, :class:`~pytest.File`, :class:`~_pytest.nodes.FSCollector` are now marked abstract (see :mod:`abc`).\n\n  We do not expect this change to affect users and plugin authors, it will only cause errors when the code is already wrong or problematic.\n\n\nOther breaking changes\n^^^^^^^^^^^^^^^^^^^^^^\n\nThese are breaking changes where deprecation was not possible.\n\n\n- `#11282 <https://github.com/pytest-dev/pytest/issues/11282>`_: Sanitized the handling of the ``default`` parameter when defining configuration options.\n\n  Previously if ``default`` was not supplied for :meth:`parser.addini <pytest.Parser.addini>` and the configuration option value was not defined in a test session, then calls to :func:`config.getini <pytest.Config.getini>` returned an *empty list* or an *empty string* depending on whether ``type`` was supplied or not respectively, which is clearly incorrect. Also, ``None`` was not honored even if ``default=None`` was used explicitly while defining the option.\n\n  Now the behavior of :meth:`parser.addini <pytest.Parser.addini>` is as follows:\n\n  * If ``default`` is NOT passed but ``type`` is provided, then a type-specific default will be returned. For example ``type=bool`` will return ``False``, ``type=str`` will return ``\"\"``, etc.\n  * If ``default=None`` is passed and the option is not defined in a test session, then ``None`` will be returned, regardless of the ``type``.\n  * If neither ``default`` nor ``type`` are provided, assume ``type=str`` and return ``\"\"`` as default (this is as per previous behavior).\n\n  The team decided to not introduce a deprecation period for this change, as doing so would be complicated both in terms of communicating this to the community as well as implementing it, and also because the team believes this change should not break existing plugins except in rare cases.\n\n\n- `#11667 <https://github.com/pytest-dev/pytest/issues/11667>`_: pytest's ``setup.py`` file is removed.\n  If you relied on this file, e.g. to install pytest using ``setup.py install``,\n  please see `Why you shouldn't invoke setup.py directly <https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html#summary>`_ for alternatives.\n\n\n- `#9288 <https://github.com/pytest-dev/pytest/issues/9288>`_: :func:`~pytest.warns` now re-emits unmatched warnings when the context\n  closes -- previously it would consume all warnings, hiding those that were not\n  matched by the function.\n\n  While this is a new feature, we announce it as a breaking change\n  because many test suites are configured to error-out on warnings, and will\n  therefore fail on the newly-re-emitted warnings.\n\n\n- The internal ``FixtureManager.getfixtureclosure`` method has changed. Plugins which use this method or\n  which subclass ``FixtureManager`` and overwrite that method will need to adapt to the change.\n\n\n\nDeprecations\n------------\n\n- `#10465 <https://github.com/pytest-dev/pytest/issues/10465>`_: Test functions returning a value other than ``None`` will now issue a :class:`pytest.PytestWarning` instead of ``pytest.PytestRemovedIn8Warning``, meaning this will stay a warning instead of becoming an error in the future.\n\n\n- `#3664 <https://github.com/pytest-dev/pytest/issues/3664>`_: Applying a mark to a fixture function now issues a warning: marks in fixtures never had any effect, but it is a common user error to apply a mark to a fixture (for example ``usefixtures``) and expect it to work.\n\n  This will become an error in pytest 9.0.\n\n\n\nFeatures and Improvements\n-------------------------\n\nImproved Diffs\n^^^^^^^^^^^^^^\n\nThese changes improve the diffs that pytest prints when an assertion fails.\nNote that syntax highlighting requires the ``pygments`` package.\n\n\n- `#11520 <https://github.com/pytest-dev/pytest/issues/11520>`_: The very verbose (``-vv``) diff output is now colored as a diff instead of a big chunk of red.\n\n  Python code in error reports is now syntax-highlighted as Python.\n\n  The sections in the error reports are now better separated.\n\n\n- `#1531 <https://github.com/pytest-dev/pytest/issues/1531>`_: The very verbose diff (``-vv``) for every standard library container type is improved. The indentation is now consistent and the markers are on their own separate lines, which should reduce the diffs shown to users.\n\n  Previously, the standard Python pretty printer was used to generate the output, which puts opening and closing\n  markers on the same line as the first/last entry, in addition to not having consistent indentation.\n\n\n- `#10617 <https://github.com/pytest-dev/pytest/issues/10617>`_: Added more comprehensive set assertion rewrites for comparisons other than equality ``==``, with\n  the following operations now providing better failure messages: ``!=``, ``<=``, ``>=``, ``<``, and ``>``.\n\n\nSeparate Control For Assertion Verbosity\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n- `#11387 <https://github.com/pytest-dev/pytest/issues/11387>`_: Added the new :confval:`verbosity_assertions` configuration option for fine-grained control of failed assertions verbosity.\n\n  If you've ever wished that pytest always show you full diffs, but without making everything else verbose, this is for you.\n\n  See :ref:`Fine-grained verbosity <pytest.fine_grained_verbosity>` for more details.\n\n  For plugin authors, :attr:`config.get_verbosity <pytest.Config.get_verbosity>` can be used to retrieve the verbosity level for a specific verbosity type.\n\n\nAdditional Support For Exception Groups and ``__notes__``\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThese changes improve pytest's support for exception groups.\n\n\n- `#10441 <https://github.com/pytest-dev/pytest/issues/10441>`_: Added :func:`ExceptionInfo.group_contains() <pytest.ExceptionInfo.group_contains>`, an assertion helper that tests if an :class:`ExceptionGroup` contains a matching exception.\n\n  See :ref:`assert-matching-exception-groups` for an example.\n\n\n- `#11227 <https://github.com/pytest-dev/pytest/issues/11227>`_: Allow :func:`pytest.raises` ``match`` argument to match against `PEP-678 <https://peps.python.org/pep-0678/>` ``__notes__``.\n\n\nCustom Directory collectors\n^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n- `#7777 <https://github.com/pytest-dev/pytest/issues/7777>`_: Added a new hook :hook:`pytest_collect_directory`,\n  which is called by filesystem-traversing collector nodes,\n  such as :class:`pytest.Session`, :class:`pytest.Dir` and :class:`pytest.Package`,\n  to create a collector node for a sub-directory.\n  It is expected to return a subclass of :class:`pytest.Directory`.\n  This hook allows plugins to :ref:`customize the collection of directories <custom directory collectors>`.\n\n\n\"New-style\" Hook Wrappers\n^^^^^^^^^^^^^^^^^^^^^^^^^\n\n- `#11122 <https://github.com/pytest-dev/pytest/issues/11122>`_: pytest now uses \"new-style\" hook wrappers internally, available since pluggy 1.2.0.\n  See `pluggy's 1.2.0 changelog <https://pluggy.readthedocs.io/en/latest/changelog.html#pluggy-1-2-0-2023-06-21>`_ and the :ref:`updated docs <hookwrapper>` for details.\n\n  Plugins which want to use new-style wrappers can do so if they require ``pytest>=8``.\n\n\nOther Improvements\n^^^^^^^^^^^^^^^^^^\n\n- `#11216 <https://github.com/pytest-dev/pytest/issues/11216>`_: If a test is skipped from inside an :ref:`xunit setup fixture <classic xunit>`, the test summary now shows the test location instead of the fixture location.\n\n\n- `#11314 <https://github.com/pytest-dev/pytest/issues/11314>`_: Logging to a file using the ``--log-file`` option will use ``--log-level``, ``--log-format`` and ``--log-date-format`` as fallback\n  if ``--log-file-level``, ``--log-file-format`` and ``--log-file-date-format`` are not provided respectively.\n\n\n- `#11610 <https://github.com/pytest-dev/pytest/issues/11610>`_: Added the :func:`LogCaptureFixture.filtering() <pytest.LogCaptureFixture.filtering>` context manager which\n  adds a given :class:`logging.Filter` object to the :fixture:`caplog` fixture.\n\n\n- `#11447 <https://github.com/pytest-dev/pytest/issues/11447>`_: :func:`pytest.deprecated_call` now also considers warnings of type :class:`FutureWarning`.\n\n\n- `#11600 <https://github.com/pytest-dev/pytest/issues/11600>`_: Improved the documentation and type signature for :func:`pytest.mark.xfail <pytest.mark.xfail>`'s ``condition`` param to use ``False`` as the default value.\n\n\n- `#7469 <https://github.com/pytest-dev/pytest/issues/7469>`_: :class:`~pytest.FixtureDef` is now exported as ``pytest.FixtureDef`` for typing purposes.\n\n\n- `#11353 <https://github.com/pytest-dev/pytest/issues/11353>`_: Added typing to :class:`~pytest.PytestPluginManager`.\n\n\nBug Fixes\n---------\n\n- `#10701 <https://github.com/pytest-dev/pytest/issues/10701>`_: :meth:`pytest.WarningsRecorder.pop` will return the most-closely-matched warning in the list,\n  rather than the first warning which is an instance of the requested type.\n\n\n- `#11255 <https://github.com/pytest-dev/pytest/issues/11255>`_: Fixed crash on `parametrize(..., scope=\"package\")` without a package present.\n\n\n- `#11277 <https://github.com/pytest-dev/pytest/issues/11277>`_: Fixed a bug that when there are multiple fixtures for an indirect parameter,\n  the scope of the highest-scope fixture is picked for the parameter set, instead of that of the one with the narrowest scope.\n\n\n- `#11456 <https://github.com/pytest-dev/pytest/issues/11456>`_: Parametrized tests now *really do* ensure that the ids given to each input are unique - for\n  example, ``a, a, a0`` now results in ``a1, a2, a0`` instead of the previous (buggy) ``a0, a1, a0``.\n  This necessarily means changing nodeids where these were previously colliding, and for\n  readability adds an underscore when non-unique ids end in a number.\n\n\n- `#11563 <https://github.com/pytest-dev/pytest/issues/11563>`_: Fixed a crash when using an empty string for the same parametrized value more than once.\n\n\n- `#11712 <https://github.com/pytest-dev/pytest/issues/11712>`_: Fixed handling ``NO_COLOR`` and ``FORCE_COLOR`` to ignore an empty value.\n\n\n- `#9036 <https://github.com/pytest-dev/pytest/issues/9036>`_: ``pytest.warns`` and similar functions now capture warnings when an exception is raised inside a ``with`` block.\n\n\n\nImproved Documentation\n----------------------\n\n- `#11011 <https://github.com/pytest-dev/pytest/issues/11011>`_: Added a warning about modifying the root logger during tests when using ``caplog``.\n\n\n- `#11065 <https://github.com/pytest-dev/pytest/issues/11065>`_: Use ``pytestconfig`` instead of ``request.config`` in cache example to be consistent with the API documentation.\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#11208 <https://github.com/pytest-dev/pytest/issues/11208>`_: The (internal) ``FixtureDef.cached_result`` type has changed.\n  Now the third item ``cached_result[2]``, when set, is an exception instance instead of an exception triplet.\n\n\n- `#11218 <https://github.com/pytest-dev/pytest/issues/11218>`_: (This entry is meant to assist plugins which access private pytest internals to instantiate ``FixtureRequest`` objects.)\n\n  :class:`~pytest.FixtureRequest` is now an abstract class which can't be instantiated directly.\n  A new concrete ``TopRequest`` subclass of ``FixtureRequest`` has been added for the ``request`` fixture in test functions,\n  as counterpart to the existing ``SubRequest`` subclass for the ``request`` fixture in fixture functions.\n\n\n- `#11315 <https://github.com/pytest-dev/pytest/issues/11315>`_: The :fixture:`pytester` fixture now uses the :fixture:`monkeypatch` fixture to manage the current working directory.\n  If you use ``pytester`` in combination with :func:`monkeypatch.undo() <pytest.MonkeyPatch.undo>`, the CWD might get restored.\n  Use :func:`monkeypatch.context() <pytest.MonkeyPatch.context>` instead.\n\n\n- `#11333 <https://github.com/pytest-dev/pytest/issues/11333>`_: Corrected the spelling of ``Config.ArgsSource.INVOCATION_DIR``.\n  The previous spelling ``INCOVATION_DIR`` remains as an alias.\n\n\n- `#11638 <https://github.com/pytest-dev/pytest/issues/11638>`_: Fixed the selftests to pass correctly if ``FORCE_COLOR``, ``NO_COLOR`` or ``PY_COLORS`` is set in the calling environment.\n\npytest 7.4.4 (2023-12-31)\n=========================\n\nBug Fixes\n---------\n\n- `#11140 <https://github.com/pytest-dev/pytest/issues/11140>`_: Fix non-string constants at the top of file being detected as docstrings on Python>=3.8.\n\n\n- `#11572 <https://github.com/pytest-dev/pytest/issues/11572>`_: Handle an edge case where :data:`sys.stderr` and :data:`sys.__stderr__` might already be closed when :ref:`faulthandler` is tearing down.\n\n\n- `#11710 <https://github.com/pytest-dev/pytest/issues/11710>`_: Fixed tracebacks from collection errors not getting pruned.\n\n\n- `#7966 <https://github.com/pytest-dev/pytest/issues/7966>`_: Removed unhelpful error message from assertion rewrite mechanism when exceptions are raised in ``__iter__`` methods. Now they are treated un-iterable instead.\n\n\n\nImproved Documentation\n----------------------\n\n- `#11091 <https://github.com/pytest-dev/pytest/issues/11091>`_: Updated documentation to refer to hyphenated options: replaced ``--junitxml`` with ``--junit-xml`` and ``--collectonly`` with ``--collect-only``.\n\n\npytest 7.4.3 (2023-10-24)\n=========================\n\nBug Fixes\n---------\n\n- `#10447 <https://github.com/pytest-dev/pytest/issues/10447>`_: Markers are now considered in the reverse mro order to ensure base  class markers are considered first -- this resolves a regression.\n\n\n- `#11239 <https://github.com/pytest-dev/pytest/issues/11239>`_: Fixed ``:=`` in asserts impacting unrelated test cases.\n\n\n- `#11439 <https://github.com/pytest-dev/pytest/issues/11439>`_: Handled an edge case where :data:`sys.stderr` might already be closed when :ref:`faulthandler` is tearing down.\n\n\npytest 7.4.2 (2023-09-07)\n=========================\n\nBug Fixes\n---------\n\n- `#11237 <https://github.com/pytest-dev/pytest/issues/11237>`_: Fix doctest collection of `functools.cached_property` objects.\n\n\n- `#11306 <https://github.com/pytest-dev/pytest/issues/11306>`_: Fixed bug using ``--importmode=importlib`` which would cause package ``__init__.py`` files to be imported more than once in some cases.\n\n\n- `#11367 <https://github.com/pytest-dev/pytest/issues/11367>`_: Fixed bug where `user_properties` where not being saved in the JUnit XML file if a fixture failed during teardown.\n\n\n- `#11394 <https://github.com/pytest-dev/pytest/issues/11394>`_: Fixed crash when parsing long command line arguments that might be interpreted as files.\n\n\n\nImproved Documentation\n----------------------\n\n- `#11391 <https://github.com/pytest-dev/pytest/issues/11391>`_: Improved disclaimer on pytest plugin reference page to better indicate this is an automated, non-curated listing.\n\n\npytest 7.4.1 (2023-09-02)\n=========================\n\nBug Fixes\n---------\n\n- `#10337 <https://github.com/pytest-dev/pytest/issues/10337>`_: Fixed bug where fake intermediate modules generated by ``--import-mode=importlib`` would not include the\n  child modules as attributes of the parent modules.\n\n\n- `#10702 <https://github.com/pytest-dev/pytest/issues/10702>`_: Fixed error assertion handling in :func:`pytest.approx` when ``None`` is an expected or received value when comparing dictionaries.\n\n\n- `#10811 <https://github.com/pytest-dev/pytest/issues/10811>`_: Fixed issue when using ``--import-mode=importlib`` together with ``--doctest-modules`` that caused modules\n  to be imported more than once, causing problems with modules that have import side effects.\n\n\npytest 7.4.0 (2023-06-23)\n=========================\n\nFeatures\n--------\n\n- `#10901 <https://github.com/pytest-dev/pytest/issues/10901>`_: Added :func:`ExceptionInfo.from_exception() <pytest.ExceptionInfo.from_exception>`, a simpler way to create an :class:`~pytest.ExceptionInfo` from an exception.\n  This can replace :func:`ExceptionInfo.from_exc_info() <pytest.ExceptionInfo.from_exc_info()>` for most uses.\n\n\n\nImprovements\n------------\n\n- `#10872 <https://github.com/pytest-dev/pytest/issues/10872>`_: Update test log report annotation to named tuple and fixed inconsistency in docs for :hook:`pytest_report_teststatus` hook.\n\n\n- `#10907 <https://github.com/pytest-dev/pytest/issues/10907>`_: When an exception traceback to be displayed is completely filtered out (by mechanisms such as ``__tracebackhide__``, internal frames, and similar), now only the exception string and the following message are shown:\n\n  \"All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames.\".\n\n  Previously, the last frame of the traceback was shown, even though it was hidden.\n\n\n- `#10940 <https://github.com/pytest-dev/pytest/issues/10940>`_: Improved verbose output (``-vv``) of ``skip`` and ``xfail`` reasons by performing text wrapping while leaving a clear margin for progress output.\n\n  Added ``TerminalReporter.wrap_write()`` as a helper for that.\n\n\n- `#10991 <https://github.com/pytest-dev/pytest/issues/10991>`_: Added handling of ``%f`` directive to print microseconds in log format options, such as ``log-date-format``.\n\n\n- `#11005 <https://github.com/pytest-dev/pytest/issues/11005>`_: Added the underlying exception to the cache provider's path creation and write warning messages.\n\n\n- `#11013 <https://github.com/pytest-dev/pytest/issues/11013>`_: Added warning when :confval:`testpaths` is set, but paths are not found by glob. In this case, pytest will fall back to searching from the current directory.\n\n\n- `#11043 <https://github.com/pytest-dev/pytest/issues/11043>`_: When `--confcutdir` is not specified, and there is no config file present, the conftest cutoff directory (`--confcutdir`) is now set to the :ref:`rootdir <rootdir>`.\n  Previously in such cases, `conftest.py` files would be probed all the way to the root directory of the filesystem.\n  If you are badly affected by this change, consider adding an empty config file to your desired cutoff directory, or explicitly set `--confcutdir`.\n\n\n- `#11081 <https://github.com/pytest-dev/pytest/issues/11081>`_: The :confval:`norecursedirs` check is now performed in a :hook:`pytest_ignore_collect` implementation, so plugins can affect it.\n\n  If after updating to this version you see that your `norecursedirs` setting is not being respected,\n  it means that a conftest or a plugin you use has a bad `pytest_ignore_collect` implementation.\n  Most likely, your hook returns `False` for paths it does not want to ignore,\n  which ends the processing and doesn't allow other plugins, including pytest itself, to ignore the path.\n  The fix is to return `None` instead of `False` for paths your hook doesn't want to ignore.\n\n\n- `#8711 <https://github.com/pytest-dev/pytest/issues/8711>`_: :func:`caplog.set_level() <pytest.LogCaptureFixture.set_level>` and :func:`caplog.at_level() <pytest.LogCaptureFixture.at_level>`\n  will temporarily enable the requested ``level`` if ``level`` was disabled globally via\n  ``logging.disable(LEVEL)``.\n\n\n\nBug Fixes\n---------\n\n- `#10831 <https://github.com/pytest-dev/pytest/issues/10831>`_: Terminal Reporting: Fixed bug when running in ``--tb=line`` mode where ``pytest.fail(pytrace=False)`` tests report ``None``.\n\n\n- `#11068 <https://github.com/pytest-dev/pytest/issues/11068>`_: Fixed the ``--last-failed`` whole-file skipping functionality (\"skipped N files\") for :ref:`non-python test files <non-python tests>`.\n\n\n- `#11104 <https://github.com/pytest-dev/pytest/issues/11104>`_: Fixed a regression in pytest 7.3.2 which caused to :confval:`testpaths` to be considered for loading initial conftests,\n  even when it was not utilized (e.g. when explicit paths were given on the command line).\n  Now the ``testpaths`` are only considered when they are in use.\n\n\n- `#1904 <https://github.com/pytest-dev/pytest/issues/1904>`_: Fixed traceback entries hidden with ``__tracebackhide__ = True`` still being shown for chained exceptions (parts after \"... the above exception ...\" message).\n\n\n- `#7781 <https://github.com/pytest-dev/pytest/issues/7781>`_: Fix writing non-encodable text to log file when using ``--debug``.\n\n\n\nImproved Documentation\n----------------------\n\n- `#9146 <https://github.com/pytest-dev/pytest/issues/9146>`_: Improved documentation for :func:`caplog.set_level() <pytest.LogCaptureFixture.set_level>`.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#11031 <https://github.com/pytest-dev/pytest/issues/11031>`_: Enhanced the CLI flag for ``-c`` to now include ``--config-file`` to make it clear that this flag applies to the usage of a custom config file.\n\n\npytest 7.3.2 (2023-06-10)\n=========================\n\nBug Fixes\n---------\n\n- `#10169 <https://github.com/pytest-dev/pytest/issues/10169>`_: Fix bug where very long option names could cause pytest to break with ``OSError: [Errno 36] File name too long`` on some systems.\n\n\n- `#10894 <https://github.com/pytest-dev/pytest/issues/10894>`_: Support for Python 3.12 (beta at the time of writing).\n\n\n- `#10987 <https://github.com/pytest-dev/pytest/issues/10987>`_: :confval:`testpaths` is now honored to load root ``conftests``.\n\n\n- `#10999 <https://github.com/pytest-dev/pytest/issues/10999>`_: The `monkeypatch` `setitem`/`delitem` type annotations now allow `TypedDict` arguments.\n\n\n- `#11028 <https://github.com/pytest-dev/pytest/issues/11028>`_: Fixed bug in assertion rewriting where a variable assigned with the walrus operator could not be used later in a function call.\n\n\n- `#11054 <https://github.com/pytest-dev/pytest/issues/11054>`_: Fixed ``--last-failed``'s \"(skipped N files)\" functionality for files inside of packages (directories with `__init__.py` files).\n\n\npytest 7.3.1 (2023-04-14)\n=========================\n\nImprovements\n------------\n\n- `#10875 <https://github.com/pytest-dev/pytest/issues/10875>`_: Python 3.12 support: fixed ``RuntimeError: TestResult has no addDuration method`` when running ``unittest`` tests.\n\n\n- `#10890 <https://github.com/pytest-dev/pytest/issues/10890>`_: Python 3.12 support: fixed ``shutil.rmtree(onerror=...)`` deprecation warning when using :fixture:`tmp_path`.\n\n\n\nBug Fixes\n---------\n\n- `#10896 <https://github.com/pytest-dev/pytest/issues/10896>`_: Fixed performance regression related to :fixture:`tmp_path` and the new :confval:`tmp_path_retention_policy` option.\n\n\n- `#10903 <https://github.com/pytest-dev/pytest/issues/10903>`_: Fix crash ``INTERNALERROR IndexError: list index out of range`` which happens when displaying an exception where all entries are hidden.\n  This reverts the change \"Correctly handle ``__tracebackhide__`` for chained exceptions.\" introduced in version 7.3.0.\n\n\npytest 7.3.0 (2023-04-08)\n=========================\n\nFeatures\n--------\n\n- `#10525 <https://github.com/pytest-dev/pytest/issues/10525>`_: Test methods decorated with ``@classmethod`` can now be discovered as tests, following the same rules as normal methods. This fills the gap that static methods were discoverable as tests but not class methods.\n\n\n- `#10755 <https://github.com/pytest-dev/pytest/issues/10755>`_: :confval:`console_output_style` now supports ``progress-even-when-capture-no`` to force the use of the progress output even when capture is disabled. This is useful in large test suites where capture may have significant performance impact.\n\n\n- `#7431 <https://github.com/pytest-dev/pytest/issues/7431>`_: ``--log-disable`` CLI option added to disable individual loggers.\n\n\n- `#8141 <https://github.com/pytest-dev/pytest/issues/8141>`_: Added :confval:`tmp_path_retention_count` and :confval:`tmp_path_retention_policy` configuration options to control how directories created by the :fixture:`tmp_path` fixture are kept.\n\n\n\nImprovements\n------------\n\n- `#10226 <https://github.com/pytest-dev/pytest/issues/10226>`_: If multiple errors are raised in teardown, we now re-raise an ``ExceptionGroup`` of them instead of discarding all but the last.\n\n\n- `#10658 <https://github.com/pytest-dev/pytest/issues/10658>`_: Allow ``-p`` arguments to include spaces (eg: ``-p no:logging`` instead of\n  ``-pno:logging``). Mostly useful in the ``addopts`` section of the configuration\n  file.\n\n\n- `#10710 <https://github.com/pytest-dev/pytest/issues/10710>`_: Added ``start`` and ``stop`` timestamps to ``TestReport`` objects.\n\n\n- `#10727 <https://github.com/pytest-dev/pytest/issues/10727>`_: Split the report header for ``rootdir``, ``config file`` and ``testpaths`` so each has its own line.\n\n\n- `#10840 <https://github.com/pytest-dev/pytest/issues/10840>`_: pytest should no longer crash on AST with pathological position attributes, for example testing AST produced by `Hylang <https://github.com/hylang/hy>__`.\n\n\n- `#6267 <https://github.com/pytest-dev/pytest/issues/6267>`_: The full output of a test is no longer truncated if the truncation message would be longer than\n  the hidden text. The line number shown has also been fixed.\n\n\n\nBug Fixes\n---------\n\n- `#10743 <https://github.com/pytest-dev/pytest/issues/10743>`_: The assertion rewriting mechanism now works correctly when assertion expressions contain the walrus operator.\n\n\n- `#10765 <https://github.com/pytest-dev/pytest/issues/10765>`_: Fixed :fixture:`tmp_path` fixture always raising :class:`OSError` on ``emscripten`` platform due to missing :func:`os.getuid`.\n\n\n- `#1904 <https://github.com/pytest-dev/pytest/issues/1904>`_: Correctly handle ``__tracebackhide__`` for chained exceptions.\n  NOTE: This change was reverted in version 7.3.1.\n\n\n\nImproved Documentation\n----------------------\n\n- `#10782 <https://github.com/pytest-dev/pytest/issues/10782>`_: Fixed the minimal example in :ref:`goodpractices`: ``pip install -e .`` requires a ``version`` entry in ``pyproject.toml`` to run successfully.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#10669 <https://github.com/pytest-dev/pytest/issues/10669>`_: pytest no longer directly depends on the `attrs <https://www.attrs.org/en/stable/>`__ package. While\n  we at pytest all love the package dearly and would like to thank the ``attrs`` team for many years of cooperation and support,\n  it makes sense for ``pytest`` to have as little external dependencies as possible, as this helps downstream projects.\n  With that in mind, we have replaced the pytest's limited internal usage to use the standard library's ``dataclasses`` instead.\n\n  Nice diffs for ``attrs`` classes are still supported though.\n\n\npytest 7.2.2 (2023-03-03)\n=========================\n\nBug Fixes\n---------\n\n- `#10533 <https://github.com/pytest-dev/pytest/issues/10533>`_: Fixed :func:`pytest.approx` handling of dictionaries containing one or more values of `0.0`.\n\n\n- `#10592 <https://github.com/pytest-dev/pytest/issues/10592>`_: Fixed crash if `--cache-show` and `--help` are passed at the same time.\n\n\n- `#10597 <https://github.com/pytest-dev/pytest/issues/10597>`_: Fixed bug where a fixture method named ``teardown`` would be called as part of ``nose`` teardown stage.\n\n\n- `#10626 <https://github.com/pytest-dev/pytest/issues/10626>`_: Fixed crash if ``--fixtures`` and ``--help`` are passed at the same time.\n\n\n- `#10660 <https://github.com/pytest-dev/pytest/issues/10660>`_: Fixed :py:func:`pytest.raises` to return a 'ContextManager' so that type-checkers could narrow\n  :code:`pytest.raises(...) if ... else nullcontext()` down to 'ContextManager' rather than 'object'.\n\n\n\nImproved Documentation\n----------------------\n\n- `#10690 <https://github.com/pytest-dev/pytest/issues/10690>`_: Added `CI` and `BUILD_NUMBER` environment variables to the documentation.\n\n\n- `#10721 <https://github.com/pytest-dev/pytest/issues/10721>`_: Fixed entry-points declaration in the documentation example using Hatch.\n\n\n- `#10753 <https://github.com/pytest-dev/pytest/issues/10753>`_: Changed wording of the module level skip to be very explicit\n  about not collecting tests and not executing the rest of the module.\n\n\npytest 7.2.1 (2023-01-13)\n=========================\n\nBug Fixes\n---------\n\n- `#10452 <https://github.com/pytest-dev/pytest/issues/10452>`_: Fix 'importlib.abc.TraversableResources' deprecation warning in Python 3.12.\n\n\n- `#10457 <https://github.com/pytest-dev/pytest/issues/10457>`_: If a test is skipped from inside a fixture, the test summary now shows the test location instead of the fixture location.\n\n\n- `#10506 <https://github.com/pytest-dev/pytest/issues/10506>`_: Fix bug where sometimes pytest would use the file system root directory as :ref:`rootdir <rootdir>` on Windows.\n\n\n- `#10607 <https://github.com/pytest-dev/pytest/issues/10607>`_: Fix a race condition when creating junitxml reports, which could occur when multiple instances of pytest execute in parallel.\n\n\n- `#10641 <https://github.com/pytest-dev/pytest/issues/10641>`_: Fix a race condition when creating or updating the stepwise plugin's cache, which could occur when multiple xdist worker nodes try to simultaneously update the stepwise plugin's cache.\n\n\npytest 7.2.0 (2022-10-23)\n=========================\n\nDeprecations\n------------\n\n- `#10012 <https://github.com/pytest-dev/pytest/issues/10012>`_: Update ``pytest.PytestUnhandledCoroutineWarning`` to a deprecation; it will raise an error in pytest 8.\n\n\n- `#10396 <https://github.com/pytest-dev/pytest/issues/10396>`_: pytest no longer depends on the ``py`` library.  ``pytest`` provides a vendored copy of ``py.error`` and ``py.path`` modules but will use the ``py`` library if it is installed.  If you need other ``py.*`` modules, continue to install the deprecated ``py`` library separately, otherwise it can usually be removed as a dependency.\n\n\n- `#4562 <https://github.com/pytest-dev/pytest/issues/4562>`_: Deprecate configuring hook specs/impls using attributes/marks.\n\n  Instead use :py:func:`pytest.hookimpl` and :py:func:`pytest.hookspec`.\n  For more details, see the :ref:`docs <legacy-path-hooks-deprecated>`.\n\n\n- `#9886 <https://github.com/pytest-dev/pytest/issues/9886>`_: The functionality for running tests written for ``nose`` has been officially deprecated.\n\n  This includes:\n\n  * Plain ``setup`` and ``teardown`` functions and methods: this might catch users by surprise, as ``setup()`` and ``teardown()`` are not pytest idioms, but part of the ``nose`` support.\n  * Setup/teardown using the `@with_setup <with-setup-nose>`_ decorator.\n\n  For more details, consult the :ref:`deprecation docs <nose-deprecation>`.\n\n  .. _`with-setup-nose`: https://nose.readthedocs.io/en/latest/testing_tools.html?highlight=with_setup#nose.tools.with_setup\n\n- `#7337 <https://github.com/pytest-dev/pytest/issues/7337>`_: A deprecation warning is now emitted if a test function returns something other than `None`. This prevents a common mistake among beginners that expect that returning a `bool` (for example `return foo(a, b) == result`) would cause a test to pass or fail, instead of using `assert`. The plan is to make returning non-`None` from tests an error in the future.\n\n\nFeatures\n--------\n\n- `#9897 <https://github.com/pytest-dev/pytest/issues/9897>`_: Added shell-style wildcard support to ``testpaths``.\n\n\n\nImprovements\n------------\n\n- `#10218 <https://github.com/pytest-dev/pytest/issues/10218>`_: ``@pytest.mark.parametrize()`` (and similar functions) now accepts any ``Sequence[str]`` for the argument names,\n  instead of just ``list[str]`` and ``tuple[str, ...]``.\n\n  (Note that ``str``, which is itself a ``Sequence[str]``, is still treated as a\n  comma-delimited name list, as before).\n\n\n- `#10381 <https://github.com/pytest-dev/pytest/issues/10381>`_: The ``--no-showlocals`` flag has been added. This can be passed directly to tests to override ``--showlocals`` declared through ``addopts``.\n\n\n- `#3426 <https://github.com/pytest-dev/pytest/issues/3426>`_: Assertion failures with strings in NFC and NFD forms that normalize to the same string now have a dedicated error message detailing the issue, and their utf-8 representation is expressed instead.\n\n\n- `#8508 <https://github.com/pytest-dev/pytest/issues/8508>`_: Introduce multiline display for warning matching  via :py:func:`pytest.warns` and\n  enhance match comparison for :py:func:`pytest.ExceptionInfo.match` as returned by :py:func:`pytest.raises`.\n\n\n- `#8646 <https://github.com/pytest-dev/pytest/issues/8646>`_: Improve :py:func:`pytest.raises`. Previously passing an empty tuple would give a confusing\n  error. We now raise immediately with a more helpful message.\n\n\n- `#9741 <https://github.com/pytest-dev/pytest/issues/9741>`_: On Python 3.11, use the standard library's :mod:`tomllib` to parse TOML.\n\n  `tomli` is no longer a dependency on Python 3.11.\n\n\n- `#9742 <https://github.com/pytest-dev/pytest/issues/9742>`_: Display assertion message without escaped newline characters with ``-vv``.\n\n\n- `#9823 <https://github.com/pytest-dev/pytest/issues/9823>`_: Improved error message that is shown when no collector is found for a given file.\n\n\n- `#9873 <https://github.com/pytest-dev/pytest/issues/9873>`_: Some coloring has been added to the short test summary.\n\n\n- `#9883 <https://github.com/pytest-dev/pytest/issues/9883>`_: Normalize the help description of all command-line options.\n\n\n- `#9920 <https://github.com/pytest-dev/pytest/issues/9920>`_: Display full crash messages in ``short test summary info``, when running in a CI environment.\n\n\n- `#9987 <https://github.com/pytest-dev/pytest/issues/9987>`_: Added support for hidden configuration file by allowing ``.pytest.ini`` as an alternative to ``pytest.ini``.\n\n\n\nBug Fixes\n---------\n\n- `#10150 <https://github.com/pytest-dev/pytest/issues/10150>`_: :data:`sys.stdin` now contains all expected methods of a file-like object when capture is enabled.\n\n\n- `#10382 <https://github.com/pytest-dev/pytest/issues/10382>`_: Do not break into pdb when ``raise unittest.SkipTest()`` appears top-level in a file.\n\n\n- `#7792 <https://github.com/pytest-dev/pytest/issues/7792>`_: Marks are now inherited according to the full MRO in test classes. Previously, if a test class inherited from two or more classes, only marks from the first super-class would apply.\n\n  When inheriting marks from super-classes, marks from the sub-classes are now ordered before marks from the super-classes, in MRO order. Previously it was the reverse.\n\n  When inheriting marks from super-classes, the `pytestmark` attribute of the sub-class now only contains the marks directly applied to it. Previously, it also contained marks from its super-classes. Please note that this attribute should not normally be accessed directly; use :func:`Node.iter_markers <_pytest.nodes.Node.iter_markers>` instead.\n\n\n- `#9159 <https://github.com/pytest-dev/pytest/issues/9159>`_: Showing inner exceptions by forcing native display in ``ExceptionGroups`` even when using display options other than ``--tb=native``. A temporary step before full implementation of pytest-native display for inner exceptions in ``ExceptionGroups``.\n\n\n- `#9877 <https://github.com/pytest-dev/pytest/issues/9877>`_: Ensure ``caplog.get_records(when)`` returns current/correct data after invoking ``caplog.clear()``.\n\n\n\nImproved Documentation\n----------------------\n\n- `#10344 <https://github.com/pytest-dev/pytest/issues/10344>`_: Update information on writing plugins to use ``pyproject.toml`` instead of ``setup.py``.\n\n\n- `#9248 <https://github.com/pytest-dev/pytest/issues/9248>`_: The documentation is now built using Sphinx 5.x (up from 3.x previously).\n\n\n- `#9291 <https://github.com/pytest-dev/pytest/issues/9291>`_: Update documentation on how :func:`pytest.warns` affects :class:`DeprecationWarning`.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#10313 <https://github.com/pytest-dev/pytest/issues/10313>`_: Made ``_pytest.doctest.DoctestItem`` export ``pytest.DoctestItem`` for\n  type check and runtime purposes. Made `_pytest.doctest` use internal APIs\n  to avoid circular imports.\n\n\n- `#9906 <https://github.com/pytest-dev/pytest/issues/9906>`_: Made ``_pytest.compat`` re-export ``importlib_metadata`` in the eyes of type checkers.\n\n\n- `#9910 <https://github.com/pytest-dev/pytest/issues/9910>`_: Fix default encoding warning (``EncodingWarning``) in ``cacheprovider``\n\n\n- `#9984 <https://github.com/pytest-dev/pytest/issues/9984>`_: Improve the error message when we attempt to access a fixture that has been\n  torn down.\n  Add an additional sentence to the docstring explaining when it's not a good\n  idea to call ``getfixturevalue``.\n\n\npytest 7.1.3 (2022-08-31)\n=========================\n\nBug Fixes\n---------\n\n- `#10060 <https://github.com/pytest-dev/pytest/issues/10060>`_: When running with ``--pdb``, ``TestCase.tearDown`` is no longer called for tests when the *class* has been skipped via ``unittest.skip`` or ``pytest.mark.skip``.\n\n\n- `#10190 <https://github.com/pytest-dev/pytest/issues/10190>`_: Invalid XML characters in setup or teardown error messages are now properly escaped for JUnit XML reports.\n\n\n- `#10230 <https://github.com/pytest-dev/pytest/issues/10230>`_: Ignore ``.py`` files created by ``pyproject.toml``-based editable builds introduced in `pip 21.3 <https://pip.pypa.io/en/stable/news/#v21-3>`__.\n\n\n- `#3396 <https://github.com/pytest-dev/pytest/issues/3396>`_: Doctests now respect the ``--import-mode`` flag.\n\n\n- `#9514 <https://github.com/pytest-dev/pytest/issues/9514>`_: Type-annotate ``FixtureRequest.param`` as ``Any`` as a stop gap measure until :issue:`8073` is fixed.\n\n\n- `#9791 <https://github.com/pytest-dev/pytest/issues/9791>`_: Fixed a path handling code in ``rewrite.py`` that seems to work fine, but was incorrect and fails in some systems.\n\n\n- `#9917 <https://github.com/pytest-dev/pytest/issues/9917>`_: Fixed string representation for :func:`pytest.approx` when used to compare tuples.\n\n\n\nImproved Documentation\n----------------------\n\n- `#9937 <https://github.com/pytest-dev/pytest/issues/9937>`_: Explicit note that :fixture:`tmpdir` fixture is discouraged in favour of :fixture:`tmp_path`.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#10114 <https://github.com/pytest-dev/pytest/issues/10114>`_: Replace `atomicwrites <https://github.com/untitaker/python-atomicwrites>`__ dependency on windows with `os.replace`.\n\n\npytest 7.1.2 (2022-04-23)\n=========================\n\nBug Fixes\n---------\n\n- `#9726 <https://github.com/pytest-dev/pytest/issues/9726>`_: An unnecessary ``numpy`` import inside :func:`pytest.approx` was removed.\n\n\n- `#9820 <https://github.com/pytest-dev/pytest/issues/9820>`_: Fix comparison of  ``dataclasses`` with ``InitVar``.\n\n\n- `#9869 <https://github.com/pytest-dev/pytest/issues/9869>`_: Increase ``stacklevel`` for the ``NODE_CTOR_FSPATH_ARG`` deprecation to point to the\n  user's code, not pytest.\n\n\n- `#9871 <https://github.com/pytest-dev/pytest/issues/9871>`_: Fix a bizarre (and fortunately rare) bug where the `temp_path` fixture could raise\n  an internal error while attempting to get the current user's username.\n\n\npytest 7.1.1 (2022-03-17)\n=========================\n\nBug Fixes\n---------\n\n- `#9767 <https://github.com/pytest-dev/pytest/issues/9767>`_: Fixed a regression in pytest 7.1.0 where some conftest.py files outside of the source tree (e.g. in the `site-packages` directory) were not picked up.\n\n\npytest 7.1.0 (2022-03-13)\n=========================\n\nBreaking Changes\n----------------\n\n- `#8838 <https://github.com/pytest-dev/pytest/issues/8838>`_: As per our policy, the following features have been deprecated in the 6.X series and are now\n  removed:\n\n  * ``pytest._fillfuncargs`` function.\n\n  * ``pytest_warning_captured`` hook - use ``pytest_warning_recorded`` instead.\n\n  * ``-k -foobar`` syntax - use ``-k 'not foobar'`` instead.\n\n  * ``-k foobar:`` syntax.\n\n  * ``pytest.collect`` module - import from ``pytest`` directly.\n\n  For more information consult\n  `Deprecations and Removals <https://docs.pytest.org/en/latest/deprecations.html>`__ in the docs.\n\n\n- `#9437 <https://github.com/pytest-dev/pytest/issues/9437>`_: Dropped support for Python 3.6, which reached `end-of-life <https://devguide.python.org/#status-of-python-branches>`__ at 2021-12-23.\n\n\n\nImprovements\n------------\n\n- `#5192 <https://github.com/pytest-dev/pytest/issues/5192>`_: Fixed test output for some data types where ``-v`` would show less information.\n\n  Also, when showing diffs for sequences, ``-q`` would produce full diffs instead of the expected diff.\n\n\n- `#9362 <https://github.com/pytest-dev/pytest/issues/9362>`_: pytest now avoids specialized assert formatting when it is detected that the default ``__eq__`` is overridden in ``attrs`` or ``dataclasses``.\n\n\n- `#9536 <https://github.com/pytest-dev/pytest/issues/9536>`_: When ``-vv`` is given on command line, show skipping and xfail reasons in full instead of truncating them to fit the terminal width.\n\n\n- `#9644 <https://github.com/pytest-dev/pytest/issues/9644>`_: More information about the location of resources that led Python to raise :class:`ResourceWarning` can now\n  be obtained by enabling :mod:`tracemalloc`.\n\n  See :ref:`resource-warnings` for more information.\n\n\n- `#9678 <https://github.com/pytest-dev/pytest/issues/9678>`_: More types are now accepted in the ``ids`` argument to ``@pytest.mark.parametrize``.\n  Previously only `str`, `float`, `int` and `bool` were accepted;\n  now `bytes`, `complex`, `re.Pattern`, `Enum` and anything with a `__name__` are also accepted.\n\n\n- `#9692 <https://github.com/pytest-dev/pytest/issues/9692>`_: :func:`pytest.approx` now raises a :class:`TypeError` when given an unordered sequence (such as :class:`set`).\n\n  Note that this implies that custom classes which only implement ``__iter__`` and ``__len__`` are no longer supported as they don't guarantee order.\n\n\n\nBug Fixes\n---------\n\n- `#8242 <https://github.com/pytest-dev/pytest/issues/8242>`_: The deprecation of raising :class:`unittest.SkipTest` to skip collection of\n  tests during the pytest collection phase is reverted - this is now a supported\n  feature again.\n\n\n- `#9493 <https://github.com/pytest-dev/pytest/issues/9493>`_: Symbolic link components are no longer resolved in conftest paths.\n  This means that if a conftest appears twice in collection tree, using symlinks, it will be executed twice.\n  For example, given\n\n      tests/real/conftest.py\n      tests/real/test_it.py\n      tests/link -> tests/real\n\n  running ``pytest tests`` now imports the conftest twice, once as ``tests/real/conftest.py`` and once as ``tests/link/conftest.py``.\n  This is a fix to match a similar change made to test collection itself in pytest 6.0 (see :pr:`6523` for details).\n\n\n- `#9626 <https://github.com/pytest-dev/pytest/issues/9626>`_: Fixed count of selected tests on terminal collection summary when there were errors or skipped modules.\n\n  If there were errors or skipped modules on collection, pytest would mistakenly subtract those from the selected count.\n\n\n- `#9645 <https://github.com/pytest-dev/pytest/issues/9645>`_: Fixed regression where ``--import-mode=importlib`` used together with :envvar:`PYTHONPATH` or :confval:`pythonpath` would cause import errors in test suites.\n\n\n- `#9708 <https://github.com/pytest-dev/pytest/issues/9708>`_: :fixture:`pytester` now requests a :fixture:`monkeypatch` fixture instead of creating one internally. This solves some issues with tests that involve pytest environment variables.\n\n\n- `#9730 <https://github.com/pytest-dev/pytest/issues/9730>`_: Malformed ``pyproject.toml`` files now produce a clearer error message.\n\n\npytest 7.0.1 (2022-02-11)\n=========================\n\nBug Fixes\n---------\n\n- `#9608 <https://github.com/pytest-dev/pytest/issues/9608>`_: Fix invalid importing of ``importlib.readers`` in Python 3.9.\n\n\n- `#9610 <https://github.com/pytest-dev/pytest/issues/9610>`_: Restore `UnitTestFunction.obj` to return unbound rather than bound method.\n  Fixes a crash during a failed teardown in unittest TestCases with non-default `__init__`.\n  Regressed in pytest 7.0.0.\n\n\n- `#9636 <https://github.com/pytest-dev/pytest/issues/9636>`_: The ``pythonpath`` plugin was renamed to ``python_path``. This avoids a conflict with the ``pytest-pythonpath`` plugin.\n\n\n- `#9642 <https://github.com/pytest-dev/pytest/issues/9642>`_: Fix running tests by id with ``::`` in the parametrize portion.\n\n\n- `#9643 <https://github.com/pytest-dev/pytest/issues/9643>`_: Delay issuing a :class:`~pytest.PytestWarning` about diamond inheritance involving :class:`~pytest.Item` and\n  :class:`~pytest.Collector` so it can be filtered using :ref:`standard warning filters <warnings>`.\n\n\npytest 7.0.0 (2022-02-03)\n=========================\n\n(**Please see the full set of changes for this release also in the 7.0.0rc1 notes below**)\n\nDeprecations\n------------\n\n- `#9488 <https://github.com/pytest-dev/pytest/issues/9488>`_: If custom subclasses of nodes like :class:`pytest.Item` override the\n  ``__init__`` method, they should take ``**kwargs``. See\n  :ref:`uncooperative-constructors-deprecated` for details.\n\n  Note that a deprecation warning is only emitted when there is a conflict in the\n  arguments pytest expected to pass. This deprecation was already part of pytest\n  7.0.0rc1 but wasn't documented.\n\n\n\nBug Fixes\n---------\n\n- `#9355 <https://github.com/pytest-dev/pytest/issues/9355>`_: Fixed error message prints function decorators when using assert in Python 3.8 and above.\n\n\n- `#9396 <https://github.com/pytest-dev/pytest/issues/9396>`_: Ensure `pytest.Config.inifile` is available during the :hook:`pytest_cmdline_main` hook (regression during ``7.0.0rc1``).\n\n\n\nImproved Documentation\n----------------------\n\n- `#9404 <https://github.com/pytest-dev/pytest/issues/9404>`_: Added extra documentation on alternatives to common misuses of `pytest.warns(None)` ahead of its deprecation.\n\n\n- `#9505 <https://github.com/pytest-dev/pytest/issues/9505>`_: Clarify where the configuration files are located. To avoid confusions documentation mentions\n  that configuration file is located in the root of the repository.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#9521 <https://github.com/pytest-dev/pytest/issues/9521>`_: Add test coverage to assertion rewrite path.\n\n\npytest 7.0.0rc1 (2021-12-06)\n============================\n\nBreaking Changes\n----------------\n\n- `#7259 <https://github.com/pytest-dev/pytest/issues/7259>`_: The :ref:`Node.reportinfo() <non-python tests>` function first return value type has been expanded from `py.path.local | str` to `os.PathLike[str] | str`.\n\n  Most plugins which refer to `reportinfo()` only define it as part of a custom :class:`pytest.Item` implementation.\n  Since `py.path.local` is an `os.PathLike[str]`, these plugins are unaffected.\n\n  Plugins and users which call `reportinfo()`, use the first return value and interact with it as a `py.path.local`, would need to adjust by calling `py.path.local(fspath)`.\n  Although preferably, avoid the legacy `py.path.local` and use `pathlib.Path`, or use `item.location` or `item.path`, instead.\n\n  Note: pytest was not able to provide a deprecation period for this change.\n\n\n- `#8246 <https://github.com/pytest-dev/pytest/issues/8246>`_: ``--version`` now writes version information to ``stdout`` rather than ``stderr``.\n\n- `#8592 <https://github.com/pytest-dev/pytest/issues/8592>`_: The ``pytest_cmdline_preparse`` hook has been removed following its deprecation. See :ref:`the deprecation note <cmdline-preparse-deprecated>` for more details.\n\n- `#8733 <https://github.com/pytest-dev/pytest/issues/8733>`_: Drop a workaround for `pyreadline <https://github.com/pyreadline/pyreadline>`__ that made it work with ``--pdb``.\n\n  The workaround was introduced in `#1281 <https://github.com/pytest-dev/pytest/pull/1281>`__ in 2015, however since then\n  `pyreadline seems to have gone unmaintained <https://github.com/pyreadline/pyreadline/issues/58>`__, is `generating\n  warnings <https://github.com/pytest-dev/pytest/issues/8847>`__, and will stop working on Python 3.10.\n\n\n- `#9061 <https://github.com/pytest-dev/pytest/issues/9061>`_: Using :func:`pytest.approx` in a boolean context now raises an error hinting at the proper usage.\n\n  It is apparently common for users to mistakenly use ``pytest.approx`` like this:\n\n  .. code-block:: python\n\n      assert pytest.approx(actual, expected)\n\n  While the correct usage is:\n\n  .. code-block:: python\n\n      assert actual == pytest.approx(expected)\n\n  The new error message helps catch those mistakes.\n\n\n- `#9277 <https://github.com/pytest-dev/pytest/issues/9277>`_: The ``pytest.Instance`` collector type has been removed.\n  Importing ``pytest.Instance`` or ``_pytest.python.Instance`` returns a dummy type and emits a deprecation warning.\n  See :ref:`instance-collector-deprecation` for details.\n\n\n- `#9308 <https://github.com/pytest-dev/pytest/issues/9308>`_: **PytestRemovedIn7Warning deprecation warnings are now errors by default.**\n\n  Following our plan to remove deprecated features with as little disruption as\n  possible, all warnings of type ``PytestRemovedIn7Warning`` now generate errors\n  instead of warning messages by default.\n\n  **The affected features will be effectively removed in pytest 7.1**, so please consult the\n  :ref:`deprecations` section in the docs for directions on how to update existing code.\n\n  In the pytest ``7.0.X`` series, it is possible to change the errors back into warnings as a\n  stopgap measure by adding this to your ``pytest.ini`` file:\n\n  .. code-block:: ini\n\n      [pytest]\n      filterwarnings =\n          ignore::pytest.PytestRemovedIn7Warning\n\n  But this will stop working when pytest ``7.1`` is released.\n\n  **If you have concerns** about the removal of a specific feature, please add a\n  comment to :issue:`9308`.\n\n\n\nDeprecations\n------------\n\n- `#7259 <https://github.com/pytest-dev/pytest/issues/7259>`_: ``py.path.local`` arguments for hooks have been deprecated. See :ref:`the deprecation note <legacy-path-hooks-deprecated>` for full details.\n\n  ``py.path.local`` arguments to Node constructors have been deprecated. See :ref:`the deprecation note <node-ctor-fspath-deprecation>` for full details.\n\n  .. note::\n      The name of the :class:`~_pytest.nodes.Node` arguments and attributes (the\n      new attribute being ``path``) is **the opposite** of the situation for hooks\n      (the old argument being ``path``).\n\n      This is an unfortunate artifact due to historical reasons, which should be\n      resolved in future versions as we slowly get rid of the :pypi:`py`\n      dependency (see :issue:`9283` for a longer discussion).\n\n\n- `#7469 <https://github.com/pytest-dev/pytest/issues/7469>`_: Directly constructing the following classes is now deprecated:\n\n  - ``_pytest.mark.structures.Mark``\n  - ``_pytest.mark.structures.MarkDecorator``\n  - ``_pytest.mark.structures.MarkGenerator``\n  - ``_pytest.python.Metafunc``\n  - ``_pytest.runner.CallInfo``\n  - ``_pytest._code.ExceptionInfo``\n  - ``_pytest.config.argparsing.Parser``\n  - ``_pytest.config.argparsing.OptionGroup``\n  - ``_pytest.pytester.HookRecorder``\n\n  These constructors have always been considered private, but now issue a deprecation warning, which may become a hard error in pytest 8.\n\n\n- `#8242 <https://github.com/pytest-dev/pytest/issues/8242>`_: Raising :class:`unittest.SkipTest` to skip collection of tests during the\n  pytest collection phase is deprecated. Use :func:`pytest.skip` instead.\n\n  Note: This deprecation only relates to using :class:`unittest.SkipTest` during test\n  collection. You are probably not doing that. Ordinary usage of\n  :class:`unittest.SkipTest` / :meth:`unittest.TestCase.skipTest` /\n  :func:`unittest.skip` in unittest test cases is fully supported.\n\n  .. note:: This deprecation has been reverted in pytest 7.1.0.\n\n\n- `#8315 <https://github.com/pytest-dev/pytest/issues/8315>`_: Several behaviors of :meth:`Parser.addoption <pytest.Parser.addoption>` are now\n  scheduled for removal in pytest 8 (deprecated since pytest 2.4.0):\n\n  - ``parser.addoption(..., help=\".. %default ..\")`` - use ``%(default)s`` instead.\n  - ``parser.addoption(..., type=\"int/string/float/complex\")`` - use ``type=int`` etc. instead.\n\n\n- `#8447 <https://github.com/pytest-dev/pytest/issues/8447>`_: Defining a custom pytest node type which is both an :class:`~pytest.Item` and a :class:`~pytest.Collector` (e.g. :class:`~pytest.File`) now issues a warning.\n  It was never sanely supported and triggers hard to debug errors.\n\n  See :ref:`the deprecation note <diamond-inheritance-deprecated>` for full details.\n\n\n- `#8592 <https://github.com/pytest-dev/pytest/issues/8592>`_: ``pytest_cmdline_preparse`` has been officially deprecated.  It will be removed in a future release.  Use :hook:`pytest_load_initial_conftests` instead.\n\n  See :ref:`the deprecation note <cmdline-preparse-deprecated>` for full details.\n\n\n- `#8645 <https://github.com/pytest-dev/pytest/issues/8645>`_: :func:`pytest.warns(None) <pytest.warns>` is now deprecated because many people used\n  it to mean \"this code does not emit warnings\", but it actually had the effect of\n  checking that the code emits at least one warning of any type - like ``pytest.warns()``\n  or ``pytest.warns(Warning)``.\n\n\n- `#8948 <https://github.com/pytest-dev/pytest/issues/8948>`_: :func:`pytest.skip(msg=...) <pytest.skip>`, :func:`pytest.fail(msg=...) <pytest.fail>` and :func:`pytest.exit(msg=...) <pytest.exit>`\n  signatures now accept a ``reason`` argument instead of ``msg``.  Using ``msg`` still works, but is deprecated and will be removed in a future release.\n\n  This was changed for consistency with :func:`pytest.mark.skip <pytest.mark.skip>` and  :func:`pytest.mark.xfail <pytest.mark.xfail>` which both accept\n  ``reason`` as an argument.\n\n- `#8174 <https://github.com/pytest-dev/pytest/issues/8174>`_: The following changes have been made to types reachable through :attr:`pytest.ExceptionInfo.traceback`:\n\n  - The ``path`` property of ``_pytest.code.Code`` returns ``Path`` instead of ``py.path.local``.\n  - The ``path`` property of ``_pytest.code.TracebackEntry`` returns ``Path`` instead of ``py.path.local``.\n\n  There was no deprecation period for this change (sorry!).\n\n\nFeatures\n--------\n\n- `#5196 <https://github.com/pytest-dev/pytest/issues/5196>`_: Tests are now ordered by definition order in more cases.\n\n  In a class hierarchy, tests from base classes are now consistently ordered before tests defined on their subclasses (reverse MRO order).\n\n\n- `#7132 <https://github.com/pytest-dev/pytest/issues/7132>`_: Added two environment variables :envvar:`PYTEST_THEME` and :envvar:`PYTEST_THEME_MODE` to let the users customize the pygments theme used.\n\n\n- `#7259 <https://github.com/pytest-dev/pytest/issues/7259>`_: Added :meth:`cache.mkdir() <pytest.Cache.mkdir>`, which is similar to the existing ``cache.makedir()``,\n  but returns a :class:`pathlib.Path` instead of a legacy ``py.path.local``.\n\n  Added a ``paths`` type to :meth:`parser.addini() <pytest.Parser.addini>`,\n  as in ``parser.addini(\"mypaths\", \"my paths\", type=\"paths\")``,\n  which is similar to the existing ``pathlist``,\n  but returns a list of :class:`pathlib.Path` instead of legacy ``py.path.local``.\n\n\n- `#7469 <https://github.com/pytest-dev/pytest/issues/7469>`_: The types of objects used in pytest's API are now exported so they may be used in type annotations.\n\n  The newly-exported types are:\n\n  - ``pytest.Config`` for :class:`Config <pytest.Config>`.\n  - ``pytest.Mark`` for :class:`marks <pytest.Mark>`.\n  - ``pytest.MarkDecorator`` for :class:`mark decorators <pytest.MarkDecorator>`.\n  - ``pytest.MarkGenerator`` for the :class:`pytest.mark <pytest.MarkGenerator>` singleton.\n  - ``pytest.Metafunc`` for the :class:`metafunc <pytest.MarkGenerator>` argument to the :hook:`pytest_generate_tests` hook.\n  - ``pytest.CallInfo`` for the :class:`CallInfo <pytest.CallInfo>` type passed to various hooks.\n  - ``pytest.PytestPluginManager`` for :class:`PytestPluginManager <pytest.PytestPluginManager>`.\n  - ``pytest.ExceptionInfo`` for the :class:`ExceptionInfo <pytest.ExceptionInfo>` type returned from :func:`pytest.raises` and passed to various hooks.\n  - ``pytest.Parser`` for the :class:`Parser <pytest.Parser>` type passed to the :hook:`pytest_addoption` hook.\n  - ``pytest.OptionGroup`` for the :class:`OptionGroup <pytest.OptionGroup>` type returned from the :func:`parser.addgroup <pytest.Parser.getgroup>` method.\n  - ``pytest.HookRecorder`` for the :class:`HookRecorder <pytest.HookRecorder>` type returned from :class:`~pytest.Pytester`.\n  - ``pytest.RecordedHookCall`` for the :class:`RecordedHookCall <pytest.HookRecorder>` type returned from :class:`~pytest.HookRecorder`.\n  - ``pytest.RunResult`` for the :class:`RunResult <pytest.RunResult>` type returned from :class:`~pytest.Pytester`.\n  - ``pytest.LineMatcher`` for the :class:`LineMatcher <pytest.LineMatcher>` type used in :class:`~pytest.RunResult` and others.\n  - ``pytest.TestReport`` for the :class:`TestReport <pytest.TestReport>` type used in various hooks.\n  - ``pytest.CollectReport`` for the :class:`CollectReport <pytest.CollectReport>` type used in various hooks.\n\n  Constructing most of them directly is not supported; they are only meant for use in type annotations.\n  Doing so will emit a deprecation warning, and may become a hard-error in pytest 8.0.\n\n  Subclassing them is also not supported. This is not currently enforced at runtime, but is detected by type-checkers such as mypy.\n\n\n- `#7856 <https://github.com/pytest-dev/pytest/issues/7856>`_: :ref:`--import-mode=importlib <import-modes>` now works with features that\n  depend on modules being on :py:data:`sys.modules`, such as :mod:`pickle` and :mod:`dataclasses`.\n\n\n- `#8144 <https://github.com/pytest-dev/pytest/issues/8144>`_: The following hooks now receive an additional ``pathlib.Path`` argument, equivalent to an existing ``py.path.local`` argument:\n\n  - :hook:`pytest_ignore_collect` - The ``collection_path`` parameter (equivalent to existing ``path`` parameter).\n  - :hook:`pytest_collect_file` - The ``file_path`` parameter (equivalent to existing ``path`` parameter).\n  - :hook:`pytest_pycollect_makemodule` - The ``module_path`` parameter (equivalent to existing ``path`` parameter).\n  - :hook:`pytest_report_header` - The ``start_path`` parameter (equivalent to existing ``startdir`` parameter).\n  - :hook:`pytest_report_collectionfinish` - The ``start_path`` parameter (equivalent to existing ``startdir`` parameter).\n\n  .. note::\n      The name of the :class:`~_pytest.nodes.Node` arguments and attributes (the\n      new attribute being ``path``) is **the opposite** of the situation for hooks\n      (the old argument being ``path``).\n\n      This is an unfortunate artifact due to historical reasons, which should be\n      resolved in future versions as we slowly get rid of the :pypi:`py`\n      dependency (see :issue:`9283` for a longer discussion).\n\n\n- `#8251 <https://github.com/pytest-dev/pytest/issues/8251>`_: Implement ``Node.path`` as a ``pathlib.Path``. Both the old ``fspath`` and this new attribute gets set no matter whether ``path`` or ``fspath`` (deprecated) is passed to the constructor. It is a replacement for the ``fspath`` attribute (which represents the same path as ``py.path.local``). While ``fspath`` is not deprecated yet\n  due to the ongoing migration of methods like :meth:`~pytest.Item.reportinfo`, we expect to deprecate it in a future release.\n\n  .. note::\n      The name of the :class:`~_pytest.nodes.Node` arguments and attributes (the\n      new attribute being ``path``) is **the opposite** of the situation for hooks\n      (the old argument being ``path``).\n\n      This is an unfortunate artifact due to historical reasons, which should be\n      resolved in future versions as we slowly get rid of the :pypi:`py`\n      dependency (see :issue:`9283` for a longer discussion).\n\n\n- `#8421 <https://github.com/pytest-dev/pytest/issues/8421>`_: :func:`pytest.approx` now works on :class:`~decimal.Decimal` within mappings/dicts and sequences/lists.\n\n\n- `#8606 <https://github.com/pytest-dev/pytest/issues/8606>`_: pytest invocations with ``--fixtures-per-test`` and ``--fixtures`` have been enriched with:\n\n  - Fixture location path printed with the fixture name.\n  - First section of the fixture's docstring printed under the fixture name.\n  - Whole of fixture's docstring printed under the fixture name using ``--verbose`` option.\n\n\n- `#8761 <https://github.com/pytest-dev/pytest/issues/8761>`_: New :ref:`version-tuple` attribute, which makes it simpler for users to do something depending on the pytest version (such as declaring hooks which are introduced in later versions).\n\n\n- `#8789 <https://github.com/pytest-dev/pytest/issues/8789>`_: Switch TOML parser from ``toml`` to ``tomli`` for TOML v1.0.0 support in ``pyproject.toml``.\n\n\n- `#8920 <https://github.com/pytest-dev/pytest/issues/8920>`_: Added :class:`pytest.Stash`, a facility for plugins to store their data on :class:`~pytest.Config` and :class:`~_pytest.nodes.Node`\\s in a type-safe and conflict-free manner.\n  See :ref:`plugin-stash` for details.\n\n\n- `#8953 <https://github.com/pytest-dev/pytest/issues/8953>`_: :class:`~pytest.RunResult` method :meth:`~pytest.RunResult.assert_outcomes` now accepts a\n  ``warnings`` argument to assert the total number of warnings captured.\n\n\n- `#8954 <https://github.com/pytest-dev/pytest/issues/8954>`_: ``--debug`` flag now accepts a :class:`str` file to route debug logs into, remains defaulted to `pytestdebug.log`.\n\n\n- `#9023 <https://github.com/pytest-dev/pytest/issues/9023>`_: Full diffs are now always shown for equality assertions of iterables when\n  `CI` or ``BUILD_NUMBER`` is found in the environment, even when ``-v`` isn't\n  used.\n\n\n- `#9113 <https://github.com/pytest-dev/pytest/issues/9113>`_: :class:`~pytest.RunResult` method :meth:`~pytest.RunResult.assert_outcomes` now accepts a\n  ``deselected`` argument to assert the total number of deselected tests.\n\n\n- `#9114 <https://github.com/pytest-dev/pytest/issues/9114>`_: Added :confval:`pythonpath` setting that adds listed paths to :data:`sys.path` for the duration of the test session. If you currently use the pytest-pythonpath or pytest-srcpaths plugins, you should be able to replace them with built-in `pythonpath` setting.\n\n\n\nImprovements\n------------\n\n- `#7480 <https://github.com/pytest-dev/pytest/issues/7480>`_: A deprecation scheduled to be removed in a major version X (e.g. pytest 7, 8, 9, ...) now uses warning category `PytestRemovedInXWarning`,\n  a subclass of :class:`~pytest.PytestDeprecationWarning`,\n  instead of :class:`~pytest.PytestDeprecationWarning` directly.\n\n  See :ref:`backwards-compatibility` for more details.\n\n\n- `#7864 <https://github.com/pytest-dev/pytest/issues/7864>`_: Improved error messages when parsing warning filters.\n\n  Previously pytest would show an internal traceback, which besides being ugly sometimes would hide the cause\n  of the problem (for example an ``ImportError`` while importing a specific warning type).\n\n\n- `#8335 <https://github.com/pytest-dev/pytest/issues/8335>`_: Improved :func:`pytest.approx` assertion messages for sequences of numbers.\n\n  The assertion messages now dumps a table with the index and the error of each diff.\n  Example::\n\n      >       assert [1, 2, 3, 4] == pytest.approx([1, 3, 3, 5])\n      E       assert comparison failed for 2 values:\n      E         Index | Obtained | Expected\n      E         1     | 2        | 3 +- 3.0e-06\n      E         3     | 4        | 5 +- 5.0e-06\n\n\n- `#8403 <https://github.com/pytest-dev/pytest/issues/8403>`_: By default, pytest will truncate long strings in assert errors so they don't clutter the output too much,\n  currently at ``240`` characters by default.\n\n  However, in some cases the longer output helps, or is even crucial, to diagnose a failure. Using ``-v`` will\n  now increase the truncation threshold to ``2400`` characters, and ``-vv`` or higher will disable truncation entirely.\n\n\n- `#8509 <https://github.com/pytest-dev/pytest/issues/8509>`_: Fixed issue where :meth:`unittest.TestCase.setUpClass` is not called when a test has `/` in its name since pytest 6.2.0.\n\n  This refers to the path part in pytest node IDs, e.g. ``TestClass::test_it`` in the node ID ``tests/test_file.py::TestClass::test_it``.\n\n  Now, instead of assuming that the test name does not contain ``/``, it is assumed that test path does not contain ``::``. We plan to hopefully make both of these work in the future.\n\n\n- `#8803 <https://github.com/pytest-dev/pytest/issues/8803>`_: It is now possible to add colors to custom log levels on cli log.\n\n  By using ``add_color_level`` from a :hook:`pytest_configure` hook, colors can be added::\n\n      logging_plugin = config.pluginmanager.get_plugin('logging-plugin')\n      logging_plugin.log_cli_handler.formatter.add_color_level(logging.INFO, 'cyan')\n      logging_plugin.log_cli_handler.formatter.add_color_level(logging.SPAM, 'blue')\n\n  See :ref:`log_colors` for more information.\n\n\n- `#8822 <https://github.com/pytest-dev/pytest/issues/8822>`_: When showing fixture paths in `--fixtures` or `--fixtures-by-test`, fixtures coming from pytest itself now display an elided path, rather than the full path to the file in the `site-packages` directory.\n\n\n- `#8898 <https://github.com/pytest-dev/pytest/issues/8898>`_: Complex numbers are now treated like floats and integers when generating parameterization IDs.\n\n\n- `#9062 <https://github.com/pytest-dev/pytest/issues/9062>`_: ``--stepwise-skip`` now implicitly enables ``--stepwise`` and can be used on its own.\n\n\n- `#9205 <https://github.com/pytest-dev/pytest/issues/9205>`_: :meth:`pytest.Cache.set` now preserves key order when saving dicts.\n\n\n\nBug Fixes\n---------\n\n- `#7124 <https://github.com/pytest-dev/pytest/issues/7124>`_: Fixed an issue where ``__main__.py`` would raise an ``ImportError`` when ``--doctest-modules`` was provided.\n\n\n- `#8061 <https://github.com/pytest-dev/pytest/issues/8061>`_: Fixed failing ``staticmethod`` test cases if they are inherited from a parent test class.\n\n\n- `#8192 <https://github.com/pytest-dev/pytest/issues/8192>`_: ``testdir.makefile`` now silently accepts values which don't start with ``.`` to maintain backward compatibility with older pytest versions.\n\n  ``pytester.makefile`` now issues a clearer error if the ``.`` is missing in the ``ext`` argument.\n\n\n- `#8258 <https://github.com/pytest-dev/pytest/issues/8258>`_: Fixed issue where pytest's ``faulthandler`` support would not dump traceback on crashes\n  if the :mod:`faulthandler` module was already enabled during pytest startup (using\n  ``python -X dev -m pytest`` for example).\n\n\n- `#8317 <https://github.com/pytest-dev/pytest/issues/8317>`_: Fixed an issue where illegal directory characters derived from ``getpass.getuser()`` raised an ``OSError``.\n\n\n- `#8367 <https://github.com/pytest-dev/pytest/issues/8367>`_: Fix ``Class.from_parent`` so it forwards extra keyword arguments to the constructor.\n\n\n- `#8377 <https://github.com/pytest-dev/pytest/issues/8377>`_: The test selection options ``pytest -k`` and ``pytest -m`` now support matching\n  names containing forward slash (``/``) characters.\n\n\n- `#8384 <https://github.com/pytest-dev/pytest/issues/8384>`_: The ``@pytest.mark.skip`` decorator now correctly handles its arguments. When the ``reason`` argument is accidentally given both positional and as a keyword (e.g. because it was confused with ``skipif``), a ``TypeError`` now occurs. Before, such tests were silently skipped, and the positional argument ignored. Additionally, ``reason`` is now documented correctly as positional or keyword (rather than keyword-only).\n\n\n- `#8394 <https://github.com/pytest-dev/pytest/issues/8394>`_: Use private names for internal fixtures that handle classic setup/teardown so that they don't show up with the default ``--fixtures`` invocation (but they still show up with ``--fixtures -v``).\n\n\n- `#8456 <https://github.com/pytest-dev/pytest/issues/8456>`_: The :confval:`required_plugins` config option now works correctly when pre-releases of plugins are installed, rather than falsely claiming that those plugins aren't installed at all.\n\n\n- `#8464 <https://github.com/pytest-dev/pytest/issues/8464>`_: ``-c <config file>`` now also properly defines ``rootdir`` as the directory that contains ``<config file>``.\n\n\n- `#8503 <https://github.com/pytest-dev/pytest/issues/8503>`_: :meth:`pytest.MonkeyPatch.syspath_prepend` no longer fails when\n  ``setuptools`` is not installed.\n  It now only calls ``pkg_resources.fixup_namespace_packages`` if\n  ``pkg_resources`` was previously imported, because it is not needed otherwise.\n\n\n- `#8548 <https://github.com/pytest-dev/pytest/issues/8548>`_: Introduce fix to handle precision width in ``log-cli-format`` in turn to fix output coloring for certain formats.\n\n\n- `#8796 <https://github.com/pytest-dev/pytest/issues/8796>`_: Fixed internal error when skipping doctests.\n\n\n- `#8983 <https://github.com/pytest-dev/pytest/issues/8983>`_: The test selection options ``pytest -k`` and ``pytest -m`` now support matching names containing backslash (`\\\\`) characters.\n  Backslashes are treated literally, not as escape characters (the values being matched against are already escaped).\n\n\n- `#8990 <https://github.com/pytest-dev/pytest/issues/8990>`_: Fix `pytest -vv` crashing with an internal exception `AttributeError: 'str' object has no attribute 'relative_to'` in some cases.\n\n\n- `#9077 <https://github.com/pytest-dev/pytest/issues/9077>`_: Fixed confusing error message when ``request.fspath`` / ``request.path`` was accessed from a session-scoped fixture.\n\n\n- `#9131 <https://github.com/pytest-dev/pytest/issues/9131>`_: Fixed the URL used by ``--pastebin`` to use `bpa.st <http://bpa.st>`__.\n\n\n- `#9163 <https://github.com/pytest-dev/pytest/issues/9163>`_: The end line number and end column offset are now properly set for rewritten assert statements.\n\n\n- `#9169 <https://github.com/pytest-dev/pytest/issues/9169>`_: Support for the ``files`` API from ``importlib.resources`` within rewritten files.\n\n\n- `#9272 <https://github.com/pytest-dev/pytest/issues/9272>`_: The nose compatibility module-level fixtures `setup()` and `teardown()` are now only called once per module, instead of for each test function.\n  They are now called even if object-level `setup`/`teardown` is defined.\n\n\n\nImproved Documentation\n----------------------\n\n- `#4320 <https://github.com/pytest-dev/pytest/issues/4320>`_: Improved docs for `pytester.copy_example`.\n\n\n- `#5105 <https://github.com/pytest-dev/pytest/issues/5105>`_: Add automatically generated :ref:`plugin-list`. The list is updated on a periodic schedule.\n\n\n- `#8337 <https://github.com/pytest-dev/pytest/issues/8337>`_: Recommend `numpy.testing <https://numpy.org/doc/stable/reference/routines.testing.html>`__ module on :func:`pytest.approx` documentation.\n\n\n- `#8655 <https://github.com/pytest-dev/pytest/issues/8655>`_: Help text for ``--pdbcls`` more accurately reflects the option's behavior.\n\n\n- `#9210 <https://github.com/pytest-dev/pytest/issues/9210>`_: Remove incorrect docs about ``confcutdir`` being a configuration option: it can only be set through the ``--confcutdir`` command-line option.\n\n\n- `#9242 <https://github.com/pytest-dev/pytest/issues/9242>`_: Upgrade readthedocs configuration to use a `newer Ubuntu version <https://blog.readthedocs.com/new-build-specification/>`__` with better unicode support for PDF docs.\n\n\n- `#9341 <https://github.com/pytest-dev/pytest/issues/9341>`_: Various methods commonly used for :ref:`non-python tests` are now correctly documented in the reference docs. They were undocumented previously.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- `#8133 <https://github.com/pytest-dev/pytest/issues/8133>`_: Migrate to ``setuptools_scm`` 6.x to use ``SETUPTOOLS_SCM_PRETEND_VERSION_FOR_PYTEST`` for more robust release tooling.\n\n\n- `#8174 <https://github.com/pytest-dev/pytest/issues/8174>`_: The following changes have been made to internal pytest types/functions:\n\n  - The ``_pytest.code.getfslineno()`` function returns ``Path`` instead of ``py.path.local``.\n  - The ``_pytest.python.path_matches_patterns()`` function takes ``Path`` instead of ``py.path.local``.\n  - The ``_pytest._code.Traceback.cut()`` function accepts any ``os.PathLike[str]``, not just ``py.path.local``.\n\n\n- `#8248 <https://github.com/pytest-dev/pytest/issues/8248>`_: Internal Restructure: let ``python.PyObjMixin`` inherit from ``nodes.Node`` to carry over typing information.\n\n\n- `#8432 <https://github.com/pytest-dev/pytest/issues/8432>`_: Improve error message when :func:`pytest.skip` is used at module level without passing `allow_module_level=True`.\n\n\n- `#8818 <https://github.com/pytest-dev/pytest/issues/8818>`_: Ensure ``regendoc`` opts out of ``TOX_ENV`` cachedir selection to ensure independent example test runs.\n\n\n- `#8913 <https://github.com/pytest-dev/pytest/issues/8913>`_: The private ``CallSpec2._arg2scopenum`` attribute has been removed after an internal refactoring.\n\n\n- `#8967 <https://github.com/pytest-dev/pytest/issues/8967>`_: :hook:`pytest_assertion_pass` is no longer considered experimental and\n  future changes to it will be considered more carefully.\n\n\n- `#9202 <https://github.com/pytest-dev/pytest/issues/9202>`_: Add github action to upload coverage report to codecov instead of bash uploader.\n\n\n- `#9225 <https://github.com/pytest-dev/pytest/issues/9225>`_: Changed the command used to create sdist and wheel artifacts: using the build package instead of setup.py.\n\n\n- `#9351 <https://github.com/pytest-dev/pytest/issues/9351>`_: Correct minor typos in doc/en/example/special.rst.\n\n\npytest 6.2.5 (2021-08-29)\n=========================\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`8494`: Python 3.10 is now supported.\n\n\n- :issue:`9040`: Enable compatibility with ``pluggy 1.0`` or later.\n\n\npytest 6.2.4 (2021-05-04)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`8539`: Fixed assertion rewriting on Python 3.10.\n\n\npytest 6.2.3 (2021-04-03)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`8414`: pytest used to create directories under ``/tmp`` with world-readable\n  permissions. This means that any user in the system was able to read\n  information written by tests in temporary directories (such as those created by\n  the ``tmp_path``/``tmpdir`` fixture). Now the directories are created with\n  private permissions.\n\n  pytest used to silently use a preexisting ``/tmp/pytest-of-<username>`` directory,\n  even if owned by another user. This means another user could pre-create such a\n  directory and gain control of another user's temporary directory. Now such a\n  condition results in an error.\n\n\npytest 6.2.2 (2021-01-25)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`8152`: Fixed \"(<Skipped instance>)\" being shown as a skip reason in the verbose test summary line when the reason is empty.\n\n\n- :issue:`8249`: Fix the ``faulthandler`` plugin for occasions when running with ``twisted.logger`` and using ``pytest --capture=no``.\n\n\npytest 6.2.1 (2020-12-15)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`7678`: Fixed bug where ``ImportPathMismatchError`` would be raised for files compiled in\n  the host and loaded later from an UNC mounted path (Windows).\n\n\n- :issue:`8132`: Fixed regression in ``approx``: in 6.2.0 ``approx`` no longer raises\n  ``TypeError`` when dealing with non-numeric types, falling back to normal comparison.\n  Before 6.2.0, array types like tf.DeviceArray fell through to the scalar case,\n  and happened to compare correctly to a scalar if they had only one element.\n  After 6.2.0, these types began failing, because they inherited neither from\n  standard Python number hierarchy nor from ``numpy.ndarray``.\n\n  ``approx`` now converts arguments to ``numpy.ndarray`` if they expose the array\n  protocol and are not scalars. This treats array-like objects like numpy arrays,\n  regardless of size.\n\n\npytest 6.2.0 (2020-12-12)\n=========================\n\nBreaking Changes\n----------------\n\n- :issue:`7808`: pytest now supports python3.6+ only.\n\n\n\nDeprecations\n------------\n\n- :issue:`7469`: Directly constructing/calling the following classes/functions is now deprecated:\n\n  - ``_pytest.cacheprovider.Cache``\n  - ``_pytest.cacheprovider.Cache.for_config()``\n  - ``_pytest.cacheprovider.Cache.clear_cache()``\n  - ``_pytest.cacheprovider.Cache.cache_dir_from_config()``\n  - ``_pytest.capture.CaptureFixture``\n  - ``_pytest.fixtures.FixtureRequest``\n  - ``_pytest.fixtures.SubRequest``\n  - ``_pytest.logging.LogCaptureFixture``\n  - ``_pytest.pytester.Pytester``\n  - ``_pytest.pytester.Testdir``\n  - ``_pytest.recwarn.WarningsRecorder``\n  - ``_pytest.recwarn.WarningsChecker``\n  - ``_pytest.tmpdir.TempPathFactory``\n  - ``_pytest.tmpdir.TempdirFactory``\n\n  These have always been considered private, but now issue a deprecation warning, which may become a hard error in pytest 8.0.0.\n\n\n- :issue:`7530`: The ``--strict`` command-line option has been deprecated, use ``--strict-markers`` instead.\n\n  We have plans to maybe in the future to reintroduce ``--strict`` and make it an encompassing flag for all strictness\n  related options (``--strict-markers`` and ``--strict-config`` at the moment, more might be introduced in the future).\n\n\n- :issue:`7988`: The ``@pytest.yield_fixture`` decorator/function is now deprecated. Use :func:`pytest.fixture` instead.\n\n  ``yield_fixture`` has been an alias for ``fixture`` for a very long time, so can be search/replaced safely.\n\n\n\nFeatures\n--------\n\n- :issue:`5299`: pytest now warns about unraisable exceptions and unhandled thread exceptions that occur in tests on Python>=3.8.\n  See :ref:`unraisable` for more information.\n\n\n- :issue:`7425`: New :fixture:`pytester` fixture, which is identical to :fixture:`testdir` but its methods return :class:`pathlib.Path` when appropriate instead of ``py.path.local``.\n\n  This is part of the movement to use :class:`pathlib.Path` objects internally, in order to remove the dependency to ``py`` in the future.\n\n  Internally, the old ``pytest.Testdir`` is now a thin wrapper around :class:`~pytest.Pytester`, preserving the old interface.\n\n\n- :issue:`7695`: A new hook was added, `pytest_markeval_namespace` which should return a dictionary.\n  This dictionary will be used to augment the \"global\" variables available to evaluate skipif/xfail/xpass markers.\n\n  Pseudo example\n\n  ``conftest.py``:\n\n  .. code-block:: python\n\n     def pytest_markeval_namespace():\n         return {\"color\": \"red\"}\n\n  ``test_func.py``:\n\n  .. code-block:: python\n\n     @pytest.mark.skipif(\"color == 'blue'\", reason=\"Color is not red\")\n     def test_func():\n         assert False\n\n\n- :issue:`8006`: It is now possible to construct a :class:`~pytest.MonkeyPatch` object directly as ``pytest.MonkeyPatch()``,\n  in cases when the :fixture:`monkeypatch` fixture cannot be used. Previously some users imported it\n  from the private `_pytest.monkeypatch.MonkeyPatch` namespace.\n\n  Additionally, :meth:`MonkeyPatch.context <pytest.MonkeyPatch.context>` is now a classmethod,\n  and can be used as ``with MonkeyPatch.context() as mp: ...``. This is the recommended way to use\n  ``MonkeyPatch`` directly, since unlike the ``monkeypatch`` fixture, an instance created directly\n  is not ``undo()``-ed automatically.\n\n\n\nImprovements\n------------\n\n- :issue:`1265`: Added an ``__str__`` implementation to the :class:`~pytest.LineMatcher` class which is returned from ``pytester.run_pytest().stdout`` and similar. It returns the entire output, like the existing ``str()`` method.\n\n\n- :issue:`2044`: Verbose mode now shows the reason that a test was skipped in the test's terminal line after the \"SKIPPED\", \"XFAIL\" or \"XPASS\".\n\n\n- :issue:`7469` The types of builtin pytest fixtures are now exported so they may be used in type annotations of test functions.\n  The newly-exported types are:\n\n  - ``pytest.FixtureRequest`` for the :fixture:`request` fixture.\n  - ``pytest.Cache`` for the :fixture:`cache` fixture.\n  - ``pytest.CaptureFixture[str]`` for the :fixture:`capfd` and :fixture:`capsys` fixtures.\n  - ``pytest.CaptureFixture[bytes]`` for the :fixture:`capfdbinary` and :fixture:`capsysbinary` fixtures.\n  - ``pytest.LogCaptureFixture`` for the :fixture:`caplog` fixture.\n  - ``pytest.Pytester`` for the :fixture:`pytester` fixture.\n  - ``pytest.Testdir`` for the :fixture:`testdir` fixture.\n  - ``pytest.TempdirFactory`` for the :fixture:`tmpdir_factory` fixture.\n  - ``pytest.TempPathFactory`` for the :fixture:`tmp_path_factory` fixture.\n  - ``pytest.MonkeyPatch`` for the :fixture:`monkeypatch` fixture.\n  - ``pytest.WarningsRecorder`` for the :fixture:`recwarn` fixture.\n\n  Constructing them is not supported (except for `MonkeyPatch`); they are only meant for use in type annotations.\n  Doing so will emit a deprecation warning, and may become a hard-error in pytest 8.0.\n\n  Subclassing them is also not supported. This is not currently enforced at runtime, but is detected by type-checkers such as mypy.\n\n\n- :issue:`7527`: When a comparison between :func:`namedtuple <collections.namedtuple>` instances of the same type fails, pytest now shows the differing field names (possibly nested) instead of their indexes.\n\n\n- :issue:`7615`: :meth:`Node.warn <_pytest.nodes.Node.warn>` now permits any subclass of :class:`Warning`, not just :class:`PytestWarning <pytest.PytestWarning>`.\n\n\n- :issue:`7701`: Improved reporting when using ``--collected-only``. It will now show the number of collected tests in the summary stats.\n\n\n- :issue:`7710`: Use strict equality comparison for non-numeric types in :func:`pytest.approx` instead of\n  raising :class:`TypeError`.\n\n  This was the undocumented behavior before 3.7, but is now officially a supported feature.\n\n\n- :issue:`7938`: New ``--sw-skip`` argument which is a shorthand for ``--stepwise-skip``.\n\n\n- :issue:`8023`: Added ``'node_modules'`` to default value for :confval:`norecursedirs`.\n\n\n- :issue:`8032`: :meth:`doClassCleanups <unittest.TestCase.doClassCleanups>` (introduced in :mod:`unittest` in Python and 3.8) is now called appropriately.\n\n\n\nBug Fixes\n---------\n\n- :issue:`4824`: Fixed quadratic behavior and improved performance of collection of items using autouse fixtures and xunit fixtures.\n\n\n- :issue:`7758`: Fixed an issue where some files in packages are getting lost from ``--lf`` even though they contain tests that failed. Regressed in pytest 5.4.0.\n\n\n- :issue:`7911`: Directories created by by :fixture:`tmp_path` and :fixture:`tmpdir` are now considered stale after 3 days without modification (previous value was 3 hours) to avoid deleting directories still in use in long running test suites.\n\n\n- :issue:`7913`: Fixed a crash or hang in :meth:`pytester.spawn <pytest.Pytester.spawn>` when the :mod:`readline` module is involved.\n\n\n- :issue:`7951`: Fixed handling of recursive symlinks when collecting tests.\n\n\n- :issue:`7981`: Fixed symlinked directories not being followed during collection. Regressed in pytest 6.1.0.\n\n\n- :issue:`8016`: Fixed only one doctest being collected when using ``pytest --doctest-modules path/to/an/__init__.py``.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`7429`: Add more information and use cases about skipping doctests.\n\n\n- :issue:`7780`: Classes which should not be inherited from are now marked ``final class`` in the API reference.\n\n\n- :issue:`7872`: ``_pytest.config.argparsing.Parser.addini()`` accepts explicit ``None`` and ``\"string\"``.\n\n\n- :issue:`7878`: In pull request section, ask to commit after editing changelog and authors file.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`7802`: The ``attrs`` dependency requirement is now >=19.2.0 instead of >=17.4.0.\n\n\n- :issue:`8014`: `.pyc` files created by pytest's assertion rewriting now conform to the newer :pep:`552` format on Python>=3.7.\n  (These files are internal and only interpreted by pytest itself.)\n\n\npytest 6.1.2 (2020-10-28)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`7758`: Fixed an issue where some files in packages are getting lost from ``--lf`` even though they contain tests that failed. Regressed in pytest 5.4.0.\n\n\n- :issue:`7911`: Directories created by `tmpdir` are now considered stale after 3 days without modification (previous value was 3 hours) to avoid deleting directories still in use in long running test suites.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`7815`: Improve deprecation warning message for ``pytest._fillfuncargs()``.\n\n\npytest 6.1.1 (2020-10-03)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`7807`: Fixed regression in pytest 6.1.0 causing incorrect rootdir to be determined in some non-trivial cases where parent directories have config files as well.\n\n\n- :issue:`7814`: Fixed crash in header reporting when :confval:`testpaths` is used and contains absolute paths (regression in 6.1.0).\n\n\npytest 6.1.0 (2020-09-26)\n=========================\n\nBreaking Changes\n----------------\n\n- :issue:`5585`: As per our policy, the following features which have been deprecated in the 5.X series are now\n  removed:\n\n  * The ``funcargnames`` read-only property of ``FixtureRequest``, ``Metafunc``, and ``Function`` classes. Use ``fixturenames`` attribute.\n\n  * ``@pytest.fixture`` no longer supports positional arguments, pass all arguments by keyword instead.\n\n  * Direct construction of ``Node`` subclasses now raise an error, use ``from_parent`` instead.\n\n  * The default value for ``junit_family`` has changed to ``xunit2``. If you require the old format, add ``junit_family=xunit1`` to your configuration file.\n\n  * The ``TerminalReporter`` no longer has a ``writer`` attribute. Plugin authors may use the public functions of the ``TerminalReporter`` instead of accessing the ``TerminalWriter`` object directly.\n\n  * The ``--result-log`` option has been removed. Users are recommended to use the `pytest-reportlog <https://github.com/pytest-dev/pytest-reportlog>`__ plugin instead.\n\n\n  For more information consult :std:doc:`deprecations` in the docs.\n\n\n\nDeprecations\n------------\n\n- :issue:`6981`: The ``pytest.collect`` module is deprecated: all its names can be imported from ``pytest`` directly.\n\n\n- :issue:`7097`: The ``pytest._fillfuncargs`` function is deprecated. This function was kept\n  for backward compatibility with an older plugin.\n\n  It's functionality is not meant to be used directly, but if you must replace\n  it, use `function._request._fillfixtures()` instead, though note this is not\n  a public API and may break in the future.\n\n\n- :issue:`7210`: The special ``-k '-expr'`` syntax to ``-k`` is deprecated. Use ``-k 'not expr'``\n  instead.\n\n  The special ``-k 'expr:'`` syntax to ``-k`` is deprecated. Please open an issue\n  if you use this and want a replacement.\n\n\n- :issue:`7255`: The ``pytest_warning_captured`` hook is deprecated in favor\n  of :hook:`pytest_warning_recorded`, and will be removed in a future version.\n\n\n- :issue:`7648`: The ``gethookproxy()`` and ``isinitpath()`` methods of ``FSCollector`` and ``Package`` are deprecated;\n  use ``self.session.gethookproxy()`` and ``self.session.isinitpath()`` instead.\n  This should work on all pytest versions.\n\n\n\nFeatures\n--------\n\n- :issue:`7667`: New ``--durations-min`` command-line flag controls the minimal duration for inclusion in the slowest list of tests shown by ``--durations``. Previously this was hard-coded to ``0.005s``.\n\n\n\nImprovements\n------------\n\n- :issue:`6681`: Internal pytest warnings issued during the early stages of initialization are now properly handled and can filtered through :confval:`filterwarnings` or ``--pythonwarnings/-W``.\n\n  This also fixes a number of long standing issues: :issue:`2891`, :issue:`7620`, :issue:`7426`.\n\n\n- :issue:`7572`: When a plugin listed in ``required_plugins`` is missing or an unknown config key is used with ``--strict-config``, a simple error message is now shown instead of a stacktrace.\n\n\n- :issue:`7685`: Added two new attributes :attr:`rootpath <pytest.Config.rootpath>` and :attr:`inipath <pytest.Config.inipath>` to :class:`~pytest.Config`.\n  These attributes are :class:`pathlib.Path` versions of the existing ``rootdir`` and ``inifile`` attributes,\n  and should be preferred over them when possible.\n\n\n- :issue:`7780`: Public classes which are not designed to be inherited from are now marked :func:`@final <typing.final>`.\n  Code which inherits from these classes will trigger a type-checking (e.g. mypy) error, but will still work in runtime.\n  Currently the ``final`` designation does not appear in the API Reference but hopefully will in the future.\n\n\n\nBug Fixes\n---------\n\n- :issue:`1953`: Fixed error when overwriting a parametrized fixture, while also reusing the super fixture value.\n\n  .. code-block:: python\n\n      # conftest.py\n      import pytest\n\n\n      @pytest.fixture(params=[1, 2])\n      def foo(request):\n          return request.param\n\n\n      # test_foo.py\n      import pytest\n\n\n      @pytest.fixture\n      def foo(foo):\n          return foo * 2\n\n\n- :issue:`4984`: Fixed an internal error crash with ``IndexError: list index out of range`` when\n  collecting a module which starts with a decorated function, the decorator\n  raises, and assertion rewriting is enabled.\n\n\n- :issue:`7591`: pylint shouldn't complain anymore about unimplemented abstract methods when inheriting from :ref:`File <non-python tests>`.\n\n\n- :issue:`7628`: Fixed test collection when a full path without a drive letter was passed to pytest on Windows (for example ``\\projects\\tests\\test.py`` instead of ``c:\\projects\\tests\\pytest.py``).\n\n\n- :issue:`7638`: Fix handling of command-line options that appear as paths but trigger an OS-level syntax error on Windows, such as the options used internally by ``pytest-xdist``.\n\n\n- :issue:`7742`: Fixed INTERNALERROR when accessing locals / globals with faulty ``exec``.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`1477`: Removed faq.rst and its reference in contents.rst.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`7536`: The internal ``junitxml`` plugin has rewritten to use ``xml.etree.ElementTree``.\n  The order of attributes in XML elements might differ. Some unneeded escaping is\n  no longer performed.\n\n\n- :issue:`7587`: The dependency on the ``more-itertools`` package has been removed.\n\n\n- :issue:`7631`: The result type of :meth:`capfd.readouterr() <pytest.CaptureFixture.readouterr>` (and similar) is no longer a namedtuple,\n  but should behave like one in all respects. This was done for technical reasons.\n\n\n- :issue:`7671`: When collecting tests, pytest finds test classes and functions by examining the\n  attributes of python objects (modules, classes and instances). To speed up this\n  process, pytest now ignores builtin attributes (like ``__class__``,\n  ``__delattr__`` and ``__new__``) without consulting the :confval:`python_classes` and\n  :confval:`python_functions` configuration options and without passing them to plugins\n  using the :hook:`pytest_pycollect_makeitem` hook.\n\n\npytest 6.0.2 (2020-09-04)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`7148`: Fixed ``--log-cli`` potentially causing unrelated ``print`` output to be swallowed.\n\n\n- :issue:`7672`: Fixed log-capturing level restored incorrectly if ``caplog.set_level`` is called more than once.\n\n\n- :issue:`7686`: Fixed `NotSetType.token` being used as the parameter ID when the parametrization list is empty.\n  Regressed in pytest 6.0.0.\n\n\n- :issue:`7707`: Fix internal error when handling some exceptions that contain multiple lines or the style uses multiple lines (``--tb=line`` for example).\n\n\npytest 6.0.1 (2020-07-30)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`7394`: Passing an empty ``help`` value to ``Parser.add_option`` is now accepted instead of crashing when running ``pytest --help``.\n  Passing ``None`` raises a more informative ``TypeError``.\n\n\n- :issue:`7558`: Fix pylint ``not-callable`` lint on ``pytest.mark.parametrize()`` and the other builtin marks:\n  ``skip``, ``skipif``, ``xfail``, ``usefixtures``, ``filterwarnings``.\n\n\n- :issue:`7559`: Fix regression in plugins using ``TestReport.longreprtext`` (such as ``pytest-html``) when ``TestReport.longrepr`` is not a string.\n\n\n- :issue:`7569`: Fix logging capture handler's level not reset on teardown after a call to ``caplog.set_level()``.\n\n\npytest 6.0.0 (2020-07-28)\n=========================\n\n(**Please see the full set of changes for this release also in the 6.0.0rc1 notes below**)\n\nBreaking Changes\n----------------\n\n- :issue:`5584`: **PytestDeprecationWarning are now errors by default.**\n\n  Following our plan to remove deprecated features with as little disruption as\n  possible, all warnings of type ``PytestDeprecationWarning`` now generate errors\n  instead of warning messages.\n\n  **The affected features will be effectively removed in pytest 6.1**, so please consult the\n  :std:doc:`deprecations` section in the docs for directions on how to update existing code.\n\n  In the pytest ``6.0.X`` series, it is possible to change the errors back into warnings as a\n  stopgap measure by adding this to your ``pytest.ini`` file:\n\n  .. code-block:: ini\n\n      [pytest]\n      filterwarnings =\n          ignore::pytest.PytestDeprecationWarning\n\n  But this will stop working when pytest ``6.1`` is released.\n\n  **If you have concerns** about the removal of a specific feature, please add a\n  comment to :issue:`5584`.\n\n\n- :issue:`7472`: The ``exec_()`` and ``is_true()`` methods of ``_pytest._code.Frame`` have been removed.\n\n\n\nFeatures\n--------\n\n- :issue:`7464`: Added support for :envvar:`NO_COLOR` and :envvar:`FORCE_COLOR` environment variables to control colored output.\n\n\n\nImprovements\n------------\n\n- :issue:`7467`: ``--log-file`` CLI option and ``log_file`` ini marker now create subdirectories if needed.\n\n\n- :issue:`7489`: The :func:`pytest.raises` function has a clearer error message when ``match`` equals the obtained string but is not a regex match. In this case it is suggested to escape the regex.\n\n\n\nBug Fixes\n---------\n\n- :issue:`7392`: Fix the reported location of tests skipped with ``@pytest.mark.skip`` when ``--runxfail`` is used.\n\n\n- :issue:`7491`: :fixture:`tmpdir` and :fixture:`tmp_path` no longer raise an error if the lock to check for\n  stale temporary directories is not accessible.\n\n\n- :issue:`7517`: Preserve line endings when captured via ``capfd``.\n\n\n- :issue:`7534`: Restored the previous formatting of ``TracebackEntry.__str__`` which was changed by accident.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`7422`: Clarified when the ``usefixtures`` mark can apply fixtures to test.\n\n\n- :issue:`7441`: Add a note about ``-q`` option used in getting started guide.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`7389`: Fixture scope ``package`` is no longer considered experimental.\n\n\npytest 6.0.0rc1 (2020-07-08)\n============================\n\nBreaking Changes\n----------------\n\n- :issue:`1316`: ``TestReport.longrepr`` is now always an instance of ``ReprExceptionInfo``. Previously it was a ``str`` when a test failed with ``pytest.fail(..., pytrace=False)``.\n\n\n- :issue:`5965`: symlinks are no longer resolved during collection and matching `conftest.py` files with test file paths.\n\n  Resolving symlinks for the current directory and during collection was introduced as a bugfix in 3.9.0, but it actually is a new feature which had unfortunate consequences in Windows and surprising results in other platforms.\n\n  The team decided to step back on resolving symlinks at all, planning to review this in the future with a more solid solution (see discussion in\n  :pr:`6523` for details).\n\n  This might break test suites which made use of this feature; the fix is to create a symlink\n  for the entire test tree, and not only to partial files/tress as it was possible previously.\n\n\n- :issue:`6505`: ``Testdir.run().parseoutcomes()`` now always returns the parsed nouns in plural form.\n\n  Originally ``parseoutcomes()`` would always returns the nouns in plural form, but a change\n  meant to improve the terminal summary by using singular form single items (``1 warning`` or ``1 error``)\n  caused an unintended regression by changing the keys returned by ``parseoutcomes()``.\n\n  Now the API guarantees to always return the plural form, so calls like this:\n\n  .. code-block:: python\n\n      result = testdir.runpytest()\n      result.assert_outcomes(error=1)\n\n  Need to be changed to:\n\n\n  .. code-block:: python\n\n      result = testdir.runpytest()\n      result.assert_outcomes(errors=1)\n\n\n- :issue:`6903`: The ``os.dup()`` function is now assumed to exist. We are not aware of any\n  supported Python 3 implementations which do not provide it.\n\n\n- :issue:`7040`: ``-k`` no longer matches against the names of the directories outside the test session root.\n\n  Also, ``pytest.Package.name`` is now just the name of the directory containing the package's\n  ``__init__.py`` file, instead of the full path. This is consistent with how the other nodes\n  are named, and also one of the reasons why ``-k`` would match against any directory containing\n  the test suite.\n\n\n- :issue:`7122`: Expressions given to the ``-m`` and ``-k`` options are no longer evaluated using Python's :func:`eval`.\n  The format supports ``or``, ``and``, ``not``, parenthesis and general identifiers to match against.\n  Python constants, keywords or other operators are no longer evaluated differently.\n\n\n- :issue:`7135`: Pytest now uses its own ``TerminalWriter`` class instead of using the one from the ``py`` library.\n  Plugins generally access this class through ``TerminalReporter.writer``, ``TerminalReporter.write()``\n  (and similar methods), or ``_pytest.config.create_terminal_writer()``.\n\n  The following breaking changes were made:\n\n  - Output (``write()`` method and others) no longer flush implicitly; the flushing behavior\n    of the underlying file is respected. To flush explicitly (for example, if you\n    want output to be shown before an end-of-line is printed), use ``write(flush=True)`` or\n    ``terminal_writer.flush()``.\n  - Explicit Windows console support was removed, delegated to the colorama library.\n  - Support for writing ``bytes`` was removed.\n  - The ``reline`` method and ``chars_on_current_line`` property were removed.\n  - The ``stringio`` and ``encoding`` arguments was removed.\n  - Support for passing a callable instead of a file was removed.\n\n\n- :issue:`7224`: The `item.catch_log_handler` and `item.catch_log_handlers` attributes, set by the\n  logging plugin and never meant to be public, are no longer available.\n\n  The deprecated ``--no-print-logs`` option and ``log_print`` ini option are removed. Use ``--show-capture`` instead.\n\n\n- :issue:`7226`: Removed the unused ``args`` parameter from ``pytest.Function.__init__``.\n\n\n- :issue:`7418`: Removed the `pytest_doctest_prepare_content` hook specification. This hook\n  hasn't been triggered by pytest for at least 10 years.\n\n\n- :issue:`7438`: Some changes were made to the internal ``_pytest._code.source``, listed here\n  for the benefit of plugin authors who may be using it:\n\n  - The ``deindent`` argument to ``Source()`` has been removed, now it is always true.\n  - Support for zero or multiple arguments to ``Source()`` has been removed.\n  - Support for comparing ``Source`` with an ``str`` has been removed.\n  - The methods ``Source.isparseable()`` and ``Source.putaround()`` have been removed.\n  - The method ``Source.compile()`` and function ``_pytest._code.compile()`` have\n    been removed; use plain ``compile()`` instead.\n  - The function ``_pytest._code.source.getsource()`` has been removed; use\n    ``Source()`` directly instead.\n\n\n\nDeprecations\n------------\n\n- :issue:`7210`: The special ``-k '-expr'`` syntax to ``-k`` is deprecated. Use ``-k 'not expr'``\n  instead.\n\n  The special ``-k 'expr:'`` syntax to ``-k`` is deprecated. Please open an issue\n  if you use this and want a replacement.\n\n- :issue:`4049`: ``pytest_warning_captured`` is deprecated in favor of the ``pytest_warning_recorded`` hook.\n\n\nFeatures\n--------\n\n- :issue:`1556`: pytest now supports ``pyproject.toml`` files for configuration.\n\n  The configuration options is similar to the one available in other formats, but must be defined\n  in a ``[tool.pytest.ini_options]`` table to be picked up by pytest:\n\n  .. code-block:: toml\n\n      # pyproject.toml\n      [tool.pytest.ini_options]\n      minversion = \"6.0\"\n      addopts = \"-ra -q\"\n      testpaths = [\n          \"tests\",\n          \"integration\",\n      ]\n\n  More information can be found :ref:`in the docs <config file formats>`.\n\n\n- :issue:`3342`: pytest now includes inline type annotations and exposes them to user programs.\n  Most of the user-facing API is covered, as well as internal code.\n\n  If you are running a type checker such as mypy on your tests, you may start\n  noticing type errors indicating incorrect usage. If you run into an error that\n  you believe to be incorrect, please let us know in an issue.\n\n  The types were developed against mypy version 0.780. Versions before 0.750\n  are known not to work. We recommend using the latest version. Other type\n  checkers may work as well, but they are not officially verified to work by\n  pytest yet.\n\n\n- :issue:`4049`: Introduced a new hook named `pytest_warning_recorded` to convey information about warnings captured by the internal `pytest` warnings plugin.\n\n  This hook is meant to replace `pytest_warning_captured`, which is deprecated and will be removed in a future release.\n\n\n- :issue:`6471`: New command-line flags:\n\n  * `--no-header`: disables the initial header, including platform, version, and plugins.\n  * `--no-summary`: disables the final test summary, including warnings.\n\n\n- :issue:`6856`: A warning is now shown when an unknown key is read from a config INI file.\n\n  The `--strict-config` flag has been added to treat these warnings as errors.\n\n\n- :issue:`6906`: Added `--code-highlight` command line option to enable/disable code highlighting in terminal output.\n\n\n- :issue:`7245`: New ``--import-mode=importlib`` option that uses :mod:`importlib` to import test modules.\n\n  Traditionally pytest used ``__import__`` while changing ``sys.path`` to import test modules (which\n  also changes ``sys.modules`` as a side-effect), which works but has a number of drawbacks, like requiring test modules\n  that don't live in packages to have unique names (as they need to reside under a unique name in ``sys.modules``).\n\n  ``--import-mode=importlib`` uses more fine-grained import mechanisms from ``importlib`` which don't\n  require pytest to change ``sys.path`` or ``sys.modules`` at all, eliminating much of the drawbacks\n  of the previous mode.\n\n  We intend to make ``--import-mode=importlib`` the default in future versions, so users are encouraged\n  to try the new mode and provide feedback (both positive or negative) in issue :issue:`7245`.\n\n  You can read more about this option in :std:ref:`the documentation <import-modes>`.\n\n\n- :issue:`7305`: New ``required_plugins`` configuration option allows the user to specify a list of plugins, including version information, that are required for pytest to run. An error is raised if any required plugins are not found when running pytest.\n\n\nImprovements\n------------\n\n- :issue:`4375`: The ``pytest`` command now suppresses the ``BrokenPipeError`` error message that\n  is printed to stderr when the output of ``pytest`` is piped and the pipe is\n  closed by the piped-to program (common examples are ``less`` and ``head``).\n\n\n- :issue:`4391`: Improved precision of test durations measurement. ``CallInfo`` items now have a new ``<CallInfo>.duration`` attribute, created using ``time.perf_counter()``. This attribute is used to fill the ``<TestReport>.duration`` attribute, which is more accurate than the previous ``<CallInfo>.stop - <CallInfo>.start`` (as these are based on ``time.time()``).\n\n\n- :issue:`4675`: Rich comparison for dataclasses and `attrs`-classes is now recursive.\n\n\n- :issue:`6285`: Exposed the `pytest.FixtureLookupError` exception which is raised by `request.getfixturevalue()`\n  (where `request` is a `FixtureRequest` fixture) when a fixture with the given name cannot be returned.\n\n\n- :issue:`6433`: If an error is encountered while formatting the message in a logging call, for\n  example ``logging.warning(\"oh no!: %s: %s\", \"first\")`` (a second argument is\n  missing), pytest now propagates the error, likely causing the test to fail.\n\n  Previously, such a mistake would cause an error to be printed to stderr, which\n  is not displayed by default for passing tests. This change makes the mistake\n  visible during testing.\n\n  You may suppress this behavior temporarily or permanently by setting\n  ``logging.raiseExceptions = False``.\n\n\n- :issue:`6817`: Explicit new-lines in help texts of command-line options are preserved, allowing plugins better control\n  of the help displayed to users.\n\n\n- :issue:`6940`: When using the ``--duration`` option, the terminal message output is now more precise about the number and duration of hidden items.\n\n\n- :issue:`6991`: Collected files are displayed after any reports from hooks, e.g. the status from ``--lf``.\n\n\n- :issue:`7091`: When ``fd`` capturing is used, through ``--capture=fd`` or the ``capfd`` and\n  ``capfdbinary`` fixtures, and the file descriptor (0, 1, 2) cannot be\n  duplicated, FD capturing is still performed. Previously, direct writes to the\n  file descriptors would fail or be lost in this case.\n\n\n- :issue:`7119`: Exit with an error if the ``--basetemp`` argument is empty, is the current working directory or is one of the parent directories.\n  This is done to protect against accidental data loss, as any directory passed to this argument is cleared.\n\n\n- :issue:`7128`: `pytest --version` now displays just the pytest version, while `pytest --version --version` displays more verbose information including plugins. This is more consistent with how other tools show `--version`.\n\n\n- :issue:`7133`: :meth:`caplog.set_level() <pytest.LogCaptureFixture.set_level>` will now override any :confval:`log_level` set via the CLI or configuration file.\n\n\n- :issue:`7159`: :meth:`caplog.set_level() <pytest.LogCaptureFixture.set_level>` and :meth:`caplog.at_level() <pytest.LogCaptureFixture.at_level>` no longer affect\n  the level of logs that are shown in the *Captured log report* report section.\n\n\n- :issue:`7348`: Improve recursive diff report for comparison asserts on dataclasses / attrs.\n\n\n- :issue:`7385`: ``--junitxml`` now includes the exception cause in the ``message`` XML attribute for failures during setup and teardown.\n\n  Previously:\n\n  .. code-block:: xml\n\n      <error message=\"test setup failure\">\n\n  Now:\n\n  .. code-block:: xml\n\n      <error message=\"failed on setup with &quot;ValueError: Some error during setup&quot;\">\n\n\n\nBug Fixes\n---------\n\n- :issue:`1120`: Fix issue where directories from :fixture:`tmpdir` are not removed properly when multiple instances of pytest are running in parallel.\n\n\n- :issue:`4583`: Prevent crashing and provide a user-friendly error when a marker expression (`-m`) invoking of :func:`eval` raises any exception.\n\n\n- :issue:`4677`: The path shown in the summary report for SKIPPED tests is now always relative. Previously it was sometimes absolute.\n\n\n- :issue:`5456`: Fix a possible race condition when trying to remove lock files used to control access to folders\n  created by :fixture:`tmp_path` and :fixture:`tmpdir`.\n\n\n- :issue:`6240`: Fixes an issue where logging during collection step caused duplication of log\n  messages to stderr.\n\n\n- :issue:`6428`: Paths appearing in error messages are now correct in case the current working directory has\n  changed since the start of the session.\n\n\n- :issue:`6755`: Support deleting paths longer than 260 characters on windows created inside :fixture:`tmpdir`.\n\n\n- :issue:`6871`: Fix crash with captured output when using :fixture:`capsysbinary`.\n\n\n- :issue:`6909`: Revert the change introduced by :pr:`6330`, which required all arguments to ``@pytest.mark.parametrize`` to be explicitly defined in the function signature.\n\n  The intention of the original change was to remove what was expected to be an unintended/surprising behavior, but it turns out many people relied on it, so the restriction has been reverted.\n\n\n- :issue:`6910`: Fix crash when plugins return an unknown stats while using the ``--reportlog`` option.\n\n\n- :issue:`6924`: Ensure a ``unittest.IsolatedAsyncioTestCase`` is actually awaited.\n\n\n- :issue:`6925`: Fix `TerminalRepr` instances to be hashable again.\n\n\n- :issue:`6947`: Fix regression where functions registered with :meth:`unittest.TestCase.addCleanup` were not being called on test failures.\n\n\n- :issue:`6951`: Allow users to still set the deprecated ``TerminalReporter.writer`` attribute.\n\n\n- :issue:`6956`: Prevent pytest from printing `ConftestImportFailure` traceback to stdout.\n\n\n- :issue:`6991`: Fix regressions with `--lf` filtering too much since pytest 5.4.\n\n\n- :issue:`6992`: Revert \"tmpdir: clean up indirection via config for factories\" :issue:`6767` as it breaks pytest-xdist.\n\n\n- :issue:`7061`: When a yielding fixture fails to yield a value, report a test setup error instead of crashing.\n\n\n- :issue:`7076`: The path of file skipped by ``@pytest.mark.skip`` in the SKIPPED report is now relative to invocation directory. Previously it was relative to root directory.\n\n\n- :issue:`7110`: Fixed regression: ``asyncbase.TestCase`` tests are executed correctly again.\n\n\n- :issue:`7126`: ``--setup-show`` now doesn't raise an error when a bytes value is used as a ``parametrize``\n  parameter when Python is called with the ``-bb`` flag.\n\n\n- :issue:`7143`: Fix :meth:`pytest.File.from_parent <_pytest.nodes.Node.from_parent>` so it forwards extra keyword arguments to the constructor.\n\n\n- :issue:`7145`: Classes with broken ``__getattribute__`` methods are displayed correctly during failures.\n\n\n- :issue:`7150`: Prevent hiding the underlying exception when ``ConfTestImportFailure`` is raised.\n\n\n- :issue:`7180`: Fix ``_is_setup_py`` for files encoded differently than locale.\n\n\n- :issue:`7215`: Fix regression where running with ``--pdb`` would call :meth:`unittest.TestCase.tearDown` for skipped tests.\n\n\n- :issue:`7253`: When using ``pytest.fixture`` on a function directly, as in ``pytest.fixture(func)``,\n  if the ``autouse`` or ``params`` arguments are also passed, the function is no longer\n  ignored, but is marked as a fixture.\n\n\n- :issue:`7360`: Fix possibly incorrect evaluation of string expressions passed to ``pytest.mark.skipif`` and ``pytest.mark.xfail``,\n  in rare circumstances where the exact same string is used but refers to different global values.\n\n\n- :issue:`7383`: Fixed exception causes all over the codebase, i.e. use `raise new_exception from old_exception` when wrapping an exception.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`7202`: The development guide now links to the contributing section of the docs and `RELEASING.rst` on GitHub.\n\n\n- :issue:`7233`: Add a note about ``--strict`` and ``--strict-markers`` and the preference for the latter one.\n\n\n- :issue:`7345`: Explain indirect parametrization and markers for fixtures.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`7035`: The ``originalname`` attribute of ``_pytest.python.Function`` now defaults to ``name`` if not\n  provided explicitly, and is always set.\n\n\n- :issue:`7264`: The dependency on the ``wcwidth`` package has been removed.\n\n\n- :issue:`7291`: Replaced ``py.iniconfig`` with :pypi:`iniconfig`.\n\n\n- :issue:`7295`: ``src/_pytest/config/__init__.py`` now uses the ``warnings`` module to report warnings instead of ``sys.stderr.write``.\n\n\n- :issue:`7356`: Remove last internal uses of deprecated *slave* term from old ``pytest-xdist``.\n\n\n- :issue:`7357`: ``py``>=1.8.2 is now required.\n\n\npytest 5.4.3 (2020-06-02)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`6428`: Paths appearing in error messages are now correct in case the current working directory has\n  changed since the start of the session.\n\n\n- :issue:`6755`: Support deleting paths longer than 260 characters on windows created inside tmpdir.\n\n\n- :issue:`6956`: Prevent pytest from printing ConftestImportFailure traceback to stdout.\n\n\n- :issue:`7150`: Prevent hiding the underlying exception when ``ConfTestImportFailure`` is raised.\n\n\n- :issue:`7215`: Fix regression where running with ``--pdb`` would call the ``tearDown`` methods of ``unittest.TestCase``\n  subclasses for skipped tests.\n\n\npytest 5.4.2 (2020-05-08)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`6871`: Fix crash with captured output when using the :fixture:`capsysbinary fixture <capsysbinary>`.\n\n\n- :issue:`6924`: Ensure a ``unittest.IsolatedAsyncioTestCase`` is actually awaited.\n\n\n- :issue:`6925`: Fix TerminalRepr instances to be hashable again.\n\n\n- :issue:`6947`: Fix regression where functions registered with ``TestCase.addCleanup`` were not being called on test failures.\n\n\n- :issue:`6951`: Allow users to still set the deprecated ``TerminalReporter.writer`` attribute.\n\n\n- :issue:`6992`: Revert \"tmpdir: clean up indirection via config for factories\" #6767 as it breaks pytest-xdist.\n\n\n- :issue:`7110`: Fixed regression: ``asyncbase.TestCase`` tests are executed correctly again.\n\n\n- :issue:`7143`: Fix ``File.from_parent`` so it forwards extra keyword arguments to the constructor.\n\n\n- :issue:`7145`: Classes with broken ``__getattribute__`` methods are displayed correctly during failures.\n\n\n- :issue:`7180`: Fix ``_is_setup_py`` for files encoded differently than locale.\n\n\npytest 5.4.1 (2020-03-13)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`6909`: Revert the change introduced by :pr:`6330`, which required all arguments to ``@pytest.mark.parametrize`` to be explicitly defined in the function signature.\n\n  The intention of the original change was to remove what was expected to be an unintended/surprising behavior, but it turns out many people relied on it, so the restriction has been reverted.\n\n\n- :issue:`6910`: Fix crash when plugins return an unknown stats while using the ``--reportlog`` option.\n\n\npytest 5.4.0 (2020-03-12)\n=========================\n\nBreaking Changes\n----------------\n\n- :issue:`6316`: Matching of ``-k EXPRESSION`` to test names is now case-insensitive.\n\n\n- :issue:`6443`: Plugins specified with ``-p`` are now loaded after internal plugins, which results in their hooks being called *before* the internal ones.\n\n  This makes the ``-p`` behavior consistent with ``PYTEST_PLUGINS``.\n\n\n- :issue:`6637`: Removed the long-deprecated ``pytest_itemstart`` hook.\n\n  This hook has been marked as deprecated and not been even called by pytest for over 10 years now.\n\n\n- :issue:`6673`: Reversed / fix meaning of \"+/-\" in error diffs.  \"-\" means that something expected is missing in the result and \"+\" means that there are unexpected extras in the result.\n\n\n- :issue:`6737`: The ``cached_result`` attribute of ``FixtureDef`` is now set to ``None`` when\n  the result is unavailable, instead of being deleted.\n\n  If your plugin performs checks like ``hasattr(fixturedef, 'cached_result')``,\n  for example in a ``pytest_fixture_post_finalizer`` hook implementation, replace\n  it with ``fixturedef.cached_result is not None``. If you ``del`` the attribute,\n  set it to ``None`` instead.\n\n\n\nDeprecations\n------------\n\n- :issue:`3238`: Option ``--no-print-logs`` is deprecated and meant to be removed in a future release. If you use ``--no-print-logs``, please try out ``--show-capture`` and\n  provide feedback.\n\n  ``--show-capture`` command-line option was added in ``pytest 3.5.0`` and allows to specify how to\n  display captured output when tests fail: ``no``, ``stdout``, ``stderr``, ``log`` or ``all`` (the default).\n\n\n- :issue:`571`: Deprecate the unused/broken `pytest_collect_directory` hook.\n  It was misaligned since the removal of the ``Directory`` collector in 2010\n  and incorrect/unusable as soon as collection was split from test execution.\n\n\n- :issue:`5975`: Deprecate using direct constructors for ``Nodes``.\n\n  Instead they are now constructed via ``Node.from_parent``.\n\n  This transitional mechanism enables us to untangle the very intensely\n  entangled ``Node`` relationships by enforcing more controlled creation/configuration patterns.\n\n  As part of this change, session/config are already disallowed parameters and as we work on the details we might need disallow a few more as well.\n\n  Subclasses are expected to use `super().from_parent` if they intend to expand the creation of `Nodes`.\n\n\n- :issue:`6779`: The ``TerminalReporter.writer`` attribute has been deprecated and should no longer be used. This\n  was inadvertently exposed as part of the public API of that plugin and ties it too much\n  with ``py.io.TerminalWriter``.\n\n\n\nFeatures\n--------\n\n- :issue:`4597`: New :ref:`--capture=tee-sys <capture-method>` option to allow both live printing and capturing of test output.\n\n\n- :issue:`5712`: Now all arguments to ``@pytest.mark.parametrize`` need to be explicitly declared in the function signature or via ``indirect``.\n  Previously it was possible to omit an argument if a fixture with the same name existed, which was just an accident of implementation and was not meant to be a part of the API.\n\n\n- :issue:`6454`: Changed default for `-r` to `fE`, which displays failures and errors in the :ref:`short test summary <pytest.detailed_failed_tests_usage>`.  `-rN` can be used to disable it (the old behavior).\n\n\n- :issue:`6469`: New options have been added to the :confval:`junit_logging` option: ``log``, ``out-err``, and ``all``.\n\n\n- :issue:`6834`: Excess warning summaries are now collapsed per file to ensure readable display of warning summaries.\n\n\n\nImprovements\n------------\n\n- :issue:`1857`: ``pytest.mark.parametrize`` accepts integers for ``ids`` again, converting it to strings.\n\n\n- :issue:`449`: Use \"yellow\" main color with any XPASSED tests.\n\n\n- :issue:`4639`: Revert \"A warning is now issued when assertions are made for ``None``\".\n\n  The warning proved to be less useful than initially expected and had quite a\n  few false positive cases.\n\n\n- :issue:`5686`: ``tmpdir_factory.mktemp`` now fails when given absolute and non-normalized paths.\n\n\n- :issue:`5984`: The ``pytest_warning_captured`` hook now receives a ``location`` parameter with the code location that generated the warning.\n\n\n- :issue:`6213`: pytester: the ``testdir`` fixture respects environment settings from the ``monkeypatch`` fixture for inner runs.\n\n\n- :issue:`6247`: ``--fulltrace`` is honored with collection errors.\n\n\n- :issue:`6384`: Make `--showlocals` work also with `--tb=short`.\n\n\n- :issue:`6653`: Add support for matching lines consecutively with :class:`~pytest.LineMatcher`'s :func:`~pytest.LineMatcher.fnmatch_lines` and :func:`~pytest.LineMatcher.re_match_lines`.\n\n\n- :issue:`6658`: Code is now highlighted in tracebacks when ``pygments`` is installed.\n\n  Users are encouraged to install ``pygments`` into their environment and provide feedback, because\n  the plan is to make ``pygments`` a regular dependency in the future.\n\n\n- :issue:`6795`: Import usage error message with invalid `-o` option.\n\n\n- :issue:`759`: ``pytest.mark.parametrize`` supports iterators and generators for ``ids``.\n\n\n\nBug Fixes\n---------\n\n- :issue:`310`: Add support for calling `pytest.xfail()` and `pytest.importorskip()` with doctests.\n\n\n- :issue:`3823`: ``--trace`` now works with unittests.\n\n\n- :issue:`4445`: Fixed some warning reports produced by pytest to point to the correct location of the warning in the user's code.\n\n\n- :issue:`5301`: Fix ``--last-failed`` to collect new tests from files with known failures.\n\n\n- :issue:`5928`: Report ``PytestUnknownMarkWarning`` at the level of the user's code, not ``pytest``'s.\n\n\n- :issue:`5991`: Fix interaction with ``--pdb`` and unittests: do not use unittest's ``TestCase.debug()``.\n\n\n- :issue:`6334`: Fix summary entries appearing twice when ``f/F`` and ``s/S`` report chars were used at the same time in the ``-r`` command-line option (for example ``-rFf``).\n\n  The upper case variants were never documented and the preferred form should be the lower case.\n\n\n- :issue:`6409`: Fallback to green (instead of yellow) for non-last items without previous passes with colored terminal progress indicator.\n\n\n- :issue:`6454`: `--disable-warnings` is honored with `-ra` and `-rA`.\n\n\n- :issue:`6497`: Fix bug in the comparison of request key with cached key in fixture.\n\n  A construct ``if key == cached_key:`` can fail either because ``==`` is explicitly disallowed, or for, e.g., NumPy arrays, where the result of ``a == b`` cannot generally be converted to :class:`bool`.\n  The implemented fix replaces `==` with ``is``.\n\n\n- :issue:`6557`: Make capture output streams ``.write()`` method return the same return value from original streams.\n\n\n- :issue:`6566`: Fix ``EncodedFile.writelines`` to call the underlying buffer's ``writelines`` method.\n\n\n- :issue:`6575`: Fix internal crash when ``faulthandler`` starts initialized\n  (for example with ``PYTHONFAULTHANDLER=1`` environment variable set) and ``faulthandler_timeout`` defined\n  in the configuration file.\n\n\n- :issue:`6597`: Fix node ids which contain a parametrized empty-string variable.\n\n\n- :issue:`6646`: Assertion rewriting hooks are (re)stored for the current item, which fixes them being still used after e.g. pytester's ``testdir.runpytest`` etc.\n\n\n- :issue:`6660`: :py:func:`pytest.exit` is handled when emitted from the :hook:`pytest_sessionfinish` hook.  This includes quitting from a debugger.\n\n\n- :issue:`6752`: When :py:func:`pytest.raises` is used as a function (as opposed to a context manager),\n  a `match` keyword argument is now passed through to the tested function. Previously\n  it was swallowed and ignored (regression in pytest 5.1.0).\n\n\n- :issue:`6801`: Do not display empty lines in between traceback for unexpected exceptions with doctests.\n\n\n- :issue:`6802`: The :fixture:`testdir fixture <testdir>` works within doctests now.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`6696`: Add list of fixtures to start of fixture chapter.\n\n\n- :issue:`6742`: Expand first sentence on fixtures into a paragraph.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`6404`: Remove usage of ``parser`` module, deprecated in Python 3.9.\n\n\npytest 5.3.5 (2020-01-29)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`6517`: Fix regression in pytest 5.3.4 causing an INTERNALERROR due to a wrong assertion.\n\n\npytest 5.3.4 (2020-01-20)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`6496`: Revert :issue:`6436`: unfortunately this change has caused a number of regressions in many suites,\n  so the team decided to revert this change and make a new release while we continue to look for a solution.\n\n\npytest 5.3.3 (2020-01-16)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`2780`: Captured output during teardown is shown with ``-rP``.\n\n\n- :issue:`5971`: Fix a ``pytest-xdist`` crash when dealing with exceptions raised in subprocesses created by the\n  ``multiprocessing`` module.\n\n\n- :issue:`6436`: :class:`~pytest.FixtureDef` objects now properly register their finalizers with autouse and\n  parameterized fixtures that execute before them in the fixture stack so they are torn\n  down at the right times, and in the right order.\n\n\n- :issue:`6532`: Fix parsing of outcomes containing multiple errors with ``testdir`` results (regression in 5.3.0).\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`6350`: Optimized automatic renaming of test parameter IDs.\n\n\npytest 5.3.2 (2019-12-13)\n=========================\n\nImprovements\n------------\n\n- :issue:`4639`: Revert \"A warning is now issued when assertions are made for ``None``\".\n\n  The warning proved to be less useful than initially expected and had quite a\n  few false positive cases.\n\n\n\nBug Fixes\n---------\n\n- :issue:`5430`: junitxml: Logs for failed test are now passed to junit report in case the test fails during call phase.\n\n\n- :issue:`6290`: The supporting files in the ``.pytest_cache`` directory are kept with ``--cache-clear``, which only clears cached values now.\n\n\n- :issue:`6301`: Fix assertion rewriting for egg-based distributions and ``editable`` installs (``pip install --editable``).\n\n\npytest 5.3.1 (2019-11-25)\n=========================\n\nImprovements\n------------\n\n- :issue:`6231`: Improve check for misspelling of :ref:`pytest.mark.parametrize ref`.\n\n\n- :issue:`6257`: Handle :func:`pytest.exit` being used via :hook:`pytest_internalerror`, e.g. when quitting pdb from post mortem.\n\n\n\nBug Fixes\n---------\n\n- :issue:`5914`: pytester: fix :py:func:`~pytest.LineMatcher.no_fnmatch_line` when used after positive matching.\n\n\n- :issue:`6082`: Fix line detection for doctest samples inside\n  :py:class:`python:property` docstrings, as a workaround to\n  :issue:`python/cpython#61648`.\n\n\n- :issue:`6254`: Fix compatibility with pytest-parallel (regression in pytest 5.3.0).\n\n\n- :issue:`6255`: Clear the :py:data:`sys.last_traceback`, :py:data:`sys.last_type`\n  and :py:data:`sys.last_value` attributes by deleting them instead\n  of setting them to ``None``. This better matches the behaviour of\n  the Python standard library.\n\n\npytest 5.3.0 (2019-11-19)\n=========================\n\nDeprecations\n------------\n\n- :issue:`6179`: The default value of :confval:`junit_family` option will change to ``\"xunit2\"`` in pytest 6.0, given\n  that this is the version supported by default in modern tools that manipulate this type of file.\n\n  In order to smooth the transition, pytest will issue a warning in case the ``--junitxml`` option\n  is given in the command line but :confval:`junit_family` is not explicitly configured in ``pytest.ini``.\n\n  For more information, :ref:`see the docs <junit-family changed default value>`.\n\n\n\nFeatures\n--------\n\n- :issue:`4488`: The pytest team has created the `pytest-reportlog <https://github.com/pytest-dev/pytest-reportlog>`__\n  plugin, which provides a new ``--report-log=FILE`` option that writes *report logs* into a file as the test session executes.\n\n  Each line of the report log contains a self contained JSON object corresponding to a testing event,\n  such as a collection or a test result report. The file is guaranteed to be flushed after writing\n  each line, so systems can read and process events in real-time.\n\n  The plugin is meant to replace the ``--resultlog`` option, which is deprecated and meant to be removed\n  in a future release. If you use ``--resultlog``, please try out ``pytest-reportlog`` and\n  provide feedback.\n\n\n- :issue:`4730`: When :py:data:`sys.pycache_prefix` (Python 3.8+) is set, it will be used by pytest to cache test files changed by the assertion rewriting mechanism.\n\n  This makes it easier to benefit of cached ``.pyc`` files even on file systems without permissions.\n\n\n- :issue:`5515`: Allow selective auto-indentation of multiline log messages.\n\n  Adds command line option ``--log-auto-indent``, config option\n  :confval:`log_auto_indent` and support for per-entry configuration of\n  indentation behavior on calls to :py:func:`python:logging.log()`.\n\n  Alters the default for auto-indention from ``\"on\"`` to ``\"off\"``. This\n  restores the older behavior that existed prior to v4.6.0. This\n  reversion to earlier behavior was done because it is better to\n  activate new features that may lead to broken tests explicitly\n  rather than implicitly.\n\n\n- :issue:`5914`: :fixture:`testdir` learned two new functions, :py:func:`~pytest.LineMatcher.no_fnmatch_line` and\n  :py:func:`~pytest.LineMatcher.no_re_match_line`.\n\n  The functions are used to ensure the captured text *does not* match the given\n  pattern.\n\n  The previous idiom was to use :py:func:`python:re.match`:\n\n  .. code-block:: python\n\n      result = testdir.runpytest()\n      assert re.match(pat, result.stdout.str()) is None\n\n  Or the ``in`` operator:\n\n  .. code-block:: python\n\n      result = testdir.runpytest()\n      assert text in result.stdout.str()\n\n  But the new functions produce best output on failure.\n\n\n- :issue:`6057`: Added tolerances to complex values when printing ``pytest.approx``.\n\n  For example, ``repr(pytest.approx(3+4j))`` returns ``(3+4j) ± 5e-06 ∠ ±180°``. This is polar notation indicating a circle around the expected value, with a radius of 5e-06. For ``approx`` comparisons to return ``True``, the actual value should fall within this circle.\n\n\n- :issue:`6061`: Added the pluginmanager as an argument to ``pytest_addoption``\n  so that hooks can be invoked when setting up command line options. This is\n  useful for having one plugin communicate things to another plugin,\n  such as default values or which set of command line options to add.\n\n\n\nImprovements\n------------\n\n- :issue:`5061`: Use multiple colors with terminal summary statistics.\n\n\n- :issue:`5630`: Quitting from debuggers is now properly handled in ``doctest`` items.\n\n\n- :issue:`5924`: Improved verbose diff output with sequences.\n\n  Before:\n\n  ::\n\n      E   AssertionError: assert ['version', '...version_info'] == ['version', '...version', ...]\n      E     Right contains 3 more items, first extra item: ' '\n      E     Full diff:\n      E     - ['version', 'version_info', 'sys.version', 'sys.version_info']\n      E     + ['version',\n      E     +  'version_info',\n      E     +  'sys.version',\n      E     +  'sys.version_info',\n      E     +  ' ',\n      E     +  'sys.version',\n      E     +  'sys.version_info']\n\n  After:\n\n  ::\n\n      E   AssertionError: assert ['version', '...version_info'] == ['version', '...version', ...]\n      E     Right contains 3 more items, first extra item: ' '\n      E     Full diff:\n      E       [\n      E        'version',\n      E        'version_info',\n      E        'sys.version',\n      E        'sys.version_info',\n      E     +  ' ',\n      E     +  'sys.version',\n      E     +  'sys.version_info',\n      E       ]\n\n\n- :issue:`5934`: ``repr`` of ``ExceptionInfo`` objects has been improved to honor the ``__repr__`` method of the underlying exception.\n\n- :issue:`5936`: Display untruncated assertion message with ``-vv``.\n\n\n- :issue:`5990`: Fixed plurality mismatch in test summary (e.g. display \"1 error\" instead of \"1 errors\").\n\n\n- :issue:`6008`: ``Config.InvocationParams.args`` is now always a ``tuple`` to better convey that it should be\n  immutable and avoid accidental modifications.\n\n\n- :issue:`6023`: ``pytest.main`` returns a ``pytest.ExitCode`` instance now, except for when custom exit codes are used (where it returns ``int`` then still).\n\n\n- :issue:`6026`: Align prefixes in output of pytester's ``LineMatcher``.\n\n\n- :issue:`6059`: Collection errors are reported as errors (and not failures like before) in the terminal's short test summary.\n\n\n- :issue:`6069`: ``pytester.spawn`` does not skip/xfail tests on FreeBSD anymore unconditionally.\n\n\n- :issue:`6097`: The \"[...%]\" indicator in the test summary is now colored according to the final (new) multi-colored line's main color.\n\n\n- :issue:`6116`: Added ``--co`` as a synonym to ``--collect-only``.\n\n\n- :issue:`6148`: ``atomicwrites`` is now only used on Windows, fixing a performance regression with assertion rewriting on Unix.\n\n\n- :issue:`6152`: Now parametrization will use the ``__name__`` attribute of any object for the id, if present. Previously it would only use ``__name__`` for functions and classes.\n\n\n- :issue:`6176`: Improved failure reporting with pytester's ``Hookrecorder.assertoutcome``.\n\n\n- :issue:`6181`: The reason for a stopped session, e.g. with ``--maxfail`` / ``-x``, now gets reported in the test summary.\n\n\n- :issue:`6206`: Improved ``cache.set`` robustness and performance.\n\n\n\nBug Fixes\n---------\n\n- :issue:`2049`: Fixed ``--setup-plan`` showing inaccurate information about fixture lifetimes.\n\n\n- :issue:`2548`: Fixed line offset mismatch of skipped tests in terminal summary.\n\n\n- :issue:`6039`: The ``PytestDoctestRunner`` is now properly invalidated when unconfiguring the doctest plugin.\n\n  This is important when used with ``pytester``'s ``runpytest_inprocess``.\n\n\n- :issue:`6047`: BaseExceptions are now handled in ``saferepr``, which includes ``pytest.fail.Exception`` etc.\n\n\n- :issue:`6074`: pytester: fixed order of arguments in ``rm_rf`` warning when cleaning up temporary directories, and do not emit warnings for errors with ``os.open``.\n\n\n- :issue:`6189`: Fixed result of ``getmodpath`` method.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4901`: ``RunResult`` from ``pytester`` now displays the mnemonic of the ``ret`` attribute when it is a\n  valid ``pytest.ExitCode`` value.\n\n\npytest 5.2.4 (2019-11-15)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`6194`: Fix incorrect discovery of non-test ``__init__.py`` files.\n\n\n- :issue:`6197`: Revert \"The first test in a package (``__init__.py``) marked with ``@pytest.mark.skip`` is now correctly skipped.\".\n\n\npytest 5.2.3 (2019-11-14)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5830`: The first test in a package (``__init__.py``) marked with ``@pytest.mark.skip`` is now correctly skipped.\n\n\n- :issue:`6099`: Fix ``--trace`` when used with parametrized functions.\n\n\n- :issue:`6183`: Using ``request`` as a parameter name in ``@pytest.mark.parametrize`` now produces a more\n  user-friendly error.\n\n\npytest 5.2.2 (2019-10-24)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5206`: Fix ``--nf`` to not forget about known nodeids with partial test selection.\n\n\n- :issue:`5906`: Fix crash with ``KeyboardInterrupt`` during ``--setup-show``.\n\n\n- :issue:`5946`: Fixed issue when parametrizing fixtures with numpy arrays (and possibly other sequence-like types).\n\n\n- :issue:`6044`: Properly ignore ``FileNotFoundError`` exceptions when trying to remove old temporary directories,\n  for instance when multiple processes try to remove the same directory (common with ``pytest-xdist``\n  for example).\n\n\npytest 5.2.1 (2019-10-06)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5902`: Fix warnings about deprecated ``cmp`` attribute in ``attrs>=19.2``.\n\n\npytest 5.2.0 (2019-09-28)\n=========================\n\nDeprecations\n------------\n\n- :issue:`1682`: Passing arguments to pytest.fixture() as positional arguments is deprecated - pass them\n  as a keyword argument instead.\n\n\n\nFeatures\n--------\n\n- :issue:`1682`: The ``scope`` parameter of ``@pytest.fixture`` can now be a callable that receives\n  the fixture name and the ``config`` object as keyword-only parameters.\n  See :ref:`the docs <dynamic scope>` for more information.\n\n\n- :issue:`5764`: New behavior of the ``--pastebin`` option: failures to connect to the pastebin server are reported, without failing the pytest run\n\n\n\nBug Fixes\n---------\n\n- :issue:`5806`: Fix \"lexer\" being used when uploading to bpaste.net from ``--pastebin`` to \"text\".\n\n\n- :issue:`5884`: Fix ``--setup-only`` and ``--setup-show`` for custom pytest items.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`5056`: The HelpFormatter uses ``py.io.get_terminal_width`` for better width detection.\n\n\npytest 5.1.3 (2019-09-18)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5807`: Fix pypy3.6 (nightly) on windows.\n\n\n- :issue:`5811`: Handle ``--fulltrace`` correctly with ``pytest.raises``.\n\n\n- :issue:`5819`: Windows: Fix regression with conftest whose qualified name contains uppercase\n  characters (introduced by #5792).\n\n\npytest 5.1.2 (2019-08-30)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`2270`: Fixed ``self`` reference in function-scoped fixtures defined plugin classes: previously ``self``\n  would be a reference to a *test* class, not the *plugin* class.\n\n\n- :issue:`570`: Fixed long standing issue where fixture scope was not respected when indirect fixtures were used during\n  parametrization.\n\n\n- :issue:`5782`: Fix decoding error when printing an error response from ``--pastebin``.\n\n\n- :issue:`5786`: Chained exceptions in test and collection reports are now correctly serialized, allowing plugins like\n  ``pytest-xdist`` to display them properly.\n\n\n- :issue:`5792`: Windows: Fix error that occurs in certain circumstances when loading\n  ``conftest.py`` from a working directory that has casing other than the one stored\n  in the filesystem (e.g., ``c:\\test`` instead of ``C:\\test``).\n\n\npytest 5.1.1 (2019-08-20)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5751`: Fixed ``TypeError`` when importing pytest on Python 3.5.0 and 3.5.1.\n\n\npytest 5.1.0 (2019-08-15)\n=========================\n\nRemovals\n--------\n\n- :issue:`5180`: As per our policy, the following features have been deprecated in the 4.X series and are now\n  removed:\n\n  * ``Request.getfuncargvalue``: use ``Request.getfixturevalue`` instead.\n\n  * ``pytest.raises`` and ``pytest.warns`` no longer support strings as the second argument.\n\n  * ``message`` parameter of ``pytest.raises``.\n\n  * ``pytest.raises``, ``pytest.warns`` and ``ParameterSet.param`` now use native keyword-only\n    syntax. This might change the exception message from previous versions, but they still raise\n    ``TypeError`` on unknown keyword arguments as before.\n\n  * ``pytest.config`` global variable.\n\n  * ``tmpdir_factory.ensuretemp`` method.\n\n  * ``pytest_logwarning`` hook.\n\n  * ``RemovedInPytest4Warning`` warning type.\n\n  * ``request`` is now a reserved name for fixtures.\n\n\n  For more information consult :std:doc:`deprecations` in the docs.\n\n\n- :issue:`5565`: Removed unused support code for :pypi:`unittest2`.\n\n  The ``unittest2`` backport module is no longer\n  necessary since Python 3.3+, and the small amount of code in pytest to support it also doesn't seem\n  to be used: after removed, all tests still pass unchanged.\n\n  Although our policy is to introduce a deprecation period before removing any features or support\n  for third party libraries, because this code is apparently not used\n  at all (even if ``unittest2`` is used by a test suite executed by pytest), it was decided to\n  remove it in this release.\n\n  If you experience a regression because of this, please :issue:`file an issue <new>`.\n\n\n- :issue:`5615`: ``pytest.fail``, ``pytest.xfail`` and ``pytest.skip`` no longer support bytes for the message argument.\n\n  This was supported for Python 2 where it was tempting to use ``\"message\"``\n  instead of ``u\"message\"``.\n\n  Python 3 code is unlikely to pass ``bytes`` to these functions. If you do,\n  please decode it to an ``str`` beforehand.\n\n\n\nFeatures\n--------\n\n- :issue:`5564`: New ``Config.invocation_args`` attribute containing the unchanged arguments passed to ``pytest.main()``.\n\n\n- :issue:`5576`: New :ref:`NUMBER <using doctest options>`\n  option for doctests to ignore irrelevant differences in floating-point numbers.\n  Inspired by Sébastien Boisgérault's `numtest <https://github.com/boisgera/numtest>`__\n  extension for doctest.\n\n\n\nImprovements\n------------\n\n- :issue:`5471`: JUnit XML now includes a timestamp and hostname in the testsuite tag.\n\n\n- :issue:`5707`: Time taken to run the test suite now includes a human-readable representation when it takes over\n  60 seconds, for example::\n\n      ===== 2 failed in 102.70s (0:01:42) =====\n\n\n\nBug Fixes\n---------\n\n- :issue:`4344`: Fix RuntimeError/StopIteration when trying to collect package with \"__init__.py\" only.\n\n\n- :issue:`5115`: Warnings issued during ``pytest_configure`` are explicitly not treated as errors, even if configured as such, because it otherwise completely breaks pytest.\n\n\n- :issue:`5477`: The XML file produced by ``--junitxml`` now correctly contain a ``<testsuites>`` root element.\n\n\n- :issue:`5524`: Fix issue where ``tmp_path`` and ``tmpdir`` would not remove directories containing files marked as read-only,\n  which could lead to pytest crashing when executed a second time with the ``--basetemp`` option.\n\n\n- :issue:`5537`: Replace ``importlib_metadata`` backport with ``importlib.metadata`` from the\n  standard library on Python 3.8+.\n\n\n- :issue:`5578`: Improve type checking for some exception-raising functions (``pytest.xfail``, ``pytest.skip``, etc)\n  so they provide better error messages when users meant to use marks (for example ``@pytest.xfail``\n  instead of ``@pytest.mark.xfail``).\n\n\n- :issue:`5606`: Fixed internal error when test functions were patched with objects that cannot be compared\n  for truth values against others, like ``numpy`` arrays.\n\n\n- :issue:`5634`: ``pytest.exit`` is now correctly handled in ``unittest`` cases.\n  This makes ``unittest`` cases handle ``quit`` from pytest's pdb correctly.\n\n\n- :issue:`5650`: Improved output when parsing an ini configuration file fails.\n\n\n- :issue:`5701`: Fix collection of ``staticmethod`` objects defined with ``functools.partial``.\n\n\n- :issue:`5734`: Skip async generator test functions, and update the warning message to refer to ``async def`` functions.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`5669`: Add docstring for ``Testdir.copy_example``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`5095`: XML files of the ``xunit2`` family are now validated against the schema by pytest's own test suite\n  to avoid future regressions.\n\n\n- :issue:`5516`: Cache node splitting function which can improve collection performance in very large test suites.\n\n\n- :issue:`5603`: Simplified internal ``SafeRepr`` class and removed some dead code.\n\n\n- :issue:`5664`: When invoking pytest's own testsuite with ``PYTHONDONTWRITEBYTECODE=1``,\n  the ``test_xfail_handling`` test no longer fails.\n\n\n- :issue:`5684`: Replace manual handling of ``OSError.errno`` in the codebase by new ``OSError`` subclasses (``PermissionError``, ``FileNotFoundError``, etc.).\n\n\npytest 5.0.1 (2019-07-04)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5479`: Improve quoting in ``raises`` match failure message.\n\n\n- :issue:`5523`: Fixed using multiple short options together in the command-line (for example ``-vs``) in Python 3.8+.\n\n\n- :issue:`5547`: ``--step-wise`` now handles ``xfail(strict=True)`` markers properly.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`5517`: Improve \"Declaring new hooks\" section in chapter \"Writing Plugins\"\n\n\npytest 5.0.0 (2019-06-28)\n=========================\n\nImportant\n---------\n\nThis release is a Python3.5+ only release.\n\nFor more details, see our `Python 2.7 and 3.4 support plan\n<https://docs.pytest.org/en/7.0.x/py27-py34-deprecation.html>`_.\n\nRemovals\n--------\n\n- :issue:`1149`: Pytest no longer accepts prefixes of command-line arguments, for example\n  typing ``pytest --doctest-mod`` inplace of ``--doctest-modules``.\n  This was previously allowed where the ``ArgumentParser`` thought it was unambiguous,\n  but this could be incorrect due to delayed parsing of options for plugins.\n  See for example issues :issue:`1149`,\n  :issue:`3413`, and\n  :issue:`4009`.\n\n\n- :issue:`5402`: **PytestDeprecationWarning are now errors by default.**\n\n  Following our plan to remove deprecated features with as little disruption as\n  possible, all warnings of type ``PytestDeprecationWarning`` now generate errors\n  instead of warning messages.\n\n  **The affected features will be effectively removed in pytest 5.1**, so please consult the\n  :std:doc:`deprecations` section in the docs for directions on how to update existing code.\n\n  In the pytest ``5.0.X`` series, it is possible to change the errors back into warnings as a stop\n  gap measure by adding this to your ``pytest.ini`` file:\n\n  .. code-block:: ini\n\n      [pytest]\n      filterwarnings =\n          ignore::pytest.PytestDeprecationWarning\n\n  But this will stop working when pytest ``5.1`` is released.\n\n  **If you have concerns** about the removal of a specific feature, please add a\n  comment to :issue:`5402`.\n\n\n- :issue:`5412`: ``ExceptionInfo`` objects (returned by ``pytest.raises``) now have the same ``str`` representation as ``repr``, which\n  avoids some confusion when users use ``print(e)`` to inspect the object.\n\n  This means code like:\n\n  .. code-block:: python\n\n        with pytest.raises(SomeException) as e:\n            ...\n        assert \"some message\" in str(e)\n\n\n  Needs to be changed to:\n\n  .. code-block:: python\n\n        with pytest.raises(SomeException) as e:\n            ...\n        assert \"some message\" in str(e.value)\n\n\n\n\nDeprecations\n------------\n\n- :issue:`4488`: The removal of the ``--result-log`` option and module has been postponed to (tentatively) pytest 6.0 as\n  the team has not yet got around to implement a good alternative for it.\n\n\n- :issue:`466`: The ``funcargnames`` attribute has been an alias for ``fixturenames`` since\n  pytest 2.3, and is now deprecated in code too.\n\n\n\nFeatures\n--------\n\n- :issue:`3457`: New :hook:`pytest_assertion_pass`\n  hook, called with context information when an assertion *passes*.\n\n  This hook is still **experimental** so use it with caution.\n\n\n- :issue:`5440`: The :mod:`faulthandler` standard library\n  module is now enabled by default to help users diagnose crashes in C modules.\n\n  This functionality was provided by integrating the external\n  `pytest-faulthandler <https://github.com/pytest-dev/pytest-faulthandler>`__ plugin into the core,\n  so users should remove that plugin from their requirements if used.\n\n  For more information see the docs: :ref:`faulthandler`.\n\n\n- :issue:`5452`: When warnings are configured as errors, pytest warnings now appear as originating from ``pytest.`` instead of the internal ``_pytest.warning_types.`` module.\n\n\n- :issue:`5125`: ``Session.exitcode`` values are now coded in ``pytest.ExitCode``, an ``IntEnum``. This makes the exit code available for consumer code and are more explicit other than just documentation. User defined exit codes are still valid, but should be used with caution.\n\n  The team doesn't expect this change to break test suites or plugins in general, except in esoteric/specific scenarios.\n\n  **pytest-xdist** users should upgrade to ``1.29.0`` or later, as ``pytest-xdist`` required a compatibility fix because of this change.\n\n\n\nBug Fixes\n---------\n\n- :issue:`1403`: Switch from ``imp`` to ``importlib``.\n\n\n- :issue:`1671`: The name of the ``.pyc`` files cached by the assertion writer now includes the pytest version\n  to avoid stale caches.\n\n\n- :issue:`2761`: Honor :pep:`235` on case-insensitive file systems.\n\n\n- :issue:`5078`: Test module is no longer double-imported when using ``--pyargs``.\n\n\n- :issue:`5260`: Improved comparison of byte strings.\n\n  When comparing bytes, the assertion message used to show the byte numeric value when showing the differences::\n\n          def test():\n      >       assert b'spam' == b'eggs'\n      E       AssertionError: assert b'spam' == b'eggs'\n      E         At index 0 diff: 115 != 101\n      E         Use -v to get the full diff\n\n  It now shows the actual ascii representation instead, which is often more useful::\n\n          def test():\n      >       assert b'spam' == b'eggs'\n      E       AssertionError: assert b'spam' == b'eggs'\n      E         At index 0 diff: b's' != b'e'\n      E         Use -v to get the full diff\n\n\n- :issue:`5335`: Colorize level names when the level in the logging format is formatted using\n  '%(levelname).Xs' (truncated fixed width alignment), where X is an integer.\n\n\n- :issue:`5354`: Fix ``pytest.mark.parametrize`` when the argvalues is an iterator.\n\n\n- :issue:`5370`: Revert unrolling of ``all()`` to fix ``NameError`` on nested comprehensions.\n\n\n- :issue:`5371`: Revert unrolling of ``all()`` to fix incorrect handling of generators with ``if``.\n\n\n- :issue:`5372`: Revert unrolling of ``all()`` to fix incorrect assertion when using ``all()`` in an expression.\n\n\n- :issue:`5383`: ``-q`` has again an impact on the style of the collected items\n  (``--collect-only``) when ``--log-cli-level`` is used.\n\n\n- :issue:`5389`: Fix regressions of :pr:`5063` for ``importlib_metadata.PathDistribution`` which have their ``files`` attribute being ``None``.\n\n\n- :issue:`5390`: Fix regression where the ``obj`` attribute of ``TestCase`` items was no longer bound to methods.\n\n\n- :issue:`5404`: Emit a warning when attempting to unwrap a broken object raises an exception,\n  for easier debugging (:issue:`5080`).\n\n\n- :issue:`5432`: Prevent \"already imported\" warnings from assertion rewriter when invoking pytest in-process multiple times.\n\n\n- :issue:`5433`: Fix assertion rewriting in packages (``__init__.py``).\n\n\n- :issue:`5444`: Fix ``--stepwise`` mode when the first file passed on the command-line fails to collect.\n\n\n- :issue:`5482`: Fix bug introduced in 4.6.0 causing collection errors when passing\n  more than 2 positional arguments to ``pytest.mark.parametrize``.\n\n\n- :issue:`5505`: Fix crash when discovery fails while using ``-p no:terminal``.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`5315`: Expand docs on mocking classes and dictionaries with ``monkeypatch``.\n\n\n- :issue:`5416`: Fix PytestUnknownMarkWarning in run/skip example.\n\n\npytest 4.6.11 (2020-06-04)\n==========================\n\nBug Fixes\n---------\n\n- :issue:`6334`: Fix summary entries appearing twice when ``f/F`` and ``s/S`` report chars were used at the same time in the ``-r`` command-line option (for example ``-rFf``).\n\n  The upper case variants were never documented and the preferred form should be the lower case.\n\n\n- :issue:`7310`: Fix ``UnboundLocalError: local variable 'letter' referenced before\n  assignment`` in ``_pytest.terminal.pytest_report_teststatus()``\n  when plugins return report objects in an unconventional state.\n\n  This was making ``pytest_report_teststatus()`` skip\n  entering if-block branches that declare the ``letter`` variable.\n\n  The fix was to set the initial value of the ``letter`` before\n  the if-block cascade so that it always has a value.\n\n\npytest 4.6.10 (2020-05-08)\n==========================\n\nFeatures\n--------\n\n- :issue:`6870`: New ``Config.invocation_args`` attribute containing the unchanged arguments passed to ``pytest.main()``.\n\n  Remark: while this is technically a new feature and according to our\n  `policy <https://docs.pytest.org/en/7.0.x/py27-py34-deprecation.html#what-goes-into-4-6-x-releases>`_\n  it should not have been backported, we have opened an exception in this\n  particular case because it fixes a serious interaction with ``pytest-xdist``,\n  so it can also be considered a bugfix.\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`6404`: Remove usage of ``parser`` module, deprecated in Python 3.9.\n\n\npytest 4.6.9 (2020-01-04)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`6301`: Fix assertion rewriting for egg-based distributions and ``editable`` installs (``pip install --editable``).\n\n\npytest 4.6.8 (2019-12-19)\n=========================\n\nFeatures\n--------\n\n- :issue:`5471`: JUnit XML now includes a timestamp and hostname in the testsuite tag.\n\n\n\nBug Fixes\n---------\n\n- :issue:`5430`: junitxml: Logs for failed test are now passed to junit report in case the test fails during call phase.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`6345`: Pin ``colorama`` to ``0.4.1`` only for Python 3.4 so newer Python versions can still receive colorama updates.\n\n\npytest 4.6.7 (2019-12-05)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5477`: The XML file produced by ``--junitxml`` now correctly contain a ``<testsuites>`` root element.\n\n\n- :issue:`6044`: Properly ignore ``FileNotFoundError`` (``OSError.errno == NOENT`` in Python 2) exceptions when trying to remove old temporary directories,\n  for instance when multiple processes try to remove the same directory (common with ``pytest-xdist``\n  for example).\n\n\npytest 4.6.6 (2019-10-11)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5523`: Fixed using multiple short options together in the command-line (for example ``-vs``) in Python 3.8+.\n\n\n- :issue:`5537`: Replace ``importlib_metadata`` backport with ``importlib.metadata`` from the\n  standard library on Python 3.8+.\n\n\n- :issue:`5806`: Fix \"lexer\" being used when uploading to bpaste.net from ``--pastebin`` to \"text\".\n\n\n- :issue:`5902`: Fix warnings about deprecated ``cmp`` attribute in ``attrs>=19.2``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`5801`: Fixes python version checks (detected by ``flake8-2020``) in case python4 becomes a thing.\n\n\npytest 4.6.5 (2019-08-05)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`4344`: Fix RuntimeError/StopIteration when trying to collect package with \"__init__.py\" only.\n\n\n- :issue:`5478`: Fix encode error when using unicode strings in exceptions with ``pytest.raises``.\n\n\n- :issue:`5524`: Fix issue where ``tmp_path`` and ``tmpdir`` would not remove directories containing files marked as read-only,\n  which could lead to pytest crashing when executed a second time with the ``--basetemp`` option.\n\n\n- :issue:`5547`: ``--step-wise`` now handles ``xfail(strict=True)`` markers properly.\n\n\n- :issue:`5650`: Improved output when parsing an ini configuration file fails.\n\npytest 4.6.4 (2019-06-28)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5404`: Emit a warning when attempting to unwrap a broken object raises an exception,\n  for easier debugging (:issue:`5080`).\n\n\n- :issue:`5444`: Fix ``--stepwise`` mode when the first file passed on the command-line fails to collect.\n\n\n- :issue:`5482`: Fix bug introduced in 4.6.0 causing collection errors when passing\n  more than 2 positional arguments to ``pytest.mark.parametrize``.\n\n\n- :issue:`5505`: Fix crash when discovery fails while using ``-p no:terminal``.\n\n\npytest 4.6.3 (2019-06-11)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5383`: ``-q`` has again an impact on the style of the collected items\n  (``--collect-only``) when ``--log-cli-level`` is used.\n\n\n- :issue:`5389`: Fix regressions of :pr:`5063` for ``importlib_metadata.PathDistribution`` which have their ``files`` attribute being ``None``.\n\n\n- :issue:`5390`: Fix regression where the ``obj`` attribute of ``TestCase`` items was no longer bound to methods.\n\n\npytest 4.6.2 (2019-06-03)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5370`: Revert unrolling of ``all()`` to fix ``NameError`` on nested comprehensions.\n\n\n- :issue:`5371`: Revert unrolling of ``all()`` to fix incorrect handling of generators with ``if``.\n\n\n- :issue:`5372`: Revert unrolling of ``all()`` to fix incorrect assertion when using ``all()`` in an expression.\n\n\npytest 4.6.1 (2019-06-02)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5354`: Fix ``pytest.mark.parametrize`` when the argvalues is an iterator.\n\n\n- :issue:`5358`: Fix assertion rewriting of ``all()`` calls to deal with non-generators.\n\n\npytest 4.6.0 (2019-05-31)\n=========================\n\nImportant\n---------\n\nThe ``4.6.X`` series will be the last series to support **Python 2 and Python 3.4**.\n\nFor more details, see our `Python 2.7 and 3.4 support plan\n<https://docs.pytest.org/en/7.0.x/py27-py34-deprecation.html>`_.\n\n\nFeatures\n--------\n\n- :issue:`4559`: Added the ``junit_log_passing_tests`` ini value which can be used to enable or disable logging of passing test output in the Junit XML file.\n\n\n- :issue:`4956`: pytester's ``testdir.spawn`` uses ``tmpdir`` as HOME/USERPROFILE directory.\n\n\n- :issue:`5062`: Unroll calls to ``all`` to full for-loops with assertion rewriting for better failure messages, especially when using Generator Expressions.\n\n\n- :issue:`5063`: Switch from ``pkg_resources`` to ``importlib-metadata`` for entrypoint detection for improved performance and import time.\n\n\n- :issue:`5091`: The output for ini options in ``--help`` has been improved.\n\n\n- :issue:`5269`: ``pytest.importorskip`` includes the ``ImportError`` now in the default ``reason``.\n\n\n- :issue:`5311`: Captured logs that are output for each failing test are formatted using the\n  ColoredLevelFormatter.\n\n\n- :issue:`5312`: Improved formatting of multiline log messages in Python 3.\n\n\n\nBug Fixes\n---------\n\n- :issue:`2064`: The debugging plugin imports the wrapped ``Pdb`` class (``--pdbcls``) on-demand now.\n\n\n- :issue:`4908`: The ``pytest_enter_pdb`` hook gets called with post-mortem (``--pdb``).\n\n\n- :issue:`5036`: Fix issue where fixtures dependent on other parametrized fixtures would be erroneously parametrized.\n\n\n- :issue:`5256`: Handle internal error due to a lone surrogate unicode character not being representable in Jython.\n\n\n- :issue:`5257`: Ensure that ``sys.stdout.mode`` does not include ``'b'`` as it is a text stream.\n\n\n- :issue:`5278`: Pytest's internal python plugin can be disabled using ``-p no:python`` again.\n\n\n- :issue:`5286`: Fix issue with ``disable_test_id_escaping_and_forfeit_all_rights_to_community_support`` option not working when using a list of test IDs in parametrized tests.\n\n\n- :issue:`5330`: Show the test module being collected when emitting ``PytestCollectionWarning`` messages for\n  test classes with ``__init__`` and ``__new__`` methods to make it easier to pin down the problem.\n\n\n- :issue:`5333`: Fix regression in 4.5.0 with ``--lf`` not re-running all tests with known failures from non-selected tests.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`5250`: Expand docs on use of ``setenv`` and ``delenv`` with ``monkeypatch``.\n\n\npytest 4.5.0 (2019-05-11)\n=========================\n\nFeatures\n--------\n\n- :issue:`4826`: A warning is now emitted when unknown marks are used as a decorator.\n  This is often due to a typo, which can lead to silently broken tests.\n\n\n- :issue:`4907`: Show XFail reason as part of JUnitXML message field.\n\n\n- :issue:`5013`: Messages from crash reports are displayed within test summaries now, truncated to the terminal width.\n\n\n- :issue:`5023`: New flag ``--strict-markers`` that triggers an error when unknown markers (e.g. those not registered using the :confval:`markers` option in the configuration file) are used in the test suite.\n\n  The existing ``--strict`` option has the same behavior currently, but can be augmented in the future for additional checks.\n\n\n- :issue:`5026`: Assertion failure messages for sequences and dicts contain the number of different items now.\n\n\n- :issue:`5034`: Improve reporting with ``--lf`` and ``--ff`` (run-last-failure).\n\n\n- :issue:`5035`: The ``--cache-show`` option/action accepts an optional glob to show only matching cache entries.\n\n\n- :issue:`5059`: Standard input (stdin) can be given to pytester's ``Testdir.run()`` and ``Testdir.popen()``.\n\n\n- :issue:`5068`: The ``-r`` option learnt about ``A`` to display all reports (including passed ones) in the short test summary.\n\n\n- :issue:`5108`: The short test summary is displayed after passes with output (``-rP``).\n\n\n- :issue:`5172`: The ``--last-failed`` (``--lf``) option got smarter and will now skip entire files if all tests\n  of that test file have passed in previous runs, greatly speeding up collection.\n\n\n- :issue:`5177`: Introduce new specific warning ``PytestWarning`` subclasses to make it easier to filter warnings based on the class, rather than on the message. The new subclasses are:\n\n\n  * ``PytestAssertRewriteWarning``\n\n  * ``PytestCacheWarning``\n\n  * ``PytestCollectionWarning``\n\n  * ``PytestConfigWarning``\n\n  * ``PytestUnhandledCoroutineWarning``\n\n  * ``PytestUnknownMarkWarning``\n\n\n- :issue:`5202`: New ``record_testsuite_property`` session-scoped fixture allows users to log ``<property>`` tags at the ``testsuite``\n  level with the ``junitxml`` plugin.\n\n  The generated XML is compatible with the latest xunit standard, contrary to\n  the properties recorded by ``record_property`` and ``record_xml_attribute``.\n\n\n- :issue:`5214`: The default logging format has been changed to improve readability. Here is an\n  example of a previous logging message::\n\n      test_log_cli_enabled_disabled.py    3 CRITICAL critical message logged by test\n\n  This has now become::\n\n      CRITICAL root:test_log_cli_enabled_disabled.py:3 critical message logged by test\n\n  The formatting can be changed through the :confval:`log_format` configuration option.\n\n\n- :issue:`5220`: ``--fixtures`` now also shows fixture scope for scopes other than ``\"function\"``.\n\n\n\nBug Fixes\n---------\n\n- :issue:`5113`: Deselected items from plugins using ``pytest_collect_modifyitems`` as a hookwrapper are correctly reported now.\n\n\n- :issue:`5144`: With usage errors ``exitstatus`` is set to ``EXIT_USAGEERROR`` in the ``pytest_sessionfinish`` hook now as expected.\n\n\n- :issue:`5235`: ``outcome.exit`` is not used with ``EOF`` in the pdb wrapper anymore, but only with ``quit``.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`4935`: Expand docs on registering marks and the effect of ``--strict``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4942`: ``logging.raiseExceptions`` is not set to ``False`` anymore.\n\n\n- :issue:`5013`: pytest now depends on :pypi:`wcwidth` to properly track unicode character sizes for more precise terminal output.\n\n\n- :issue:`5059`: pytester's ``Testdir.popen()`` uses ``stdout`` and ``stderr`` via keyword arguments with defaults now (``subprocess.PIPE``).\n\n\n- :issue:`5069`: The code for the short test summary in the terminal was moved to the terminal plugin.\n\n\n- :issue:`5082`: Improved validation of kwargs for various methods in the pytester plugin.\n\n\n- :issue:`5202`: ``record_property`` now emits a ``PytestWarning`` when used with ``junit_family=xunit2``: the fixture generates\n  ``property`` tags as children of ``testcase``, which is not permitted according to the most\n  `recent schema <https://github.com/jenkinsci/xunit-plugin/blob/master/\n  src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd>`__.\n\n\n- :issue:`5239`: Pin ``pluggy`` to ``< 1.0`` so we don't update to ``1.0`` automatically when\n  it gets released: there are planned breaking changes, and we want to ensure\n  pytest properly supports ``pluggy 1.0``.\n\n\npytest 4.4.2 (2019-05-08)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5089`: Fix crash caused by error in ``__repr__`` function with both ``showlocals`` and verbose output enabled.\n\n\n- :issue:`5139`: Eliminate core dependency on 'terminal' plugin.\n\n\n- :issue:`5229`: Require ``pluggy>=0.11.0`` which reverts a dependency to ``importlib-metadata`` added in ``0.10.0``.\n  The ``importlib-metadata`` package cannot be imported when installed as an egg and causes issues when relying on ``setup.py`` to install test dependencies.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`5171`: Doc: ``pytest_ignore_collect``, ``pytest_collect_directory``, ``pytest_collect_file`` and ``pytest_pycollect_makemodule`` hooks's 'path' parameter documented type is now ``py.path.local``\n\n\n- :issue:`5188`: Improve help for ``--runxfail`` flag.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`5182`: Removed internal and unused ``_pytest.deprecated.MARK_INFO_ATTRIBUTE``.\n\n\npytest 4.4.1 (2019-04-15)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`5031`: Environment variables are properly restored when using pytester's ``testdir`` fixture.\n\n\n- :issue:`5039`: Fix regression with ``--pdbcls``, which stopped working with local modules in 4.0.0.\n\n\n- :issue:`5092`: Produce a warning when unknown keywords are passed to ``pytest.param(...)``.\n\n\n- :issue:`5098`: Invalidate import caches with ``monkeypatch.syspath_prepend``, which is required with namespace packages being used.\n\n\npytest 4.4.0 (2019-03-29)\n=========================\n\nFeatures\n--------\n\n- :issue:`2224`: ``async`` test functions are skipped and a warning is emitted when a suitable\n  async plugin is not installed (such as ``pytest-asyncio`` or ``pytest-trio``).\n\n  Previously ``async`` functions would not execute at all but still be marked as \"passed\".\n\n\n- :issue:`2482`: Include new ``disable_test_id_escaping_and_forfeit_all_rights_to_community_support`` option to disable ascii-escaping in parametrized values. This may cause a series of problems and as the name makes clear, use at your own risk.\n\n\n- :issue:`4718`: The ``-p`` option can now be used to early-load plugins also by entry-point name, instead of just\n  by module name.\n\n  This makes it possible to early load external plugins like ``pytest-cov`` in the command-line::\n\n      pytest -p pytest_cov\n\n\n- :issue:`4855`: The ``--pdbcls`` option handles classes via module attributes now (e.g.\n  ``pdb:pdb.Pdb`` with :pypi:`pdbpp`), and its validation was improved.\n\n\n- :issue:`4875`: The :confval:`testpaths` configuration option is now displayed next\n  to the ``rootdir`` and ``inifile`` lines in the pytest header if the option is in effect, i.e., directories or file names were\n  not explicitly passed in the command line.\n\n  Also, ``inifile`` is only displayed if there's a configuration file, instead of an empty ``inifile:`` string.\n\n\n- :issue:`4911`: Doctests can be skipped now dynamically using ``pytest.skip()``.\n\n\n- :issue:`4920`: Internal refactorings have been made in order to make the implementation of the\n  `pytest-subtests <https://github.com/pytest-dev/pytest-subtests>`__ plugin\n  possible, which adds unittest sub-test support and a new ``subtests`` fixture as discussed in\n  :issue:`1367`.\n\n  For details on the internal refactorings, please see the details on the related PR.\n\n\n- :issue:`4931`: pytester's ``LineMatcher`` asserts that the passed lines are a sequence.\n\n\n- :issue:`4936`: Handle ``-p plug`` after ``-p no:plug``.\n\n  This can be used to override a blocked plugin (e.g. in \"addopts\") from the\n  command line etc.\n\n\n- :issue:`4951`: Output capturing is handled correctly when only capturing via fixtures (capsys, capfs) with ``pdb.set_trace()``.\n\n\n- :issue:`4956`: ``pytester`` sets ``$HOME`` and ``$USERPROFILE`` to the temporary directory during test runs.\n\n  This ensures to not load configuration files from the real user's home directory.\n\n\n- :issue:`4980`: Namespace packages are handled better with ``monkeypatch.syspath_prepend`` and ``testdir.syspathinsert`` (via ``pkg_resources.fixup_namespace_packages``).\n\n\n- :issue:`4993`: The stepwise plugin reports status information now.\n\n\n- :issue:`5008`: If a ``setup.cfg`` file contains ``[tool:pytest]`` and also the no longer supported ``[pytest]`` section, pytest will use ``[tool:pytest]`` ignoring ``[pytest]``. Previously it would unconditionally error out.\n\n  This makes it simpler for plugins to support old pytest versions.\n\n\n\nBug Fixes\n---------\n\n- :issue:`1895`: Fix bug where fixtures requested dynamically via ``request.getfixturevalue()`` might be teardown\n  before the requesting fixture.\n\n\n- :issue:`4851`: pytester unsets ``PYTEST_ADDOPTS`` now to not use outer options with ``testdir.runpytest()``.\n\n\n- :issue:`4903`: Use the correct modified time for years after 2038 in rewritten ``.pyc`` files.\n\n\n- :issue:`4928`: Fix line offsets with ``ScopeMismatch`` errors.\n\n\n- :issue:`4957`: ``-p no:plugin`` is handled correctly for default (internal) plugins now, e.g. with ``-p no:capture``.\n\n  Previously they were loaded (imported) always, making e.g. the ``capfd`` fixture available.\n\n\n- :issue:`4968`: The pdb ``quit`` command is handled properly when used after the ``debug`` command with :pypi:`pdbpp`.\n\n\n- :issue:`4975`: Fix the interpretation of ``-qq`` option where it was being considered as ``-v`` instead.\n\n\n- :issue:`4978`: ``outcomes.Exit`` is not swallowed in ``assertrepr_compare`` anymore.\n\n\n- :issue:`4988`: Close logging's file handler explicitly when the session finishes.\n\n\n- :issue:`5003`: Fix line offset with mark collection error (off by one).\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`4974`: Update docs for ``pytest_cmdline_parse`` hook to note availability limitations\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4718`: ``pluggy>=0.9`` is now required.\n\n\n- :issue:`4815`: ``funcsigs>=1.0`` is now required for Python 2.7.\n\n\n- :issue:`4829`: Some left-over internal code related to ``yield`` tests has been removed.\n\n\n- :issue:`4890`: Remove internally unused ``anypython`` fixture from the pytester plugin.\n\n\n- :issue:`4912`: Remove deprecated Sphinx directive, ``add_description_unit()``,\n  pin sphinx-removed-in to >= 0.2.0 to support Sphinx 2.0.\n\n\n- :issue:`4913`: Fix pytest tests invocation with custom ``PYTHONPATH``.\n\n\n- :issue:`4965`: New ``pytest_report_to_serializable`` and ``pytest_report_from_serializable`` **experimental** hooks.\n\n  These hooks will be used by ``pytest-xdist``, ``pytest-subtests``, and the replacement for\n  resultlog to serialize and customize reports.\n\n  They are experimental, meaning that their details might change or even be removed\n  completely in future patch releases without warning.\n\n  Feedback is welcome from plugin authors and users alike.\n\n\n- :issue:`4987`: ``Collector.repr_failure`` respects the ``--tb`` option, but only defaults to ``short`` now (with ``auto``).\n\n\npytest 4.3.1 (2019-03-11)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`4810`: Logging messages inside ``pytest_runtest_logreport()`` are now properly captured and displayed.\n\n\n- :issue:`4861`: Improve validation of contents written to captured output so it behaves the same as when capture is disabled.\n\n\n- :issue:`4898`: Fix ``AttributeError: FixtureRequest has no 'confg' attribute`` bug in ``testdir.copy_example``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4768`: Avoid pkg_resources import at the top-level.\n\n\npytest 4.3.0 (2019-02-16)\n=========================\n\nDeprecations\n------------\n\n- :issue:`4724`: ``pytest.warns()`` now emits a warning when it receives unknown keyword arguments.\n\n  This will be changed into an error in the future.\n\n\n\nFeatures\n--------\n\n- :issue:`2753`: Usage errors from argparse are mapped to pytest's ``UsageError``.\n\n\n- :issue:`3711`: Add the ``--ignore-glob`` parameter to exclude test-modules with Unix shell-style wildcards.\n  Add the :globalvar:`collect_ignore_glob` for ``conftest.py`` to exclude test-modules with Unix shell-style wildcards.\n\n\n- :issue:`4698`: The warning about Python 2.7 and 3.4 not being supported in pytest 5.0 has been removed.\n\n  In the end it was considered to be more\n  of a nuisance than actual utility and users of those Python versions shouldn't have problems as ``pip`` will not\n  install pytest 5.0 on those interpreters.\n\n\n- :issue:`4707`: With the help of new ``set_log_path()`` method there is a way to set ``log_file`` paths from hooks.\n\n\n\nBug Fixes\n---------\n\n- :issue:`4651`: ``--help`` and ``--version`` are handled with ``UsageError``.\n\n\n- :issue:`4782`: Fix ``AssertionError`` with collection of broken symlinks with packages.\n\n\npytest 4.2.1 (2019-02-12)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`2895`: The ``pytest_report_collectionfinish`` hook now is also called with ``--collect-only``.\n\n\n- :issue:`3899`: Do not raise ``UsageError`` when an imported package has a ``pytest_plugins.py`` child module.\n\n\n- :issue:`4347`: Fix output capturing when using pdb++ with recursive debugging.\n\n\n- :issue:`4592`: Fix handling of ``collect_ignore`` via parent ``conftest.py``.\n\n\n- :issue:`4700`: Fix regression where ``setUpClass`` would always be called in subclasses even if all tests\n  were skipped by a ``unittest.skip()`` decorator applied in the subclass.\n\n\n- :issue:`4739`: Fix ``parametrize(... ids=<function>)`` when the function returns non-strings.\n\n\n- :issue:`4745`: Fix/improve collection of args when passing in ``__init__.py`` and a test file.\n\n\n- :issue:`4770`: ``more_itertools`` is now constrained to <6.0.0 when required for Python 2.7 compatibility.\n\n\n- :issue:`526`: Fix \"ValueError: Plugin already registered\" exceptions when running in build directories that symlink to actual source.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3899`: Add note to ``plugins.rst`` that ``pytest_plugins`` should not be used as a name for a user module containing plugins.\n\n\n- :issue:`4324`: Document how to use ``raises`` and ``does_not_raise`` to write parametrized tests with conditional raises.\n\n\n- :issue:`4709`: Document how to customize test failure messages when using\n  ``pytest.warns``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4741`: Some verbosity related attributes of the TerminalReporter plugin are now\n  read only properties.\n\n\npytest 4.2.0 (2019-01-30)\n=========================\n\nFeatures\n--------\n\n- :issue:`3094`: :doc:`Classic xunit-style <how-to/xunit_setup>` functions and methods\n  now obey the scope of *autouse* fixtures.\n\n  This fixes a number of surprising issues like ``setup_method`` being called before session-scoped\n  autouse fixtures (see :issue:`517` for an example).\n\n\n- :issue:`4627`: Display a message at the end of the test session when running under Python 2.7 and 3.4 that pytest 5.0 will no longer\n  support those Python versions.\n\n\n- :issue:`4660`: The number of *selected* tests now are also displayed when the ``-k`` or ``-m`` flags are used.\n\n\n- :issue:`4688`: ``pytest_report_teststatus`` hook now can also receive a ``config`` parameter.\n\n\n- :issue:`4691`: ``pytest_terminal_summary`` hook now can also receive a ``config`` parameter.\n\n\n\nBug Fixes\n---------\n\n- :issue:`3547`: ``--junitxml`` can emit XML compatible with Jenkins xUnit.\n  ``junit_family`` INI option accepts ``legacy|xunit1``, which produces old style output, and ``xunit2`` that conforms more strictly to https://github.com/jenkinsci/xunit-plugin/blob/xunit-2.3.2/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd\n\n\n- :issue:`4280`: Improve quitting from pdb, especially with ``--trace``.\n\n  Using ``q[quit]`` after ``pdb.set_trace()`` will quit pytest also.\n\n\n- :issue:`4402`: Warning summary now groups warnings by message instead of by test id.\n\n  This makes the output more compact and better conveys the general idea of how much code is\n  actually generating warnings, instead of how many tests call that code.\n\n\n- :issue:`4536`: ``monkeypatch.delattr`` handles class descriptors like ``staticmethod``/``classmethod``.\n\n\n- :issue:`4649`: Restore marks being considered keywords for keyword expressions.\n\n\n- :issue:`4653`: ``tmp_path`` fixture and other related ones provides resolved path (a.k.a real path)\n\n\n- :issue:`4667`: ``pytest_terminal_summary`` uses result from ``pytest_report_teststatus`` hook, rather than hardcoded strings.\n\n\n- :issue:`4669`: Correctly handle ``unittest.SkipTest`` exception containing non-ascii characters on Python 2.\n\n\n- :issue:`4680`: Ensure the ``tmpdir`` and the ``tmp_path`` fixtures are the same folder.\n\n\n- :issue:`4681`: Ensure ``tmp_path`` is always a real path.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4643`: Use ``a.item()`` instead of the deprecated ``np.asscalar(a)`` in ``pytest.approx``.\n\n  ``np.asscalar`` has been :doc:`deprecated <numpy:release/1.16.0-notes>` in ``numpy 1.16.``.\n\n\n- :issue:`4657`: Copy saferepr from pylib\n\n\n- :issue:`4668`: The verbose word for expected failures in the teststatus report changes from ``xfail`` to ``XFAIL`` to be consistent with other test outcomes.\n\n\npytest 4.1.1 (2019-01-12)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`2256`: Show full repr with ``assert a==b`` and ``-vv``.\n\n\n- :issue:`3456`: Extend Doctest-modules to ignore mock objects.\n\n\n- :issue:`4617`: Fixed ``pytest.warns`` bug when context manager is reused (e.g. multiple parametrization).\n\n\n- :issue:`4631`: Don't rewrite assertion when ``__getattr__`` is broken\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3375`: Document that using ``setup.cfg`` may crash other tools or cause hard to track down problems because it uses a different parser than ``pytest.ini`` or ``tox.ini`` files.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4602`: Uninstall ``hypothesis`` in regen tox env.\n\n\npytest 4.1.0 (2019-01-05)\n=========================\n\nRemovals\n--------\n\n- :issue:`2169`: ``pytest.mark.parametrize``: in previous versions, errors raised by id functions were suppressed and changed into warnings. Now the exceptions are propagated, along with a pytest message informing the node, parameter value and index where the exception occurred.\n\n\n- :issue:`3078`: Remove legacy internal warnings system: ``config.warn``, ``Node.warn``. The ``pytest_logwarning`` now issues a warning when implemented.\n\n  See our :ref:`docs <config.warn and node.warn deprecated>` on information on how to update your code.\n\n\n- :issue:`3079`: Removed support for yield tests - they are fundamentally broken because they don't support fixtures properly since collection and test execution were separated.\n\n  See our :ref:`docs <yield tests deprecated>` on information on how to update your code.\n\n\n- :issue:`3082`: Removed support for applying marks directly to values in ``@pytest.mark.parametrize``. Use ``pytest.param`` instead.\n\n  See our :ref:`docs <marks in pytest.parametrize deprecated>` on information on how to update your code.\n\n\n- :issue:`3083`: Removed ``Metafunc.addcall``. This was the predecessor mechanism to ``@pytest.mark.parametrize``.\n\n  See our :ref:`docs <metafunc.addcall deprecated>` on information on how to update your code.\n\n\n- :issue:`3085`: Removed support for passing strings to ``pytest.main``. Now, always pass a list of strings instead.\n\n  See our :ref:`docs <passing command-line string to pytest.main deprecated>` on information on how to update your code.\n\n\n- :issue:`3086`: ``[pytest]`` section in **setup.cfg** files is no longer supported, use ``[tool:pytest]`` instead. ``setup.cfg`` files\n  are meant for use with ``distutils``, and a section named ``pytest`` has notoriously been a source of conflicts and bugs.\n\n  Note that for **pytest.ini** and **tox.ini** files the section remains ``[pytest]``.\n\n\n- :issue:`3616`: Removed the deprecated compat properties for ``node.Class/Function/Module`` - use ``pytest.Class/Function/Module`` now.\n\n  See our :ref:`docs <internal classes accessed through node deprecated>` on information on how to update your code.\n\n\n- :issue:`4421`: Removed the implementation of the ``pytest_namespace`` hook.\n\n  See our :ref:`docs <pytest.namespace deprecated>` on information on how to update your code.\n\n\n- :issue:`4489`: Removed ``request.cached_setup``. This was the predecessor mechanism to modern fixtures.\n\n  See our :ref:`docs <cached_setup deprecated>` on information on how to update your code.\n\n\n- :issue:`4535`: Removed the deprecated ``PyCollector.makeitem`` method. This method was made public by mistake a long time ago.\n\n\n- :issue:`4543`: Removed support to define fixtures using the ``pytest_funcarg__`` prefix. Use the ``@pytest.fixture`` decorator instead.\n\n  See our :ref:`docs <pytest_funcarg__ prefix deprecated>` on information on how to update your code.\n\n\n- :issue:`4545`: Calling fixtures directly is now always an error instead of a warning.\n\n  See our :ref:`docs <calling fixtures directly deprecated>` on information on how to update your code.\n\n\n- :issue:`4546`: Remove ``Node.get_marker(name)`` the return value was not usable for more than an existence check.\n\n  Use ``Node.get_closest_marker(name)`` as a replacement.\n\n\n- :issue:`4547`: The deprecated ``record_xml_property`` fixture has been removed, use the more generic ``record_property`` instead.\n\n  See our :ref:`docs <record_xml_property deprecated>` for more information.\n\n\n- :issue:`4548`: An error is now raised if the ``pytest_plugins`` variable is defined in a non-top-level ``conftest.py`` file (i.e., not residing in the ``rootdir``).\n\n  See our :ref:`docs <pytest_plugins in non-top-level conftest files deprecated>` for more information.\n\n\n- :issue:`891`: Remove ``testfunction.markername`` attributes - use ``Node.iter_markers(name=None)`` to iterate them.\n\n\n\nDeprecations\n------------\n\n- :issue:`3050`: Deprecated the ``pytest.config`` global.\n\n  See :ref:`pytest.config global deprecated` for rationale.\n\n\n- :issue:`3974`: Passing the ``message`` parameter of ``pytest.raises`` now issues a ``DeprecationWarning``.\n\n  It is a common mistake to think this parameter will match the exception message, while in fact\n  it only serves to provide a custom message in case the ``pytest.raises`` check fails. To avoid this\n  mistake and because it is believed to be little used, pytest is deprecating it without providing\n  an alternative for the moment.\n\n  If you have concerns about this, please comment on :issue:`3974`.\n\n\n- :issue:`4435`: Deprecated ``raises(..., 'code(as_a_string)')`` and ``warns(..., 'code(as_a_string)')``.\n\n  See :std:ref:`raises-warns-exec` for rationale and examples.\n\n\n\nFeatures\n--------\n\n- :issue:`3191`: A warning is now issued when assertions are made for ``None``.\n\n  This is a common source of confusion among new users, which write:\n\n  .. code-block:: python\n\n      assert mocked_object.assert_called_with(3, 4, 5, key=\"value\")\n\n  When they should write:\n\n  .. code-block:: python\n\n      mocked_object.assert_called_with(3, 4, 5, key=\"value\")\n\n  Because the ``assert_called_with`` method of mock objects already executes an assertion.\n\n  This warning will not be issued when ``None`` is explicitly checked. An assertion like:\n\n  .. code-block:: python\n\n      assert variable is None\n\n  will not issue the warning.\n\n\n- :issue:`3632`: Richer equality comparison introspection on ``AssertionError`` for objects created using `attrs <https://www.attrs.org/en/stable/>`__ or :mod:`dataclasses` (Python 3.7+, :pypi:`backported to 3.6 <dataclasses>`).\n\n\n- :issue:`4278`: ``CACHEDIR.TAG`` files are now created inside cache directories.\n\n  Those files are part of the `Cache Directory Tagging Standard <https://bford.info/cachedir/spec.html>`__, and can\n  be used by backup or synchronization programs to identify pytest's cache directory as such.\n\n\n- :issue:`4292`: ``pytest.outcomes.Exit`` is derived from ``SystemExit`` instead of ``KeyboardInterrupt``. This allows us to better handle ``pdb`` exiting.\n\n\n- :issue:`4371`: Updated the ``--collect-only`` option to display test descriptions when ran using ``--verbose``.\n\n\n- :issue:`4386`: Restructured ``ExceptionInfo`` object construction and ensure incomplete instances have a ``repr``/``str``.\n\n\n- :issue:`4416`: pdb: added support for keyword arguments with ``pdb.set_trace``.\n\n  It handles ``header`` similar to Python 3.7 does it, and forwards any\n  other keyword arguments to the ``Pdb`` constructor.\n\n  This allows for ``__import__(\"pdb\").set_trace(skip=[\"foo.*\"])``.\n\n\n- :issue:`4483`: Added ini parameter ``junit_duration_report`` to optionally report test call durations, excluding setup and teardown times.\n\n  The JUnit XML specification and the default pytest behavior is to include setup and teardown times in the test duration\n  report. You can include just the call durations instead (excluding setup and teardown) by adding this to your ``pytest.ini`` file:\n\n  .. code-block:: ini\n\n      [pytest]\n      junit_duration_report = call\n\n\n- :issue:`4532`: ``-ra`` now will show errors and failures last, instead of as the first items in the summary.\n\n  This makes it easier to obtain a list of errors and failures to run tests selectively.\n\n\n- :issue:`4599`: ``pytest.importorskip`` now supports a ``reason`` parameter, which will be shown when the\n  requested module cannot be imported.\n\n\n\nBug Fixes\n---------\n\n- :issue:`3532`: ``-p`` now accepts its argument without a space between the value, for example ``-pmyplugin``.\n\n\n- :issue:`4327`: ``approx`` again works with more generic containers, more precisely instances of ``Iterable`` and ``Sized`` instead of more restrictive ``Sequence``.\n\n\n- :issue:`4397`: Ensure that node ids are printable.\n\n\n- :issue:`4435`: Fixed ``raises(..., 'code(string)')`` frame filename.\n\n\n- :issue:`4458`: Display actual test ids in ``--collect-only``.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`4557`: Markers example documentation page updated to support latest pytest version.\n\n\n- :issue:`4558`: Update cache documentation example to correctly show cache hit and miss.\n\n\n- :issue:`4580`: Improved detailed summary report documentation.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4447`: Changed the deprecation type of ``--result-log`` to ``PytestDeprecationWarning``.\n\n  It was decided to remove this feature at the next major revision.\n\n\npytest 4.0.2 (2018-12-13)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`4265`: Validate arguments from the ``PYTEST_ADDOPTS`` environment variable and the ``addopts`` ini option separately.\n\n\n- :issue:`4435`: Fix ``raises(..., 'code(string)')`` frame filename.\n\n\n- :issue:`4500`: When a fixture yields and a log call is made after the test runs, and, if the test is interrupted, capture attributes are ``None``.\n\n\n- :issue:`4538`: Raise ``TypeError`` for ``with raises(..., match=<non-None falsey value>)``.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`1495`: Document common doctest fixture directory tree structure pitfalls\n\n\npytest 4.0.1 (2018-11-23)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`3952`: Display warnings before \"short test summary info\" again, but still later warnings in the end.\n\n\n- :issue:`4386`: Handle uninitialized exceptioninfo in repr/str.\n\n\n- :issue:`4393`: Do not create ``.gitignore``/``README.md`` files in existing cache directories.\n\n\n- :issue:`4400`: Rearrange warning handling for the yield test errors so the opt-out in 4.0.x correctly works.\n\n\n- :issue:`4405`: Fix collection of testpaths with ``--pyargs``.\n\n\n- :issue:`4412`: Fix assertion rewriting involving ``Starred`` + side-effects.\n\n\n- :issue:`4425`: Ensure we resolve the absolute path when the given ``--basetemp`` is a relative path.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4315`: Use ``pkg_resources.parse_version`` instead of ``LooseVersion`` in minversion check.\n\n\n- :issue:`4440`: Adjust the stack level of some internal pytest warnings.\n\n\npytest 4.0.0 (2018-11-13)\n=========================\n\nRemovals\n--------\n\n- :issue:`3737`: **RemovedInPytest4Warnings are now errors by default.**\n\n  Following our plan to remove deprecated features with as little disruption as\n  possible, all warnings of type ``RemovedInPytest4Warnings`` now generate errors\n  instead of warning messages.\n\n  **The affected features will be effectively removed in pytest 4.1**, so please consult the\n  :std:doc:`deprecations` section in the docs for directions on how to update existing code.\n\n  In the pytest ``4.0.X`` series, it is possible to change the errors back into warnings as a stop\n  gap measure by adding this to your ``pytest.ini`` file:\n\n  .. code-block:: ini\n\n      [pytest]\n      filterwarnings =\n          ignore::pytest.RemovedInPytest4Warning\n\n  But this will stop working when pytest ``4.1`` is released.\n\n  **If you have concerns** about the removal of a specific feature, please add a\n  comment to :issue:`4348`.\n\n\n- :issue:`4358`: Remove the ``::()`` notation to denote a test class instance in node ids.\n\n  Previously, node ids that contain test instances would use ``::()`` to denote the instance like this::\n\n      test_foo.py::Test::()::test_bar\n\n  The extra ``::()`` was puzzling to most users and has been removed, so that the test id becomes now::\n\n      test_foo.py::Test::test_bar\n\n  This change could not accompany a deprecation period as is usual when user-facing functionality changes because\n  it was not really possible to detect when the functionality was being used explicitly.\n\n  The extra ``::()`` might have been removed in some places internally already,\n  which then led to confusion in places where it was expected, e.g. with\n  ``--deselect`` (:issue:`4127`).\n\n  Test class instances are also not listed with ``--collect-only`` anymore.\n\n\n\nFeatures\n--------\n\n- :issue:`4270`: The ``cache_dir`` option uses ``$TOX_ENV_DIR`` as prefix (if set in the environment).\n\n  This uses a different cache per tox environment by default.\n\n\n\nBug Fixes\n---------\n\n- :issue:`3554`: Fix ``CallInfo.__repr__`` for when the call is not finished yet.\n\n\npytest 3.10.1 (2018-11-11)\n==========================\n\nBug Fixes\n---------\n\n- :issue:`4287`: Fix nested usage of debugging plugin (pdb), e.g. with pytester's ``testdir.runpytest``.\n\n\n- :issue:`4304`: Block the ``stepwise`` plugin if ``cacheprovider`` is also blocked, as one depends on the other.\n\n\n- :issue:`4306`: Parse ``minversion`` as an actual version and not as dot-separated strings.\n\n\n- :issue:`4310`: Fix duplicate collection due to multiple args matching the same packages.\n\n\n- :issue:`4321`: Fix ``item.nodeid`` with resolved symlinks.\n\n\n- :issue:`4325`: Fix collection of direct symlinked files, where the target does not match ``python_files``.\n\n\n- :issue:`4329`: Fix TypeError in report_collect with _collect_report_last_write.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4305`: Replace byte/unicode helpers in test_capture with python level syntax.\n\n\npytest 3.10.0 (2018-11-03)\n==========================\n\nFeatures\n--------\n\n- :issue:`2619`: Resume capturing output after ``continue`` with ``__import__(\"pdb\").set_trace()``.\n\n  This also adds a new ``pytest_leave_pdb`` hook, and passes in ``pdb`` to the\n  existing ``pytest_enter_pdb`` hook.\n\n\n- :issue:`4147`: Add ``--sw``, ``--stepwise`` as an alternative to ``--lf -x`` for stopping at the first failure, but starting the next test invocation from that test.  See :ref:`the documentation <cache stepwise>` for more info.\n\n\n- :issue:`4188`: Make ``--color`` emit colorful dots when not running in verbose mode. Earlier, it would only colorize the test-by-test output if ``--verbose`` was also passed.\n\n\n- :issue:`4225`: Improve performance with collection reporting in non-quiet mode with terminals.\n\n  The \"collecting …\" message is only printed/updated every 0.5s.\n\n\n\nBug Fixes\n---------\n\n- :issue:`2701`: Fix false ``RemovedInPytest4Warning: usage of Session... is deprecated, please use pytest`` warnings.\n\n\n- :issue:`4046`: Fix problems with running tests in package ``__init__.py`` files.\n\n\n- :issue:`4260`: Swallow warnings during anonymous compilation of source.\n\n\n- :issue:`4262`: Fix access denied error when deleting stale directories created by ``tmpdir`` / ``tmp_path``.\n\n\n- :issue:`611`: Naming a fixture ``request`` will now raise a warning: the ``request`` fixture is internal and\n  should not be overwritten as it will lead to internal errors.\n\n- :issue:`4266`: Handle (ignore) exceptions raised during collection, e.g. with Django's LazySettings proxy class.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`4255`: Added missing documentation about the fact that module names passed to filter warnings are not regex-escaped.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4272`: Display cachedir also in non-verbose mode if non-default.\n\n\n- :issue:`4277`: pdb: improve message about output capturing with ``set_trace``.\n\n  Do not display \"IO-capturing turned off/on\" when ``-s`` is used to avoid\n  confusion.\n\n\n- :issue:`4279`: Improve message and stack level of warnings issued by ``monkeypatch.setenv`` when the value of the environment variable is not a ``str``.\n\n\npytest 3.9.3 (2018-10-27)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`4174`: Fix \"ValueError: Plugin already registered\" with conftest plugins via symlink.\n\n\n- :issue:`4181`: Handle race condition between creation and deletion of temporary folders.\n\n\n- :issue:`4221`: Fix bug where the warning summary at the end of the test session was not showing the test where the warning was originated.\n\n\n- :issue:`4243`: Fix regression when ``stacklevel`` for warnings was passed as positional argument on python2.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3851`: Add reference to ``empty_parameter_set_mark`` ini option in documentation of ``@pytest.mark.parametrize``\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`4028`: Revert patching of ``sys.breakpointhook`` since it appears to do nothing.\n\n\n- :issue:`4233`: Apply an import sorter (``reorder-python-imports``) to the codebase.\n\n\n- :issue:`4248`: Remove use of unnecessary compat shim, six.binary_type\n\n\npytest 3.9.2 (2018-10-22)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`2909`: Improve error message when a recursive dependency between fixtures is detected.\n\n\n- :issue:`3340`: Fix logging messages not shown in hooks ``pytest_sessionstart()`` and ``pytest_sessionfinish()``.\n\n\n- :issue:`3533`: Fix unescaped XML raw objects in JUnit report for skipped tests\n\n\n- :issue:`3691`: Python 2: safely format warning message about passing unicode strings to ``warnings.warn``, which may cause\n  surprising ``MemoryError`` exception when monkey patching ``warnings.warn`` itself.\n\n\n- :issue:`4026`: Improve error message when it is not possible to determine a function's signature.\n\n\n- :issue:`4177`: Pin ``setuptools>=40.0`` to support ``py_modules`` in ``setup.cfg``\n\n\n- :issue:`4179`: Restore the tmpdir behaviour of symlinking the current test run.\n\n\n- :issue:`4192`: Fix filename reported by ``warnings.warn`` when using ``recwarn`` under python2.\n\n\npytest 3.9.1 (2018-10-16)\n=========================\n\nFeatures\n--------\n\n- :issue:`4159`: For test-suites containing test classes, the information about the subclassed\n  module is now output only if a higher verbosity level is specified (at least\n  \"-vv\").\n\n\npytest 3.9.0 (2018-10-15 - not published due to a release automation bug)\n=========================================================================\n\nDeprecations\n------------\n\n- :issue:`3616`: The following accesses have been documented as deprecated for years, but are now actually emitting deprecation warnings.\n\n  * Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances. Now\n    users will this warning::\n\n          usage of Function.Module is deprecated, please use pytest.Module instead\n\n    Users should just ``import pytest`` and access those objects using the ``pytest`` module.\n\n  * ``request.cached_setup``, this was the precursor of the setup/teardown mechanism available to fixtures. You can\n    consult :std:doc:`funcarg comparison section in the docs <funcarg_compare>`.\n\n  * Using objects named ``\"Class\"`` as a way to customize the type of nodes that are collected in ``Collector``\n    subclasses has been deprecated. Users instead should use ``pytest_collect_make_item`` to customize node types during\n    collection.\n\n    This issue should affect only advanced plugins who create new collection types, so if you see this warning\n    message please contact the authors so they can change the code.\n\n  * The warning that produces the message below has changed to ``RemovedInPytest4Warning``::\n\n          getfuncargvalue is deprecated, use getfixturevalue\n\n\n- :issue:`3988`: Add a Deprecation warning for pytest.ensuretemp as it was deprecated since a while.\n\n\n\nFeatures\n--------\n\n- :issue:`2293`: Improve usage errors messages by hiding internal details which can be distracting and noisy.\n\n  This has the side effect that some error conditions that previously raised generic errors (such as\n  ``ValueError`` for unregistered marks) are now raising ``Failed`` exceptions.\n\n\n- :issue:`3332`: Improve the error displayed when a ``conftest.py`` file could not be imported.\n\n  In order to implement this, a new ``chain`` parameter was added to ``ExceptionInfo.getrepr``\n  to show or hide chained tracebacks in Python 3 (defaults to ``True``).\n\n\n- :issue:`3849`: Add ``empty_parameter_set_mark=fail_at_collect`` ini option for raising an exception when parametrize collects an empty set.\n\n\n- :issue:`3964`: Log messages generated in the collection phase are shown when\n  live-logging is enabled and/or when they are logged to a file.\n\n\n- :issue:`3985`: Introduce ``tmp_path`` as a fixture providing a Path object. Also introduce ``tmp_path_factory`` as\n  a session-scoped fixture for creating arbitrary temporary directories from any other fixture or test.\n\n\n- :issue:`4013`: Deprecation warnings are now shown even if you customize the warnings filters yourself. In the previous version\n  any customization would override pytest's filters and deprecation warnings would fall back to being hidden by default.\n\n\n- :issue:`4073`: Allow specification of timeout for ``Testdir.runpytest_subprocess()`` and ``Testdir.run()``.\n\n\n- :issue:`4098`: Add returncode argument to pytest.exit() to exit pytest with a specific return code.\n\n\n- :issue:`4102`: Reimplement ``pytest.deprecated_call`` using ``pytest.warns`` so it supports the ``match='...'`` keyword argument.\n\n  This has the side effect that ``pytest.deprecated_call`` now raises ``pytest.fail.Exception`` instead\n  of ``AssertionError``.\n\n\n- :issue:`4149`: Require setuptools>=30.3 and move most of the metadata to ``setup.cfg``.\n\n\n\nBug Fixes\n---------\n\n- :issue:`2535`: Improve error message when test functions of ``unittest.TestCase`` subclasses use a parametrized fixture.\n\n\n- :issue:`3057`: ``request.fixturenames`` now correctly returns the name of fixtures created by ``request.getfixturevalue()``.\n\n\n- :issue:`3946`: Warning filters passed as command line options using ``-W`` now take precedence over filters defined in ``ini``\n  configuration files.\n\n\n- :issue:`4066`: Fix source reindenting by using ``textwrap.dedent`` directly.\n\n\n- :issue:`4102`: ``pytest.warn`` will capture previously-warned warnings in Python 2. Previously they were never raised.\n\n\n- :issue:`4108`: Resolve symbolic links for args.\n\n  This fixes running ``pytest tests/test_foo.py::test_bar``, where ``tests``\n  is a symlink to ``project/app/tests``:\n  previously ``project/app/conftest.py`` would be ignored for fixtures then.\n\n\n- :issue:`4132`: Fix duplicate printing of internal errors when using ``--pdb``.\n\n\n- :issue:`4135`: pathlib based tmpdir cleanup now correctly handles symlinks in the folder.\n\n\n- :issue:`4152`: Display the filename when encountering ``SyntaxWarning``.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3713`: Update usefixtures documentation to clarify that it can't be used with fixture functions.\n\n\n- :issue:`4058`: Update fixture documentation to specify that a fixture can be invoked twice in the scope it's defined for.\n\n\n- :issue:`4064`: According to unittest.rst, setUpModule and tearDownModule were not implemented, but it turns out they are. So updated the documentation for unittest.\n\n\n- :issue:`4151`: Add tempir testing example to CONTRIBUTING.rst guide\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`2293`: The internal ``MarkerError`` exception has been removed.\n\n\n- :issue:`3988`: Port the implementation of tmpdir to pathlib.\n\n\n- :issue:`4063`: Exclude 0.00 second entries from ``--duration`` output unless ``-vv`` is passed on the command-line.\n\n\n- :issue:`4093`: Fixed formatting of string literals in internal tests.\n\n\npytest 3.8.2 (2018-10-02)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- :issue:`4036`: The ``item`` parameter of ``pytest_warning_captured`` hook is now documented as deprecated. We realized only after\n  the ``3.8`` release that this parameter is incompatible with ``pytest-xdist``.\n\n  Our policy is to not deprecate features during bug-fix releases, but in this case we believe it makes sense as we are\n  only documenting it as deprecated, without issuing warnings which might potentially break test suites. This will get\n  the word out that hook implementers should not use this parameter at all.\n\n  In a future release ``item`` will always be ``None`` and will emit a proper warning when a hook implementation\n  makes use of it.\n\n\n\nBug Fixes\n---------\n\n- :issue:`3539`: Fix reload on assertion rewritten modules.\n\n\n- :issue:`4034`: The ``.user_properties`` attribute of ``TestReport`` objects is a list\n  of (name, value) tuples, but could sometimes be instantiated as a tuple\n  of tuples.  It is now always a list.\n\n\n- :issue:`4039`: No longer issue warnings about using ``pytest_plugins`` in non-top-level directories when using ``--pyargs``: the\n  current ``--pyargs`` mechanism is not reliable and might give false negatives.\n\n\n- :issue:`4040`: Exclude empty reports for passed tests when ``-rP`` option is used.\n\n\n- :issue:`4051`: Improve error message when an invalid Python expression is passed to the ``-m`` option.\n\n\n- :issue:`4056`: ``MonkeyPatch.setenv`` and ``MonkeyPatch.delenv`` issue a warning if the environment variable name is not ``str`` on Python 2.\n\n  In Python 2, adding ``unicode`` keys to ``os.environ`` causes problems with ``subprocess`` (and possible other modules),\n  making this a subtle bug specially susceptible when used with ``from __future__ import unicode_literals``.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3928`: Add possible values for fixture scope to docs.\n\n\npytest 3.8.1 (2018-09-22)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`3286`: ``.pytest_cache`` directory is now automatically ignored by Git. Users who would like to contribute a solution for other SCMs please consult/comment on this issue.\n\n\n- :issue:`3749`: Fix the following error during collection of tests inside packages::\n\n      TypeError: object of type 'Package' has no len()\n\n\n- :issue:`3941`: Fix bug where indirect parametrization would consider the scope of all fixtures used by the test function to determine the parametrization scope, and not only the scope of the fixtures being parametrized.\n\n\n- :issue:`3973`: Fix crash of the assertion rewriter if a test changed the current working directory without restoring it afterwards.\n\n\n- :issue:`3998`: Fix issue that prevented some caplog properties (for example ``record_tuples``) from being available when entering the debugger with ``--pdb``.\n\n\n- :issue:`3999`: Fix ``UnicodeDecodeError`` in python2.x when a class returns a non-ascii binary ``__repr__`` in an assertion which also contains non-ascii text.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3996`: New :std:doc:`deprecations` page shows all currently\n  deprecated features, the rationale to do so, and alternatives to update your code. It also list features removed\n  from pytest in past major releases to help those with ancient pytest versions to upgrade.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`3955`: Improve pre-commit detection for changelog filenames\n\n\n- :issue:`3975`: Remove legacy code around im_func as that was python2 only\n\n\npytest 3.8.0 (2018-09-05)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- :issue:`2452`: ``Config.warn`` and ``Node.warn`` have been\n  deprecated, see :ref:`config.warn and node.warn deprecated` for rationale and\n  examples.\n\n- :issue:`3936`: ``@pytest.mark.filterwarnings`` second parameter is no longer regex-escaped,\n  making it possible to actually use regular expressions to check the warning message.\n\n  **Note**: regex-escaping the match string was an implementation oversight that might break test suites which depend\n  on the old behavior.\n\n\n\nFeatures\n--------\n\n- :issue:`2452`: Internal pytest warnings are now issued using the standard ``warnings`` module, making it possible to use\n  the standard warnings filters to manage those warnings. This introduces ``PytestWarning``,\n  ``PytestDeprecationWarning`` and ``RemovedInPytest4Warning`` warning types as part of the public API.\n\n  Consult :ref:`the documentation <internal-warnings>` for more info.\n\n\n- :issue:`2908`: ``DeprecationWarning`` and ``PendingDeprecationWarning`` are now shown by default if no other warning filter is\n  configured. This makes pytest more compliant with\n  :pep:`506#recommended-filter-settings-for-test-runners`. See\n  :ref:`the docs <deprecation-warnings>` for\n  more info.\n\n\n- :issue:`3251`: Warnings are now captured and displayed during test collection.\n\n\n- :issue:`3784`: ``PYTEST_DISABLE_PLUGIN_AUTOLOAD`` environment variable disables plugin auto-loading when set.\n\n\n- :issue:`3829`: Added the ``count`` option to ``console_output_style`` to enable displaying the progress as a count instead of a percentage.\n\n\n- :issue:`3837`: Added support for 'xfailed' and 'xpassed' outcomes to the ``pytester.RunResult.assert_outcomes`` signature.\n\n\n\nBug Fixes\n---------\n\n- :issue:`3911`: Terminal writer now takes into account unicode character width when writing out progress.\n\n\n- :issue:`3913`: Pytest now returns with correct exit code (EXIT_USAGEERROR, 4) when called with unknown arguments.\n\n\n- :issue:`3918`: Improve performance of assertion rewriting.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3566`: Added a blurb in usage.rst for the usage of -r flag which is used to show an extra test summary info.\n\n\n- :issue:`3907`: Corrected type of the exceptions collection passed to ``xfail``: ``raises`` argument accepts a ``tuple`` instead of ``list``.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`3853`: Removed ``\"run all (no recorded failures)\"`` message printed with ``--failed-first`` and ``--last-failed`` when there are no failed tests.\n\n\npytest 3.7.4 (2018-08-29)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`3506`: Fix possible infinite recursion when writing ``.pyc`` files.\n\n\n- :issue:`3853`: Cache plugin now obeys the ``-q`` flag when ``--last-failed`` and ``--failed-first`` flags are used.\n\n\n- :issue:`3883`: Fix bad console output when using ``console_output_style=classic``.\n\n\n- :issue:`3888`: Fix macOS specific code using ``capturemanager`` plugin in doctests.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3902`: Fix pytest.org links\n\n\npytest 3.7.3 (2018-08-26)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`3033`: Fixtures during teardown can again use ``capsys`` and ``capfd`` to inspect output captured during tests.\n\n\n- :issue:`3773`: Fix collection of tests from ``__init__.py`` files if they match the ``python_files`` configuration option.\n\n\n- :issue:`3796`: Fix issue where teardown of fixtures of consecutive sub-packages were executed once, at the end of the outer\n  package.\n\n\n- :issue:`3816`: Fix bug where ``--show-capture=no`` option would still show logs printed during fixture teardown.\n\n\n- :issue:`3819`: Fix ``stdout/stderr`` not getting captured when real-time cli logging is active.\n\n\n- :issue:`3843`: Fix collection error when specifying test functions directly in the command line using ``test.py::test`` syntax together with ``--doctest-modules``.\n\n\n- :issue:`3848`: Fix bugs where unicode arguments could not be passed to ``testdir.runpytest`` on Python 2.\n\n\n- :issue:`3854`: Fix double collection of tests within packages when the filename starts with a capital letter.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3824`: Added example for multiple glob pattern matches in ``python_files``.\n\n\n- :issue:`3833`: Added missing docs for ``pytester.Testdir``.\n\n\n- :issue:`3870`: Correct documentation for setuptools integration.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`3826`: Replace broken type annotations with type comments.\n\n\n- :issue:`3845`: Remove a reference to issue :issue:`568` from the documentation, which has since been\n  fixed.\n\n\npytest 3.7.2 (2018-08-16)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`3671`: Fix ``filterwarnings`` not being registered as a builtin mark.\n\n\n- :issue:`3768`, :issue:`3789`: Fix test collection from packages mixed with normal directories.\n\n\n- :issue:`3771`: Fix infinite recursion during collection if a ``pytest_ignore_collect`` hook returns ``False`` instead of ``None``.\n\n\n- :issue:`3774`: Fix bug where decorated fixtures would lose functionality (for example ``@mock.patch``).\n\n\n- :issue:`3775`: Fix bug where importing modules or other objects with prefix ``pytest_`` prefix would raise a ``PluginValidationError``.\n\n\n- :issue:`3788`: Fix ``AttributeError`` during teardown of ``TestCase`` subclasses which raise an exception during ``__init__``.\n\n\n- :issue:`3804`: Fix traceback reporting for exceptions with ``__cause__`` cycles.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3746`: Add documentation for ``metafunc.config`` that had been mistakenly hidden.\n\n\npytest 3.7.1 (2018-08-02)\n=========================\n\nBug Fixes\n---------\n\n- :issue:`3473`: Raise immediately if ``approx()`` is given an expected value of a type it doesn't understand (e.g. strings, nested dicts, etc.).\n\n\n- :issue:`3712`: Correctly represent the dimensions of a numpy array when calling ``repr()`` on ``approx()``.\n\n- :issue:`3742`: Fix incompatibility with third party plugins during collection, which produced the error ``object has no attribute '_collectfile'``.\n\n- :issue:`3745`: Display the absolute path if ``cache_dir`` is not relative to the ``rootdir`` instead of failing.\n\n\n- :issue:`3747`: Fix compatibility problem with plugins and the warning code issued by fixture functions when they are called directly.\n\n\n- :issue:`3748`: Fix infinite recursion in ``pytest.approx`` with arrays in ``numpy<1.13``.\n\n\n- :issue:`3757`: Pin pathlib2 to ``>=2.2.0`` as we require ``__fspath__`` support.\n\n\n- :issue:`3763`: Fix ``TypeError`` when the assertion message is ``bytes`` in python 3.\n\n\npytest 3.7.0 (2018-07-30)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- :issue:`2639`: ``pytest_namespace`` has been :ref:`deprecated <pytest.namespace deprecated>`.\n\n\n- :issue:`3661`: Calling a fixture function directly, as opposed to request them in a test function, now issues a ``RemovedInPytest4Warning``. See :ref:`the documentation for rationale and examples <calling fixtures directly deprecated>`.\n\n\n\nFeatures\n--------\n\n- :issue:`2283`: New ``package`` fixture scope: fixtures are finalized when the last test of a *package* finishes. This feature is considered **experimental**, so use it sparingly.\n\n\n- :issue:`3576`: ``Node.add_marker`` now supports an ``append=True/False`` parameter to determine whether the mark comes last (default) or first.\n\n\n- :issue:`3579`: Fixture ``caplog`` now has a ``messages`` property, providing convenient access to the format-interpolated log messages without the extra data provided by the formatter/handler.\n\n\n- :issue:`3610`: New ``--trace`` option to enter the debugger at the start of a test.\n\n\n- :issue:`3623`: Introduce ``pytester.copy_example`` as helper to do acceptance tests against examples from the project.\n\n\n\nBug Fixes\n---------\n\n- :issue:`2220`: Fix a bug where fixtures overridden by direct parameters (for example parametrization) were being instantiated even if they were not being used by a test.\n\n\n- :issue:`3695`: Fix ``ApproxNumpy`` initialisation argument mixup, ``abs`` and ``rel`` tolerances were flipped causing strange comparison results.\n  Add tests to check ``abs`` and ``rel`` tolerances for ``np.array`` and test for expecting ``nan`` with ``np.array()``\n\n\n- :issue:`980`: Fix truncated locals output in verbose mode.\n\n\n\nImproved Documentation\n----------------------\n\n- :issue:`3295`: Correct the usage documentation of ``--last-failed-no-failures`` by adding the missing ``--last-failed`` argument in the presented examples, because they are misleading and lead to think that the missing argument is not needed.\n\n\n\nTrivial/Internal Changes\n------------------------\n\n- :issue:`3519`: Now a ``README.md`` file is created in ``.pytest_cache`` to make it clear why the directory exists.\n\n\npytest 3.6.4 (2018-07-28)\n=========================\n\nBug Fixes\n---------\n\n- Invoke pytest using ``-mpytest`` so ``sys.path`` does not get polluted by packages installed in ``site-packages``. (:issue:`742`)\n\n\nImproved Documentation\n----------------------\n\n- Use ``smtp_connection`` instead of ``smtp`` in fixtures documentation to avoid possible confusion. (:issue:`3592`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Remove obsolete ``__future__`` imports. (:issue:`2319`)\n\n- Add CITATION to provide information on how to formally cite pytest. (:issue:`3402`)\n\n- Replace broken type annotations with type comments. (:issue:`3635`)\n\n- Pin ``pluggy`` to ``<0.8``. (:issue:`3727`)\n\n\npytest 3.6.3 (2018-07-04)\n=========================\n\nBug Fixes\n---------\n\n- Fix ``ImportWarning`` triggered by explicit relative imports in\n  assertion-rewritten package modules. (:issue:`3061`)\n\n- Fix error in ``pytest.approx`` when dealing with 0-dimension numpy\n  arrays. (:issue:`3593`)\n\n- No longer raise ``ValueError`` when using the ``get_marker`` API. (:issue:`3605`)\n\n- Fix problem where log messages with non-ascii characters would not\n  appear in the output log file.\n  (:issue:`3630`)\n\n- No longer raise ``AttributeError`` when legacy marks can't be stored in\n  functions. (:issue:`3631`)\n\n\nImproved Documentation\n----------------------\n\n- The description above the example for ``@pytest.mark.skipif`` now better\n  matches the code. (:issue:`3611`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Internal refactoring: removed unused ``CallSpec2tox ._globalid_args``\n  attribute and ``metafunc`` parameter from ``CallSpec2.copy()``. (:issue:`3598`)\n\n- Silence usage of ``reduce`` warning in Python 2 (:issue:`3609`)\n\n- Fix usage of ``attr.ib`` deprecated ``convert`` parameter. (:issue:`3653`)\n\n\npytest 3.6.2 (2018-06-20)\n=========================\n\nBug Fixes\n---------\n\n- Fix regression in ``Node.add_marker`` by extracting the mark object of a\n  ``MarkDecorator``. (:issue:`3555`)\n\n- Warnings without ``location`` were reported as ``None``. This is corrected to\n  now report ``<undetermined location>``. (:issue:`3563`)\n\n- Continue to call finalizers in the stack when a finalizer in a former scope\n  raises an exception. (:issue:`3569`)\n\n- Fix encoding error with ``print`` statements in doctests (:issue:`3583`)\n\n\nImproved Documentation\n----------------------\n\n- Add documentation for the ``--strict`` flag. (:issue:`3549`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Update old quotation style to parens in fixture.rst documentation. (:issue:`3525`)\n\n- Improve display of hint about ``--fulltrace`` with ``KeyboardInterrupt``.\n  (:issue:`3545`)\n\n- pytest's testsuite is no longer runnable through ``python setup.py test`` --\n  instead invoke ``pytest`` or ``tox`` directly. (:issue:`3552`)\n\n- Fix typo in documentation (:issue:`3567`)\n\n\npytest 3.6.1 (2018-06-05)\n=========================\n\nBug Fixes\n---------\n\n- Fixed a bug where stdout and stderr were logged twice by junitxml when a test\n  was marked xfail. (:issue:`3491`)\n\n- Fix ``usefixtures`` mark applied to unittest tests by correctly instantiating\n  ``FixtureInfo``. (:issue:`3498`)\n\n- Fix assertion rewriter compatibility with libraries that monkey patch\n  ``file`` objects. (:issue:`3503`)\n\n\nImproved Documentation\n----------------------\n\n- Added a section on how to use fixtures as factories to the fixture\n  documentation. (:issue:`3461`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Enable caching for pip/pre-commit in order to reduce build time on\n  travis/appveyor. (:issue:`3502`)\n\n- Switch pytest to the src/ layout as we already suggested it for good practice\n  - now we implement it as well. (:issue:`3513`)\n\n- Fix if in tests to support 3.7.0b5, where a docstring handling in AST got\n  reverted. (:issue:`3530`)\n\n- Remove some python2.5 compatibility code. (:issue:`3529`)\n\n\npytest 3.6.0 (2018-05-23)\n=========================\n\nFeatures\n--------\n\n- Revamp the internals of the ``pytest.mark`` implementation with correct per\n  node handling which fixes a number of long standing bugs caused by the old\n  design. This introduces new ``Node.iter_markers(name)`` and\n  ``Node.get_closest_marker(name)`` APIs. Users are **strongly encouraged** to\n  read the :ref:`reasons for the revamp in the docs <marker-revamp>`,\n  or jump over to details about :ref:`updating existing code to use the new APIs\n  <update marker code>`.\n  (:issue:`3317`)\n\n- Now when ``@pytest.fixture`` is applied more than once to the same function a\n  ``ValueError`` is raised. This buggy behavior would cause surprising problems\n  and if was working for a test suite it was mostly by accident. (:issue:`2334`)\n\n- Support for Python 3.7's builtin ``breakpoint()`` method, see\n  :ref:`Using the builtin breakpoint function <breakpoint-builtin>` for\n  details. (:issue:`3180`)\n\n- ``monkeypatch`` now supports a ``context()`` function which acts as a context\n  manager which undoes all patching done within the ``with`` block. (:issue:`3290`)\n\n- The ``--pdb`` option now causes KeyboardInterrupt to enter the debugger,\n  instead of stopping the test session. On python 2.7, hitting CTRL+C again\n  exits the debugger. On python 3.2 and higher, use CTRL+D. (:issue:`3299`)\n\n- pytest no longer changes the log level of the root logger when the\n  ``log-level`` parameter has greater numeric value than that of the level of\n  the root logger, which makes it play better with custom logging configuration\n  in user code. (:issue:`3307`)\n\n\nBug Fixes\n---------\n\n- A rare race-condition which might result in corrupted ``.pyc`` files on\n  Windows has been hopefully solved. (:issue:`3008`)\n\n- Also use iter_marker for discovering the marks applying for marker\n  expressions from the cli to avoid the bad data from the legacy mark storage.\n  (:issue:`3441`)\n\n- When showing diffs of failed assertions where the contents contain only\n  whitespace, escape them using ``repr()`` first to make it easy to spot the\n  differences. (:issue:`3443`)\n\n\nImproved Documentation\n----------------------\n\n- Change documentation copyright year to a range which auto-updates itself each\n  time it is published. (:issue:`3303`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- ``pytest`` now depends on the `python-atomicwrites\n  <https://github.com/untitaker/python-atomicwrites>`_ library. (:issue:`3008`)\n\n- Update all pypi.python.org URLs to pypi.org. (:issue:`3431`)\n\n- Detect `pytest_` prefixed hooks using the internal plugin manager since\n  ``pluggy`` is deprecating the ``implprefix`` argument to ``PluginManager``.\n  (:issue:`3487`)\n\n- Import ``Mapping`` and ``Sequence`` from ``_pytest.compat`` instead of\n  directly from ``collections`` in ``python_api.py::approx``. Add ``Mapping``\n  to ``_pytest.compat``, import it from ``collections`` on python 2, but from\n  ``collections.abc`` on Python 3 to avoid a ``DeprecationWarning`` on Python\n  3.7 or newer. (:issue:`3497`)\n\n\npytest 3.5.1 (2018-04-23)\n=========================\n\n\nBug Fixes\n---------\n\n- Reset ``sys.last_type``, ``sys.last_value`` and ``sys.last_traceback`` before\n  each test executes. Those attributes are added by pytest during the test run\n  to aid debugging, but were never reset so they would create a leaking\n  reference to the last failing test's frame which in turn could never be\n  reclaimed by the garbage collector. (:issue:`2798`)\n\n- ``pytest.raises`` now raises ``TypeError`` when receiving an unknown keyword\n  argument. (:issue:`3348`)\n\n- ``pytest.raises`` now works with exception classes that look like iterables.\n  (:issue:`3372`)\n\n\nImproved Documentation\n----------------------\n\n- Fix typo in ``caplog`` fixture documentation, which incorrectly identified\n  certain attributes as methods. (:issue:`3406`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Added a more indicative error message when parametrizing a function whose\n  argument takes a default value. (:issue:`3221`)\n\n- Remove internal ``_pytest.terminal.flatten`` function in favor of\n  ``more_itertools.collapse``. (:issue:`3330`)\n\n- Import some modules from ``collections.abc`` instead of ``collections`` as\n  the former modules trigger ``DeprecationWarning`` in Python 3.7. (:issue:`3339`)\n\n- record_property is no longer experimental, removing the warnings was\n  forgotten. (:issue:`3360`)\n\n- Mention in documentation and CLI help that fixtures with leading ``_`` are\n  printed by ``pytest --fixtures`` only if the ``-v`` option is added. (:issue:`3398`)\n\n\npytest 3.5.0 (2018-03-21)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- ``record_xml_property`` fixture is now deprecated in favor of the more\n  generic ``record_property``. (:issue:`2770`)\n\n- Defining ``pytest_plugins`` is now deprecated in non-top-level conftest.py\n  files, because they \"leak\" to the entire directory tree.\n  :ref:`See the docs <pytest_plugins in non-top-level conftest files deprecated>`\n  for the rationale behind this decision (:issue:`3084`)\n\n\nFeatures\n--------\n\n- New ``--show-capture`` command-line option that allows to specify how to\n  display captured output when tests fail: ``no``, ``stdout``, ``stderr``,\n  ``log`` or ``all`` (the default). (:issue:`1478`)\n\n- New ``--rootdir`` command-line option to override the rules for discovering\n  the root directory. See :doc:`customize <reference/customize>` in the documentation for\n  details. (:issue:`1642`)\n\n- Fixtures are now instantiated based on their scopes, with higher-scoped\n  fixtures (such as ``session``) being instantiated first than lower-scoped\n  fixtures (such as ``function``). The relative order of fixtures of the same\n  scope is kept unchanged, based in their declaration order and their\n  dependencies. (:issue:`2405`)\n\n- ``record_xml_property`` renamed to ``record_property`` and is now compatible\n  with xdist, markers and any reporter. ``record_xml_property`` name is now\n  deprecated. (:issue:`2770`)\n\n- New ``--nf``, ``--new-first`` options: run new tests first followed by the\n  rest of the tests, in both cases tests are also sorted by the file modified\n  time, with more recent files coming first. (:issue:`3034`)\n\n- New ``--last-failed-no-failures`` command-line option that allows to specify\n  the behavior of the cache plugin's ```--last-failed`` feature when no tests\n  failed in the last run (or no cache was found): ``none`` or ``all`` (the\n  default). (:issue:`3139`)\n\n- New ``--doctest-continue-on-failure`` command-line option to enable doctests\n  to show multiple failures for each snippet, instead of stopping at the first\n  failure. (:issue:`3149`)\n\n- Captured log messages are added to the ``<system-out>`` tag in the generated\n  junit xml file if the ``junit_logging`` ini option is set to ``system-out``.\n  If the value of this ini option is ``system-err``, the logs are written to\n  ``<system-err>``. The default value for ``junit_logging`` is ``no``, meaning\n  captured logs are not written to the output file. (:issue:`3156`)\n\n- Allow the logging plugin to handle ``pytest_runtest_logstart`` and\n  ``pytest_runtest_logfinish`` hooks when live logs are enabled. (:issue:`3189`)\n\n- Passing ``--log-cli-level`` in the command-line now automatically activates\n  live logging. (:issue:`3190`)\n\n- Add command line option ``--deselect`` to allow deselection of individual\n  tests at collection time. (:issue:`3198`)\n\n- Captured logs are printed before entering pdb. (:issue:`3204`)\n\n- Deselected item count is now shown before tests are run, e.g. ``collected X\n  items / Y deselected``. (:issue:`3213`)\n\n- The builtin module ``platform`` is now available for use in expressions in\n  ``pytest.mark``. (:issue:`3236`)\n\n- The *short test summary info* section now is displayed after tracebacks and\n  warnings in the terminal. (:issue:`3255`)\n\n- New ``--verbosity`` flag to set verbosity level explicitly. (:issue:`3296`)\n\n- ``pytest.approx`` now accepts comparing a numpy array with a scalar. (:issue:`3312`)\n\n\nBug Fixes\n---------\n\n- Suppress ``IOError`` when closing the temporary file used for capturing\n  streams in Python 2.7. (:issue:`2370`)\n\n- Fixed ``clear()`` method on ``caplog`` fixture which cleared ``records``, but\n  not the ``text`` property. (:issue:`3297`)\n\n- During test collection, when stdin is not allowed to be read, the\n  ``DontReadFromStdin`` object still allow itself to be iterable and resolved\n  to an iterator without crashing. (:issue:`3314`)\n\n\nImproved Documentation\n----------------------\n\n- Added a :doc:`reference <reference/reference>` page\n  to the docs. (:issue:`1713`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Change minimum requirement of ``attrs`` to ``17.4.0``. (:issue:`3228`)\n\n- Renamed example directories so all tests pass when ran from the base\n  directory. (:issue:`3245`)\n\n- Internal ``mark.py`` module has been turned into a package. (:issue:`3250`)\n\n- ``pytest`` now depends on the `more-itertools\n  <https://github.com/erikrose/more-itertools>`_ package. (:issue:`3265`)\n\n- Added warning when ``[pytest]`` section is used in a ``.cfg`` file passed\n  with ``-c`` (:issue:`3268`)\n\n- ``nodeids`` can now be passed explicitly to ``FSCollector`` and ``Node``\n  constructors. (:issue:`3291`)\n\n- Internal refactoring of ``FormattedExcinfo`` to use ``attrs`` facilities and\n  remove old support code for legacy Python versions. (:issue:`3292`)\n\n- Refactoring to unify how verbosity is handled internally. (:issue:`3296`)\n\n- Internal refactoring to better integrate with argparse. (:issue:`3304`)\n\n- Fix a python example when calling a fixture in doc/en/usage.rst (:issue:`3308`)\n\n\npytest 3.4.2 (2018-03-04)\n=========================\n\nBug Fixes\n---------\n\n- Removed progress information when capture option is ``no``. (:issue:`3203`)\n\n- Refactor check of bindir from ``exists`` to ``isdir``. (:issue:`3241`)\n\n- Fix ``TypeError`` issue when using ``approx`` with a ``Decimal`` value.\n  (:issue:`3247`)\n\n- Fix reference cycle generated when using the ``request`` fixture. (:issue:`3249`)\n\n- ``[tool:pytest]`` sections in ``*.cfg`` files passed by the ``-c`` option are\n  now properly recognized. (:issue:`3260`)\n\n\nImproved Documentation\n----------------------\n\n- Add logging plugin to plugins list. (:issue:`3209`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Fix minor typo in fixture.rst (:issue:`3259`)\n\n\npytest 3.4.1 (2018-02-20)\n=========================\n\nBug Fixes\n---------\n\n- Move import of ``doctest.UnexpectedException`` to top-level to avoid possible\n  errors when using ``--pdb``. (:issue:`1810`)\n\n- Added printing of captured stdout/stderr before entering pdb, and improved a\n  test which was giving false negatives about output capturing. (:issue:`3052`)\n\n- Fix ordering of tests using parametrized fixtures which can lead to fixtures\n  being created more than necessary. (:issue:`3161`)\n\n- Fix bug where logging happening at hooks outside of \"test run\" hooks would\n  cause an internal error. (:issue:`3184`)\n\n- Detect arguments injected by ``unittest.mock.patch`` decorator correctly when\n  pypi ``mock.patch`` is installed and imported. (:issue:`3206`)\n\n- Errors shown when a ``pytest.raises()`` with ``match=`` fails are now cleaner\n  on what happened: When no exception was raised, the \"matching '...'\" part got\n  removed as it falsely implies that an exception was raised but it didn't\n  match. When a wrong exception was raised, it's now thrown (like\n  ``pytest.raised()`` without ``match=`` would) instead of complaining about\n  the unmatched text. (:issue:`3222`)\n\n- Fixed output capture handling in doctests on macOS. (:issue:`985`)\n\n\nImproved Documentation\n----------------------\n\n- Add Sphinx parameter docs for ``match`` and ``message`` args to\n  ``pytest.raises``. (:issue:`3202`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- pytest has changed the publication procedure and is now being published to\n  PyPI directly from Travis. (:issue:`3060`)\n\n- Rename ``ParameterSet._for_parameterize()`` to ``_for_parametrize()`` in\n  order to comply with the naming convention. (:issue:`3166`)\n\n- Skip failing pdb/doctest test on mac. (:issue:`985`)\n\n\npytest 3.4.0 (2018-01-30)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- All pytest classes now subclass ``object`` for better Python 2/3 compatibility.\n  This should not affect user code except in very rare edge cases. (:issue:`2147`)\n\n\nFeatures\n--------\n\n- Introduce ``empty_parameter_set_mark`` ini option to select which mark to\n  apply when ``@pytest.mark.parametrize`` is given an empty set of parameters.\n  Valid options are ``skip`` (default) and ``xfail``. Note that it is planned\n  to change the default to ``xfail`` in future releases as this is considered\n  less error prone. (:issue:`2527`)\n\n- **Incompatible change**: after community feedback the :doc:`logging <how-to/logging>` functionality has\n  undergone some changes. Please consult the :ref:`logging documentation <log_changes_3_4>`\n  for details. (:issue:`3013`)\n\n- Console output falls back to \"classic\" mode when capturing is disabled (``-s``),\n  otherwise the output gets garbled to the point of being useless. (:issue:`3038`)\n\n- New :hook:`pytest_runtest_logfinish`\n  hook which is called when a test item has finished executing, analogous to\n  :hook:`pytest_runtest_logstart`.\n  (:issue:`3101`)\n\n- Improve performance when collecting tests using many fixtures. (:issue:`3107`)\n\n- New ``caplog.get_records(when)`` method which provides access to the captured\n  records for the ``\"setup\"``, ``\"call\"`` and ``\"teardown\"``\n  testing stages. (:issue:`3117`)\n\n- New fixture ``record_xml_attribute`` that allows modifying and inserting\n  attributes on the ``<testcase>`` xml node in JUnit reports. (:issue:`3130`)\n\n- The default cache directory has been renamed from ``.cache`` to\n  ``.pytest_cache`` after community feedback that the name ``.cache`` did not\n  make it clear that it was used by pytest. (:issue:`3138`)\n\n- Colorize the levelname column in the live-log output. (:issue:`3142`)\n\n\nBug Fixes\n---------\n\n- Fix hanging pexpect test on macOS by using flush() instead of wait().\n  (:issue:`2022`)\n\n- Fix restoring Python state after in-process pytest runs with the\n  ``pytester`` plugin; this may break tests using multiple inprocess\n  pytest runs if later ones depend on earlier ones leaking global interpreter\n  changes. (:issue:`3016`)\n\n- Fix skipping plugin reporting hook when test aborted before plugin setup\n  hook. (:issue:`3074`)\n\n- Fix progress percentage reported when tests fail during teardown. (:issue:`3088`)\n\n- **Incompatible change**: ``-o/--override`` option no longer eats all the\n  remaining options, which can lead to surprising behavior: for example,\n  ``pytest -o foo=1 /path/to/test.py`` would fail because ``/path/to/test.py``\n  would be considered as part of the ``-o`` command-line argument. One\n  consequence of this is that now multiple configuration overrides need\n  multiple ``-o`` flags: ``pytest -o foo=1 -o bar=2``. (:issue:`3103`)\n\n\nImproved Documentation\n----------------------\n\n- Document hooks (defined with ``historic=True``) which cannot be used with\n  ``hookwrapper=True``. (:issue:`2423`)\n\n- Clarify that warning capturing doesn't change the warning filter by default.\n  (:issue:`2457`)\n\n- Clarify a possible confusion when using pytest_fixture_setup with fixture\n  functions that return None. (:issue:`2698`)\n\n- Fix the wording of a sentence on doctest flags used in pytest. (:issue:`3076`)\n\n- Prefer ``https://*.readthedocs.io`` over ``http://*.rtfd.org`` for links in\n  the documentation. (:issue:`3092`)\n\n- Improve readability (wording, grammar) of Getting Started guide (:issue:`3131`)\n\n- Added note that calling pytest.main multiple times from the same process is\n  not recommended because of import caching. (:issue:`3143`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Show a simple and easy error when keyword expressions trigger a syntax error\n  (for example, ``\"-k foo and import\"`` will show an error that you cannot use\n  the ``import`` keyword in expressions). (:issue:`2953`)\n\n- Change parametrized automatic test id generation to use the ``__name__``\n  attribute of functions instead of the fallback argument name plus counter.\n  (:issue:`2976`)\n\n- Replace py.std with stdlib imports. (:issue:`3067`)\n\n- Corrected 'you' to 'your' in logging docs. (:issue:`3129`)\n\n\npytest 3.3.2 (2017-12-25)\n=========================\n\nBug Fixes\n---------\n\n- pytester: ignore files used to obtain current user metadata in the fd leak\n  detector. (:issue:`2784`)\n\n- Fix **memory leak** where objects returned by fixtures were never destructed\n  by the garbage collector. (:issue:`2981`)\n\n- Fix conversion of pyargs to filename to not convert symlinks on Python 2. (:issue:`2985`)\n\n- ``PYTEST_DONT_REWRITE`` is now checked for plugins too rather than only for\n  test modules. (:issue:`2995`)\n\n\nImproved Documentation\n----------------------\n\n- Add clarifying note about behavior of multiple parametrized arguments (:issue:`3001`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Code cleanup. (:issue:`3015`,\n  :issue:`3021`)\n\n- Clean up code by replacing imports and references of ``_ast`` to ``ast``.\n  (:issue:`3018`)\n\n\npytest 3.3.1 (2017-12-05)\n=========================\n\nBug Fixes\n---------\n\n- Fix issue about ``-p no:<plugin>`` having no effect. (:issue:`2920`)\n\n- Fix regression with warnings that contained non-strings in their arguments in\n  Python 2. (:issue:`2956`)\n\n- Always escape null bytes when setting ``PYTEST_CURRENT_TEST``. (:issue:`2957`)\n\n- Fix ``ZeroDivisionError`` when using the ``testmon`` plugin when no tests\n  were actually collected. (:issue:`2971`)\n\n- Bring back ``TerminalReporter.writer`` as an alias to\n  ``TerminalReporter._tw``. This alias was removed by accident in the ``3.3.0``\n  release. (:issue:`2984`)\n\n- The ``pytest-capturelog`` plugin is now also blacklisted, avoiding errors when\n  running pytest with it still installed. (:issue:`3004`)\n\n\nImproved Documentation\n----------------------\n\n- Fix broken link to plugin ``pytest-localserver``. (:issue:`2963`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Update github \"bugs\" link in ``CONTRIBUTING.rst`` (:issue:`2949`)\n\n\npytest 3.3.0 (2017-11-23)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- pytest no longer supports Python **2.6** and **3.3**. Those Python versions\n  are EOL for some time now and incur maintenance and compatibility costs on\n  the pytest core team, and following up with the rest of the community we\n  decided that they will no longer be supported starting on this version. Users\n  which still require those versions should pin pytest to ``<3.3``. (:issue:`2812`)\n\n- Remove internal ``_preloadplugins()`` function. This removal is part of the\n  ``pytest_namespace()`` hook deprecation. (:issue:`2636`)\n\n- Internally change ``CallSpec2`` to have a list of marks instead of a broken\n  mapping of keywords. This removes the keywords attribute of the internal\n  ``CallSpec2`` class. (:issue:`2672`)\n\n- Remove ParameterSet.deprecated_arg_dict - its not a public api and the lack\n  of the underscore was a naming error. (:issue:`2675`)\n\n- Remove the internal multi-typed attribute ``Node._evalskip`` and replace it\n  with the boolean ``Node._skipped_by_mark``. (:issue:`2767`)\n\n- The ``params`` list passed to ``pytest.fixture`` is now for\n  all effects considered immutable and frozen at the moment of the ``pytest.fixture``\n  call. Previously the list could be changed before the first invocation of the fixture\n  allowing for a form of dynamic parametrization (for example, updated from command-line options),\n  but this was an unwanted implementation detail which complicated the internals and prevented\n  some internal cleanup. See issue :issue:`2959`\n  for details and a recommended workaround.\n\nFeatures\n--------\n\n- ``pytest_fixture_post_finalizer`` hook can now receive a ``request``\n  argument. (:issue:`2124`)\n\n- Replace the old introspection code in compat.py that determines the available\n  arguments of fixtures with inspect.signature on Python 3 and\n  funcsigs.signature on Python 2. This should respect ``__signature__``\n  declarations on functions. (:issue:`2267`)\n\n- Report tests with global ``pytestmark`` variable only once. (:issue:`2549`)\n\n- Now pytest displays the total progress percentage while running tests. The\n  previous output style can be set by configuring the ``console_output_style``\n  setting to ``classic``. (:issue:`2657`)\n\n- Match ``warns`` signature to ``raises`` by adding ``match`` keyword. (:issue:`2708`)\n\n- pytest now captures and displays output from the standard ``logging`` module.\n  The user can control the logging level to be captured by specifying options\n  in ``pytest.ini``, the command line and also during individual tests using\n  markers. Also, a ``caplog`` fixture is available that enables users to test\n  the captured log during specific tests (similar to ``capsys`` for example).\n  For more information, please see the :doc:`logging docs <how-to/logging>`. This feature was\n  introduced by merging the popular :pypi:`pytest-catchlog` plugin, thanks to :user:`thisch`.\n  Be advised that during the merging the\n  backward compatibility interface with the defunct ``pytest-capturelog`` has\n  been dropped. (:issue:`2794`)\n\n- Add ``allow_module_level`` kwarg to ``pytest.skip()``, enabling to skip the\n  whole module. (:issue:`2808`)\n\n- Allow setting ``file_or_dir``, ``-c``, and ``-o`` in PYTEST_ADDOPTS. (:issue:`2824`)\n\n- Return stdout/stderr capture results as a ``namedtuple``, so ``out`` and\n  ``err`` can be accessed by attribute. (:issue:`2879`)\n\n- Add ``capfdbinary``, a version of ``capfd`` which returns bytes from\n  ``readouterr()``. (:issue:`2923`)\n\n- Add ``capsysbinary`` a version of ``capsys`` which returns bytes from\n  ``readouterr()``. (:issue:`2934`)\n\n- Implement feature to skip ``setup.py`` files when run with\n  ``--doctest-modules``. (:issue:`502`)\n\n\nBug Fixes\n---------\n\n- Resume output capturing after ``capsys/capfd.disabled()`` context manager.\n  (:issue:`1993`)\n\n- ``pytest_fixture_setup`` and ``pytest_fixture_post_finalizer`` hooks are now\n  called for all ``conftest.py`` files. (:issue:`2124`)\n\n- If an exception happens while loading a plugin, pytest no longer hides the\n  original traceback. In Python 2 it will show the original traceback with a new\n  message that explains in which plugin. In Python 3 it will show 2 canonized\n  exceptions, the original exception while loading the plugin in addition to an\n  exception that pytest throws about loading a plugin. (:issue:`2491`)\n\n- ``capsys`` and ``capfd`` can now be used by other fixtures. (:issue:`2709`)\n\n- Internal ``pytester`` plugin properly encodes ``bytes`` arguments to\n  ``utf-8``. (:issue:`2738`)\n\n- ``testdir`` now uses use the same method used by ``tmpdir`` to create its\n  temporary directory. This changes the final structure of the ``testdir``\n  directory slightly, but should not affect usage in normal scenarios and\n  avoids a number of potential problems. (:issue:`2751`)\n\n- pytest no longer complains about warnings with unicode messages being\n  non-ascii compatible even for ascii-compatible messages. As a result of this,\n  warnings with unicode messages are converted first to an ascii representation\n  for safety. (:issue:`2809`)\n\n- Change return value of pytest command when ``--maxfail`` is reached from\n  ``2`` (interrupted) to ``1`` (failed). (:issue:`2845`)\n\n- Fix issue in assertion rewriting which could lead it to rewrite modules which\n  should not be rewritten. (:issue:`2939`)\n\n- Handle marks without description in ``pytest.ini``. (:issue:`2942`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- pytest now depends on :pypi:`attrs` for internal\n  structures to ease code maintainability. (:issue:`2641`)\n\n- Refactored internal Python 2/3 compatibility code to use ``six``. (:issue:`2642`)\n\n- Stop vendoring ``pluggy`` - we're missing out on its latest changes for not\n  much benefit (:issue:`2719`)\n\n- Internal refactor: simplify ascii string escaping by using the\n  backslashreplace error handler in newer Python 3 versions. (:issue:`2734`)\n\n- Remove unnecessary mark evaluator in unittest plugin (:issue:`2767`)\n\n- Calls to ``Metafunc.addcall`` now emit a deprecation warning. This function\n  is scheduled to be removed in ``pytest-4.0``. (:issue:`2876`)\n\n- Internal move of the parameterset extraction to a more maintainable place.\n  (:issue:`2877`)\n\n- Internal refactoring to simplify scope node lookup. (:issue:`2910`)\n\n- Configure ``pytest`` to prevent pip from installing pytest in unsupported\n  Python versions. (:issue:`2922`)\n\n\npytest 3.2.5 (2017-11-15)\n=========================\n\nBug Fixes\n---------\n\n- Remove ``py<1.5`` restriction from ``pytest`` as this can cause version\n  conflicts in some installations. (:issue:`2926`)\n\n\npytest 3.2.4 (2017-11-13)\n=========================\n\nBug Fixes\n---------\n\n- Fix the bug where running with ``--pyargs`` will result in items with\n  empty ``parent.nodeid`` if run from a different root directory. (:issue:`2775`)\n\n- Fix issue with ``@pytest.parametrize`` if argnames was specified as keyword arguments.\n  (:issue:`2819`)\n\n- Strip whitespace from marker names when reading them from INI config. (:issue:`2856`)\n\n- Show full context of doctest source in the pytest output, if the line number of\n  failed example in the docstring is < 9. (:issue:`2882`)\n\n- Match fixture paths against actual path segments in order to avoid matching folders which share a prefix.\n  (:issue:`2836`)\n\nImproved Documentation\n----------------------\n\n- Introduce a dedicated section about conftest.py. (:issue:`1505`)\n\n- Explicitly mention ``xpass`` in the documentation of ``xfail``. (:issue:`1997`)\n\n- Append example for pytest.param in the example/parametrize document. (:issue:`2658`)\n\n- Clarify language of proposal for fixtures parameters (:issue:`2893`)\n\n- List python 3.6 in the documented supported versions in the getting started\n  document. (:issue:`2903`)\n\n- Clarify the documentation of available fixture scopes. (:issue:`538`)\n\n- Add documentation about the ``python -m pytest`` invocation adding the\n  current directory to sys.path. (:issue:`911`)\n\n\npytest 3.2.3 (2017-10-03)\n=========================\n\nBug Fixes\n---------\n\n- Fix crash in tab completion when no prefix is given. (:issue:`2748`)\n\n- The equality checking function (``__eq__``) of ``MarkDecorator`` returns\n  ``False`` if one object is not an instance of ``MarkDecorator``. (:issue:`2758`)\n\n- When running ``pytest --fixtures-per-test``: don't crash if an item has no\n  _fixtureinfo attribute (e.g. doctests) (:issue:`2788`)\n\n\nImproved Documentation\n----------------------\n\n- In help text of ``-k`` option, add example of using ``not`` to not select\n  certain tests whose names match the provided expression. (:issue:`1442`)\n\n- Add note in ``parametrize.rst`` about calling ``metafunc.parametrize``\n  multiple times. (:issue:`1548`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Set ``xfail_strict=True`` in pytest's own test suite to catch expected\n  failures as soon as they start to pass. (:issue:`2722`)\n\n- Fix typo in example of passing a callable to markers (in example/markers.rst)\n  (:issue:`2765`)\n\n\npytest 3.2.2 (2017-09-06)\n=========================\n\nBug Fixes\n---------\n\n- Calling the deprecated ``request.getfuncargvalue()`` now shows the source of\n  the call. (:issue:`2681`)\n\n- Allow tests declared as ``@staticmethod`` to use fixtures. (:issue:`2699`)\n\n- Fixed edge-case during collection: attributes which raised ``pytest.fail``\n  when accessed would abort the entire collection. (:issue:`2707`)\n\n- Fix ``ReprFuncArgs`` with mixed unicode and UTF-8 args. (:issue:`2731`)\n\n\nImproved Documentation\n----------------------\n\n- In examples on working with custom markers, add examples demonstrating the\n  usage of ``pytest.mark.MARKER_NAME.with_args`` in comparison with\n  ``pytest.mark.MARKER_NAME.__call__`` (:issue:`2604`)\n\n- In one of the simple examples, use ``pytest_collection_modifyitems()`` to skip\n  tests based on a command-line option, allowing its sharing while preventing a\n  user error when accessing ``pytest.config`` before the argument parsing.\n  (:issue:`2653`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Fixed minor error in 'Good Practices/Manual Integration' code snippet.\n  (:issue:`2691`)\n\n- Fixed typo in goodpractices.rst. (:issue:`2721`)\n\n- Improve user guidance regarding ``--resultlog`` deprecation. (:issue:`2739`)\n\n\npytest 3.2.1 (2017-08-08)\n=========================\n\nBug Fixes\n---------\n\n- Fixed small terminal glitch when collecting a single test item. (:issue:`2579`)\n\n- Correctly consider ``/`` as the file separator to automatically mark plugin\n  files for rewrite on Windows. (:issue:`2591`)\n\n- Properly escape test names when setting ``PYTEST_CURRENT_TEST`` environment\n  variable. (:issue:`2644`)\n\n- Fix error on Windows and Python 3.6+ when ``sys.stdout`` has been replaced\n  with a stream-like object which does not implement the full ``io`` module\n  buffer protocol. In particular this affects ``pytest-xdist`` users on the\n  aforementioned platform. (:issue:`2666`)\n\n\nImproved Documentation\n----------------------\n\n- Explicitly document which pytest features work with ``unittest``. (:issue:`2626`)\n\n\npytest 3.2.0 (2017-07-30)\n=========================\n\nDeprecations and Removals\n-------------------------\n\n- ``pytest.approx`` no longer supports ``>``, ``>=``, ``<`` and ``<=``\n  operators to avoid surprising/inconsistent behavior. See the :func:`~pytest.approx` docs for more\n  information. (:issue:`2003`)\n\n- All old-style specific behavior in current classes in the pytest's API is\n  considered deprecated at this point and will be removed in a future release.\n  This affects Python 2 users only and in rare situations. (:issue:`2147`)\n\n- A deprecation warning is now raised when using marks for parameters\n  in ``pytest.mark.parametrize``. Use ``pytest.param`` to apply marks to\n  parameters instead. (:issue:`2427`)\n\n\nFeatures\n--------\n\n- Add support for numpy arrays (and dicts) to approx. (:issue:`1994`)\n\n- Now test function objects have a ``pytestmark`` attribute containing a list\n  of marks applied directly to the test function, as opposed to marks inherited\n  from parent classes or modules. (:issue:`2516`)\n\n- Collection ignores local virtualenvs by default; ``--collect-in-virtualenv``\n  overrides this behavior. (:issue:`2518`)\n\n- Allow class methods decorated as ``@staticmethod`` to be candidates for\n  collection as a test function. (Only for Python 2.7 and above. Python 2.6\n  will still ignore static methods.) (:issue:`2528`)\n\n- Introduce ``mark.with_args`` in order to allow passing functions/classes as\n  sole argument to marks. (:issue:`2540`)\n\n- New ``cache_dir`` ini option: sets the directory where the contents of the\n  cache plugin are stored. Directory may be relative or absolute path: if relative path, then\n  directory is created relative to ``rootdir``, otherwise it is used as is.\n  Additionally path may contain environment variables which are expanded during\n  runtime. (:issue:`2543`)\n\n- Introduce the ``PYTEST_CURRENT_TEST`` environment variable that is set with\n  the ``nodeid`` and stage (``setup``, ``call`` and ``teardown``) of the test\n  being currently executed. See the :ref:`documentation <pytest current test env>`\n  for more info. (:issue:`2583`)\n\n- Introduced ``@pytest.mark.filterwarnings`` mark which allows overwriting the\n  warnings filter on a per test, class or module level. See the :ref:`docs <filterwarnings>`\n  for more information. (:issue:`2598`)\n\n- ``--last-failed`` now remembers forever when a test has failed and only\n  forgets it if it passes again. This makes it easy to fix a test suite by\n  selectively running files and fixing tests incrementally. (:issue:`2621`)\n\n- New ``pytest_report_collectionfinish`` hook which allows plugins to add\n  messages to the terminal reporting after collection has been finished\n  successfully. (:issue:`2622`)\n\n- Added support for :pep:`415`\\'s\n  ``Exception.__suppress_context__``. Now if a ``raise exception from None`` is\n  caught by pytest, pytest will no longer chain the context in the test report.\n  The behavior now matches Python's traceback behavior. (:issue:`2631`)\n\n- Exceptions raised by ``pytest.fail``, ``pytest.skip`` and ``pytest.xfail``\n  now subclass BaseException, making them harder to be caught unintentionally\n  by normal code. (:issue:`580`)\n\n\nBug Fixes\n---------\n\n- Set ``stdin`` to a closed ``PIPE`` in ``pytester.py.Testdir.popen()`` for\n  avoid unwanted interactive ``pdb`` (:issue:`2023`)\n\n- Add missing ``encoding`` attribute to ``sys.std*`` streams when using\n  ``capsys`` capture mode. (:issue:`2375`)\n\n- Fix terminal color changing to black on Windows if ``colorama`` is imported\n  in a ``conftest.py`` file. (:issue:`2510`)\n\n- Fix line number when reporting summary of skipped tests. (:issue:`2548`)\n\n- capture: ensure that EncodedFile.name is a string. (:issue:`2555`)\n\n- The options ``--fixtures`` and ``--fixtures-per-test`` will now keep\n  indentation within docstrings. (:issue:`2574`)\n\n- doctests line numbers are now reported correctly, fixing `pytest-sugar#122\n  <https://github.com/Frozenball/pytest-sugar/issues/122>`_. (:issue:`2610`)\n\n- Fix non-determinism in order of fixture collection. Adds new dependency\n  (ordereddict) for Python 2.6. (:issue:`920`)\n\n\nImproved Documentation\n----------------------\n\n- Clarify ``pytest_configure`` hook call order. (:issue:`2539`)\n\n- Extend documentation for testing plugin code with the ``pytester`` plugin.\n  (:issue:`971`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Update help message for ``--strict`` to make it clear it only deals with\n  unregistered markers, not warnings. (:issue:`2444`)\n\n- Internal code move: move code for pytest.approx/pytest.raises to own files in\n  order to cut down the size of python.py (:issue:`2489`)\n\n- Renamed the utility function ``_pytest.compat._escape_strings`` to\n  ``_ascii_escaped`` to better communicate the function's purpose. (:issue:`2533`)\n\n- Improve error message for CollectError with skip/skipif. (:issue:`2546`)\n\n- Emit warning about ``yield`` tests being deprecated only once per generator.\n  (:issue:`2562`)\n\n- Ensure final collected line doesn't include artifacts of previous write.\n  (:issue:`2571`)\n\n- Fixed all flake8 errors and warnings. (:issue:`2581`)\n\n- Added ``fix-lint`` tox environment to run automatic pep8 fixes on the code.\n  (:issue:`2582`)\n\n- Turn warnings into errors in pytest's own test suite in order to catch\n  regressions due to deprecations more promptly. (:issue:`2588`)\n\n- Show multiple issue links in CHANGELOG entries. (:issue:`2620`)\n\n\npytest 3.1.3 (2017-07-03)\n=========================\n\nBug Fixes\n---------\n\n- Fix decode error in Python 2 for doctests in docstrings. (:issue:`2434`)\n\n- Exceptions raised during teardown by finalizers are now suppressed until all\n  finalizers are called, with the initial exception reraised. (:issue:`2440`)\n\n- Fix incorrect \"collected items\" report when specifying tests on the command-\n  line. (:issue:`2464`)\n\n- ``deprecated_call`` in context-manager form now captures deprecation warnings\n  even if the same warning has already been raised. Also, ``deprecated_call``\n  will always produce the same error message (previously it would produce\n  different messages in context-manager vs. function-call mode). (:issue:`2469`)\n\n- Fix issue where paths collected by pytest could have triple leading ``/``\n  characters. (:issue:`2475`)\n\n- Fix internal error when trying to detect the start of a recursive traceback.\n  (:issue:`2486`)\n\n\nImproved Documentation\n----------------------\n\n- Explicitly state for which hooks the calls stop after the first non-None\n  result. (:issue:`2493`)\n\n\nTrivial/Internal Changes\n------------------------\n\n- Create invoke tasks for updating the vendored packages. (:issue:`2474`)\n\n- Update copyright dates in LICENSE, README.rst and in the documentation.\n  (:issue:`2499`)\n\n\npytest 3.1.2 (2017-06-08)\n=========================\n\nBug Fixes\n---------\n\n- Required options added via ``pytest_addoption`` will no longer prevent using\n  --help without passing them. (#1999)\n\n- Respect ``python_files`` in assertion rewriting. (#2121)\n\n- Fix recursion error detection when frames in the traceback contain objects\n  that can't be compared (like ``numpy`` arrays). (#2459)\n\n- ``UnicodeWarning`` is issued from the internal pytest warnings plugin only\n  when the message contains non-ascii unicode (Python 2 only). (#2463)\n\n- Added a workaround for Python 3.6 ``WindowsConsoleIO`` breaking due to Pytests's\n  ``FDCapture``. Other code using console handles might still be affected by the\n  very same issue and might require further workarounds/fixes, i.e. ``colorama``.\n  (#2467)\n\n\nImproved Documentation\n----------------------\n\n- Fix internal API links to ``pluggy`` objects. (#2331)\n\n- Make it clear that ``pytest.xfail`` stops test execution at the calling point\n  and improve overall flow of the ``skipping`` docs. (#810)\n\n\npytest 3.1.1 (2017-05-30)\n=========================\n\nBug Fixes\n---------\n\n- pytest warning capture no longer overrides existing warning filters. The\n  previous behaviour would override all filters and caused regressions in test\n  suites which configure warning filters to match their needs. Note that as a\n  side-effect of this is that ``DeprecationWarning`` and\n  ``PendingDeprecationWarning`` are no longer shown by default. (#2430)\n\n- Fix issue with non-ascii contents in doctest text files. (#2434)\n\n- Fix encoding errors for unicode warnings in Python 2. (#2436)\n\n- ``pytest.deprecated_call`` now captures ``PendingDeprecationWarning`` in\n  context manager form. (#2441)\n\n\nImproved Documentation\n----------------------\n\n- Addition of towncrier for changelog management. (#2390)\n\n\n3.1.0 (2017-05-22)\n==================\n\n\nNew Features\n------------\n\n* The ``pytest-warnings`` plugin has been integrated into the core and now ``pytest`` automatically\n  captures and displays warnings at the end of the test session.\n\n  .. warning::\n\n    This feature may disrupt test suites which apply and treat warnings themselves, and can be\n    disabled in your ``pytest.ini``:\n\n    .. code-block:: ini\n\n      [pytest]\n      addopts = -p no:warnings\n\n    See the :doc:`warnings documentation page <how-to/capture-warnings>` for more\n    information.\n\n  Thanks :user:`nicoddemus` for the PR.\n\n* Added ``junit_suite_name`` ini option to specify root ``<testsuite>`` name for JUnit XML reports (:issue:`533`).\n\n* Added an ini option ``doctest_encoding`` to specify which encoding to use for doctest files.\n  Thanks :user:`wheerd` for the PR (:pr:`2101`).\n\n* ``pytest.warns`` now checks for subclass relationship rather than\n  class equality. Thanks :user:`lesteve` for the PR (:pr:`2166`)\n\n* ``pytest.raises`` now asserts that the error message matches a text or regex\n  with the ``match`` keyword argument. Thanks :user:`Kriechi` for the PR.\n\n* ``pytest.param`` can be used to declare test parameter sets with marks and test ids.\n  Thanks :user:`RonnyPfannschmidt` for the PR.\n\n\nChanges\n-------\n\n* remove all internal uses of pytest_namespace hooks,\n  this is to prepare the removal of preloadconfig in pytest 4.0\n  Thanks to :user:`RonnyPfannschmidt` for the PR.\n\n* pytest now warns when a callable ids raises in a parametrized test. Thanks :user:`fogo` for the PR.\n\n* It is now possible to skip test classes from being collected by setting a\n  ``__test__`` attribute to ``False`` in the class body (:issue:`2007`). Thanks\n  to :user:`syre` for the report and :user:`lwm` for the PR.\n\n* Change junitxml.py to produce reports that comply with Junitxml schema.\n  If the same test fails with failure in call and then errors in teardown\n  we split testcase element into two, one containing the error and the other\n  the failure. (:issue:`2228`) Thanks to :user:`kkoukiou` for the PR.\n\n* Testcase reports with a ``url`` attribute will now properly write this to junitxml.\n  Thanks :user:`fushi` for the PR (:pr:`1874`).\n\n* Remove common items from dict comparison output when verbosity=1. Also update\n  the truncation message to make it clearer that pytest truncates all\n  assertion messages if verbosity < 2 (:issue:`1512`).\n  Thanks :user:`mattduck` for the PR\n\n* ``--pdbcls`` no longer implies ``--pdb``. This makes it possible to use\n  ``addopts=--pdbcls=module.SomeClass`` on ``pytest.ini``. Thanks :user:`davidszotten` for\n  the PR (:pr:`1952`).\n\n* fix :issue:`2013`: turn RecordedWarning into ``namedtuple``,\n  to give it a comprehensible repr while preventing unwarranted modification.\n\n* fix :issue:`2208`: ensure an iteration limit for ``_pytest.compat.get_real_func``.\n  Thanks :user:`RonnyPfannschmidt` for the report and PR.\n\n* Hooks are now verified after collection is complete, rather than right after loading installed plugins. This\n  makes it easy to write hooks for plugins which will be loaded during collection, for example using the\n  ``pytest_plugins`` special variable (:issue:`1821`).\n  Thanks :user:`nicoddemus` for the PR.\n\n* Modify ``pytest_make_parametrize_id()`` hook to accept ``argname`` as an\n  additional parameter.\n  Thanks :user:`unsignedint` for the PR.\n\n* Add ``venv`` to the default ``norecursedirs`` setting.\n  Thanks :user:`The-Compiler` for the PR.\n\n* ``PluginManager.import_plugin`` now accepts unicode plugin names in Python 2.\n  Thanks :user:`reutsharabani` for the PR.\n\n* fix :issue:`2308`: When using both ``--lf`` and ``--ff``, only the last failed tests are run.\n  Thanks :user:`ojii` for the PR.\n\n* Replace minor/patch level version numbers in the documentation with placeholders.\n  This significantly reduces change-noise as different contributors regenerate\n  the documentation on different platforms.\n  Thanks :user:`RonnyPfannschmidt` for the PR.\n\n* fix :issue:`2391`: consider pytest_plugins on all plugin modules\n  Thanks :user:`RonnyPfannschmidt` for the PR.\n\n\nBug Fixes\n---------\n\n* Fix ``AttributeError`` on ``sys.stdout.buffer`` / ``sys.stderr.buffer``\n  while using ``capsys`` fixture in python 3. (:issue:`1407`).\n  Thanks to :user:`asottile`.\n\n* Change capture.py's ``DontReadFromInput`` class to throw ``io.UnsupportedOperation`` errors rather\n  than ValueErrors in the ``fileno`` method (:issue:`2276`).\n  Thanks :user:`metasyn` and :user:`vlad-dragos` for the PR.\n\n* Fix exception formatting while importing modules when the exception message\n  contains non-ascii characters (:issue:`2336`).\n  Thanks :user:`fabioz` for the report and :user:`nicoddemus` for the PR.\n\n* Added documentation related to issue (:issue:`1937`)\n  Thanks :user:`skylarjhdownes` for the PR.\n\n* Allow collecting files with any file extension as Python modules (:issue:`2369`).\n  Thanks :user:`Kodiologist` for the PR.\n\n* Show the correct error message when collect \"parametrize\" func with wrong args (:issue:`2383`).\n  Thanks :user:`The-Compiler` for the report and :user:`robin0371` for the PR.\n\n\n3.0.7 (2017-03-14)\n==================\n\n\n* Fix issue in assertion rewriting breaking due to modules silently discarding\n  other modules when importing fails\n  Notably, importing the ``anydbm`` module is fixed. (:issue:`2248`).\n  Thanks :user:`pfhayes` for the PR.\n\n* junitxml: Fix problematic case where system-out tag occurred twice per testcase\n  element in the XML report. Thanks :user:`kkoukiou` for the PR.\n\n* Fix regression, pytest now skips unittest correctly if run with ``--pdb``\n  (:issue:`2137`). Thanks to :user:`gst` for the report and :user:`mbyt` for the PR.\n\n* Ignore exceptions raised from descriptors (e.g. properties) during Python test collection (:issue:`2234`).\n  Thanks to :user:`bluetech`.\n\n* ``--override-ini`` now correctly overrides some fundamental options like ``python_files`` (:issue:`2238`).\n  Thanks :user:`sirex` for the report and :user:`nicoddemus` for the PR.\n\n* Replace ``raise StopIteration`` usages in the code by simple ``returns`` to finish generators, in accordance to :pep:`479` (:issue:`2160`).\n  Thanks to :user:`nicoddemus` for the PR.\n\n* Fix internal errors when an unprintable ``AssertionError`` is raised inside a test.\n  Thanks :user:`omerhadari` for the PR.\n\n* Skipping plugin now also works with test items generated by custom collectors (:issue:`2231`).\n  Thanks to :user:`vidartf`.\n\n* Fix trailing whitespace in console output if no .ini file presented (:issue:`2281`). Thanks :user:`fbjorn` for the PR.\n\n* Conditionless ``xfail`` markers no longer rely on the underlying test item\n  being an instance of ``PyobjMixin``, and can therefore apply to tests not\n  collected by the built-in python test collector. Thanks :user:`barneygale` for the\n  PR.\n\n\n3.0.6 (2017-01-22)\n==================\n\n* pytest no longer generates ``PendingDeprecationWarning`` from its own operations, which was introduced by mistake in version ``3.0.5`` (:issue:`2118`).\n  Thanks to :user:`nicoddemus` for the report and :user:`RonnyPfannschmidt` for the PR.\n\n\n* pytest no longer recognizes coroutine functions as yield tests (:issue:`2129`).\n  Thanks to :user:`malinoff` for the PR.\n\n* Plugins loaded by the ``PYTEST_PLUGINS`` environment variable are now automatically\n  considered for assertion rewriting (:issue:`2185`).\n  Thanks :user:`nicoddemus` for the PR.\n\n* Improve error message when pytest.warns fails (:issue:`2150`). The type(s) of the\n  expected warnings and the list of caught warnings is added to the\n  error message. Thanks :user:`lesteve` for the PR.\n\n* Fix ``pytester`` internal plugin to work correctly with latest versions of\n  ``zope.interface`` (:issue:`1989`). Thanks :user:`nicoddemus` for the PR.\n\n* Assert statements of the ``pytester`` plugin again benefit from assertion rewriting (:issue:`1920`).\n  Thanks :user:`RonnyPfannschmidt` for the report and :user:`nicoddemus` for the PR.\n\n* Specifying tests with colons like ``test_foo.py::test_bar`` for tests in\n  subdirectories with ini configuration files now uses the correct ini file\n  (:issue:`2148`).  Thanks :user:`pelme`.\n\n* Fail ``testdir.runpytest().assert_outcomes()`` explicitly if the pytest\n  terminal output it relies on is missing. Thanks to :user:`eli-b` for the PR.\n\n\n3.0.5 (2016-12-05)\n==================\n\n* Add warning when not passing ``option=value`` correctly to ``-o/--override-ini`` (:issue:`2105`).\n  Also improved the help documentation. Thanks to :user:`mbukatov` for the report and\n  :user:`lwm` for the PR.\n\n* Now ``--confcutdir`` and ``--junit-xml`` are properly validated if they are directories\n  and filenames, respectively (:issue:`2089` and :issue:`2078`). Thanks to :user:`lwm` for the PR.\n\n* Add hint to error message hinting possible missing ``__init__.py`` (:issue:`478`). Thanks :user:`DuncanBetts`.\n\n* More accurately describe when fixture finalization occurs in documentation (:issue:`687`). Thanks :user:`DuncanBetts`.\n\n* Provide ``:ref:`` targets for ``recwarn.rst`` so we can use intersphinx referencing.\n  Thanks to :user:`dupuy` for the report and :user:`lwm` for the PR.\n\n* In Python 2, use a simple ``+-`` ASCII string in the string representation of ``pytest.approx`` (for example ``\"4 +- 4.0e-06\"``)\n  because it is brittle to handle that in different contexts and representations internally in pytest\n  which can result in bugs such as :issue:`2111`. In Python 3, the representation still uses ``±`` (for example ``4 ± 4.0e-06``).\n  Thanks :user:`kerrick-lyft` for the report and :user:`nicoddemus` for the PR.\n\n* Using ``item.Function``, ``item.Module``, etc., is now issuing deprecation warnings, prefer\n  ``pytest.Function``, ``pytest.Module``, etc., instead (:issue:`2034`).\n  Thanks :user:`nmundar` for the PR.\n\n* Fix error message using ``approx`` with complex numbers (:issue:`2082`).\n  Thanks :user:`adler-j` for the report and :user:`nicoddemus` for the PR.\n\n* Fixed false-positives warnings from assertion rewrite hook for modules imported more than\n  once by the ``pytest_plugins`` mechanism.\n  Thanks :user:`nicoddemus` for the PR.\n\n* Remove an internal cache which could cause hooks from ``conftest.py`` files in\n  sub-directories to be called in other directories incorrectly (:issue:`2016`).\n  Thanks :user:`d-b-w` for the report and :user:`nicoddemus` for the PR.\n\n* Remove internal code meant to support earlier Python 3 versions that produced the side effect\n  of leaving ``None`` in ``sys.modules`` when expressions were evaluated by pytest (for example passing a condition\n  as a string to ``pytest.mark.skipif``)(:issue:`2103`).\n  Thanks :user:`jaraco` for the report and :user:`nicoddemus` for the PR.\n\n* Cope gracefully with a .pyc file with no matching .py file (:issue:`2038`). Thanks\n  :user:`nedbat`.\n\n\n3.0.4 (2016-11-09)\n==================\n\n* Import errors when collecting test modules now display the full traceback (:issue:`1976`).\n  Thanks :user:`cwitty` for the report and :user:`nicoddemus` for the PR.\n\n* Fix confusing command-line help message for custom options with two or more ``metavar`` properties (:issue:`2004`).\n  Thanks :user:`okulynyak` and :user:`davehunt` for the report and :user:`nicoddemus` for the PR.\n\n* When loading plugins, import errors which contain non-ascii messages are now properly handled in Python 2 (:issue:`1998`).\n  Thanks :user:`nicoddemus` for the PR.\n\n* Fixed cyclic reference when ``pytest.raises`` is used in context-manager form (:issue:`1965`). Also as a\n  result of this fix, ``sys.exc_info()`` is left empty in both context-manager and function call usages.\n  Previously, ``sys.exc_info`` would contain the exception caught by the context manager,\n  even when the expected exception occurred.\n  Thanks :user:`MSeifert04` for the report and the PR.\n\n* Fixed false-positives warnings from assertion rewrite hook for modules that were rewritten but\n  were later marked explicitly by ``pytest.register_assert_rewrite``\n  or implicitly as a plugin (:issue:`2005`).\n  Thanks :user:`RonnyPfannschmidt` for the report and :user:`nicoddemus` for the PR.\n\n* Report teardown output on test failure (:issue:`442`).\n  Thanks :user:`matclab` for the PR.\n\n* Fix teardown error message in generated xUnit XML.\n  Thanks :user:`gdyuldin` for the PR.\n\n* Properly handle exceptions in ``multiprocessing`` tasks (:issue:`1984`).\n  Thanks :user:`adborden` for the report and :user:`nicoddemus` for the PR.\n\n* Clean up unittest TestCase objects after tests are complete (:issue:`1649`).\n  Thanks :user:`d-b-w` for the report and PR.\n\n\n3.0.3 (2016-09-28)\n==================\n\n* The ``ids`` argument to ``parametrize`` again accepts ``unicode`` strings\n  in Python 2 (:issue:`1905`).\n  Thanks :user:`philpep` for the report and :user:`nicoddemus` for the PR.\n\n* Assertions are now being rewritten for plugins in development mode\n  (``pip install -e``) (:issue:`1934`).\n  Thanks :user:`nicoddemus` for the PR.\n\n* Fix pkg_resources import error in Jython projects (:issue:`1853`).\n  Thanks :user:`raquelalegre` for the PR.\n\n* Got rid of ``AttributeError: 'Module' object has no attribute '_obj'`` exception\n  in Python 3 (:issue:`1944`).\n  Thanks :user:`axil` for the PR.\n\n* Explain a bad scope value passed to ``@fixture`` declarations or\n  a ``MetaFunc.parametrize()`` call.\n\n* This version includes ``pluggy-0.4.0``, which correctly handles\n  ``VersionConflict`` errors in plugins (:issue:`704`).\n  Thanks :user:`nicoddemus` for the PR.\n\n\n3.0.2 (2016-09-01)\n==================\n\n* Improve error message when passing non-string ids to ``pytest.mark.parametrize`` (:issue:`1857`).\n  Thanks :user:`okken` for the report and :user:`nicoddemus` for the PR.\n\n* Add ``buffer`` attribute to stdin stub class ``pytest.capture.DontReadFromInput``\n  Thanks :user:`joguSD` for the PR.\n\n* Fix ``UnicodeEncodeError`` when string comparison with unicode has failed. (:issue:`1864`)\n  Thanks :user:`AiOO` for the PR.\n\n* ``pytest_plugins`` is now handled correctly if defined as a string (as opposed as\n  a sequence of strings) when modules are considered for assertion rewriting.\n  Due to this bug, much more modules were being rewritten than necessary\n  if a test suite uses ``pytest_plugins`` to load internal plugins (:issue:`1888`).\n  Thanks :user:`jaraco` for the report and :user:`nicoddemus` for the PR (:pr:`1891`).\n\n* Do not call tearDown and cleanups when running tests from\n  ``unittest.TestCase`` subclasses with ``--pdb``\n  enabled. This allows proper post mortem debugging for all applications\n  which have significant logic in their tearDown machinery (:issue:`1890`). Thanks\n  :user:`mbyt` for the PR.\n\n* Fix use of deprecated ``getfuncargvalue`` method in the internal doctest plugin.\n  Thanks :user:`ViviCoder` for the report (:issue:`1898`).\n\n\n3.0.1 (2016-08-23)\n==================\n\n* Fix regression when ``importorskip`` is used at module level (:issue:`1822`).\n  Thanks :user:`jaraco` and :user:`The-Compiler` for the report and :user:`nicoddemus` for the PR.\n\n* Fix parametrization scope when session fixtures are used in conjunction\n  with normal parameters in the same call (:issue:`1832`).\n  Thanks :user:`The-Compiler` for the report, :user:`Kingdread` and :user:`nicoddemus` for the PR.\n\n* Fix internal error when parametrizing tests or fixtures using an empty ``ids`` argument (:issue:`1849`).\n  Thanks :user:`OPpuolitaival` for the report and :user:`nicoddemus` for the PR.\n\n* Fix loader error when running ``pytest`` embedded in a zipfile.\n  Thanks :user:`mbachry` for the PR.\n\n\n.. _release-3.0.0:\n\n3.0.0 (2016-08-18)\n==================\n\n**Incompatible changes**\n\n\nA number of incompatible changes were made in this release, with the intent of removing features deprecated for a long\ntime or change existing behaviors in order to make them less surprising/more useful.\n\n* Reinterpretation mode has now been removed.  Only plain and rewrite\n  mode are available, consequently the ``--assert=reinterp`` option is\n  no longer available.  This also means files imported from plugins or\n  ``conftest.py`` will not benefit from improved assertions by\n  default, you should use ``pytest.register_assert_rewrite()`` to\n  explicitly turn on assertion rewriting for those files.  Thanks\n  :user:`flub` for the PR.\n\n* The following deprecated commandline options were removed:\n\n  * ``--genscript``: no longer supported;\n  * ``--no-assert``: use ``--assert=plain`` instead;\n  * ``--nomagic``: use ``--assert=plain`` instead;\n  * ``--report``: use ``-r`` instead;\n\n  Thanks to :user:`RedBeardCode` for the PR (:pr:`1664`).\n\n* ImportErrors in plugins now are a fatal error instead of issuing a\n  pytest warning (:issue:`1479`). Thanks to :user:`The-Compiler` for the PR.\n\n* Removed support code for Python 3 versions < 3.3 (:pr:`1627`).\n\n* Removed all ``py.test-X*`` entry points. The versioned, suffixed entry points\n  were never documented and a leftover from a pre-virtualenv era. These entry\n  points also created broken entry points in wheels, so removing them also\n  removes a source of confusion for users (:issue:`1632`).\n  Thanks :user:`obestwalter` for the PR.\n\n* ``pytest.skip()`` now raises an error when used to decorate a test function,\n  as opposed to its original intent (to imperatively skip a test inside a test function). Previously\n  this usage would cause the entire module to be skipped (:issue:`607`).\n  Thanks :user:`omarkohl` for the complete PR (:pr:`1519`).\n\n* Exit tests if a collection error occurs. A poll indicated most users will hit CTRL-C\n  anyway as soon as they see collection errors, so pytest might as well make that the default behavior (:issue:`1421`).\n  A ``--continue-on-collection-errors`` option has been added to restore the previous behaviour.\n  Thanks :user:`olegpidsadnyi` and :user:`omarkohl` for the complete PR (:pr:`1628`).\n\n* Renamed the pytest ``pdb`` module (plugin) into ``debugging`` to avoid clashes with the builtin ``pdb`` module.\n\n* Raise a helpful failure message when requesting a parametrized fixture at runtime,\n  e.g. with ``request.getfixturevalue``. Previously these parameters were simply\n  never defined, so a fixture decorated like ``@pytest.fixture(params=[0, 1, 2])``\n  only ran once (:pr:`460`).\n  Thanks to :user:`nikratio` for the bug report, :user:`RedBeardCode` and :user:`tomviner` for the PR.\n\n* ``_pytest.monkeypatch.monkeypatch`` class has been renamed to ``_pytest.monkeypatch.MonkeyPatch``\n  so it doesn't conflict with the ``monkeypatch`` fixture.\n\n* ``--exitfirst / -x`` can now be overridden by a following ``--maxfail=N``\n  and is just a synonym for ``--maxfail=1``.\n\n\n**New Features**\n\n* Support nose-style ``__test__`` attribute on methods of classes,\n  including unittest-style Classes. If set to ``False``, the test will not be\n  collected.\n\n* New ``doctest_namespace`` fixture for injecting names into the\n  namespace in which doctests run.\n  Thanks :user:`milliams` for the complete PR (:pr:`1428`).\n\n* New ``--doctest-report`` option available to change the output format of diffs\n  when running (failing) doctests (implements :issue:`1749`).\n  Thanks :user:`hartym` for the PR.\n\n* New ``name`` argument to ``pytest.fixture`` decorator which allows a custom name\n  for a fixture (to solve the funcarg-shadowing-fixture problem).\n  Thanks :user:`novas0x2a` for the complete PR (:pr:`1444`).\n\n* New ``approx()`` function for easily comparing floating-point numbers in\n  tests.\n  Thanks :user:`kalekundert` for the complete PR (:pr:`1441`).\n\n* Ability to add global properties in the final xunit output file by accessing\n  the internal ``junitxml`` plugin (experimental).\n  Thanks :user:`tareqalayan` for the complete PR :pr:`1454`).\n\n* New ``ExceptionInfo.match()`` method to match a regular expression on the\n  string representation of an exception (:issue:`372`).\n  Thanks :user:`omarkohl` for the complete PR (:pr:`1502`).\n\n* ``__tracebackhide__`` can now also be set to a callable which then can decide\n  whether to filter the traceback based on the ``ExceptionInfo`` object passed\n  to it. Thanks :user:`The-Compiler` for the complete PR (:pr:`1526`).\n\n* New ``pytest_make_parametrize_id(config, val)`` hook which can be used by plugins to provide\n  friendly strings for custom types.\n  Thanks :user:`palaviv` for the PR.\n\n* ``capsys`` and ``capfd`` now have a ``disabled()`` context-manager method, which\n  can be used to temporarily disable capture within a test.\n  Thanks :user:`nicoddemus` for the PR.\n\n* New cli flag ``--fixtures-per-test``: shows which fixtures are being used\n  for each selected test item. Features doc strings of fixtures by default.\n  Can also show where fixtures are defined if combined with ``-v``.\n  Thanks :user:`hackebrot` for the PR.\n\n* Introduce ``pytest`` command as recommended entry point. Note that ``py.test``\n  still works and is not scheduled for removal. Closes proposal\n  :issue:`1629`. Thanks :user:`obestwalter` and :user:`davehunt` for the complete PR\n  (:pr:`1633`).\n\n* New cli flags:\n\n  + ``--setup-plan``: performs normal collection and reports\n    the potential setup and teardown and does not execute any fixtures and tests;\n  + ``--setup-only``: performs normal collection, executes setup and teardown of\n    fixtures and reports them;\n  + ``--setup-show``: performs normal test execution and additionally shows\n    setup and teardown of fixtures;\n  + ``--keep-duplicates``: py.test now ignores duplicated paths given in the command\n    line. To retain the previous behavior where the same test could be run multiple\n    times by specifying it in the command-line multiple times, pass the ``--keep-duplicates``\n    argument (:issue:`1609`);\n\n  Thanks :user:`d6e`, :user:`kvas-it`, :user:`sallner`, :user:`ioggstream` and :user:`omarkohl` for the PRs.\n\n* New CLI flag ``--override-ini``/``-o``: overrides values from the ini file.\n  For example: ``\"-o xfail_strict=True\"``'.\n  Thanks :user:`blueyed` and :user:`fengxx` for the PR.\n\n* New hooks:\n\n  + ``pytest_fixture_setup(fixturedef, request)``: executes fixture setup;\n  + ``pytest_fixture_post_finalizer(fixturedef)``: called after the fixture's\n    finalizer and has access to the fixture's result cache.\n\n  Thanks :user:`d6e`, :user:`sallner`.\n\n* Issue warnings for asserts whose test is a tuple literal. Such asserts will\n  never fail because tuples are always truthy and are usually a mistake\n  (see :issue:`1562`). Thanks :user:`kvas-it`, for the PR.\n\n* Allow passing a custom debugger class (e.g. ``--pdbcls=IPython.core.debugger:Pdb``).\n  Thanks to :user:`anntzer` for the PR.\n\n\n**Changes**\n\n* Plugins now benefit from assertion rewriting.  Thanks\n  :user:`sober7`, :user:`nicoddemus` and :user:`flub` for the PR.\n\n* Change ``report.outcome`` for ``xpassed`` tests to ``\"passed\"`` in non-strict\n  mode and ``\"failed\"`` in strict mode. Thanks to :user:`hackebrot` for the PR\n  (:pr:`1795`) and :user:`gprasad84` for report (:issue:`1546`).\n\n* Tests marked with ``xfail(strict=False)`` (the default) now appear in\n  JUnitXML reports as passing tests instead of skipped.\n  Thanks to :user:`hackebrot` for the PR (:pr:`1795`).\n\n* Highlight path of the file location in the error report to make it easier to copy/paste.\n  Thanks :user:`suzaku` for the PR (:pr:`1778`).\n\n* Fixtures marked with ``@pytest.fixture`` can now use ``yield`` statements exactly like\n  those marked with the ``@pytest.yield_fixture`` decorator. This change renders\n  ``@pytest.yield_fixture`` deprecated and makes ``@pytest.fixture`` with ``yield`` statements\n  the preferred way to write teardown code (:pr:`1461`).\n  Thanks :user:`csaftoiu` for bringing this to attention and :user:`nicoddemus` for the PR.\n\n* Explicitly passed parametrize ids do not get escaped to ascii (:issue:`1351`).\n  Thanks :user:`ceridwen` for the PR.\n\n* Fixtures are now sorted in the error message displayed when an unknown\n  fixture is declared in a test function.\n  Thanks :user:`nicoddemus` for the PR.\n\n* ``pytest_terminal_summary`` hook now receives the ``exitstatus``\n  of the test session as argument. Thanks :user:`blueyed` for the PR (:pr:`1809`).\n\n* Parametrize ids can accept ``None`` as specific test id, in which case the\n  automatically generated id for that argument will be used.\n  Thanks :user:`palaviv` for the complete PR (:pr:`1468`).\n\n* The parameter to xunit-style setup/teardown methods (``setup_method``,\n  ``setup_module``, etc.) is now optional and may be omitted.\n  Thanks :user:`okken` for bringing this to attention and :user:`nicoddemus` for the PR.\n\n* Improved automatic id generation selection in case of duplicate ids in\n  parametrize.\n  Thanks :user:`palaviv` for the complete PR (:pr:`1474`).\n\n* Now pytest warnings summary is shown up by default. Added a new flag\n  ``--disable-pytest-warnings`` to explicitly disable the warnings summary (:issue:`1668`).\n\n* Make ImportError during collection more explicit by reminding\n  the user to check the name of the test module/package(s) (:issue:`1426`).\n  Thanks :user:`omarkohl` for the complete PR (:pr:`1520`).\n\n* Add ``build/`` and ``dist/`` to the default ``--norecursedirs`` list. Thanks\n  :user:`mikofski` for the report and :user:`tomviner` for the PR (:issue:`1544`).\n\n* ``pytest.raises`` in the context manager form accepts a custom\n  ``message`` to raise when no exception occurred.\n  Thanks :user:`palaviv` for the complete PR (:pr:`1616`).\n\n* ``conftest.py`` files now benefit from assertion rewriting; previously it\n  was only available for test modules. Thanks :user:`flub`, :user:`sober7` and\n  :user:`nicoddemus` for the PR (:issue:`1619`).\n\n* Text documents without any doctests no longer appear as \"skipped\".\n  Thanks :user:`graingert` for reporting and providing a full PR (:pr:`1580`).\n\n* Ensure that a module within a namespace package can be found when it\n  is specified on the command line together with the ``--pyargs``\n  option.  Thanks to :user:`taschini` for the PR (:pr:`1597`).\n\n* Always include full assertion explanation during assertion rewriting. The previous behaviour was hiding\n  sub-expressions that happened to be ``False``, assuming this was redundant information.\n  Thanks :user:`bagerard` for reporting (:issue:`1503`). Thanks to :user:`davehunt` and\n  :user:`tomviner` for the PR.\n\n* ``OptionGroup.addoption()`` now checks if option names were already\n  added before, to make it easier to track down issues like :issue:`1618`.\n  Before, you only got exceptions later from ``argparse`` library,\n  giving no clue about the actual reason for double-added options.\n\n* ``yield``-based tests are considered deprecated and will be removed in pytest-4.0.\n  Thanks :user:`nicoddemus` for the PR.\n\n* ``[pytest]`` sections in ``setup.cfg`` files should now be named ``[tool:pytest]``\n  to avoid conflicts with other distutils commands (see :pr:`567`). ``[pytest]`` sections in\n  ``pytest.ini`` or ``tox.ini`` files are supported and unchanged.\n  Thanks :user:`nicoddemus` for the PR.\n\n* Using ``pytest_funcarg__`` prefix to declare fixtures is considered deprecated and will be\n  removed in pytest-4.0 (:pr:`1684`).\n  Thanks :user:`nicoddemus` for the PR.\n\n* Passing a command-line string to ``pytest.main()`` is considered deprecated and scheduled\n  for removal in pytest-4.0. It is recommended to pass a list of arguments instead (:pr:`1723`).\n\n* Rename ``getfuncargvalue`` to ``getfixturevalue``. ``getfuncargvalue`` is\n  still present but is now considered deprecated. Thanks to :user:`RedBeardCode` and :user:`tomviner`\n  for the PR (:pr:`1626`).\n\n* ``optparse`` type usage now triggers DeprecationWarnings (:issue:`1740`).\n\n\n* ``optparse`` backward compatibility supports float/complex types (:issue:`457`).\n\n* Refined logic for determining the ``rootdir``, considering only valid\n  paths which fixes a number of issues: :issue:`1594`, :issue:`1435` and :issue:`1471`.\n  Updated the documentation according to current behavior. Thanks to\n  :user:`blueyed`, :user:`davehunt` and :user:`matthiasha` for the PR.\n\n* Always include full assertion explanation. The previous behaviour was hiding\n  sub-expressions that happened to be False, assuming this was redundant information.\n  Thanks :user:`bagerard` for reporting (:issue:`1503`). Thanks to :user:`davehunt` and\n  :user:`tomviner` for PR.\n\n* Better message in case of not using parametrized variable (see :issue:`1539`).\n  Thanks to :user:`tramwaj29` for the PR.\n\n* Updated docstrings with a more uniform style.\n\n* Add stderr write for ``pytest.exit(msg)`` during startup. Previously the message was never shown.\n  Thanks :user:`BeyondEvil` for reporting :issue:`1210`. Thanks to @jgsonesen and\n  :user:`tomviner` for the PR.\n\n* No longer display the incorrect test deselection reason (:issue:`1372`).\n  Thanks :user:`ronnypfannschmidt` for the PR.\n\n* The ``--resultlog`` command line option has been deprecated: it is little used\n  and there are more modern and better alternatives (see :issue:`830`).\n  Thanks :user:`nicoddemus` for the PR.\n\n* Improve error message with fixture lookup errors: add an 'E' to the first\n  line and '>' to the rest. Fixes :issue:`717`. Thanks :user:`blueyed` for reporting and\n  a PR, :user:`eolo999` for the initial PR and :user:`tomviner` for his guidance during\n  EuroPython2016 sprint.\n\n\n**Bug Fixes**\n\n* Parametrize now correctly handles duplicated test ids.\n\n* Fix internal error issue when the ``method`` argument is missing for\n  ``teardown_method()`` (:issue:`1605`).\n\n* Fix exception visualization in case the current working directory (CWD) gets\n  deleted during testing (:issue:`1235`). Thanks :user:`bukzor` for reporting. PR by\n  :user:`marscher`.\n\n* Improve test output for logical expression with brackets (:issue:`925`).\n  Thanks :user:`DRMacIver` for reporting and :user:`RedBeardCode` for the PR.\n\n* Create correct diff for strings ending with newlines (:issue:`1553`).\n  Thanks :user:`Vogtinator` for reporting and :user:`RedBeardCode` and\n  :user:`tomviner` for the PR.\n\n* ``ConftestImportFailure`` now shows the traceback making it easier to\n  identify bugs in ``conftest.py`` files (:pr:`1516`). Thanks :user:`txomon` for\n  the PR.\n\n* Text documents without any doctests no longer appear as \"skipped\".\n  Thanks :user:`graingert` for reporting and providing a full PR (:pr:`1580`).\n\n* Fixed collection of classes with custom ``__new__`` method.\n  Fixes :issue:`1579`. Thanks to :user:`Stranger6667` for the PR.\n\n* Fixed scope overriding inside metafunc.parametrize (:issue:`634`).\n  Thanks to :user:`Stranger6667` for the PR.\n\n* Fixed the total tests tally in junit xml output (:pr:`1798`).\n  Thanks to :user:`cboelsen` for the PR.\n\n* Fixed off-by-one error with lines from ``request.node.warn``.\n  Thanks to :user:`blueyed` for the PR.\n\n\n2.9.2 (2016-05-31)\n==================\n\n**Bug Fixes**\n\n* fix :issue:`510`: skip tests where one parameterize dimension was empty\n  thanks Alex Stapleton for the Report and :user:`RonnyPfannschmidt` for the PR\n\n* Fix Xfail does not work with condition keyword argument.\n  Thanks :user:`astraw38` for reporting the issue (:issue:`1496`) and :user:`tomviner`\n  for PR the (:pr:`1524`).\n\n* Fix win32 path issue when putting custom config file with absolute path\n  in ``pytest.main(\"-c your_absolute_path\")``.\n\n* Fix maximum recursion depth detection when raised error class is not aware\n  of unicode/encoded bytes.\n  Thanks :user:`prusse-martin` for the PR (:pr:`1506`).\n\n* Fix ``pytest.mark.skip`` mark when used in strict mode.\n  Thanks :user:`pquentin` for the PR and :user:`RonnyPfannschmidt` for\n  showing how to fix the bug.\n\n* Minor improvements and fixes to the documentation.\n  Thanks :user:`omarkohl` for the PR.\n\n* Fix ``--fixtures`` to show all fixture definitions as opposed to just\n  one per fixture name.\n  Thanks to :user:`hackebrot` for the PR.\n\n\n2.9.1 (2016-03-17)\n==================\n\n**Bug Fixes**\n\n* Improve error message when a plugin fails to load.\n  Thanks :user:`nicoddemus` for the PR.\n\n* Fix (:issue:`1178`):\n  ``pytest.fail`` with non-ascii characters raises an internal pytest error.\n  Thanks :user:`nicoddemus` for the PR.\n\n* Fix (:issue:`469`): junit parses report.nodeid incorrectly, when params IDs\n  contain ``::``. Thanks :user:`tomviner` for the PR (:pr:`1431`).\n\n* Fix (:issue:`578`): SyntaxErrors\n  containing non-ascii lines at the point of failure generated an internal\n  py.test error.\n  Thanks :user:`asottile` for the report and :user:`nicoddemus` for the PR.\n\n* Fix (:issue:`1437`): When passing in a bytestring regex pattern to parameterize\n  attempt to decode it as utf-8 ignoring errors.\n\n* Fix (:issue:`649`): parametrized test nodes cannot be specified to run on the command line.\n\n* Fix (:issue:`138`): better reporting for python 3.3+ chained exceptions\n\n\n2.9.0 (2016-02-29)\n==================\n\n**New Features**\n\n* New ``pytest.mark.skip`` mark, which unconditionally skips marked tests.\n  Thanks :user:`MichaelAquilina` for the complete PR (:pr:`1040`).\n\n* ``--doctest-glob`` may now be passed multiple times in the command-line.\n  Thanks :user:`jab` and :user:`nicoddemus` for the PR.\n\n* New ``-rp`` and ``-rP`` reporting options give the summary and full output\n  of passing tests, respectively. Thanks to :user:`codewarrior0` for the PR.\n\n* ``pytest.mark.xfail`` now has a ``strict`` option, which makes ``XPASS``\n  tests to fail the test suite (defaulting to ``False``). There's also a\n  ``xfail_strict`` ini option that can be used to configure it project-wise.\n  Thanks :user:`rabbbit` for the request and :user:`nicoddemus` for the PR (:pr:`1355`).\n\n* ``Parser.addini`` now supports options of type ``bool``.\n  Thanks :user:`nicoddemus` for the PR.\n\n* New ``ALLOW_BYTES`` doctest option. This strips ``b`` prefixes from byte strings\n  in doctest output (similar to ``ALLOW_UNICODE``).\n  Thanks :user:`jaraco` for the request and :user:`nicoddemus` for the PR (:pr:`1287`).\n\n* Give a hint on ``KeyboardInterrupt`` to use the ``--fulltrace`` option to show the errors.\n  Fixes :issue:`1366`.\n  Thanks to :user:`hpk42` for the report and :user:`RonnyPfannschmidt` for the PR.\n\n* Catch ``IndexError`` exceptions when getting exception source location.\n  Fixes a pytest internal error for dynamically generated code (fixtures and tests)\n  where source lines are fake by intention.\n\n**Changes**\n\n* **Important**: `py.code <https://pylib.readthedocs.io/en/stable/code.html>`_ has been\n  merged into the ``pytest`` repository as ``pytest._code``. This decision\n  was made because ``py.code`` had very few uses outside ``pytest`` and the\n  fact that it was in a different repository made it difficult to fix bugs on\n  its code in a timely manner. The team hopes with this to be able to better\n  refactor out and improve that code.\n  This change shouldn't affect users, but it is useful to let users aware\n  if they encounter any strange behavior.\n\n  Keep in mind that the code for ``pytest._code`` is **private** and\n  **experimental**, so you definitely should not import it explicitly!\n\n  Please note that the original ``py.code`` is still available in\n  `pylib <https://pylib.readthedocs.io>`_.\n\n* ``pytest_enter_pdb`` now optionally receives the pytest config object.\n  Thanks :user:`nicoddemus` for the PR.\n\n* Removed code and documentation for Python 2.5 or lower versions,\n  including removal of the obsolete ``_pytest.assertion.oldinterpret`` module.\n  Thanks :user:`nicoddemus` for the PR (:pr:`1226`).\n\n* Comparisons now always show up in full when ``CI`` or ``BUILD_NUMBER`` is\n  found in the environment, even when ``-vv`` isn't used.\n  Thanks :user:`The-Compiler` for the PR.\n\n* ``--lf`` and ``--ff`` now support long names: ``--last-failed`` and\n  ``--failed-first`` respectively.\n  Thanks :user:`MichaelAquilina` for the PR.\n\n* Added expected exceptions to ``pytest.raises`` fail message.\n\n* Collection only displays progress (\"collecting X items\") when in a terminal.\n  This avoids cluttering the output when using ``--color=yes`` to obtain\n  colors in CI integrations systems (:issue:`1397`).\n\n**Bug Fixes**\n\n* The ``-s`` and ``-c`` options should now work under ``xdist``;\n  ``Config.fromdictargs`` now represents its input much more faithfully.\n  Thanks to :user:`bukzor` for the complete PR (:issue:`680`).\n\n* Fix (:issue:`1290`): support Python 3.5's ``@`` operator in assertion rewriting.\n  Thanks :user:`Shinkenjoe` for report with test case and :user:`tomviner` for the PR.\n\n* Fix formatting utf-8 explanation messages (:issue:`1379`).\n  Thanks :user:`biern` for the PR.\n\n* Fix :ref:`traceback style docs <how-to-modifying-python-tb-printing>` to describe all of the available options\n  (auto/long/short/line/native/no), with ``auto`` being the default since v2.6.\n  Thanks :user:`hackebrot` for the PR.\n\n* Fix (:issue:`1422`): junit record_xml_property doesn't allow multiple records\n  with same name.\n\n\n2.8.7 (2016-01-24)\n==================\n\n- fix #1338: use predictable object resolution for monkeypatch\n\n2.8.6 (2016-01-21)\n==================\n\n- fix #1259: allow for double nodeids in junitxml,\n  this was a regression failing plugins combinations\n  like pytest-pep8 + pytest-flakes\n\n- Workaround for exception that occurs in pyreadline when using\n  ``--pdb`` with standard I/O capture enabled.\n  Thanks Erik M. Bray for the PR.\n\n- fix #900: Better error message in case the target of a ``monkeypatch`` call\n  raises an ``ImportError``.\n\n- fix #1292: monkeypatch calls (setattr, setenv, etc.) are now O(1).\n  Thanks David R. MacIver for the report and Bruno Oliveira for the PR.\n\n- fix #1223: captured stdout and stderr are now properly displayed before\n  entering pdb when ``--pdb`` is used instead of being thrown away.\n  Thanks Cal Leeming for the PR.\n\n- fix #1305: pytest warnings emitted during ``pytest_terminal_summary`` are now\n  properly displayed.\n  Thanks Ionel Maries Cristian for the report and Bruno Oliveira for the PR.\n\n- fix #628: fixed internal UnicodeDecodeError when doctests contain unicode.\n  Thanks Jason R. Coombs for the report and Bruno Oliveira for the PR.\n\n- fix #1334: Add captured stdout to jUnit XML report on setup error.\n  Thanks Georgy Dyuldin for the PR.\n\n\n2.8.5 (2015-12-11)\n==================\n\n- fix #1243: fixed issue where class attributes injected during collection could break pytest.\n  PR by Alexei Kozlenok, thanks Ronny Pfannschmidt and Bruno Oliveira for the review and help.\n\n- fix #1074: precompute junitxml chunks instead of storing the whole tree in objects\n  Thanks Bruno Oliveira for the report and Ronny Pfannschmidt for the PR\n\n- fix #1238: fix ``pytest.deprecated_call()`` receiving multiple arguments\n  (Regression introduced in 2.8.4). Thanks Alex Gaynor for the report and\n  Bruno Oliveira for the PR.\n\n\n2.8.4 (2015-12-06)\n==================\n\n- fix #1190: ``deprecated_call()`` now works when the deprecated\n  function has been already called by another test in the same\n  module. Thanks Mikhail Chernykh for the report and Bruno Oliveira for the\n  PR.\n\n- fix #1198: ``--pastebin`` option now works on Python 3. Thanks\n  Mehdy Khoshnoody for the PR.\n\n- fix #1219: ``--pastebin`` now works correctly when captured output contains\n  non-ascii characters. Thanks Bruno Oliveira for the PR.\n\n- fix #1204: another error when collecting with a nasty __getattr__().\n  Thanks Freya Bruhin for the PR.\n\n- fix the summary printed when no tests did run.\n  Thanks Freya Bruhin for the PR.\n- fix #1185 - ensure MANIFEST.in exactly matches what should go to a sdist\n\n- a number of documentation modernizations wrt good practices.\n  Thanks Bruno Oliveira for the PR.\n\n2.8.3 (2015-11-18)\n==================\n\n- fix #1169: add __name__ attribute to testcases in TestCaseFunction to\n  support the @unittest.skip decorator on functions and methods.\n  Thanks Lee Kamentsky for the PR.\n\n- fix #1035: collecting tests if test module level obj has __getattr__().\n  Thanks Suor for the report and Bruno Oliveira / Tom Viner for the PR.\n\n- fix #331: don't collect tests if their failure cannot be reported correctly\n  e.g. they are a callable instance of a class.\n\n- fix #1133: fixed internal error when filtering tracebacks where one entry\n  belongs to a file which is no longer available.\n  Thanks Bruno Oliveira for the PR.\n\n- enhancement made to highlight in red the name of the failing tests so\n  they stand out in the output.\n  Thanks Gabriel Reis for the PR.\n\n- add more talks to the documentation\n- extend documentation on the --ignore cli option\n- use pytest-runner for setuptools integration\n- minor fixes for interaction with OS X El Capitan\n  system integrity protection (thanks Florian)\n\n\n2.8.2 (2015-10-07)\n==================\n\n- fix #1085: proper handling of encoding errors when passing encoded byte\n  strings to pytest.parametrize in Python 2.\n  Thanks Themanwithoutaplan for the report and Bruno Oliveira for the PR.\n\n- fix #1087: handling SystemError when passing empty byte strings to\n  pytest.parametrize in Python 3.\n  Thanks Paul Kehrer for the report and Bruno Oliveira for the PR.\n\n- fix #995: fixed internal error when filtering tracebacks where one entry\n  was generated by an exec() statement.\n  Thanks Daniel Hahler, Ashley C Straw, Philippe Gauthier and Pavel Savchenko\n  for contributing and Bruno Oliveira for the PR.\n\n- fix #1100 and #1057: errors when using autouse fixtures and doctest modules.\n  Thanks Sergey B Kirpichev and Vital Kudzelka for contributing and Bruno\n  Oliveira for the PR.\n\n2.8.1 (2015-09-29)\n==================\n\n- fix #1034: Add missing nodeid on pytest_logwarning call in\n  addhook.  Thanks Simon Gomizelj for the PR.\n\n- 'deprecated_call' is now only satisfied with a DeprecationWarning or\n  PendingDeprecationWarning. Before 2.8.0, it accepted any warning, and 2.8.0\n  made it accept only DeprecationWarning (but not PendingDeprecationWarning).\n  Thanks Alex Gaynor for the issue and Eric Hunsberger for the PR.\n\n- fix issue #1073: avoid calling __getattr__ on potential plugin objects.\n  This fixes an incompatibility with pytest-django.  Thanks Andreas Pelme,\n  Bruno Oliveira and Ronny Pfannschmidt for contributing and Holger Krekel\n  for the fix.\n\n- Fix issue #704: handle versionconflict during plugin loading more\n  gracefully.  Thanks Bruno Oliveira for the PR.\n\n- Fix issue #1064: \"\"--junitxml\" regression when used with the\n  \"pytest-xdist\" plugin, with test reports being assigned to the wrong tests.\n  Thanks Daniel Grunwald for the report and Bruno Oliveira for the PR.\n\n- (experimental) adapt more SEMVER style versioning and change meaning of\n  master branch in git repo: \"master\" branch now keeps the bug fixes, changes\n  aimed for micro releases.  \"features\" branch will only be released\n  with minor or major pytest releases.\n\n- Fix issue #766 by removing documentation references to distutils.\n  Thanks Russel Winder.\n\n- Fix issue #1030: now byte-strings are escaped to produce item node ids\n  to make them always serializable.\n  Thanks Andy Freeland for the report and Bruno Oliveira for the PR.\n\n- Python 2: if unicode parametrized values are convertible to ascii, their\n  ascii representation is used for the node id.\n\n- Fix issue #411: Add __eq__ method to assertion comparison example.\n  Thanks Ben Webb.\n- Fix issue #653: deprecated_call can be used as context manager.\n\n- fix issue 877: properly handle assertion explanations with non-ascii repr\n  Thanks Mathieu Agopian for the report and Ronny Pfannschmidt for the PR.\n\n- fix issue 1029: transform errors when writing cache values into pytest-warnings\n\n2.8.0 (2015-09-18)\n==================\n\n- new ``--lf`` and ``-ff`` options to run only the last failing tests or\n  \"failing tests first\" from the last run.  This functionality is provided\n  through porting the formerly external pytest-cache plugin into pytest core.\n  BACKWARD INCOMPAT: if you used pytest-cache's functionality to persist\n  data between test runs be aware that we don't serialize sets anymore.\n  Thanks Ronny Pfannschmidt for most of the merging work.\n\n- \"-r\" option now accepts \"a\" to include all possible reports, similar\n  to passing \"fEsxXw\" explicitly (issue960).\n  Thanks Abhijeet Kasurde for the PR.\n\n- avoid python3.5 deprecation warnings by introducing version\n  specific inspection helpers, thanks Michael Droettboom.\n\n- fix issue562: @nose.tools.istest now fully respected.\n\n- fix issue934: when string comparison fails and a diff is too large to display\n  without passing -vv, still show a few lines of the diff.\n  Thanks Freya Bruhin for the report and Bruno Oliveira for the PR.\n\n- fix issue736: Fix a bug where fixture params would be discarded when combined\n  with parametrization markers.\n  Thanks to Markus Unterwaditzer for the PR.\n\n- fix issue710: introduce ALLOW_UNICODE doctest option: when enabled, the\n  ``u`` prefix is stripped from unicode strings in expected doctest output. This\n  allows doctests which use unicode to run in Python 2 and 3 unchanged.\n  Thanks Jason R. Coombs for the report and Bruno Oliveira for the PR.\n\n- parametrize now also generates meaningful test IDs for enum, regex and class\n  objects (as opposed to class instances).\n  Thanks to Freya Bruhin for the PR.\n\n- Add 'warns' to assert that warnings are thrown (like 'raises').\n  Thanks to Eric Hunsberger for the PR.\n\n- Fix issue683: Do not apply an already applied mark.  Thanks ojake for the PR.\n\n- Deal with capturing failures better so fewer exceptions get lost to\n  /dev/null.  Thanks David Szotten for the PR.\n\n- fix issue730: deprecate and warn about the --genscript option.\n  Thanks Ronny Pfannschmidt for the report and Christian Pommranz for the PR.\n\n- fix issue751: multiple parametrize with ids bug if it parametrizes class with\n  two or more test methods. Thanks Sergey Chipiga for reporting and Jan\n  Bednarik for PR.\n\n- fix issue82: avoid loading conftest files from setup.cfg/pytest.ini/tox.ini\n  files and upwards by default (--confcutdir can still be set to override this).\n  Thanks Bruno Oliveira for the PR.\n\n- fix issue768: docstrings found in python modules were not setting up session\n  fixtures. Thanks Jason R. Coombs for reporting and Bruno Oliveira for the PR.\n\n- added ``tmpdir_factory``, a session-scoped fixture that can be used to create\n  directories under the base temporary directory. Previously this object was\n  installed as a ``_tmpdirhandler`` attribute of the ``config`` object, but now it\n  is part of the official API and using ``config._tmpdirhandler`` is\n  deprecated.\n  Thanks Bruno Oliveira for the PR.\n\n- fix issue808: pytest's internal assertion rewrite hook now implements the\n  optional :pep:`302` get_data API so tests can access data files next to them.\n  Thanks xmo-odoo for request and example and Bruno Oliveira for\n  the PR.\n\n- rootdir and inifile are now displayed during usage errors to help\n  users diagnose problems such as unexpected ini files which add\n  unknown options being picked up by pytest. Thanks to Pavel Savchenko for\n  bringing the problem to attention in #821 and Bruno Oliveira for the PR.\n\n- Summary bar now is colored yellow for warning\n  situations such as: all tests either were skipped or xpass/xfailed,\n  or no tests were run at all (this is a partial fix for issue500).\n\n- fix issue812: pytest now exits with status code 5 in situations where no\n  tests were run at all, such as the directory given in the command line does\n  not contain any tests or as result of a command line option filters\n  all out all tests (-k for example).\n  Thanks Eric Siegerman (issue812) and Bruno Oliveira for the PR.\n\n- Summary bar now is colored yellow for warning\n  situations such as: all tests either were skipped or xpass/xfailed,\n  or no tests were run at all (related to issue500).\n  Thanks Eric Siegerman.\n\n- New ``testpaths`` ini option: list of directories to search for tests\n  when executing pytest from the root directory. This can be used\n  to speed up test collection when a project has well specified directories\n  for tests, being usually more practical than configuring norecursedirs for\n  all directories that do not contain tests.\n  Thanks to Adrian for idea (#694) and Bruno Oliveira for the PR.\n\n- fix issue713: JUnit XML reports for doctest failures.\n  Thanks Punyashloka Biswal.\n\n- fix issue970: internal pytest warnings now appear as \"pytest-warnings\" in\n  the terminal instead of \"warnings\", so it is clear for users that those\n  warnings are from pytest and not from the builtin \"warnings\" module.\n  Thanks Bruno Oliveira.\n\n- Include setup and teardown in junitxml test durations.\n  Thanks Janne Vanhala.\n\n- fix issue735: assertion failures on debug versions of Python 3.4+\n\n- new option ``--import-mode`` to allow to change test module importing\n  behaviour to append to sys.path instead of prepending.  This better allows\n  to run test modules against installed versions of a package even if the\n  package under test has the same import root.  In this example::\n\n        testing/__init__.py\n        testing/test_pkg_under_test.py\n        pkg_under_test/\n\n  the tests will run against the installed version\n  of pkg_under_test when ``--import-mode=append`` is used whereas\n  by default they would always pick up the local version.  Thanks Holger Krekel.\n\n- pytester: add method ``TmpTestdir.delete_loaded_modules()``, and call it\n  from ``inline_run()`` to allow temporary modules to be reloaded.\n  Thanks Eduardo Schettino.\n\n- internally refactor pluginmanager API and code so that there\n  is a clear distinction between a pytest-agnostic rather simple\n  pluginmanager and the PytestPluginManager which adds a lot of\n  behaviour, among it handling of the local conftest files.\n  In terms of documented methods this is a backward compatible\n  change but it might still break 3rd party plugins which relied on\n  details like especially the pluginmanager.add_shutdown() API.\n  Thanks Holger Krekel.\n\n- pluginmanagement: introduce ``pytest.hookimpl`` and\n  ``pytest.hookspec`` decorators for setting impl/spec\n  specific parameters.  This substitutes the previous\n  now deprecated use of ``pytest.mark`` which is meant to\n  contain markers for test functions only.\n\n- write/refine docs for \"writing plugins\" which now have their\n  own page and are separate from the \"using/installing plugins`` page.\n\n- fix issue732: properly unregister plugins from any hook calling\n  sites allowing to have temporary plugins during test execution.\n\n- deprecate and warn about ``__multicall__`` argument in hook\n  implementations.  Use the ``hookwrapper`` mechanism instead already\n  introduced with pytest-2.7.\n\n- speed up pytest's own test suite considerably by using inprocess\n  tests by default (testrun can be modified with --runpytest=subprocess\n  to create subprocesses in many places instead).  The main\n  APIs to run pytest in a test is \"runpytest()\" or \"runpytest_subprocess\"\n  and \"runpytest_inprocess\" if you need a particular way of running\n  the test.  In all cases you get back a RunResult but the inprocess\n  one will also have a \"reprec\" attribute with the recorded events/reports.\n\n- fix monkeypatch.setattr(\"x.y\", raising=False) to actually not raise\n  if \"y\" is not a preexisting attribute. Thanks Freya Bruhin.\n\n- fix issue741: make running output from testdir.run copy/pasteable\n  Thanks Bruno Oliveira.\n\n- add a new ``--noconftest`` argument which ignores all ``conftest.py`` files.\n\n- add ``file`` and ``line`` attributes to JUnit-XML output.\n\n- fix issue890: changed extension of all documentation files from ``txt`` to\n  ``rst``. Thanks to Abhijeet for the PR.\n\n- fix issue714: add ability to apply indirect=True parameter on particular argnames.\n  Thanks Elizaveta239.\n\n- fix issue890: changed extension of all documentation files from ``txt`` to\n  ``rst``. Thanks to Abhijeet for the PR.\n\n- fix issue957: \"# doctest: SKIP\" option will now register doctests as SKIPPED\n  rather than PASSED.\n  Thanks Thomas Grainger for the report and Bruno Oliveira for the PR.\n\n- issue951: add new record_xml_property fixture, that supports logging\n  additional information on xml output. Thanks David Diaz for the PR.\n\n- issue949: paths after normal options (for example ``-s``, ``-v``, etc) are now\n  properly used to discover ``rootdir`` and ``ini`` files.\n  Thanks Peter Lauri for the report and Bruno Oliveira for the PR.\n\n2.7.3 (2015-09-15)\n==================\n\n- Allow 'dev', 'rc', or other non-integer version strings in ``importorskip``.\n  Thanks to Eric Hunsberger for the PR.\n\n- fix issue856: consider --color parameter in all outputs (for example\n  --fixtures). Thanks Barney Gale for the report and Bruno Oliveira for the PR.\n\n- fix issue855: passing str objects as ``plugins`` argument to pytest.main\n  is now interpreted as a module name to be imported and registered as a\n  plugin, instead of silently having no effect.\n  Thanks xmo-odoo for the report and Bruno Oliveira for the PR.\n\n- fix issue744: fix for ast.Call changes in Python 3.5+.  Thanks\n  Guido van Rossum, Matthias Bussonnier, Stefan Zimmermann and\n  Thomas Kluyver.\n\n- fix issue842: applying markers in classes no longer propagate this markers\n  to superclasses which also have markers.\n  Thanks xmo-odoo for the report and Bruno Oliveira for the PR.\n\n- preserve warning functions after call to pytest.deprecated_call. Thanks\n  Pieter Mulder for PR.\n\n- fix issue854: autouse yield_fixtures defined as class members of\n  unittest.TestCase subclasses now work as expected.\n  Thanks xmo-odoo for the report and Bruno Oliveira for the PR.\n\n- fix issue833: --fixtures now shows all fixtures of collected test files, instead of just the\n  fixtures declared on the first one.\n  Thanks Freya Bruhin for reporting and Bruno Oliveira for the PR.\n\n- fix issue863: skipped tests now report the correct reason when a skip/xfail\n  condition is met when using multiple markers.\n  Thanks Raphael Pierzina for reporting and Bruno Oliveira for the PR.\n\n- optimized tmpdir fixture initialization, which should make test sessions\n  faster (specially when using pytest-xdist). The only visible effect\n  is that now pytest uses a subdirectory in the $TEMP directory for all\n  directories created by this fixture (defaults to $TEMP/pytest-$USER).\n  Thanks Bruno Oliveira for the PR.\n\n2.7.2 (2015-06-23)\n==================\n\n- fix issue767: pytest.raises value attribute does not contain the exception\n  instance on Python 2.6. Thanks Eric Siegerman for providing the test\n  case and Bruno Oliveira for PR.\n\n- Automatically create directory for junitxml and results log.\n  Thanks Aron Curzon.\n\n- fix issue713: JUnit XML reports for doctest failures.\n  Thanks Punyashloka Biswal.\n\n- fix issue735: assertion failures on debug versions of Python 3.4+\n  Thanks Benjamin Peterson.\n\n- fix issue114: skipif marker reports to internal skipping plugin;\n  Thanks Floris Bruynooghe for reporting and Bruno Oliveira for the PR.\n\n- fix issue748: unittest.SkipTest reports to internal pytest unittest plugin.\n  Thanks Thomas De Schampheleire for reporting and Bruno Oliveira for the PR.\n\n- fix issue718: failed to create representation of sets containing unsortable\n  elements in python 2. Thanks Edison Gustavo Muenz.\n\n- fix issue756, fix issue752 (and similar issues): depend on py-1.4.29\n  which has a refined algorithm for traceback generation.\n\n\n2.7.1 (2015-05-19)\n==================\n\n- fix issue731: do not get confused by the braces which may be present\n  and unbalanced in an object's repr while collapsing False\n  explanations.  Thanks Carl Meyer for the report and test case.\n\n- fix issue553: properly handling inspect.getsourcelines failures in\n  FixtureLookupError which would lead to an internal error,\n  obfuscating the original problem. Thanks talljosh for initial\n  diagnose/patch and Bruno Oliveira for final patch.\n\n- fix issue660: properly report scope-mismatch-access errors\n  independently from ordering of fixture arguments.  Also\n  avoid the pytest internal traceback which does not provide\n  information to the user. Thanks Holger Krekel.\n\n- streamlined and documented release process.  Also all versions\n  (in setup.py and documentation generation) are now read\n  from _pytest/__init__.py. Thanks Holger Krekel.\n\n- fixed docs to remove the notion that yield-fixtures are experimental.\n  They are here to stay :)  Thanks Bruno Oliveira.\n\n- Support building wheels by using environment markers for the\n  requirements.  Thanks Ionel Maries Cristian.\n\n- fixed regression to 2.6.4 which surfaced e.g. in lost stdout capture printing\n  when tests raised SystemExit. Thanks Holger Krekel.\n\n- reintroduced _pytest fixture of the pytester plugin which is used\n  at least by pytest-xdist.\n\n2.7.0 (2015-03-26)\n==================\n\n- fix issue435: make reload() work when assert rewriting is active.\n  Thanks Daniel Hahler.\n\n- fix issue616: conftest.py files and their contained fixtures are now\n  properly considered for visibility, independently from the exact\n  current working directory and test arguments that are used.\n  Many thanks to Eric Siegerman and his PR235 which contains\n  systematic tests for conftest visibility and now passes.\n  This change also introduces the concept of a ``rootdir`` which\n  is printed as a new pytest header and documented in the pytest\n  customize web page.\n\n- change reporting of \"diverted\" tests, i.e. tests that are collected\n  in one file but actually come from another (e.g. when tests in a test class\n  come from a base class in a different file).  We now show the nodeid\n  and indicate via a postfix the other file.\n\n- add ability to set command line options by environment variable PYTEST_ADDOPTS.\n\n- added documentation on the new pytest-dev teams on bitbucket and\n  github.  See https://pytest.org/en/stable/contributing.html .\n  Thanks to Anatoly for pushing and initial work on this.\n\n- fix issue650: new option ``--doctest-ignore-import-errors`` which\n  will turn import errors in doctests into skips.  Thanks Charles Cloud\n  for the complete PR.\n\n- fix issue655: work around different ways that cause python2/3\n  to leak sys.exc_info into fixtures/tests causing failures in 3rd party code\n\n- fix issue615: assertion rewriting did not correctly escape % signs\n  when formatting boolean operations, which tripped over mixing\n  booleans with modulo operators.  Thanks to Tom Viner for the report,\n  triaging and fix.\n\n- implement issue351: add ability to specify parametrize ids as a callable\n  to generate custom test ids.  Thanks Brianna Laugher for the idea and\n  implementation.\n\n- introduce and document new hookwrapper mechanism useful for plugins\n  which want to wrap the execution of certain hooks for their purposes.\n  This supersedes the undocumented ``__multicall__`` protocol which\n  pytest itself and some external plugins use.  Note that pytest-2.8\n  is scheduled to drop supporting the old ``__multicall__``\n  and only support the hookwrapper protocol.\n\n- majorly speed up invocation of plugin hooks\n\n- use hookwrapper mechanism in builtin pytest plugins.\n\n- add a doctest ini option for doctest flags, thanks Holger Peters.\n\n- add note to docs that if you want to mark a parameter and the\n  parameter is a callable, you also need to pass in a reason to disambiguate\n  it from the \"decorator\" case.  Thanks Tom Viner.\n\n- \"python_classes\" and \"python_functions\" options now support glob-patterns\n  for test discovery, as discussed in issue600. Thanks Ldiary Translations.\n\n- allow to override parametrized fixtures with non-parametrized ones and vice versa (bubenkoff).\n\n- fix issue463: raise specific error for 'parameterize' misspelling (pfctdayelise).\n\n- On failure, the ``sys.last_value``, ``sys.last_type`` and\n  ``sys.last_traceback`` are set, so that a user can inspect the error\n  via postmortem debugging (almarklein).\n\n2.6.4 (2014-10-24)\n==================\n\n- Improve assertion failure reporting on iterables, by using ndiff and\n  pprint.\n\n- removed outdated japanese docs from source tree.\n\n- docs for \"pytest_addhooks\" hook.  Thanks Bruno Oliveira.\n\n- updated plugin index docs.  Thanks Bruno Oliveira.\n\n- fix issue557: with \"-k\" we only allow the old style \"-\" for negation\n  at the beginning of strings and even that is deprecated.  Use \"not\" instead.\n  This should allow to pick parametrized tests where \"-\" appeared in the parameter.\n\n- fix issue604: Escape % character in the assertion message.\n\n- fix issue620: add explanation in the --genscript target about what\n  the binary blob means. Thanks Dinu Gherman.\n\n- fix issue614: fixed pastebin support.\n\n\n- fix issue620: add explanation in the --genscript target about what\n  the binary blob means. Thanks Dinu Gherman.\n\n- fix issue614: fixed pastebin support.\n\n2.6.3 (2014-09-24)\n==================\n\n- fix issue575: xunit-xml was reporting collection errors as failures\n  instead of errors, thanks Oleg Sinyavskiy.\n\n- fix issue582: fix setuptools example, thanks Laszlo Papp and Ronny\n  Pfannschmidt.\n\n- Fix infinite recursion bug when pickling capture.EncodedFile, thanks\n  Uwe Schmitt.\n\n- fix issue589: fix bad interaction with numpy and others when showing\n  exceptions.  Check for precise \"maximum recursion depth exceed\" exception\n  instead of presuming any RuntimeError is that one (implemented in py\n  dep).  Thanks Charles Cloud for analysing the issue.\n\n- fix conftest related fixture visibility issue: when running with a\n  CWD outside of a test package pytest would get fixture discovery wrong.\n  Thanks to Wolfgang Schnerring for figuring out a reproducible example.\n\n- Introduce pytest_enter_pdb hook (needed e.g. by pytest_timeout to cancel the\n  timeout when interactively entering pdb).  Thanks Wolfgang Schnerring.\n\n- check xfail/skip also with non-python function test items. Thanks\n  Floris Bruynooghe.\n\n2.6.2 (2014-09-05)\n==================\n\n- Added function pytest.freeze_includes(), which makes it easy to embed\n  pytest into executables using tools like cx_freeze.\n  See docs for examples and rationale. Thanks Bruno Oliveira.\n\n- Improve assertion rewriting cache invalidation precision.\n\n- fixed issue561: adapt autouse fixture example for python3.\n\n- fixed issue453: assertion rewriting issue with __repr__ containing\n  \"\\n{\", \"\\n}\" and \"\\n~\".\n\n- fix issue560: correctly display code if an \"else:\" or \"finally:\" is\n  followed by statements on the same line.\n\n- Fix example in monkeypatch documentation, thanks t-8ch.\n\n- fix issue572: correct tmpdir doc example for python3.\n\n- Do not mark as universal wheel because Python 2.6 is different from\n  other builds due to the extra argparse dependency.  Fixes issue566.\n  Thanks sontek.\n\n- Implement issue549: user-provided assertion messages now no longer\n  replace the py.test introspection message but are shown in addition\n  to them.\n\n2.6.1 (2014-08-07)\n==================\n\n- No longer show line numbers in the --verbose output, the output is now\n  purely the nodeid.  The line number is still shown in failure reports.\n  Thanks Floris Bruynooghe.\n\n- fix issue437 where assertion rewriting could cause pytest-xdist worker nodes\n  to collect different tests. Thanks Bruno Oliveira.\n\n- fix issue555: add \"errors\" attribute to capture-streams to satisfy\n  some distutils and possibly other code accessing sys.stdout.errors.\n\n- fix issue547 capsys/capfd also work when output capturing (\"-s\") is disabled.\n\n- address issue170: allow pytest.mark.xfail(...) to specify expected exceptions via\n  an optional \"raises=EXC\" argument where EXC can be a single exception\n  or a tuple of exception classes.  Thanks David Mohr for the complete\n  PR.\n\n- fix integration of pytest with unittest.mock.patch decorator when\n  it uses the \"new\" argument.  Thanks Nicolas Delaby for test and PR.\n\n- fix issue with detecting conftest files if the arguments contain\n  \"::\" node id specifications (copy pasted from \"-v\" output)\n\n- fix issue544 by only removing \"@NUM\" at the end of \"::\" separated parts\n  and if the part has a \".py\" extension\n\n- don't use py.std import helper, rather import things directly.\n  Thanks Bruno Oliveira.\n\n2.6\n===\n\n- Cache exceptions from fixtures according to their scope (issue 467).\n\n- fix issue537: Avoid importing old assertion reinterpretation code by default.\n\n- fix issue364: shorten and enhance tracebacks representation by default.\n  The new \"--tb=auto\" option (default) will only display long tracebacks\n  for the first and last entry.  You can get the old behaviour of printing\n  all entries as long entries with \"--tb=long\".  Also short entries by\n  default are now printed very similarly to \"--tb=native\" ones.\n\n- fix issue514: teach assertion reinterpretation about private class attributes\n\n- change -v output to include full node IDs of tests.  Users can copy\n  a node ID from a test run, including line number, and use it as a\n  positional argument in order to run only a single test.\n\n- fix issue 475: fail early and comprehensible if calling\n  pytest.raises with wrong exception type.\n\n- fix issue516: tell in getting-started about current dependencies.\n\n- cleanup setup.py a bit and specify supported versions. Thanks Jurko\n  Gospodnetic for the PR.\n\n- change XPASS colour to yellow rather than red when tests are run\n  with -v.\n\n- fix issue473: work around mock putting an unbound method into a class\n  dict when double-patching.\n\n- fix issue498: if a fixture finalizer fails, make sure that\n  the fixture is still invalidated.\n\n- fix issue453: the result of the pytest_assertrepr_compare hook now gets\n  it's newlines escaped so that format_exception does not blow up.\n\n- internal new warning system: pytest will now produce warnings when\n  it detects oddities in your test collection or execution.\n  Warnings are ultimately sent to a new pytest_logwarning hook which is\n  currently only implemented by the terminal plugin which displays\n  warnings in the summary line and shows more details when -rw (report on\n  warnings) is specified.\n\n- change skips into warnings for test classes with an __init__ and\n  callables in test modules which look like a test but are not functions.\n\n- fix issue436: improved finding of initial conftest files from command\n  line arguments by using the result of parse_known_args rather than\n  the previous flaky heuristics.  Thanks Marc Abramowitz for tests\n  and initial fixing approaches in this area.\n\n- fix issue #479: properly handle nose/unittest(2) SkipTest exceptions\n  during collection/loading of test modules.  Thanks to Marc Schlaich\n  for the complete PR.\n\n- fix issue490: include pytest_load_initial_conftests in documentation\n  and improve docstring.\n\n- fix issue472: clarify that ``pytest.config.getvalue()`` cannot work\n  if it's triggered ahead of command line parsing.\n\n- merge PR123: improved integration with mock.patch decorator on tests.\n\n- fix issue412: messing with stdout/stderr FD-level streams is now\n  captured without crashes.\n\n- fix issue483: trial/py33 works now properly.  Thanks Daniel Grana for PR.\n\n- improve example for pytest integration with \"python setup.py test\"\n  which now has a generic \"-a\" or \"--pytest-args\" option where you\n  can pass additional options as a quoted string.  Thanks Trevor Bekolay.\n\n- simplified internal capturing mechanism and made it more robust\n  against tests or setups changing FD1/FD2, also better integrated\n  now with pytest.pdb() in single tests.\n\n- improvements to pytest's own test-suite leakage detection, courtesy of PRs\n  from Marc Abramowitz\n\n- fix issue492: avoid leak in test_writeorg.  Thanks Marc Abramowitz.\n\n- fix issue493: don't run tests in doc directory with ``python setup.py test``\n  (use tox -e doctesting for that)\n\n- fix issue486: better reporting and handling of early conftest loading failures\n\n- some cleanup and simplification of internal conftest handling.\n\n- work a bit harder to break reference cycles when catching exceptions.\n  Thanks Jurko Gospodnetic.\n\n- fix issue443: fix skip examples to use proper comparison.  Thanks Alex\n  Groenholm.\n\n- support nose-style ``__test__`` attribute on modules, classes and\n  functions, including unittest-style Classes.  If set to False, the\n  test will not be collected.\n\n- fix issue512: show \"<notset>\" for arguments which might not be set\n  in monkeypatch plugin.  Improves output in documentation.\n\n\n2.5.2 (2014-01-29)\n==================\n\n- fix issue409 -- better interoperate with cx_freeze by not\n  trying to import from collections.abc which causes problems\n  for py27/cx_freeze.  Thanks Wolfgang L. for reporting and tracking it down.\n\n- fixed docs and code to use \"pytest\" instead of \"py.test\" almost everywhere.\n  Thanks Jurko Gospodnetic for the complete PR.\n\n- fix issue425: mention at end of \"py.test -h\" that --markers\n  and --fixtures work according to specified test path (or current dir)\n\n- fix issue413: exceptions with unicode attributes are now printed\n  correctly also on python2 and with pytest-xdist runs. (the fix\n  requires py-1.4.20)\n\n- copy, cleanup and integrate py.io capture\n  from pylib 1.4.20.dev2 (rev 13d9af95547e)\n\n- address issue416: clarify docs as to conftest.py loading semantics\n\n- fix issue429: comparing byte strings with non-ascii chars in assert\n  expressions now work better.  Thanks Floris Bruynooghe.\n\n- make capfd/capsys.capture private, its unused and shouldn't be exposed\n\n\n2.5.1 (2013-12-17)\n==================\n\n- merge new documentation styling PR from Tobias Bieniek.\n\n- fix issue403: allow parametrize of multiple same-name functions within\n  a collection node.  Thanks Andreas Kloeckner and Alex Gaynor for reporting\n  and analysis.\n\n- Allow parameterized fixtures to specify the ID of the parameters by\n  adding an ids argument to pytest.fixture() and pytest.yield_fixture().\n  Thanks Floris Bruynooghe.\n\n- fix issue404 by always using the binary xml escape in the junitxml\n  plugin.  Thanks Ronny Pfannschmidt.\n\n- fix issue407: fix addoption docstring to point to argparse instead of\n  optparse. Thanks Daniel D. Wright.\n\n\n\n2.5.0 (2013-12-12)\n==================\n\n- dropped python2.5 from automated release testing of pytest itself\n  which means it's probably going to break soon (but still works\n  with this release we believe).\n\n- simplified and fixed implementation for calling finalizers when\n  parametrized fixtures or function arguments are involved.  finalization\n  is now performed lazily at setup time instead of in the \"teardown phase\".\n  While this might sound odd at first, it helps to ensure that we are\n  correctly handling setup/teardown even in complex code.  User-level code\n  should not be affected unless it's implementing the pytest_runtest_teardown\n  hook and expecting certain fixture instances are torn down within (very\n  unlikely and would have been unreliable anyway).\n\n- PR90: add --color=yes|no|auto option to force terminal coloring\n  mode (\"auto\" is default).  Thanks Marc Abramowitz.\n\n- fix issue319 - correctly show unicode in assertion errors.  Many\n  thanks to Floris Bruynooghe for the complete PR.  Also means\n  we depend on py>=1.4.19 now.\n\n- fix issue396 - correctly sort and finalize class-scoped parametrized\n  tests independently from number of methods on the class.\n\n- refix issue323 in a better way -- parametrization should now never\n  cause Runtime Recursion errors because the underlying algorithm\n  for re-ordering tests per-scope/per-fixture is not recursive\n  anymore (it was tail-call recursive before which could lead\n  to problems for more than >966 non-function scoped parameters).\n\n- fix issue290 - there is preliminary support now for parametrizing\n  with repeated same values (sometimes useful to test if calling\n  a second time works as with the first time).\n\n- close issue240 - document precisely how pytest module importing\n  works, discuss the two common test directory layouts, and how it\n  interacts with :pep:`420`\\-namespace packages.\n\n- fix issue246 fix finalizer order to be LIFO on independent fixtures\n  depending on a parametrized higher-than-function scoped fixture.\n  (was quite some effort so please bear with the complexity of this sentence :)\n  Thanks Ralph Schmitt for the precise failure example.\n\n- fix issue244 by implementing special index for parameters to only use\n  indices for parametrized test ids\n\n- fix issue287 by running all finalizers but saving the exception\n  from the first failing finalizer and re-raising it so teardown will\n  still have failed.  We reraise the first failing exception because\n  it might be the cause for other finalizers to fail.\n\n- fix ordering when mock.patch or other standard decorator-wrappings\n  are used with test methods.  This fixes issue346 and should\n  help with random \"xdist\" collection failures.  Thanks to\n  Ronny Pfannschmidt and Donald Stufft for helping to isolate it.\n\n- fix issue357 - special case \"-k\" expressions to allow for\n  filtering with simple strings that are not valid python expressions.\n  Examples: \"-k 1.3\" matches all tests parametrized with 1.3.\n  \"-k None\" filters all tests that have \"None\" in their name\n  and conversely \"-k 'not None'\".\n  Previously these examples would raise syntax errors.\n\n- fix issue384 by removing the trial support code\n  since the unittest compat enhancements allow\n  trial to handle it on its own\n\n- don't hide an ImportError when importing a plugin produces one.\n  fixes issue375.\n\n- fix issue275 - allow usefixtures and autouse fixtures\n  for running doctest text files.\n\n- fix issue380 by making --resultlog only rely on longrepr instead\n  of the \"reprcrash\" attribute which only exists sometimes.\n\n- address issue122: allow @pytest.fixture(params=iterator) by exploding\n  into a list early on.\n\n- fix pexpect-3.0 compatibility for pytest's own tests.\n  (fixes issue386)\n\n- allow nested parametrize-value markers, thanks James Lan for the PR.\n\n- fix unicode handling with new monkeypatch.setattr(import_path, value)\n  API.  Thanks Rob Dennis.  Fixes issue371.\n\n- fix unicode handling with junitxml, fixes issue368.\n\n- In assertion rewriting mode on Python 2, fix the detection of coding\n  cookies. See issue #330.\n\n- make \"--runxfail\" turn imperative pytest.xfail calls into no ops\n  (it already did neutralize pytest.mark.xfail markers)\n\n- refine pytest / pkg_resources interactions: The AssertionRewritingHook\n  :pep:`302` compliant loader now registers itself with setuptools/pkg_resources\n  properly so that the pkg_resources.resource_stream method works properly.\n  Fixes issue366.  Thanks for the investigations and full PR to Jason R. Coombs.\n\n- pytestconfig fixture is now session-scoped as it is the same object during the\n  whole test run.  Fixes issue370.\n\n- avoid one surprising case of marker malfunction/confusion::\n\n      @pytest.mark.some(lambda arg: ...)\n      def test_function():\n\n  would not work correctly because pytest assumes @pytest.mark.some\n  gets a function to be decorated already.  We now at least detect if this\n  arg is a lambda and thus the example will work.  Thanks Alex Gaynor\n  for bringing it up.\n\n- xfail a test on pypy that checks wrong encoding/ascii (pypy does\n  not error out). fixes issue385.\n\n- internally make varnames() deal with classes's __init__,\n  although it's not needed by pytest itself atm.  Also\n  fix caching.  Fixes issue376.\n\n- fix issue221 - handle importing of namespace-package with no\n  __init__.py properly.\n\n- refactor internal FixtureRequest handling to avoid monkeypatching.\n  One of the positive user-facing effects is that the \"request\" object\n  can now be used in closures.\n\n- fixed version comparison in pytest.importskip(modname, minverstring)\n\n- fix issue377 by clarifying in the nose-compat docs that pytest\n  does not duplicate the unittest-API into the \"plain\" namespace.\n\n- fix verbose reporting for @mock'd test functions\n\n2.4.2 (2013-10-04)\n==================\n\n- on Windows require colorama and a newer py lib so that py.io.TerminalWriter()\n  now uses colorama instead of its own ctypes hacks. (fixes issue365)\n  thanks Paul Moore for bringing it up.\n\n- fix \"-k\" matching of tests where \"repr\" and \"attr\" and other names would\n  cause wrong matches because of an internal implementation quirk\n  (don't ask) which is now properly implemented. fixes issue345.\n\n- avoid tmpdir fixture to create too long filenames especially\n  when parametrization is used (issue354)\n\n- fix pytest-pep8 and pytest-flakes / pytest interactions\n  (collection names in mark plugin was assuming an item always\n  has a function which is not true for those plugins etc.)\n  Thanks Andi Zeidler.\n\n- introduce node.get_marker/node.add_marker API for plugins\n  like pytest-pep8 and pytest-flakes to avoid the messy\n  details of the node.keywords  pseudo-dicts.  Adapted\n  docs.\n\n- remove attempt to \"dup\" stdout at startup as it's icky.\n  the normal capturing should catch enough possibilities\n  of tests messing up standard FDs.\n\n- add pluginmanager.do_configure(config) as a link to\n  config.do_configure() for plugin-compatibility\n\n2.4.1 (2013-10-02)\n==================\n\n- When using parser.addoption() unicode arguments to the\n  \"type\" keyword should also be converted to the respective types.\n  thanks Floris Bruynooghe, @dnozay. (fixes issue360 and issue362)\n\n- fix dotted filename completion when using argcomplete\n  thanks Anthon van der Neuth. (fixes issue361)\n\n- fix regression when a 1-tuple (\"arg\",) is used for specifying\n  parametrization (the values of the parametrization were passed\n  nested in a tuple).  Thanks Donald Stufft.\n\n- merge doc typo fixes, thanks Andy Dirnberger\n\n2.4\n===\n\nknown incompatibilities:\n\n- if calling --genscript from python2.7 or above, you only get a\n  standalone script which works on python2.7 or above.  Use Python2.6\n  to also get a python2.5 compatible version.\n\n- all xunit-style teardown methods (nose-style, pytest-style,\n  unittest-style) will not be called if the corresponding setup method failed,\n  see issue322 below.\n\n- the pytest_plugin_unregister hook wasn't ever properly called\n  and there is no known implementation of the hook - so it got removed.\n\n- pytest.fixture-decorated functions cannot be generators (i.e. use\n  yield) anymore.  This change might be reversed in 2.4.1 if it causes\n  unforeseen real-life issues.  However, you can always write and return\n  an inner function/generator and change the fixture consumer to iterate\n  over the returned generator.  This change was done in lieu of the new\n  ``pytest.yield_fixture`` decorator, see below.\n\nnew features:\n\n- experimentally introduce a new ``pytest.yield_fixture`` decorator\n  which accepts exactly the same parameters as pytest.fixture but\n  mandates a ``yield`` statement instead of a ``return statement`` from\n  fixture functions.  This allows direct integration with \"with-style\"\n  context managers in fixture functions and generally avoids registering\n  of finalization callbacks in favour of treating the \"after-yield\" as\n  teardown code.  Thanks Andreas Pelme, Vladimir Keleshev, Floris\n  Bruynooghe, Ronny Pfannschmidt and many others for discussions.\n\n- allow boolean expression directly with skipif/xfail\n  if a \"reason\" is also specified.  Rework skipping documentation\n  to recommend \"condition as booleans\" because it prevents surprises\n  when importing markers between modules.  Specifying conditions\n  as strings will remain fully supported.\n\n- reporting: color the last line red or green depending if\n  failures/errors occurred or everything passed.  thanks Christian\n  Theunert.\n\n- make \"import pdb ; pdb.set_trace()\" work natively wrt capturing (no\n  \"-s\" needed anymore), making ``pytest.set_trace()`` a mere shortcut.\n\n- fix issue181: --pdb now also works on collect errors (and\n  on internal errors) .  This was implemented by a slight internal\n  refactoring and the introduction of a new hook\n  ``pytest_exception_interact`` hook (see next item).\n\n- fix issue341: introduce new experimental hook for IDEs/terminals to\n  intercept debugging: ``pytest_exception_interact(node, call, report)``.\n\n- new monkeypatch.setattr() variant to provide a shorter\n  invocation for patching out classes/functions from modules:\n\n     monkeypatch.setattr(\"requests.get\", myfunc)\n\n  will replace the \"get\" function of the \"requests\" module with ``myfunc``.\n\n- fix issue322: tearDownClass is not run if setUpClass failed. Thanks\n  Mathieu Agopian for the initial fix.  Also make all of pytest/nose\n  finalizer mimic the same generic behaviour: if a setupX exists and\n  fails, don't run teardownX.  This internally introduces a new method\n  \"node.addfinalizer()\" helper which can only be called during the setup\n  phase of a node.\n\n- simplify pytest.mark.parametrize() signature: allow to pass a\n  CSV-separated string to specify argnames.  For example:\n  ``pytest.mark.parametrize(\"input,expected\",  [(1,2), (2,3)])``\n  works as well as the previous:\n  ``pytest.mark.parametrize((\"input\", \"expected\"), ...)``.\n\n- add support for setUpModule/tearDownModule detection, thanks Brian Okken.\n\n- integrate tab-completion on options through use of \"argcomplete\".\n  Thanks Anthon van der Neut for the PR.\n\n- change option names to be hyphen-separated long options but keep the\n  old spelling backward compatible.  py.test -h will only show the\n  hyphenated version, for example \"--collect-only\" but \"--collectonly\"\n  will remain valid as well (for backward-compat reasons).  Many thanks to\n  Anthon van der Neut for the implementation and to Hynek Schlawack for\n  pushing us.\n\n- fix issue 308 - allow to mark/xfail/skip individual parameter sets\n  when parametrizing.  Thanks Brianna Laugher.\n\n- call new experimental pytest_load_initial_conftests hook to allow\n  3rd party plugins to do something before a conftest is loaded.\n\nBug fixes:\n\n- fix issue358 - capturing options are now parsed more properly\n  by using a new parser.parse_known_args method.\n\n- pytest now uses argparse instead of optparse (thanks Anthon) which\n  means that \"argparse\" is added as a dependency if installing into python2.6\n  environments or below.\n\n- fix issue333: fix a case of bad unittest/pytest hook interaction.\n\n- PR27: correctly handle nose.SkipTest during collection.  Thanks\n  Antonio Cuni, Ronny Pfannschmidt.\n\n- fix issue355: junitxml puts name=\"pytest\" attribute to testsuite tag.\n\n- fix issue336: autouse fixture in plugins should work again.\n\n- fix issue279: improve object comparisons on assertion failure\n  for standard datatypes and recognise collections.abc.  Thanks to\n  Brianna Laugher and Mathieu Agopian.\n\n- fix issue317: assertion rewriter support for the is_package method\n\n- fix issue335: document py.code.ExceptionInfo() object returned\n  from pytest.raises(), thanks Mathieu Agopian.\n\n- remove implicit distribute_setup support from setup.py.\n\n- fix issue305: ignore any problems when writing pyc files.\n\n- SO-17664702: call fixture finalizers even if the fixture function\n  partially failed (finalizers would not always be called before)\n\n- fix issue320 - fix class scope for fixtures when mixed with\n  module-level functions.  Thanks Anatoly Bubenkoff.\n\n- you can specify \"-q\" or \"-qq\" to get different levels of \"quieter\"\n  reporting (thanks Katarzyna Jachim)\n\n- fix issue300 - Fix order of conftest loading when starting py.test\n  in a subdirectory.\n\n- fix issue323 - sorting of many module-scoped arg parametrizations\n\n- make sessionfinish hooks execute with the same cwd-context as at\n  session start (helps fix plugin behaviour which write output files\n  with relative path such as pytest-cov)\n\n- fix issue316 - properly reference collection hooks in docs\n\n- fix issue 306 - cleanup of -k/-m options to only match markers/test\n  names/keywords respectively.  Thanks Wouter van Ackooy.\n\n- improved doctest counting for doctests in python modules --\n  files without any doctest items will not show up anymore\n  and doctest examples are counted as separate test items.\n  thanks Danilo Bellini.\n\n- fix issue245 by depending on the released py-1.4.14\n  which fixes py.io.dupfile to work with files with no\n  mode. Thanks Jason R. Coombs.\n\n- fix junitxml generation when test output contains control characters,\n  addressing issue267, thanks Jaap Broekhuizen\n\n- fix issue338: honor --tb style for setup/teardown errors as well.  Thanks Maho.\n\n- fix issue307 - use yaml.safe_load in example, thanks Mark Eichin.\n\n- better parametrize error messages, thanks Brianna Laugher\n\n- pytest_terminal_summary(terminalreporter) hooks can now use\n  \".section(title)\" and \".line(msg)\" methods to print extra\n  information at the end of a test run.\n\n2.3.5 (2013-04-30)\n==================\n\n- fix issue169: respect --tb=style with setup/teardown errors as well.\n\n- never consider a fixture function for test function collection\n\n- allow re-running of test items / helps to fix pytest-reruntests plugin\n  and also help to keep less fixture/resource references alive\n\n- put captured stdout/stderr into junitxml output even for passing tests\n  (thanks Adam Goucher)\n\n- Issue 265 - integrate nose setup/teardown with setupstate\n  so it doesn't try to teardown if it did not setup\n\n- issue 271 - don't write junitxml on worker nodes\n\n- Issue 274 - don't try to show full doctest example\n  when doctest does not know the example location\n\n- issue 280 - disable assertion rewriting on buggy CPython 2.6.0\n\n- inject \"getfixture()\" helper to retrieve fixtures from doctests,\n  thanks Andreas Zeidler\n\n- issue 259 - when assertion rewriting, be consistent with the default\n  source encoding of ASCII on Python 2\n\n- issue 251 - report a skip instead of ignoring classes with init\n\n- issue250 unicode/str mixes in parametrization names and values now works\n\n- issue257, assertion-triggered compilation of source ending in a\n  comment line doesn't blow up in python2.5 (fixed through py>=1.4.13.dev6)\n\n- fix --genscript option to generate standalone scripts that also\n  work with python3.3 (importer ordering)\n\n- issue171 - in assertion rewriting, show the repr of some\n  global variables\n\n- fix option help for \"-k\"\n\n- move long description of distribution into README.rst\n\n- improve docstring for metafunc.parametrize()\n\n- fix bug where using capsys with pytest.set_trace() in a test\n  function would break when looking at capsys.readouterr()\n\n- allow to specify prefixes starting with \"_\" when\n  customizing python_functions test discovery. (thanks Graham Horler)\n\n- improve PYTEST_DEBUG tracing output by putting\n  extra data on a new lines with additional indent\n\n- ensure OutcomeExceptions like skip/fail have initialized exception attributes\n\n- issue 260 - don't use nose special setup on plain unittest cases\n\n- fix issue134 - print the collect errors that prevent running specified test items\n\n- fix issue266 - accept unicode in MarkEvaluator expressions\n\n2.3.4 (2012-11-20)\n==================\n\n- yielded test functions will now have autouse-fixtures active but\n  cannot accept fixtures as funcargs - it's anyway recommended to\n  rather use the post-2.0 parametrize features instead of yield, see:\n  http://pytest.org/en/stable/example/how-to/parametrize.html\n- fix autouse-issue where autouse-fixtures would not be discovered\n  if defined in an a/conftest.py file and tests in a/tests/test_some.py\n- fix issue226 - LIFO ordering for fixture teardowns\n- fix issue224 - invocations with >256 char arguments now work\n- fix issue91 - add/discuss package/directory level setups in example\n- allow to dynamically define markers via\n  item.keywords[...]=assignment integrating with \"-m\" option\n- make \"-k\" accept an expressions the same as with \"-m\" so that one\n  can write: -k \"name1 or name2\" etc.  This is a slight incompatibility\n  if you used special syntax like \"TestClass.test_method\" which you now\n  need to write as -k \"TestClass and test_method\" to match a certain\n  method in a certain test class.\n\n2.3.3 (2012-11-06)\n==================\n\n- fix issue214 - parse modules that contain special objects like e. g.\n  flask's request object which blows up on getattr access if no request\n  is active. thanks Thomas Waldmann.\n\n- fix issue213 - allow to parametrize with values like numpy arrays that\n  do not support an __eq__ operator\n\n- fix issue215 - split test_python.org into multiple files\n\n- fix issue148 - @unittest.skip on classes is now recognized and avoids\n  calling setUpClass/tearDownClass, thanks Pavel Repin\n\n- fix issue209 - reintroduce python2.4 support by depending on newer\n  pylib which re-introduced statement-finding for pre-AST interpreters\n\n- nose support: only call setup if it's a callable, thanks Andrew\n  Taumoefolau\n\n- fix issue219 - add py2.4-3.3 classifiers to TROVE list\n\n- in tracebacks *,** arg values are now shown next to normal arguments\n  (thanks Manuel Jacob)\n\n- fix issue217 - support mock.patch with pytest's fixtures - note that\n  you need either mock-1.0.1 or the python3.3 builtin unittest.mock.\n\n- fix issue127 - improve documentation for pytest_addoption() and\n  add a ``config.getoption(name)`` helper function for consistency.\n\n2.3.2 (2012-10-25)\n==================\n\n- fix issue208 and fix issue29 use new py version to avoid long pauses\n  when printing tracebacks in long modules\n\n- fix issue205 - conftests in subdirs customizing\n  pytest_pycollect_makemodule and pytest_pycollect_makeitem\n  now work properly\n\n- fix teardown-ordering for parametrized setups\n\n- fix issue127 - better documentation for pytest_addoption\n  and related objects.\n\n- fix unittest behaviour: TestCase.runtest only called if there are\n  test methods defined\n\n- improve trial support: don't collect its empty\n  unittest.TestCase.runTest() method\n\n- \"python setup.py test\" now works with pytest itself\n\n- fix/improve internal/packaging related bits:\n\n  - exception message check of test_nose.py now passes on python33 as well\n\n  - issue206 - fix test_assertrewrite.py to work when a global\n    PYTHONDONTWRITEBYTECODE=1 is present\n\n  - add tox.ini to pytest distribution so that ignore-dirs and others config\n    bits are properly distributed for maintainers who run pytest-own tests\n\n2.3.1 (2012-10-20)\n==================\n\n- fix issue202 - fix regression: using \"self\" from fixture functions now\n  works as expected (it's the same \"self\" instance that a test method\n  which uses the fixture sees)\n\n- skip pexpect using tests (test_pdb.py mostly) on freebsd* systems\n  due to pexpect not supporting it properly (hanging)\n\n- link to web pages from --markers output which provides help for\n  pytest.mark.* usage.\n\n2.3.0 (2012-10-19)\n==================\n\n- fix issue202 - better automatic names for parametrized test functions\n- fix issue139 - introduce @pytest.fixture which allows direct scoping\n  and parametrization of funcarg factories.\n- fix issue198 - conftest fixtures were not found on windows32 in some\n  circumstances with nested directory structures due to path manipulation issues\n- fix issue193 skip test functions with were parametrized with empty\n  parameter sets\n- fix python3.3 compat, mostly reporting bits that previously depended\n  on dict ordering\n- introduce re-ordering of tests by resource and parametrization setup\n  which takes precedence to the usual file-ordering\n- fix issue185 monkeypatching time.time does not cause pytest to fail\n- fix issue172 duplicate call of pytest.fixture decoratored setup_module\n  functions\n- fix junitxml=path construction so that if tests change the\n  current working directory and the path is a relative path\n  it is constructed correctly from the original current working dir.\n- fix \"python setup.py test\" example to cause a proper \"errno\" return\n- fix issue165 - fix broken doc links and mention stackoverflow for FAQ\n- catch unicode-issues when writing failure representations\n  to terminal to prevent the whole session from crashing\n- fix xfail/skip confusion: a skip-mark or an imperative pytest.skip\n  will now take precedence before xfail-markers because we\n  can't determine xfail/xpass status in case of a skip. see also:\n  http://stackoverflow.com/questions/11105828/in-py-test-when-i-explicitly-skip-a-test-that-is-marked-as-xfail-how-can-i-get\n\n- always report installed 3rd party plugins in the header of a test run\n\n- fix issue160: a failing setup of an xfail-marked tests should\n  be reported as xfail (not xpass)\n\n- fix issue128: show captured output when capsys/capfd are used\n\n- fix issue179: properly show the dependency chain of factories\n\n- pluginmanager.register(...) now raises ValueError if the\n  plugin has been already registered or the name is taken\n\n- fix issue159: improve https://docs.pytest.org/en/6.0.1/faq.html\n  especially with respect to the \"magic\" history, also mention\n  pytest-django, trial and unittest integration.\n\n- make request.keywords and node.keywords writable.  All descendant\n  collection nodes will see keyword values.  Keywords are dictionaries\n  containing markers and other info.\n\n- fix issue 178: xml binary escapes are now wrapped in py.xml.raw\n\n- fix issue 176: correctly catch the builtin AssertionError\n  even when we replaced AssertionError with a subclass on the\n  python level\n\n- factory discovery no longer fails with magic global callables\n  that provide no sane __code__ object (mock.call for example)\n\n- fix issue 182: testdir.inprocess_run now considers passed plugins\n\n- fix issue 188: ensure sys.exc_info is clear on python2\n                 before calling into a test\n\n- fix issue 191: add unittest TestCase runTest method support\n- fix issue 156: monkeypatch correctly handles class level descriptors\n\n- reporting refinements:\n\n  - pytest_report_header now receives a \"startdir\" so that\n    you can use startdir.bestrelpath(yourpath) to show\n    nice relative path\n\n  - allow plugins to implement both pytest_report_header and\n    pytest_sessionstart (sessionstart is invoked first).\n\n  - don't show deselected reason line if there is none\n\n  - py.test -vv will show all of assert comparisons instead of truncating\n\n2.2.4 (2012-05-22)\n==================\n\n- fix error message for rewritten assertions involving the % operator\n- fix issue 126: correctly match all invalid xml characters for junitxml\n  binary escape\n- fix issue with unittest: now @unittest.expectedFailure markers should\n  be processed correctly (you can also use @pytest.mark markers)\n- document integration with the extended distribute/setuptools test commands\n- fix issue 140: properly get the real functions\n  of bound classmethods for setup/teardown_class\n- fix issue #141: switch from the deceased paste.pocoo.org to bpaste.net\n- fix issue #143: call unconfigure/sessionfinish always when\n  configure/sessionstart where called\n- fix issue #144: better mangle test ids to junitxml classnames\n- upgrade distribute_setup.py to 0.6.27\n\n2.2.3 (2012-02-05)\n==================\n\n- fix uploaded package to only include necessary files\n\n2.2.2 (2012-02-05)\n==================\n\n- fix issue101: wrong args to unittest.TestCase test function now\n  produce better output\n- fix issue102: report more useful errors and hints for when a\n  test directory was renamed and some pyc/__pycache__ remain\n- fix issue106: allow parametrize to be applied multiple times\n  e.g. from module, class and at function level.\n- fix issue107: actually perform session scope finalization\n- don't check in parametrize if indirect parameters are funcarg names\n- add chdir method to monkeypatch funcarg\n- fix crash resulting from calling monkeypatch undo a second time\n- fix issue115: make --collectonly robust against early failure\n  (missing files/directories)\n- \"-qq --collectonly\" now shows only files and the number of tests in them\n- \"-q --collectonly\" now shows test ids\n- allow adding of attributes to test reports such that it also works\n  with distributed testing (no upgrade of pytest-xdist needed)\n\n2.2.1 (2011-12-16)\n==================\n\n- fix issue99 (in pytest and py) internallerrors with resultlog now\n  produce better output - fixed by normalizing pytest_internalerror\n  input arguments.\n- fix issue97 / traceback issues (in pytest and py) improve traceback output\n  in conjunction with jinja2 and cython which hack tracebacks\n- fix issue93 (in pytest and pytest-xdist) avoid \"delayed teardowns\":\n  the final test in a test node will now run its teardown directly\n  instead of waiting for the end of the session. Thanks Dave Hunt for\n  the good reporting and feedback.  The pytest_runtest_protocol as well\n  as the pytest_runtest_teardown hooks now have \"nextitem\" available\n  which will be None indicating the end of the test run.\n- fix collection crash due to unknown-source collected items, thanks\n  to Ralf Schmitt (fixed by depending on a more recent pylib)\n\n2.2.0 (2011-11-18)\n==================\n\n- fix issue90: introduce eager tearing down of test items so that\n  teardown function are called earlier.\n- add an all-powerful metafunc.parametrize function which allows to\n  parametrize test function arguments in multiple steps and therefore\n  from independent plugins and places.\n- add a @pytest.mark.parametrize helper which allows to easily\n  call a test function with different argument values\n- Add examples to the \"parametrize\" example page, including a quick port\n  of Test scenarios and the new parametrize function and decorator.\n- introduce registration for \"pytest.mark.*\" helpers via ini-files\n  or through plugin hooks.  Also introduce a \"--strict\" option which\n  will treat unregistered markers as errors\n  allowing to avoid typos and maintain a well described set of markers\n  for your test suite.  See examples at http://pytest.org/en/stable/how-to/mark.html\n  and its links.\n- issue50: introduce \"-m marker\" option to select tests based on markers\n  (this is a stricter and more predictable version of '-k' in that \"-m\"\n  only matches complete markers and has more obvious rules for and/or\n  semantics.\n- new feature to help optimizing the speed of your tests:\n  --durations=N option for displaying N slowest test calls\n  and setup/teardown methods.\n- fix issue87: --pastebin now works with python3\n- fix issue89: --pdb with unexpected exceptions in doctest work more sensibly\n- fix and cleanup pytest's own test suite to not leak FDs\n- fix issue83: link to generated funcarg list\n- fix issue74: pyarg module names are now checked against imp.find_module false positives\n- fix compatibility with twisted/trial-11.1.0 use cases\n- simplify Node.listchain\n- simplify junitxml output code by relying on py.xml\n- add support for skip properties on unittest classes and functions\n\n2.1.3 (2011-10-18)\n==================\n\n- fix issue79: assertion rewriting failed on some comparisons in boolops\n- correctly handle zero length arguments (a la pytest '')\n- fix issue67 / junitxml now contains correct test durations, thanks ronny\n- fix issue75 / skipping test failure on jython\n- fix issue77 / Allow assertrepr_compare hook to apply to a subset of tests\n\n2.1.2 (2011-09-24)\n==================\n\n- fix assertion rewriting on files with windows newlines on some Python versions\n- refine test discovery by package/module name (--pyargs), thanks Florian Mayer\n- fix issue69 / assertion rewriting fixed on some boolean operations\n- fix issue68 / packages now work with assertion rewriting\n- fix issue66: use different assertion rewriting caches when the -O option is passed\n- don't try assertion rewriting on Jython, use reinterp\n\n2.1.1\n=====\n\n- fix issue64 / pytest.set_trace now works within pytest_generate_tests hooks\n- fix issue60 / fix error conditions involving the creation of __pycache__\n- fix issue63 / assertion rewriting on inserts involving strings containing '%'\n- fix assertion rewriting on calls with a ** arg\n- don't cache rewritten modules if bytecode generation is disabled\n- fix assertion rewriting in read-only directories\n- fix issue59: provide system-out/err tags for junitxml output\n- fix issue61: assertion rewriting on boolean operations with 3 or more operands\n- you can now build a man page with \"cd doc ; make man\"\n\n2.1.0 (2011-07-09)\n==================\n\n- fix issue53 call nosestyle setup functions with correct ordering\n- fix issue58 and issue59: new assertion code fixes\n- merge Benjamin's assertionrewrite branch: now assertions\n  for test modules on python 2.6 and above are done by rewriting\n  the AST and saving the pyc file before the test module is imported.\n  see doc/assert.txt for more info.\n- fix issue43: improve doctests with better traceback reporting on\n  unexpected exceptions\n- fix issue47: timing output in junitxml for test cases is now correct\n- fix issue48: typo in MarkInfo repr leading to exception\n- fix issue49: avoid confusing error when initialization partially fails\n- fix issue44: env/username expansion for junitxml file path\n- show releaselevel information in test runs for pypy\n- reworked doc pages for better navigation and PDF generation\n- report KeyboardInterrupt even if interrupted during session startup\n- fix issue 35 - provide PDF doc version and download link from index page\n\n2.0.3 (2011-05-11)\n==================\n\n- fix issue38: nicer tracebacks on calls to hooks, particularly early\n  configure/sessionstart ones\n\n- fix missing skip reason/meta information in junitxml files, reported\n  via http://lists.idyll.org/pipermail/testing-in-python/2011-March/003928.html\n\n- fix issue34: avoid collection failure with \"test\" prefixed classes\n  deriving from object.\n\n- don't require zlib (and other libs) for genscript plugin without\n  --genscript actually being used.\n\n- speed up skips (by not doing a full traceback representation\n  internally)\n\n- fix issue37: avoid invalid characters in junitxml's output\n\n2.0.2 (2011-03-09)\n==================\n\n- tackle issue32 - speed up test runs of very quick test functions\n  by reducing the relative overhead\n\n- fix issue30 - extended xfail/skipif handling and improved reporting.\n  If you have a syntax error in your skip/xfail\n  expressions you now get nice error reports.\n\n  Also you can now access module globals from xfail/skipif\n  expressions so that this for example works now::\n\n    import pytest\n    import mymodule\n    @pytest.mark.skipif(\"mymodule.__version__[0] == \"1\")\n    def test_function():\n        pass\n\n  This will not run the test function if the module's version string\n  does not start with a \"1\".  Note that specifying a string instead\n  of a boolean expressions allows py.test to report meaningful information\n  when summarizing a test run as to what conditions lead to skipping\n  (or xfail-ing) tests.\n\n- fix issue28 - setup_method and pytest_generate_tests work together\n  The setup_method fixture method now gets called also for\n  test function invocations generated from the pytest_generate_tests\n  hook.\n\n- fix issue27 - collectonly and keyword-selection (-k) now work together\n  Also, if you do \"py.test --collectonly -q\" you now get a flat list\n  of test ids that you can use to paste to the py.test commandline\n  in order to execute a particular test.\n\n- fix issue25 avoid reported problems with --pdb and python3.2/encodings output\n\n- fix issue23 - tmpdir argument now works on Python3.2 and WindowsXP\n  Starting with Python3.2 os.symlink may be supported. By requiring\n  a newer py lib version the py.path.local() implementation acknowledges\n  this.\n\n- fixed typos in the docs (thanks Victor Garcia, Brianna Laugher) and particular\n  thanks to Laura Creighton who also reviewed parts of the documentation.\n\n- fix slightly wrong output of verbose progress reporting for classes\n  (thanks Amaury)\n\n- more precise (avoiding of) deprecation warnings for node.Class|Function accesses\n\n- avoid std unittest assertion helper code in tracebacks (thanks Ronny)\n\n2.0.1 (2011-02-07)\n==================\n\n- refine and unify initial capturing so that it works nicely\n  even if the logging module is used on an early-loaded conftest.py\n  file or plugin.\n- allow to omit \"()\" in test ids to allow for uniform test ids\n  as produced by Alfredo's nice pytest.vim plugin.\n- fix issue12 - show plugin versions with \"--version\" and\n  \"--traceconfig\" and also document how to add extra information\n  to reporting test header\n- fix issue17 (import-* reporting issue on python3) by\n  requiring py>1.4.0 (1.4.1 is going to include it)\n- fix issue10 (numpy arrays truth checking) by refining\n  assertion interpretation in py lib\n- fix issue15: make nose compatibility tests compatible\n  with python3 (now that nose-1.0 supports python3)\n- remove somewhat surprising \"same-conftest\" detection because\n  it ignores conftest.py when they appear in several subdirs.\n- improve assertions (\"not in\"), thanks Floris Bruynooghe\n- improve behaviour/warnings when running on top of \"python -OO\"\n  (assertions and docstrings are turned off, leading to potential\n  false positives)\n- introduce a pytest_cmdline_processargs(args) hook\n  to allow dynamic computation of command line arguments.\n  This fixes a regression because py.test prior to 2.0\n  allowed to set command line options from conftest.py\n  files which so far pytest-2.0 only allowed from ini-files now.\n- fix issue7: assert failures in doctest modules.\n  unexpected failures in doctests will not generally\n  show nicer, i.e. within the doctest failing context.\n- fix issue9: setup/teardown functions for an xfail-marked\n  test will report as xfail if they fail but report as normally\n  passing (not xpassing) if they succeed.  This only is true\n  for \"direct\" setup/teardown invocations because teardown_class/\n  teardown_module cannot closely relate to a single test.\n- fix issue14: no logging errors at process exit\n- refinements to \"collecting\" output on non-ttys\n- refine internal plugin registration and --traceconfig output\n- introduce a mechanism to prevent/unregister plugins from the\n  command line, see http://pytest.org/en/stable/how-to/plugins.html#cmdunregister\n- activate resultlog plugin by default\n- fix regression wrt yielded tests which due to the\n  collection-before-running semantics were not\n  setup as with pytest 1.3.4.  Note, however, that\n  the recommended and much cleaner way to do test\n  parameterization remains the \"pytest_generate_tests\"\n  mechanism, see the docs.\n\n2.0.0 (2010-11-25)\n==================\n\n- pytest-2.0 is now its own package and depends on pylib-2.0\n- new ability: python -m pytest / python -m pytest.main ability\n- new python invocation: pytest.main(args, plugins) to load\n  some custom plugins early.\n- try harder to run unittest test suites in a more compatible manner\n  by deferring setup/teardown semantics to the unittest package.\n  also work harder to run twisted/trial and Django tests which\n  should now basically work by default.\n- introduce a new way to set config options via ini-style files,\n  by default setup.cfg and tox.ini files are searched.  The old\n  ways (certain environment variables, dynamic conftest.py reading\n  is removed).\n- add a new \"-q\" option which decreases verbosity and prints a more\n  nose/unittest-style \"dot\" output.\n- fix issue135 - marks now work with unittest test cases as well\n- fix issue126 - introduce py.test.set_trace() to trace execution via\n  PDB during the running of tests even if capturing is ongoing.\n- fix issue123 - new \"python -m py.test\" invocation for py.test\n  (requires Python 2.5 or above)\n- fix issue124 - make reporting more resilient against tests opening\n  files on filedescriptor 1 (stdout).\n- fix issue109 - sibling conftest.py files will not be loaded.\n  (and Directory collectors cannot be customized anymore from a Directory's\n  conftest.py - this needs to happen at least one level up).\n- introduce (customizable) assertion failure representations and enhance\n  output on assertion failures for comparisons and other cases (Floris Bruynooghe)\n- nose-plugin: pass through type-signature failures in setup/teardown\n  functions instead of not calling them (Ed Singleton)\n- remove py.test.collect.Directory (follows from a major refactoring\n  and simplification of the collection process)\n- majorly reduce py.test core code, shift function/python testing to own plugin\n- fix issue88 (finding custom test nodes from command line arg)\n- refine 'tmpdir' creation, will now create basenames better associated\n  with test names (thanks Ronny)\n- \"xpass\" (unexpected pass) tests don't cause exitcode!=0\n- fix issue131 / issue60 - importing doctests in __init__ files used as namespace packages\n- fix issue93 stdout/stderr is captured while importing conftest.py\n- fix bug: unittest collected functions now also can have \"pytestmark\"\n  applied at class/module level\n- add ability to use \"class\" level for cached_setup helper\n- fix strangeness: mark.* objects are now immutable, create new instances\n\n1.3.4 (2010-09-14)\n==================\n\n- fix issue111: improve install documentation for windows\n- fix issue119: fix custom collectability of __init__.py as a module\n- fix issue116: --doctestmodules work with __init__.py files as well\n- fix issue115: unify internal exception passthrough/catching/GeneratorExit\n- fix issue118: new --tb=native for presenting cpython-standard exceptions\n\n1.3.3 (2010-07-30)\n==================\n\n- fix issue113: assertion representation problem with triple-quoted strings\n  (and possibly other cases)\n- make conftest loading detect that a conftest file with the same\n  content was already loaded, avoids surprises in nested directory structures\n  which can be produced e.g. by Hudson. It probably removes the need to use\n  --confcutdir in most cases.\n- fix terminal coloring for win32\n  (thanks Michael Foord for reporting)\n- fix weirdness: make terminal width detection work on stdout instead of stdin\n  (thanks Armin Ronacher for reporting)\n- remove trailing whitespace in all py/text distribution files\n\n1.3.2 (2010-07-08)\n==================\n\n**New features**\n\n- fix issue103:  introduce py.test.raises as context manager, examples::\n\n    with py.test.raises(ZeroDivisionError):\n        x = 0\n        1 / x\n\n    with py.test.raises(RuntimeError) as excinfo:\n        call_something()\n\n    # you may do extra checks on excinfo.value|type|traceback here\n\n  (thanks Ronny Pfannschmidt)\n\n- Funcarg factories can now dynamically apply a marker to a\n  test invocation.  This is for example useful if a factory\n  provides parameters to a test which are expected-to-fail::\n\n    def pytest_funcarg__arg(request):\n        request.applymarker(py.test.mark.xfail(reason=\"flaky config\"))\n        ...\n\n    def test_function(arg):\n        ...\n\n- improved error reporting on collection and import errors. This makes\n  use of a more general mechanism, namely that for custom test item/collect\n  nodes ``node.repr_failure(excinfo)`` is now uniformly called so that you can\n  override it to return a string error representation of your choice\n  which is going to be reported as a (red) string.\n\n- introduce '--junitprefix=STR' option to prepend a prefix\n  to all reports in the junitxml file.\n\n**Bug fixes**\n\n- make tests and the ``pytest_recwarn`` plugin in particular fully compatible\n  to Python2.7 (if you use the ``recwarn`` funcarg warnings will be enabled so that\n  you can properly check for their existence in a cross-python manner).\n- refine --pdb: ignore xfailed tests, unify its TB-reporting and\n  don't display failures again at the end.\n- fix assertion interpretation with the ** operator (thanks Benjamin Peterson)\n- fix issue105 assignment on the same line as a failing assertion (thanks Benjamin Peterson)\n- fix issue104 proper escaping for test names in junitxml plugin (thanks anonymous)\n- fix issue57 -f|--looponfail to work with xpassing tests (thanks Ronny)\n- fix issue92 collectonly reporter and --pastebin (thanks Benjamin Peterson)\n- fix py.code.compile(source) to generate unique filenames\n- fix assertion re-interp problems on PyPy, by deferring code\n  compilation to the (overridable) Frame.eval class. (thanks Amaury Forgeot)\n- fix py.path.local.pyimport() to work with directories\n- streamline py.path.local.mkdtemp implementation and usage\n- don't print empty lines when showing junitxml-filename\n- add optional boolean ignore_errors parameter to py.path.local.remove\n- fix terminal writing on win32/python2.4\n- py.process.cmdexec() now tries harder to return properly encoded unicode objects\n  on all python versions\n- install plain py.test/py.which scripts also for Jython, this helps to\n  get canonical script paths in virtualenv situations\n- make path.bestrelpath(path) return \".\", note that when calling\n  X.bestrelpath the assumption is that X is a directory.\n- make initial conftest discovery ignore \"--\" prefixed arguments\n- fix resultlog plugin when used in a multicpu/multihost xdist situation\n  (thanks Jakub Gustak)\n- perform distributed testing related reporting in the xdist-plugin\n  rather than having dist-related code in the generic py.test\n  distribution\n- fix homedir detection on Windows\n- ship distribute_setup.py version 0.6.13\n\n1.3.1 (2010-05-25)\n==================\n\n**New features**\n\n- issue91: introduce new py.test.xfail(reason) helper\n  to imperatively mark a test as expected to fail. Can\n  be used from within setup and test functions. This is\n  useful especially for parametrized tests when certain\n  configurations are expected-to-fail.  In this case the\n  declarative approach with the @py.test.mark.xfail cannot\n  be used as it would mark all configurations as xfail.\n\n- issue102: introduce new --maxfail=NUM option to stop\n  test runs after NUM failures.  This is a generalization\n  of the '-x' or '--exitfirst' option which is now equivalent\n  to '--maxfail=1'.  Both '-x' and '--maxfail' will\n  now also print a line near the end indicating the Interruption.\n\n- issue89: allow py.test.mark decorators to be used on classes\n  (class decorators were introduced with python2.6) and\n  also allow to have multiple markers applied at class/module level\n  by specifying a list.\n\n- improve and refine letter reporting in the progress bar:\n  .  pass\n  f  failed test\n  s  skipped tests (reminder: use for dependency/platform mismatch only)\n  x  xfailed test (test that was expected to fail)\n  X  xpassed test (test that was expected to fail but passed)\n\n  You can use any combination of 'fsxX' with the '-r' extended\n  reporting option. The xfail/xpass results will show up as\n  skipped tests in the junitxml output - which also fixes\n  issue99.\n\n- make py.test.cmdline.main() return the exitstatus instead of raising\n  SystemExit and also allow it to be called multiple times.  This of\n  course requires that your application and tests are properly teared\n  down and don't have global state.\n\n**Bug Fixes**\n\n- improved traceback presentation:\n  - improved and unified reporting for \"--tb=short\" option\n  - Errors during test module imports are much shorter, (using --tb=short style)\n  - raises shows shorter more relevant tracebacks\n  - --fulltrace now more systematically makes traces longer / inhibits cutting\n\n- improve support for raises and other dynamically compiled code by\n  manipulating python's linecache.cache instead of the previous\n  rather hacky way of creating custom code objects.  This makes\n  it seamlessly work on Jython and PyPy where it previously didn't.\n\n- fix issue96: make capturing more resilient against Control-C\n  interruptions (involved somewhat substantial refactoring\n  to the underlying capturing functionality to avoid race\n  conditions).\n\n- fix chaining of conditional skipif/xfail decorators - so it works now\n  as expected to use multiple @py.test.mark.skipif(condition) decorators,\n  including specific reporting which of the conditions lead to skipping.\n\n- fix issue95: late-import zlib so that it's not required\n  for general py.test startup.\n\n- fix issue94: make reporting more robust against bogus source code\n  (and internally be more careful when presenting unexpected byte sequences)\n\n\n1.3.0 (2010-05-05)\n==================\n\n- deprecate --report option in favour of a new shorter and easier to\n  remember -r option: it takes a string argument consisting of any\n  combination of 'xfsX' characters.  They relate to the single chars\n  you see during the dotted progress printing and will print an extra line\n  per test at the end of the test run.  This extra line indicates the exact\n  position or test ID that you directly paste to the py.test cmdline in order\n  to re-run a particular test.\n\n- allow external plugins to register new hooks via the new\n  pytest_addhooks(pluginmanager) hook.  The new release of\n  the pytest-xdist plugin for distributed and looponfailing\n  testing requires this feature.\n\n- add a new pytest_ignore_collect(path, config) hook to allow projects and\n  plugins to define exclusion behaviour for their directory structure -\n  for example you may define in a conftest.py this method::\n\n        def pytest_ignore_collect(path):\n            return path.check(link=1)\n\n  to prevent even a collection try of any tests in symlinked dirs.\n\n- new pytest_pycollect_makemodule(path, parent) hook for\n  allowing customization of the Module collection object for a\n  matching test module.\n\n- extend and refine xfail mechanism:\n  ``@py.test.mark.xfail(run=False)`` do not run the decorated test\n  ``@py.test.mark.xfail(reason=\"...\")`` prints the reason string in xfail summaries\n  specifying ``--runxfail`` on command line virtually ignores xfail markers\n\n- expose (previously internal) commonly useful methods:\n  py.io.get_terminal_with() -> return terminal width\n  py.io.ansi_print(...) -> print colored/bold text on linux/win32\n  py.io.saferepr(obj) -> return limited representation string\n\n- expose test outcome related exceptions as py.test.skip.Exception,\n  py.test.raises.Exception etc., useful mostly for plugins\n  doing special outcome interpretation/tweaking\n\n- (issue85) fix junitxml plugin to handle tests with non-ascii output\n\n- fix/refine python3 compatibility (thanks Benjamin Peterson)\n\n- fixes for making the jython/win32 combination work, note however:\n  jython2.5.1/win32 does not provide a command line launcher, see\n  https://bugs.jython.org/issue1491 . See pylib install documentation\n  for how to work around.\n\n- fixes for handling of unicode exception values and unprintable objects\n\n- (issue87) fix unboundlocal error in assertionold code\n\n- (issue86) improve documentation for looponfailing\n\n- refine IO capturing: stdin-redirect pseudo-file now has a NOP close() method\n\n- ship distribute_setup.py version 0.6.10\n\n- added links to the new capturelog and coverage plugins\n\n\n1.2.0 (2010-01-18)\n==================\n\n- refined usage and options for \"py.cleanup\"::\n\n    py.cleanup     # remove \"*.pyc\" and \"*$py.class\" (jython) files\n    py.cleanup -e .swp -e .cache # also remove files with these extensions\n    py.cleanup -s  # remove \"build\" and \"dist\" directory next to setup.py files\n    py.cleanup -d  # also remove empty directories\n    py.cleanup -a  # synonym for \"-s -d -e 'pip-log.txt'\"\n    py.cleanup -n  # dry run, only show what would be removed\n\n- add a new option \"py.test --funcargs\" which shows available funcargs\n  and their help strings (docstrings on their respective factory function)\n  for a given test path\n\n- display a short and concise traceback if a funcarg lookup fails\n\n- early-load \"conftest.py\" files in non-dot first-level sub directories.\n  allows to conveniently keep and access test-related options in a ``test``\n  subdir and still add command line options.\n\n- fix issue67: new super-short traceback-printing option: \"--tb=line\" will print a single line for each failing (python) test indicating its filename, lineno and the failure value\n\n- fix issue78: always call python-level teardown functions even if the\n  according setup failed.  This includes refinements for calling setup_module/class functions\n  which will now only be called once instead of the previous behaviour where they'd be called\n  multiple times if they raise an exception (including a Skipped exception).  Any exception\n  will be re-corded and associated with all tests in the according module/class scope.\n\n- fix issue63: assume <40 columns to be a bogus terminal width, default to 80\n\n- fix pdb debugging to be in the correct frame on raises-related errors\n\n- update apipkg.py to fix an issue where recursive imports might\n  unnecessarily break importing\n\n- fix plugin links\n\n1.1.1 (2009-11-24)\n==================\n\n- moved dist/looponfailing from py.test core into a new\n  separately released pytest-xdist plugin.\n\n- new junitxml plugin: --junitxml=path will generate a junit style xml file\n  which is processable e.g. by the Hudson CI system.\n\n- new option: --genscript=path will generate a standalone py.test script\n  which will not need any libraries installed.  thanks to Ralf Schmitt.\n\n- new option: --ignore will prevent specified path from collection.\n  Can be specified multiple times.\n\n- new option: --confcutdir=dir will make py.test only consider conftest\n  files that are relative to the specified dir.\n\n- new funcarg: \"pytestconfig\" is the pytest config object for access\n  to command line args and can now be easily used in a test.\n\n- install ``py.test`` and ``py.which`` with a ``-$VERSION`` suffix to\n  disambiguate between Python3, python2.X, Jython and PyPy installed versions.\n\n- new \"pytestconfig\" funcarg allows access to test config object\n\n- new \"pytest_report_header\" hook can return additional lines\n  to be displayed at the header of a test run.\n\n- (experimental) allow \"py.test path::name1::name2::...\" for pointing\n  to a test within a test collection directly.  This might eventually\n  evolve as a full substitute to \"-k\" specifications.\n\n- streamlined plugin loading: order is now as documented in\n  customize.html: setuptools, ENV, commandline, conftest.\n  also setuptools entry point names are turned to canonical names (\"pytest_*\")\n\n- automatically skip tests that need 'capfd' but have no os.dup\n\n- allow pytest_generate_tests to be defined in classes as well\n\n- deprecate usage of 'disabled' attribute in favour of pytestmark\n- deprecate definition of Directory, Module, Class and Function nodes\n  in conftest.py files.  Use pytest collect hooks instead.\n\n- collection/item node specific runtest/collect hooks are only called exactly\n  on matching conftest.py files, i.e. ones which are exactly below\n  the filesystem path of an item\n\n- change: the first pytest_collect_directory hook to return something\n  will now prevent further hooks to be called.\n\n- change: figleaf plugin now requires --figleaf to run.  Also\n  change its long command line options to be a bit shorter (see py.test -h).\n\n- change: pytest doctest plugin is now enabled by default and has a\n  new option --doctest-glob to set a pattern for file matches.\n\n- change: remove internal py._* helper vars, only keep py._pydir\n\n- robustify capturing to survive if custom pytest_runtest_setup\n  code failed and prevented the capturing setup code from running.\n\n- make py.test.* helpers provided by default plugins visible early -\n  works transparently both for pydoc and for interactive sessions\n  which will regularly see e.g. py.test.mark and py.test.importorskip.\n\n- simplify internal plugin manager machinery\n- simplify internal collection tree by introducing a RootCollector node\n\n- fix assert reinterpreation that sees a call containing \"keyword=...\"\n\n- fix issue66: invoke pytest_sessionstart and pytest_sessionfinish\n  hooks on worker nodes during dist-testing, report module/session teardown\n  hooks correctly.\n\n- fix issue65: properly handle dist-testing if no\n  execnet/py lib installed remotely.\n\n- skip some install-tests if no execnet is available\n\n- fix docs, fix internal bin/ script generation\n\n\n1.1.0 (2009-11-05)\n==================\n\n- introduce automatic plugin registration via 'pytest11'\n  entrypoints via setuptools' pkg_resources.iter_entry_points\n\n- fix py.test dist-testing to work with execnet >= 1.0.0b4\n\n- re-introduce py.test.cmdline.main() for better backward compatibility\n\n- svn paths: fix a bug with path.check(versioned=True) for svn paths,\n  allow '%' in svn paths, make svnwc.update() default to interactive mode\n  like in 1.0.x and add svnwc.update(interactive=False) to inhibit interaction.\n\n- refine distributed tarball to contain test and no pyc files\n\n- try harder to have deprecation warnings for py.compat.* accesses\n  report a correct location\n\n1.0.3\n=====\n\n* adjust and improve docs\n\n* remove py.rest tool and internal namespace - it was\n  never really advertised and can still be used with\n  the old release if needed.  If there is interest\n  it could be revived into its own tool i guess.\n\n* fix issue48 and issue59: raise an Error if the module\n  from an imported test file does not seem to come from\n  the filepath - avoids \"same-name\" confusion that has\n  been reported repeatedly\n\n* merged Ronny's nose-compatibility hacks: now\n  nose-style setup_module() and setup() functions are\n  supported\n\n* introduce generalized py.test.mark function marking\n\n* reshuffle / refine command line grouping\n\n* deprecate parser.addgroup in favour of getgroup which creates option group\n\n* add --report command line option that allows to control showing of skipped/xfailed sections\n\n* generalized skipping: a new way to mark python functions with skipif or xfail\n  at function, class and modules level based on platform or sys-module attributes.\n\n* extend py.test.mark decorator to allow for positional args\n\n* introduce and test \"py.cleanup -d\" to remove empty directories\n\n* fix issue #59 - robustify unittest test collection\n\n* make bpython/help interaction work by adding an __all__ attribute\n  to ApiModule, cleanup initpkg\n\n* use MIT license for pylib, add some contributors\n\n* remove py.execnet code and substitute all usages with 'execnet' proper\n\n* fix issue50 - cached_setup now caches more to expectations\n  for test functions with multiple arguments.\n\n* merge Jarko's fixes, issue #45 and #46\n\n* add the ability to specify a path for py.lookup to search in\n\n* fix a funcarg cached_setup bug probably only occurring\n  in distributed testing and \"module\" scope with teardown.\n\n* many fixes and changes for making the code base python3 compatible,\n  many thanks to Benjamin Peterson for helping with this.\n\n* consolidate builtins implementation to be compatible with >=2.3,\n  add helpers to ease keeping 2 and 3k compatible code\n\n* deprecate py.compat.doctest|subprocess|textwrap|optparse\n\n* deprecate py.magic.autopath, remove py/magic directory\n\n* move pytest assertion handling to py/code and a pytest_assertion\n  plugin, add \"--no-assert\" option, deprecate py.magic namespaces\n  in favour of (less) py.code ones.\n\n* consolidate and cleanup py/code classes and files\n\n* cleanup py/misc, move tests to bin-for-dist\n\n* introduce delattr/delitem/delenv methods to py.test's monkeypatch funcarg\n\n* consolidate py.log implementation, remove old approach.\n\n* introduce py.io.TextIO and py.io.BytesIO for distinguishing between\n  text/unicode and byte-streams (uses underlying standard lib io.*\n  if available)\n\n* make py.unittest_convert helper script available which converts \"unittest.py\"\n  style files into the simpler assert/direct-test-classes py.test/nosetests\n  style.  The script was written by Laura Creighton.\n\n* simplified internal localpath implementation\n\n1.0.2 (2009-08-27)\n==================\n\n* fixing packaging issues, triggered by fedora redhat packaging,\n  also added doc, examples and contrib dirs to the tarball.\n\n* added a documentation link to the new django plugin.\n\n1.0.1 (2009-08-19)\n==================\n\n* added a 'pytest_nose' plugin which handles nose.SkipTest,\n  nose-style function/method/generator setup/teardown and\n  tries to report functions correctly.\n\n* capturing of unicode writes or encoded strings to sys.stdout/err\n  work better, also terminalwriting was adapted and somewhat\n  unified between windows and linux.\n\n* improved documentation layout and content a lot\n\n* added a \"--help-config\" option to show conftest.py / ENV-var names for\n  all longopt cmdline options, and some special conftest.py variables.\n  renamed 'conf_capture' conftest setting to 'option_capture' accordingly.\n\n* fix issue #27: better reporting on non-collectable items given on commandline\n  (e.g. pyc files)\n\n* fix issue #33: added --version flag (thanks Benjamin Peterson)\n\n* fix issue #32: adding support for \"incomplete\" paths to wcpath.status()\n\n* \"Test\" prefixed classes are *not* collected by default anymore if they\n  have an __init__ method\n\n* monkeypatch setenv() now accepts a \"prepend\" parameter\n\n* improved reporting of collection error tracebacks\n\n* simplified multicall mechanism and plugin architecture,\n  renamed some internal methods and argnames\n\n1.0.0 (2009-08-04)\n==================\n\n* more terse reporting try to show filesystem path relatively to current dir\n* improve xfail output a bit\n\n1.0.0b9 (2009-07-31)\n====================\n\n* cleanly handle and report final teardown of test setup\n\n* fix svn-1.6 compat issue with py.path.svnwc().versioned()\n  (thanks Wouter Vanden Hove)\n\n* setup/teardown or collection problems now show as ERRORs\n  or with big \"E\"'s in the progress lines.  they are reported\n  and counted separately.\n\n* dist-testing: properly handle test items that get locally\n  collected but cannot be collected on the remote side - often\n  due to platform/dependency reasons\n\n* simplified py.test.mark API - see keyword plugin documentation\n\n* integrate better with logging: capturing now by default captures\n  test functions and their immediate setup/teardown in a single stream\n\n* capsys and capfd funcargs now have a readouterr() and a close() method\n  (underlyingly py.io.StdCapture/FD objects are used which grew a\n  readouterr() method as well to return snapshots of captured out/err)\n\n* make assert-reinterpretation work better with comparisons not\n  returning bools (reported with numpy from thanks maciej fijalkowski)\n\n* reworked per-test output capturing into the pytest_iocapture.py plugin\n  and thus removed capturing code from config object\n\n* item.repr_failure(excinfo) instead of item.repr_failure(excinfo, outerr)\n\n\n1.0.0b8 (2009-07-22)\n====================\n\n* pytest_unittest-plugin is now enabled by default\n\n* introduced pytest_keyboardinterrupt hook and\n  refined pytest_sessionfinish hooked, added tests.\n\n* workaround a buggy logging module interaction (\"closing already closed\n  files\").  Thanks to Sridhar Ratnakumar for triggering.\n\n* if plugins use \"py.test.importorskip\" for importing\n  a dependency only a warning will be issued instead\n  of exiting the testing process.\n\n* many improvements to docs:\n  - refined funcargs doc , use the term \"factory\" instead of \"provider\"\n  - added a new talk/tutorial doc page\n  - better download page\n  - better plugin docstrings\n  - added new plugins page and automatic doc generation script\n\n* fixed teardown problem related to partially failing funcarg setups\n  (thanks MrTopf for reporting), \"pytest_runtest_teardown\" is now\n  always invoked even if the \"pytest_runtest_setup\" failed.\n\n* tweaked doctest output for docstrings in py modules,\n  thanks Radomir.\n\n1.0.0b7\n=======\n\n* renamed py.test.xfail back to py.test.mark.xfail to avoid\n  two ways to decorate for xfail\n\n* re-added py.test.mark decorator for setting keywords on functions\n  (it was actually documented so removing it was not nice)\n\n* remove scope-argument from request.addfinalizer() because\n  request.cached_setup has the scope arg. TOOWTDI.\n\n* perform setup finalization before reporting failures\n\n* apply modified patches from Andreas Kloeckner to allow\n  test functions to have no func_code (#22) and to make\n  \"-k\" and function keywords work  (#20)\n\n* apply patch from Daniel Peolzleithner (issue #23)\n\n* resolve issue #18, multiprocessing.Manager() and\n  redirection clash\n\n* make __name__ == \"__channelexec__\" for remote_exec code\n\n1.0.0b3 (2009-06-19)\n====================\n\n* plugin classes are removed: one now defines\n  hooks directly in conftest.py or global pytest_*.py\n  files.\n\n* added new pytest_namespace(config) hook that allows\n  to inject helpers directly to the py.test.* namespace.\n\n* documented and refined many hooks\n\n* added new style of generative tests via\n  pytest_generate_tests hook that integrates\n  well with function arguments.\n\n\n1.0.0b1\n=======\n\n* introduced new \"funcarg\" setup method,\n  see doc/test/funcarg.txt\n\n* introduced plugin architecture and many\n  new py.test plugins, see\n  doc/test/plugins.txt\n\n* teardown_method is now guaranteed to get\n  called after a test method has run.\n\n* new method: py.test.importorskip(mod,minversion)\n  will either import or call py.test.skip()\n\n* completely revised internal py.test architecture\n\n* new py.process.ForkedFunc object allowing to\n  fork execution of a function to a sub process\n  and getting a result back.\n\nXXX lots of things missing here XXX\n\n0.9.2\n=====\n\n* refined installation and metadata, created new setup.py,\n  now based on setuptools/ez_setup (thanks to Ralf Schmitt\n  for his support).\n\n* improved the way of making py.* scripts available in\n  windows environments, they are now added to the\n  Scripts directory as \".cmd\" files.\n\n* py.path.svnwc.status() now is more complete and\n  uses xml output from the 'svn' command if available\n  (Guido Wesdorp)\n\n* fix for py.path.svn* to work with svn 1.5\n  (Chris Lamb)\n\n* fix path.relto(otherpath) method on windows to\n  use normcase for checking if a path is relative.\n\n* py.test's traceback is better parseable from editors\n  (follows the filenames:LINENO: MSG convention)\n  (thanks to Osmo Salomaa)\n\n* fix to javascript-generation, \"py.test --runbrowser\"\n  should work more reliably now\n\n* removed previously accidentally added\n  py.test.broken and py.test.notimplemented helpers.\n\n* there now is a py.__version__ attribute\n\n0.9.1\n=====\n\nThis is a fairly complete list of v0.9.1, which can\nserve as a reference for developers.\n\n* allowing + signs in py.path.svn urls [39106]\n* fixed support for Failed exceptions without excinfo in py.test [39340]\n* added support for killing processes for Windows (as well as platforms that\n  support os.kill) in py.misc.killproc [39655]\n* added setup/teardown for generative tests to py.test [40702]\n* added detection of FAILED TO LOAD MODULE to py.test [40703, 40738, 40739]\n* fixed problem with calling .remove() on wcpaths of non-versioned files in\n  py.path [44248]\n* fixed some import and inheritance issues in py.test [41480, 44648, 44655]\n* fail to run greenlet tests when pypy is available, but without stackless\n  [45294]\n* small fixes in rsession tests [45295]\n* fixed issue with 2.5 type representations in py.test [45483, 45484]\n* made that internal reporting issues displaying is done atomically in py.test\n  [45518]\n* made that non-existing files are ignored by the py.lookup script [45519]\n* improved exception name creation in py.test [45535]\n* made that less threads are used in execnet [merge in 45539]\n* removed lock required for atomic reporting issue displaying in py.test\n  [45545]\n* removed globals from execnet [45541, 45547]\n* refactored cleanup mechanics, made that setDaemon is set to 1 to make atexit\n  get called in 2.5 (py.execnet) [45548]\n* fixed bug in joining threads in py.execnet's servemain [45549]\n* refactored py.test.rsession tests to not rely on exact output format anymore\n  [45646]\n* using repr() on test outcome [45647]\n* added 'Reason' classes for py.test.skip() [45648, 45649]\n* killed some unnecessary sanity check in py.test.collect [45655]\n* avoid using os.tmpfile() in py.io.fdcapture because on Windows it's only\n  usable by Administrators [45901]\n* added support for locking and non-recursive commits to py.path.svnwc [45994]\n* locking files in py.execnet to prevent CPython from segfaulting [46010]\n* added export() method to py.path.svnurl\n* fixed -d -x in py.test [47277]\n* fixed argument concatenation problem in py.path.svnwc [49423]\n* restore py.test behaviour that it exits with code 1 when there are failures\n  [49974]\n* don't fail on html files that don't have an accompanying .txt file [50606]\n* fixed 'utestconvert.py < input' [50645]\n* small fix for code indentation in py.code.source [50755]\n* fix _docgen.py documentation building [51285]\n* improved checks for source representation of code blocks in py.test [51292]\n* added support for passing authentication to py.path.svn* objects [52000,\n  52001]\n* removed sorted() call for py.apigen tests in favour of [].sort() to support\n  Python 2.3 [52481]\n"
  },
  {
    "path": "doc/en/conf.py",
    "content": "from __future__ import annotations\n\nimport os\nfrom pathlib import Path\nimport shutil\nfrom textwrap import dedent\nfrom typing import TYPE_CHECKING\n\nfrom pytest import __version__ as full_version\n\n\nif TYPE_CHECKING:\n    import sphinx.application\n\nPROJECT_ROOT_DIR = Path(__file__).parents[2].resolve()\n\n# -- Project information ---------------------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information\n\nproject = \"pytest\"\ncopyright = \"2015, holger krekel and pytest-dev team\"\nversion = full_version.split(\"+\")[0]\nrelease = \".\".join(version.split(\".\")[:2])\n\n# -- General configuration -------------------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration\n\nroot_doc = \"index\"\nextensions = [\n    \"pygments_pytest\",\n    \"sphinx.ext.autodoc\",\n    \"sphinx.ext.autosummary\",\n    \"sphinx.ext.intersphinx\",\n    \"sphinx.ext.todo\",\n    \"sphinx.ext.viewcode\",\n    \"sphinx_removed_in\",\n    \"sphinx_inline_tabs\",\n    \"sphinxcontrib_trio\",\n    \"sphinxcontrib.towncrier.ext\",  # provides `towncrier-draft-entries` directive\n    \"sphinx_issues\",  # implements `:issue:`, `:pr:` and other GH-related roles\n]\n\n# Building PDF docs on readthedocs requires inkscape for svg to pdf\n# conversion. The relevant plugin is not useful for normal HTML builds, but\n# it still raises warnings and fails CI if inkscape is not available. So\n# only use the plugin if inkscape is actually available.\nif shutil.which(\"inkscape\"):\n    extensions.append(\"sphinxcontrib.inkscapeconverter\")\n\nexclude_patterns = [\n    \"_build\",\n    \"naming20.rst\",\n    \"test/*\",\n    \"old_*\",\n    \"*attic*\",\n    \"*/attic*\",\n    \"funcargs.rst\",\n    \"setup.rst\",\n    \"example/remoteinterp.rst\",\n]\ntemplates_path = [\"_templates\"]\ndefault_role = \"literal\"\n\nnitpicky = True\nnitpick_ignore = [\n    # TODO (fix in pluggy?)\n    (\"py:class\", \"HookCaller\"),\n    (\"py:class\", \"HookspecMarker\"),\n    (\"py:exc\", \"PluginValidationError\"),\n    # Might want to expose/TODO (https://github.com/pytest-dev/pytest/issues/7469)\n    (\"py:class\", \"ExceptionRepr\"),\n    (\"py:class\", \"Exit\"),\n    (\"py:class\", \"SubRequest\"),\n    (\"py:class\", \"SubRequest\"),\n    (\"py:class\", \"TerminalReporter\"),\n    (\"py:class\", \"_pytest._code.code.TerminalRepr\"),\n    (\"py:class\", \"TerminalRepr\"),\n    (\"py:class\", \"_pytest.fixtures.FixtureFunctionMarker\"),\n    (\"py:class\", \"_pytest.fixtures.FixtureFunctionDefinition\"),\n    (\"py:class\", \"_pytest.logging.LogCaptureHandler\"),\n    (\"py:class\", \"_pytest.mark.structures.ParameterSet\"),\n    # Intentionally undocumented/private\n    (\"py:class\", \"_pytest._code.code.Traceback\"),\n    (\"py:class\", \"_pytest._py.path.LocalPath\"),\n    (\"py:class\", \"_pytest.capture.CaptureResult\"),\n    (\"py:class\", \"_pytest.compat.NotSetType\"),\n    (\"py:class\", \"_pytest.python.PyCollector\"),\n    (\"py:class\", \"_pytest.python.PyobjMixin\"),\n    (\"py:class\", \"_pytest.python_api.RaisesContext\"),\n    (\"py:class\", \"_pytest.recwarn.WarningsChecker\"),\n    (\"py:class\", \"_pytest.reports.BaseReport\"),\n    # Sphinx bugs(?)\n    (\"py:class\", \"RewriteHook\"),\n    # Undocumented third parties\n    (\"py:class\", \"_tracing.TagTracerSub\"),\n    (\"py:class\", \"warnings.WarningMessage\"),\n    # Undocumented type aliases\n    (\"py:class\", \"LEGACY_PATH\"),\n    (\"py:class\", \"_PluggyPlugin\"),\n    # TypeVars\n    (\"py:class\", \"_pytest._code.code.E\"),\n    (\"py:class\", \"E\"),  # due to delayed annotation\n    (\"py:class\", \"_pytest.fixtures.FixtureFunction\"),\n    (\"py:class\", \"_pytest.nodes._NodeType\"),\n    (\"py:class\", \"_NodeType\"),  # due to delayed annotation\n    (\"py:class\", \"_pytest.python_api.E\"),\n    (\"py:class\", \"_pytest.recwarn.T\"),\n    (\"py:class\", \"_pytest.runner.TResult\"),\n    (\"py:obj\", \"_pytest.fixtures.FixtureValue\"),\n    (\"py:obj\", \"_pytest.stash.T\"),\n    (\"py:class\", \"_ScopeName\"),\n    (\"py:class\", \"BaseExcT_1\"),\n    (\"py:class\", \"ExcT_1\"),\n]\n\nadd_module_names = False\n\n# -- Options for Autodoc --------------------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#configuration\n\nautodoc_member_order = \"bysource\"\nautodoc_typehints = \"description\"\nautodoc_typehints_description_target = \"documented\"\n\n# -- Options for intersphinx ----------------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html#configuration\n\nintersphinx_mapping = {\n    \"pluggy\": (\"https://pluggy.readthedocs.io/en/stable\", None),\n    \"python\": (\"https://docs.python.org/3\", None),\n    \"numpy\": (\"https://numpy.org/doc/stable\", None),\n    \"pip\": (\"https://pip.pypa.io/en/stable\", None),\n    \"tox\": (\"https://tox.wiki/en/stable\", None),\n    \"virtualenv\": (\"https://virtualenv.pypa.io/en/stable\", None),\n    \"setuptools\": (\"https://setuptools.pypa.io/en/stable\", None),\n    \"packaging\": (\"https://packaging.python.org/en/latest\", None),\n}\n\n# -- Options for todo -----------------------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/extensions/todo.html#configuration\n\ntodo_include_todos = True\n\n# -- Options for linkcheck builder ----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-the-linkcheck-builder\n\nlinkcheck_ignore = [\n    \"https://blogs.msdn.microsoft.com/bharry/2017/06/28/testing-in-a-cloud-delivery-cadence/\",\n    \"http://pythontesting.net/framework/pytest-introduction/\",\n    r\"https://github.com/pytest-dev/pytest/issues/\\d+\",\n    r\"https://github.com/pytest-dev/pytest/pull/\\d+\",\n]\nlinkcheck_workers = 5\n\n# -- Options for HTML output ----------------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output\n\nhtml_theme = \"furo\"\nhtml_theme_options = {\"sidebar_hide_name\": True}\n\nhtml_static_path = [\"_static\"]\nhtml_css_files = [\n    \"pytest-custom.css\",\n]\n\nhtml_title = \"pytest documentation\"\nhtml_short_title = f\"pytest-{release}\"\n\nhtml_logo = \"_static/pytest1.png\"\nhtml_favicon = \"img/favicon.png\"\n\nhtml_use_index = False\nhtml_show_sourcelink = False\n\nhtml_baseurl = \"https://docs.pytest.org/en/stable/\"\n\n# -- Options for HTML Help output -----------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-help-output\n\nhtmlhelp_basename = \"pytestdoc\"\n\n\n# -- Options for manual page output ---------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-manual-page-output\n\nman_pages = [\n    (\"how-to/usage\", \"pytest\", \"pytest usage\", [\"holger krekel at merlinux eu\"], 1)\n]\n\n# -- Options for epub output ----------------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-epub-output\n\nepub_title = \"pytest\"\nepub_author = \"holger krekel at merlinux eu\"\nepub_publisher = \"holger krekel at merlinux eu\"\nepub_copyright = \"2013, holger krekel et alii\"\n\n# -- Options for LaTeX output --------------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-latex-output\n\nlatex_documents = [\n    (\n        \"contents\",\n        \"pytest.tex\",\n        \"pytest Documentation\",\n        \"holger krekel, trainer and consultant, https://merlinux.eu/\",\n        \"manual\",\n    )\n]\nlatex_domain_indices = False\nlatex_engine = \"lualatex\"\nlatex_elements = {\n    \"preamble\": dedent(\n        r\"\"\"\n        \\directlua{\n            luaotfload.add_fallback(\"fallbacks\", {\n                \"Noto Serif CJK SC:style=Regular;\",\n                \"Symbola:Style=Regular;\"\n            })\n        }\n\n        \\setmainfont{FreeSerif}[RawFeature={fallback=fallbacks}]\n        \"\"\"\n    )\n}\n\n# -- Options for texinfo output -------------------------------------------------------\n# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-texinfo-output\n\ntexinfo_documents = [\n    (\n        root_doc,\n        \"pytest\",\n        \"pytest Documentation\",\n        (\n            \"Holger Krekel@*Benjamin Peterson@*Ronny Pfannschmidt@*\"\n            \"Floris Bruynooghe@*others\"\n        ),\n        \"pytest\",\n        \"simple powerful testing with Python\",\n        \"Programming\",\n        1,\n    )\n]\n\n# -- Options for towncrier_draft extension --------------------------------------------\n# https://sphinxcontrib-towncrier.readthedocs.io/en/latest/#how-to-use-this\n\ntowncrier_draft_autoversion_mode = \"draft\"  # or: 'sphinx-version', 'sphinx-release'\ntowncrier_draft_include_empty = True\ntowncrier_draft_working_directory = PROJECT_ROOT_DIR\ntowncrier_draft_config_path = \"pyproject.toml\"  # relative to cwd\n\n# -- Options for sphinx_issues extension -----------------------------------\n# https://github.com/sloria/sphinx-issues#installation-and-configuration\n\nissues_github_path = \"pytest-dev/pytest\"\n\n# -- Custom Read the Docs build configuration -----------------------------------------\n# https://docs.readthedocs.io/en/stable/reference/environment-variables.html#environment-variable-reference\n# https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#including-content-based-on-tags\n\nIS_RELEASE_ON_RTD = (\n    os.getenv(\"READTHEDOCS\", \"False\") == \"True\"\n    and os.environ[\"READTHEDOCS_VERSION_TYPE\"] == \"tag\"\n)\nif IS_RELEASE_ON_RTD:\n    tags: set[str]\n    # pylint: disable-next=used-before-assignment\n    tags.add(\"is_release\")  # noqa: F821\n\n# -- Custom documentation plugin ------------------------------------------------------\n# https://www.sphinx-doc.org/en/master/development/tutorials/extending_syntax.html#the-setup-function\n\n\ndef setup(app: sphinx.application.Sphinx) -> None:\n    app.add_crossref_type(\n        \"fixture\",\n        \"fixture\",\n        objname=\"built-in fixture\",\n        indextemplate=\"pair: %s; fixture\",\n    )\n\n    app.add_object_type(\n        \"confval\",\n        \"confval\",\n        objname=\"configuration value\",\n        indextemplate=\"pair: %s; configuration value\",\n    )\n\n    app.add_object_type(\n        \"globalvar\",\n        \"globalvar\",\n        objname=\"global variable interpreted by pytest\",\n        indextemplate=\"pair: %s; global variable interpreted by pytest\",\n    )\n\n    app.add_crossref_type(\n        directivename=\"hook\",\n        rolename=\"hook\",\n        objname=\"pytest hook\",\n        indextemplate=\"pair: %s; hook\",\n    )\n\n    # legacypath.py monkey-patches pytest.Testdir in. Import the file so\n    # that autodoc can discover references to it.\n    import _pytest.legacypath  # noqa: F401\n"
  },
  {
    "path": "doc/en/conftest.py",
    "content": "from __future__ import annotations\n\n\ncollect_ignore = [\"conf.py\"]\n"
  },
  {
    "path": "doc/en/contact.rst",
    "content": "\n.. _`contact channels`:\n.. _`contact`:\n\nContact channels\n================\n\nWeb\n---\n\n- `pytest issue tracker`_ to report bugs or suggest features.\n- `pytest discussions`_ at GitHub for general questions.\n- `pytest on stackoverflow.com <http://stackoverflow.com/search?q=pytest>`_\n  to post precise questions with the tag ``pytest``.  New questions will usually\n  be seen by pytest users or developers and answered quickly.\n\nChat\n----\n\n- `pytest discord server <https://discord.com/invite/pytest-dev>`_\n  for pytest development visibility and general assistance.\n- ``#pytest`` `on irc.libera.chat <ircs://irc.libera.chat:6697/#pytest>`_ IRC\n  channel for random questions (using an IRC client, or `via webchat\n  <https://web.libera.chat/#pytest>`_)\n- ``#pytest`` `on Matrix <https://matrix.to/#/#pytest:matrix.org>`_.\n\nMicroblogging\n-------------\n\n- Bluesky: `@pytest.org <https://bsky.app/profile/pytest.org>`_\n- Mastodon: `@pytest@fosstodon.org <https://fosstodon.org/@pytest>`_\n- Twitter/X: `@pytestdotorg <https://x.com/pytestdotorg>`_\n\nMail\n----\n\n- `Testing In Python`_: a mailing list for Python testing tools and discussion.\n- Mail to `core@pytest.org <mailto:core@pytest.org>`_ for topics that cannot be\n  discussed in public. Mails sent there will be distributed among the members\n  in the pytest core team, who can also be contacted individually:\n\n  * Bruno Oliveira (:user:`nicoddemus`, `bruno@pytest.org <mailto:bruno@pytest.org>`_)\n  * Freya Bruhin (:user:`The-Compiler`, `freya@pytest.org <mailto:freya@pytest.org>`_)\n  * Pierre Sassoulas (:user:`Pierre-Sassoulas`, `pierre@pytest.org <mailto:pierre@pytest.org>`_)\n  * Ran Benita (:user:`bluetech`, `ran@pytest.org <mailto:ran@pytest.org>`_)\n  * Ronny Pfannschmidt (:user:`RonnyPfannschmidt`, `ronny@pytest.org <mailto:ronny@pytest.org>`_)\n  * Zac Hatfield-Dodds (:user:`Zac-HD`, `zac@pytest.org <mailto:zac@pytest.org>`_)\n\nOther\n-----\n\n- The :doc:`contribution guide <contributing>` for help on submitting pull\n  requests to GitHub.\n- Freya Bruhin (:user:`The-Compiler`) offers pytest professional teaching and\n  consulting via `Bruhin Software <https://bruhin.software>`_.\n\n.. _`pytest issue tracker`: https://github.com/pytest-dev/pytest/issues\n.. _`pytest discussions`: https://github.com/pytest-dev/pytest/discussions\n.. _`Testing in Python`: http://lists.idyll.org/listinfo/testing-in-python\n"
  },
  {
    "path": "doc/en/contents.rst",
    "content": ":orphan:\n\n.. _toc:\n\nFull pytest documentation\n===========================\n\n`Download latest version as PDF <https://media.readthedocs.org/pdf/pytest/latest/pytest.pdf>`_\n\n.. `Download latest version as EPUB <http://media.readthedocs.org/epub/pytest/latest/pytest.epub>`_\n\n\nStart here\n-----------\n\n.. toctree::\n   :maxdepth: 2\n\n   getting-started\n\n\nHow-to guides\n-------------\n\n.. toctree::\n   :maxdepth: 2\n\n   how-to/usage\n   how-to/assert\n   how-to/fixtures\n   how-to/mark\n   how-to/parametrize\n   how-to/tmp_path\n   how-to/monkeypatch\n   how-to/doctest\n   how-to/cache\n\n   how-to/logging\n   how-to/capture-stdout-stderr\n   how-to/capture-warnings\n   how-to/skipping\n\n   how-to/plugins\n   how-to/writing_plugins\n   how-to/writing_hook_functions\n\n   how-to/existingtestsuite\n   how-to/unittest\n   how-to/xunit_setup\n\n   how-to/bash-completion\n\n\nReference guides\n-----------------\n\n.. toctree::\n   :maxdepth: 2\n\n   reference/fixtures\n   reference/plugin_list\n   reference/customize\n   reference/reference\n\n\nExplanation\n-----------------\n\n.. toctree::\n   :maxdepth: 2\n\n   explanation/anatomy\n   explanation/fixtures\n   explanation/goodpractices\n   explanation/flaky\n   explanation/pythonpath\n\n\nFurther topics\n-----------------\n\n.. toctree::\n   :maxdepth: 2\n\n   example/index\n\n   backwards-compatibility\n   deprecations\n\n   contributing\n   development_guide\n\n   sponsor\n   tidelift\n   license\n   contact\n\n   history\n   historical-notes\n   talks\n\n\n.. only:: html\n\n   .. toctree::\n      :maxdepth: 1\n\n      announce/index\n\n.. only:: html\n\n   .. toctree::\n      :hidden:\n      :maxdepth: 1\n\n      changelog\n"
  },
  {
    "path": "doc/en/contributing.rst",
    "content": ".. _contributing:\n\n.. include:: ../../CONTRIBUTING.rst\n"
  },
  {
    "path": "doc/en/deprecations.rst",
    "content": ".. _deprecations:\n\nDeprecations and Removals\n=========================\n\nThis page lists all pytest features that are currently deprecated or have been removed in past major releases.\nThe objective is to give users a clear rationale why a certain feature has been removed, and what alternatives\nshould be used instead.\n\n\nDeprecated Features\n-------------------\n\nBelow is a complete list of all pytest features which are considered deprecated. Using those features will issue\n:class:`~pytest.PytestWarning` or subclasses, which can be filtered using :ref:`standard warning filters <warnings>`.\n\n\n.. _dynamic-fixture-request-during-teardown:\n\n``request.getfixturevalue()`` during fixture teardown\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 9.1\n\nCalling :meth:`request.getfixturevalue() <pytest.FixtureRequest.getfixturevalue>`\nduring teardown to request a fixture that was not already requested is deprecated.\n\nThis pattern is brittle because teardown runs after pytest has started unwinding active scopes.\nDepending on the requested fixture's scope and the current teardown order, the lookup may appear\nto work, or it may fail.\n\nIn pytest 10, first-time fixture requests made during teardown will become an error.\nIf teardown logic needs another fixture, request it before teardown begins, either by\ndeclaring it in the fixture signature or by calling ``request.getfixturevalue()`` before\nthe fixture yields.\n\nFixtures that were already requested before teardown started are unaffected and may still\nbe retrieved while they remain active, though this is discouraged.\n\n\n.. _config-inicfg:\n\n``config.inicfg``\n~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 9.0\n\nThe private ``config.inicfg`` attribute is deprecated.\nUse :meth:`config.getini() <pytest.Config.getini>` to access configuration values instead.\n\n``config.inicfg`` was never documented and it should have had a ``_`` prefix from the start.\nPytest performs caching, transformation and aliasing on configuration options which make direct access to the raw ``config.inicfg`` untenable.\n\n**Reading configuration values:**\n\nInstead of accessing ``config.inicfg`` directly, use :meth:`config.getini() <pytest.Config.getini>`:\n\n.. code-block:: python\n\n    # Deprecated\n    value = config.inicfg[\"some_option\"]\n\n    # Use this instead\n    value = config.getini(\"some_option\")\n\n**Setting configuration values:**\n\nSetting or deleting configuration values after initialization is not supported.\nIf you need to override configuration values, use the ``-o`` command line option:\n\n.. code-block:: bash\n\n    pytest -o some_option=value\n\nor set them in your configuration file instead.\n\n\n.. _parametrize-iterators:\n\nNon-Collection iterables in ``@pytest.mark.parametrize``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 9.1\n\nUsing non-:class:`~collections.abc.Collection` iterables (such as generators, iterators, or custom iterable objects)\nfor the ``argvalues`` parameter in :ref:`@pytest.mark.parametrize <pytest.mark.parametrize ref>`\nand :meth:`metafunc.parametrize <pytest.Metafunc.parametrize>` is deprecated.\n\nThese iterables get exhausted after the first iteration, leading to tests getting unexpectedly skipped in cases such as:\n\n* Running :func:`pytest.main()` multiple times in the same process\n* Using class-level parametrize decorators where the same mark is applied to multiple test methods\n* Collecting tests multiple times\n\nExample of problematic code:\n\n.. code-block:: python\n\n    import pytest\n\n\n    def data_generator():\n        yield 1\n        yield 2\n\n\n    @pytest.mark.parametrize(\"n\", data_generator())\n    class Test:\n        def test_1(self, n):\n            pass\n\n        # test_2 will be skipped because data_generator() is exhausted.\n        def test_2(self, n):\n            pass\n\nYou can fix it by converting generators and iterators to lists or tuples:\n\n.. code-block:: python\n\n    import pytest\n\n\n    def data_generator():\n        yield 1\n        yield 2\n\n\n    @pytest.mark.parametrize(\"n\", list(data_generator()))\n    class Test:\n        def test_1(self, n):\n            pass\n\n        def test_2(self, n):\n            pass\n\nNote that :class:`range` objects are ``Collection`` and are not affected by this deprecation.\n\n\n.. _monkeypatch-fixup-namespace-packages:\n\n``monkeypatch.syspath_prepend`` with legacy namespace packages\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 9.0\n\nWhen using :meth:`monkeypatch.syspath_prepend() <pytest.MonkeyPatch.syspath_prepend>`,\npytest automatically calls ``pkg_resources.fixup_namespace_packages()`` if ``pkg_resources`` is imported.\nThis is only needed for legacy namespace packages that use ``pkg_resources.declare_namespace()``.\n\nLegacy namespace packages are deprecated in favor of native namespace packages (:pep:`420`).\nIf you are using ``pkg_resources.declare_namespace()`` in your ``__init__.py`` files,\nyou should migrate to native namespace packages by removing the ``__init__.py`` files from your namespace packages.\n\nThis deprecation warning will only be issued when:\n\n1. ``pkg_resources`` is imported, and\n2. The specific path being prepended contains a declared namespace package (via ``pkg_resources.declare_namespace()``)\n\nTo fix this warning, convert your legacy namespace packages to native namespace packages:\n\n**Legacy namespace package** (deprecated):\n\n.. code-block:: python\n\n    # mypkg/__init__.py\n    __import__(\"pkg_resources\").declare_namespace(__name__)\n\n**Native namespace package** (recommended):\n\nSimply remove the ``__init__.py`` file entirely.\nPython 3.3+ natively supports namespace packages without ``__init__.py``.\n\n\nConfiguring hook specs/impls using markers\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBefore pluggy, pytest's plugin library, was its own package and had a clear API,\npytest just used ``pytest.mark`` to configure hooks.\n\nThe :py:func:`pytest.hookimpl` and :py:func:`pytest.hookspec` decorators\nhave been available since years and should be used instead.\n\n.. code-block:: python\n\n    @pytest.mark.tryfirst\n    def pytest_runtest_call(): ...\n\n\n    # or\n    def pytest_runtest_call(): ...\n\n\n    pytest_runtest_call.tryfirst = True\n\nshould be changed to:\n\n.. code-block:: python\n\n    @pytest.hookimpl(tryfirst=True)\n    def pytest_runtest_call(): ...\n\nChanged ``hookimpl`` attributes:\n\n* ``tryfirst``\n* ``trylast``\n* ``optionalhook``\n* ``hookwrapper``\n\nChanged ``hookwrapper`` attributes:\n\n* ``firstresult``\n* ``historic``\n\n\nDirectly constructing internal classes\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 7.0\n\nDirectly constructing the following classes is now deprecated:\n\n- ``_pytest.mark.structures.Mark``\n- ``_pytest.mark.structures.MarkDecorator``\n- ``_pytest.mark.structures.MarkGenerator``\n- ``_pytest.python.Metafunc``\n- ``_pytest.runner.CallInfo``\n- ``_pytest._code.ExceptionInfo``\n- ``_pytest.config.argparsing.Parser``\n- ``_pytest.config.argparsing.OptionGroup``\n- ``_pytest.pytester.HookRecorder``\n\nThese constructors have always been considered private, but now issue a deprecation warning, which may become a hard error in pytest 8.\n\n.. _diamond-inheritance-deprecated:\n\nDiamond inheritance between :class:`pytest.Collector` and :class:`pytest.Item`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 7.0\n\nDefining a custom pytest node type which is both an :class:`~pytest.Item` and a :class:`~pytest.Collector` (e.g. :class:`~pytest.File`) now issues a warning.\nIt was never sanely supported and triggers hard to debug errors.\n\nSome plugins providing linting/code analysis have been using this as a hack.\nInstead, a separate collector node should be used, which collects the item. See\n:ref:`non-python tests` for an example, as well as an `example pr fixing inheritance`_.\n\n.. _example pr fixing inheritance: https://github.com/asmeurer/pytest-flakes/pull/40/files\n\n\n.. _uncooperative-constructors-deprecated:\n\nConstructors of custom :class:`~_pytest.nodes.Node` subclasses should take ``**kwargs``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 7.0\n\nIf custom subclasses of nodes like :class:`pytest.Item` override the\n``__init__`` method, they should take ``**kwargs``. Thus,\n\n.. code-block:: python\n\n    class CustomItem(pytest.Item):\n        def __init__(self, name, parent, additional_arg):\n            super().__init__(name, parent)\n            self.additional_arg = additional_arg\n\nshould be turned into:\n\n.. code-block:: python\n\n    class CustomItem(pytest.Item):\n        def __init__(self, *, additional_arg, **kwargs):\n            super().__init__(**kwargs)\n            self.additional_arg = additional_arg\n\nto avoid hard-coding the arguments pytest can pass to the superclass.\nSee :ref:`non-python tests` for a full example.\n\nFor cases without conflicts, no deprecation warning is emitted. For cases with\nconflicts (such as :class:`pytest.File` now taking ``path`` instead of\n``fspath``, as :ref:`outlined above <node-ctor-fspath-deprecation>`), a\ndeprecation warning is now raised.\n\n\nThe ``yield_fixture`` function/decorator\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 6.2\n\n``pytest.yield_fixture`` is a deprecated alias for :func:`pytest.fixture`.\n\nIt has been so for a very long time, so it can be searched/replaced safely.\n\n\nRemoved Features and Breaking Changes\n-------------------------------------\n\nAs stated in our :ref:`backwards-compatibility` policy, deprecated features are removed only in major releases after\nan appropriate period of deprecation has passed.\n\nSome breaking changes which could not be deprecated are also listed.\n\n\n.. _import-or-skip-import-error:\n\n``pytest.importorskip`` default behavior regarding :class:`ImportError`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 8.2\n.. versionremoved:: 9.1\n\nTraditionally :func:`pytest.importorskip` captured :class:`ImportError`, with the original intent being to skip\ntests where a dependent module is not installed, for example testing with different dependencies.\n\nHowever, some packages might be installed in the system but not importable due to some other issue, for example\na compilation error or a broken installation. In those cases, :func:`pytest.importorskip` would still silently skip\nthe test, but more often than not users would rather see the unexpected error so the underlying issue can be fixed.\n\nIn ``8.2``, the ``exc_type`` parameter was added, giving users the ability to pass\n:class:`ModuleNotFoundError` to skip tests only if the module cannot really be found, and not because of some other\nerror.\n\nAs of ``9.1``, :func:`pytest.importorskip` only captures :class:`ModuleNotFoundError` by default.\nIf you want to preserve the previous behavior and skip on other :class:`ImportError` exceptions during import,\npass ``exc_type=ImportError`` explicitly.\n\n\n.. _node-ctor-fspath-deprecation:\n\n``fspath`` argument for Node constructors replaced with ``pathlib.Path``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 7.0\n.. versionremoved:: 9.1\n\nIn order to support the transition from ``py.path.local`` to :mod:`pathlib`,\nthe ``fspath`` argument to :class:`~_pytest.nodes.Node` constructors like\n:func:`pytest.Function.from_parent()` and :func:`pytest.Class.from_parent()`\nis now deprecated.\n\nPlugins which construct nodes should pass the ``path`` argument, of type\n:class:`pathlib.Path`, instead of the ``fspath`` argument.\n\nPlugins which implement custom items and collectors are encouraged to replace\n``fspath`` parameters (``py.path.local``) with ``path`` parameters\n(``pathlib.Path``), and drop any other usage of the ``py`` library if possible.\n\nIf possible, plugins with custom items should use :ref:`cooperative\nconstructors <uncooperative-constructors-deprecated>` to avoid hardcoding\narguments they only pass on to the superclass.\n\n.. note::\n    The name of the :class:`~_pytest.nodes.Node` arguments and attributes (the\n    new attribute being ``path``) is **the opposite** of the situation for\n    hooks, :ref:`outlined below <legacy-path-hooks-deprecated>` (the old\n    argument being ``path``).\n\n    This is an unfortunate artifact due to historical reasons, which should be\n    resolved in future versions as we slowly get rid of the :pypi:`py`\n    dependency (see :issue:`9283` for a longer discussion).\n\nDue to the ongoing migration of methods like :meth:`~pytest.Item.reportinfo`\nwhich still is expected to return a ``py.path.local`` object, nodes still have\nboth ``fspath`` (``py.path.local``) and ``path`` (``pathlib.Path``) attributes,\nno matter what argument was used in the constructor. We expect to deprecate the\n``fspath`` attribute in a future release.\n\n\n.. _sync-test-async-fixture:\n\nsync test depending on async fixture\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 8.4\n.. versionremoved:: 9.0\n\nPytest has for a long time given an error when encountering an asynchronous test function, prompting the user to install\na plugin that can handle it. It has not given any errors if you have an asynchronous fixture that's depended on by a\nsynchronous test. If the fixture was an async function you did get an \"unawaited coroutine\" warning, but for async yield fixtures you didn't even get that.\nThis is a problem even if you do have a plugin installed for handling async tests, as they may require\nspecial decorators for async fixtures to be handled, and some may not robustly handle if a user accidentally requests an\nasync fixture from their sync tests. Fixture values being cached can make this even more unintuitive, where everything will\n\"work\" if the fixture is first requested by an async test, and then requested by a synchronous test.\n\nUnfortunately there is no 100% reliable method of identifying when a user has made a mistake, versus when they expect an\nunawaited object from their fixture that they will handle on their own. To suppress this warning\nwhen you in fact did intend to handle this you can wrap your async fixture in a synchronous fixture:\n\n.. code-block:: python\n\n    import asyncio\n    import pytest\n\n\n    @pytest.fixture\n    async def unawaited_fixture():\n        return 1\n\n\n    def test_foo(unawaited_fixture):\n        assert 1 == asyncio.run(unawaited_fixture)\n\nshould be changed to\n\n\n.. code-block:: python\n\n    import asyncio\n    import pytest\n\n\n    @pytest.fixture\n    def unawaited_fixture():\n        async def inner_fixture():\n            return 1\n\n        return inner_fixture()\n\n\n    def test_foo(unawaited_fixture):\n        assert 1 == asyncio.run(unawaited_fixture)\n\n\nYou can also make use of `pytest_fixture_setup` to handle the coroutine/asyncgen before pytest sees it - this is the way current async pytest plugins handle it.\n\nIf a user has an async fixture with ``autouse=True`` in their ``conftest.py``, or in a file\ncontaining both synchronous tests and the fixture, they will receive this warning.\nUnless you're using a plugin that specifically handles async fixtures\nwith synchronous tests, we strongly recommend against this practice.\nIt can lead to unpredictable behavior (with larger scopes, it may appear to \"work\" if an async\ntest is the first to request the fixture, due to value caching) and will generate\nunawaited-coroutine runtime warnings (but only for non-yield fixtures).\nAdditionally, it creates ambiguity for other developers about whether the fixture is intended to perform\nsetup for synchronous tests.\n\nThe `anyio pytest plugin <https://anyio.readthedocs.io/en/stable/testing.html>`_ supports\nsynchronous tests with async fixtures, though certain limitations apply.\n\n\n\nApplying a mark to a fixture function\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 7.4\n.. versionremoved:: 9.0\n\nApplying a mark to a fixture function never had any effect, but it is a common user error.\n\n.. code-block:: python\n\n    @pytest.mark.usefixtures(\"clean_database\")\n    @pytest.fixture\n    def user() -> User: ...\n\nUsers expected in this case that the ``usefixtures`` mark would have its intended effect of using the ``clean_database`` fixture when ``user`` was invoked, when in fact it has no effect at all.\n\nNow pytest will issue a warning when it encounters this problem, and will raise an error in the future versions.\n\n.. _legacy-path-hooks-deprecated:\n\n``py.path.local`` arguments for hooks replaced with ``pathlib.Path``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 7.0\n.. versionremoved:: 9.0\n\nIn order to support the transition from ``py.path.local`` to :mod:`pathlib`, the following hooks now receive additional arguments:\n\n*  :hook:`pytest_ignore_collect(collection_path: pathlib.Path) <pytest_ignore_collect>` as equivalent to ``path``\n*  :hook:`pytest_collect_file(file_path: pathlib.Path) <pytest_collect_file>` as equivalent to ``path``\n*  :hook:`pytest_pycollect_makemodule(module_path: pathlib.Path) <pytest_pycollect_makemodule>` as equivalent to ``path``\n*  :hook:`pytest_report_header(start_path: pathlib.Path) <pytest_report_header>` as equivalent to ``startdir``\n*  :hook:`pytest_report_collectionfinish(start_path: pathlib.Path) <pytest_report_collectionfinish>` as equivalent to ``startdir``\n\nThe accompanying ``py.path.local`` based paths have been deprecated: plugins which manually invoke those hooks should only pass the new ``pathlib.Path`` arguments, and users should change their hook implementations to use the new ``pathlib.Path`` arguments.\n\n.. note::\n    The name of the :class:`~_pytest.nodes.Node` arguments and attributes,\n    :ref:`outlined above <node-ctor-fspath-deprecation>` (the new attribute\n    being ``path``) is **the opposite** of the situation for hooks (the old\n    argument being ``path``).\n\n    This is an unfortunate artifact due to historical reasons, which should be\n    resolved in future versions as we slowly get rid of the :pypi:`py`\n    dependency (see :issue:`9283` for a longer discussion).\n\n.. _yield tests deprecated:\n\n``yield`` tests\n~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\n    ``yield`` tests ``xfail``.\n\n.. versionremoved:: 8.4\n\n    ``yield`` tests raise a collection error.\n\npytest no longer supports ``yield``-style tests, where a test function actually ``yield`` functions and values\nthat are then turned into proper test methods. Example:\n\n.. code-block:: python\n\n    def check(x, y):\n        assert x**x == y\n\n\n    def test_squared():\n        yield check, 2, 4\n        yield check, 3, 9\n\nThis would result in two actual test functions being generated.\n\nThis form of test function doesn't support fixtures properly, and users should switch to ``pytest.mark.parametrize``:\n\n.. code-block:: python\n\n    @pytest.mark.parametrize(\"x, y\", [(2, 4), (3, 9)])\n    def test_squared(x, y):\n        assert x**x == y\n\n.. _nose-deprecation:\n\nSupport for tests written for nose\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 7.2\n.. versionremoved:: 8.0\n\nSupport for running tests written for `nose <https://nose.readthedocs.io/en/latest/>`__ is now deprecated.\n\n``nose`` has been in maintenance mode-only for years, and maintaining the plugin is not trivial as it spills\nover the code base (see :issue:`9886` for more details).\n\nsetup/teardown\n^^^^^^^^^^^^^^\n\nOne thing that might catch users by surprise is that plain ``setup`` and ``teardown`` methods are not pytest native,\nthey are in fact part of the ``nose`` support.\n\n\n.. code-block:: python\n\n    class Test:\n        def setup(self):\n            self.resource = make_resource()\n\n        def teardown(self):\n            self.resource.close()\n\n        def test_foo(self): ...\n\n        def test_bar(self): ...\n\n\n\nNative pytest support uses ``setup_method`` and ``teardown_method`` (see :ref:`xunit-method-setup`), so the above should be changed to:\n\n.. code-block:: python\n\n    class Test:\n        def setup_method(self):\n            self.resource = make_resource()\n\n        def teardown_method(self):\n            self.resource.close()\n\n        def test_foo(self): ...\n\n        def test_bar(self): ...\n\n\nThis is easy to do in an entire code base by doing a simple find/replace.\n\n@with_setup\n^^^^^^^^^^^\n\nCode using `@with_setup <with-setup-nose>`_ such as this:\n\n.. code-block:: python\n\n    from nose.tools import with_setup\n\n\n    def setup_some_resource(): ...\n\n\n    def teardown_some_resource(): ...\n\n\n    @with_setup(setup_some_resource, teardown_some_resource)\n    def test_foo(): ...\n\nWill also need to be ported to a supported pytest style. One way to do it is using a fixture:\n\n.. code-block:: python\n\n    import pytest\n\n\n    def setup_some_resource(): ...\n\n\n    def teardown_some_resource(): ...\n\n\n    @pytest.fixture\n    def some_resource():\n        setup_some_resource()\n        yield\n        teardown_some_resource()\n\n\n    def test_foo(some_resource): ...\n\n\n.. _`with-setup-nose`: https://nose.readthedocs.io/en/latest/testing_tools.html?highlight=with_setup#nose.tools.with_setup\n\n\nThe ``compat_co_firstlineno`` attribute\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nNose inspects this attribute on function objects to allow overriding the function's inferred line number.\nPytest no longer respects this attribute.\n\n\n\nPassing ``msg=`` to ``pytest.skip``, ``pytest.fail`` or ``pytest.exit``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 7.0\n.. versionremoved:: 8.0\n\nPassing the keyword argument ``msg`` to :func:`pytest.skip`, :func:`pytest.fail` or :func:`pytest.exit`\nis now deprecated and ``reason`` should be used instead.  This change is to bring consistency between these\nfunctions and the ``@pytest.mark.skip`` and ``@pytest.mark.xfail`` markers which already accept a ``reason`` argument.\n\n.. code-block:: python\n\n    def test_fail_example():\n        # old\n        pytest.fail(msg=\"foo\")\n        # new\n        pytest.fail(reason=\"bar\")\n\n\n    def test_skip_example():\n        # old\n        pytest.skip(msg=\"foo\")\n        # new\n        pytest.skip(reason=\"bar\")\n\n\n    def test_exit_example():\n        # old\n        pytest.exit(msg=\"foo\")\n        # new\n        pytest.exit(reason=\"bar\")\n\n\n.. _instance-collector-deprecation:\n\nThe ``pytest.Instance`` collector\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 7.0\n\nThe ``pytest.Instance`` collector type has been removed.\n\nPreviously, Python test methods were collected as :class:`~pytest.Class` -> ``Instance`` -> :class:`~pytest.Function`.\nNow :class:`~pytest.Class` collects the test methods directly.\n\nMost plugins which reference ``Instance`` do so in order to ignore or skip it,\nusing a check such as ``if isinstance(node, Instance): return``.\nSuch plugins should simply remove consideration of ``Instance`` on pytest>=7.\nHowever, to keep such uses working, a dummy type has been instanced in ``pytest.Instance`` and ``_pytest.python.Instance``,\nand importing it emits a deprecation warning. This was removed in pytest 8.\n\n\nUsing ``pytest.warns(None)``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 7.0\n.. versionremoved:: 8.0\n\n:func:`pytest.warns(None) <pytest.warns>` is now deprecated because it was frequently misused.\nIts correct usage was checking that the code emits at least one warning of any type - like ``pytest.warns()``\nor ``pytest.warns(Warning)``.\n\nSee :ref:`warns use cases` for examples.\n\n\nBackward compatibilities in ``Parser.addoption``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 2.4\n.. versionremoved:: 8.0\n\nSeveral behaviors of :meth:`Parser.addoption <pytest.Parser.addoption>` are now\nremoved in pytest 8 (deprecated since pytest 2.4.0):\n\n- ``parser.addoption(..., help=\".. %default ..\")`` - use ``%(default)s`` instead.\n- ``parser.addoption(..., type=\"int/string/float/complex\")`` - use ``type=int`` etc. instead.\n\n\nThe ``--strict`` command-line option (reintroduced)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 6.2\n.. versionchanged:: 9.0\n\nThe ``--strict`` command-line option had been deprecated in favor of ``--strict-markers``, which\nbetter conveys what the option does.\n\nIn version 8.1, we accidentally un-deprecated ``--strict``.\n\nIn version 9.0, we changed ``--strict`` to make it set the new :confval:`strict`\nconfiguration option. It now enables all strictness related options (including\n:confval:`strict_markers`).\n\n\n.. _cmdline-preparse-deprecated:\n\nImplementing the ``pytest_cmdline_preparse`` hook\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 7.0\n.. versionremoved:: 8.0\n\nImplementing the ``pytest_cmdline_preparse`` hook has been officially deprecated.\nImplement the :hook:`pytest_load_initial_conftests` hook instead.\n\n.. code-block:: python\n\n    def pytest_cmdline_preparse(config: Config, args: List[str]) -> None: ...\n\n\n    # becomes:\n\n\n    def pytest_load_initial_conftests(\n        early_config: Config, parser: Parser, args: List[str]\n    ) -> None: ...\n\n\nCollection changes in pytest 8\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAdded a new :class:`pytest.Directory` base collection node, which all collector nodes for filesystem directories are expected to subclass.\nThis is analogous to the existing :class:`pytest.File` for file nodes.\n\nChanged :class:`pytest.Package` to be a subclass of :class:`pytest.Directory`.\nA ``Package`` represents a filesystem directory which is a Python package,\ni.e. contains an ``__init__.py`` file.\n\n:class:`pytest.Package` now only collects files in its own directory; previously it collected recursively.\nSub-directories are collected as sub-collector nodes, thus creating a collection tree which mirrors the filesystem hierarchy.\n\n:attr:`session.name <pytest.Session.name>` is now ``\"\"``; previously it was the rootdir directory name.\nThis matches :attr:`session.nodeid <_pytest.nodes.Node.nodeid>` which has always been `\"\"`.\n\nAdded a new :class:`pytest.Dir` concrete collection node, a subclass of :class:`pytest.Directory`.\nThis node represents a filesystem directory, which is not a :class:`pytest.Package`,\ni.e. does not contain an ``__init__.py`` file.\nSimilarly to ``Package``, it only collects the files in its own directory,\nwhile collecting sub-directories as sub-collector nodes.\n\nFiles and directories are now collected in alphabetical order jointly, unless changed by a plugin.\nPreviously, files were collected before directories.\n\nThe collection tree now contains directories/packages up to the :ref:`rootdir <rootdir>`,\nfor initial arguments that are found within the rootdir.\nFor files outside the rootdir, only the immediate directory/package is collected --\nnote however that collecting from outside the rootdir is discouraged.\n\nAs an example, given the following filesystem tree::\n\n    myroot/\n        pytest.ini\n        top/\n        ├── aaa\n        │   └── test_aaa.py\n        ├── test_a.py\n        ├── test_b\n        │   ├── __init__.py\n        │   └── test_b.py\n        ├── test_c.py\n        └── zzz\n            ├── __init__.py\n            └── test_zzz.py\n\nthe collection tree, as shown by `pytest --collect-only top/` but with the otherwise-hidden :class:`~pytest.Session` node added for clarity,\nis now the following::\n\n    <Session>\n      <Dir myroot>\n        <Dir top>\n          <Dir aaa>\n            <Module test_aaa.py>\n              <Function test_it>\n          <Module test_a.py>\n            <Function test_it>\n          <Package test_b>\n            <Module test_b.py>\n              <Function test_it>\n          <Module test_c.py>\n            <Function test_it>\n          <Package zzz>\n            <Module test_zzz.py>\n              <Function test_it>\n\nPreviously, it was::\n\n    <Session>\n      <Module top/test_a.py>\n        <Function test_it>\n      <Module top/test_c.py>\n        <Function test_it>\n      <Module top/aaa/test_aaa.py>\n        <Function test_it>\n      <Package test_b>\n        <Module test_b.py>\n          <Function test_it>\n      <Package zzz>\n        <Module test_zzz.py>\n          <Function test_it>\n\nCode/plugins which rely on a specific shape of the collection tree might need to update.\n\n\n:class:`pytest.Package` is no longer a :class:`pytest.Module` or :class:`pytest.File`\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionchanged:: 8.0\n\nThe ``Package`` collector node designates a Python package, that is, a directory with an `__init__.py` file.\nPreviously ``Package`` was a subtype of ``pytest.Module`` (which represents a single Python module),\nthe module being the `__init__.py` file.\nThis has been deemed a design mistake (see :issue:`11137` and :issue:`7777` for details).\n\nThe ``path`` property of ``Package`` nodes now points to the package directory instead of the ``__init__.py`` file.\n\nNote that a ``Module`` node for ``__init__.py`` (which is not a ``Package``) may still exist,\nif it is picked up during collection (e.g. if you configured :confval:`python_files` to include ``__init__.py`` files).\n\n\nCollecting ``__init__.py`` files no longer collects package\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 8.0\n\nRunning `pytest pkg/__init__.py` now collects the `pkg/__init__.py` file (module) only.\nPreviously, it collected the entire `pkg` package, including other test files in the directory, but excluding tests in the `__init__.py` file itself\n(unless :confval:`python_files` was changed to allow `__init__.py` file).\n\nTo collect the entire package, specify just the directory: `pytest pkg`.\n\n\nThe ``pytest.collect`` module\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 6.0\n.. versionremoved:: 7.0\n\nThe ``pytest.collect`` module is no longer part of the public API, all its names\nshould now be imported from ``pytest`` directly instead.\n\n\n\nThe ``pytest_warning_captured`` hook\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 6.0\n.. versionremoved:: 7.0\n\nThis hook has an `item` parameter which cannot be serialized by ``pytest-xdist``.\n\nUse the ``pytest_warning_recorded`` hook instead, which replaces the ``item`` parameter\nby a ``nodeid`` parameter.\n\n\n\nThe ``pytest._fillfuncargs`` function\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 6.0\n.. versionremoved:: 7.0\n\nThis function was kept for backward compatibility with an older plugin.\n\nIts functionality is not meant to be used directly, but if you must replace\nit, use `function._request._fillfixtures()` instead, though note this is not\na public API and may break in the future.\n\n\n``--no-print-logs`` command-line option\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 5.4\n.. versionremoved:: 6.0\n\n\nThe ``--no-print-logs`` option and ``log_print`` ini setting are removed. If\nyou used them, please use ``--show-capture`` instead.\n\nA ``--show-capture`` command-line option was added in ``pytest 3.5.0`` which allows to specify how to\ndisplay captured output when tests fail: ``no``, ``stdout``, ``stderr``, ``log`` or ``all`` (the default).\n\n\n.. _resultlog deprecated:\n\nResult log (``--result-log``)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. deprecated:: 4.0\n.. versionremoved:: 6.0\n\nThe ``--result-log`` option produces a stream of test reports which can be\nanalysed at runtime, but it uses a custom format which requires users to implement their own\nparser.\n\nThe :pypi:`pytest-reportlog` plugin provides a ``--report-log`` option, a more standard and extensible alternative, producing\none JSON object per-line, and should cover the same use cases. Please try it out and provide feedback.\n\nThe ``pytest-reportlog`` plugin might even be merged into the core\nat some point, depending on the plans for the plugins and number of users using it.\n\n``pytest_collect_directory`` hook\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 6.0\n\nThe ``pytest_collect_directory`` hook has not worked properly for years (it was called\nbut the results were ignored). Users may consider using :hook:`pytest_collection_modifyitems` instead.\n\nTerminalReporter.writer\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 6.0\n\nThe ``TerminalReporter.writer`` attribute has been deprecated and should no longer be used. This\nwas inadvertently exposed as part of the public API of that plugin and ties it too much\nwith ``py.io.TerminalWriter``.\n\nPlugins that used ``TerminalReporter.writer`` directly should instead use ``TerminalReporter``\nmethods that provide the same functionality.\n\n.. _junit-family changed default value:\n\n``junit_family`` default value change to \"xunit2\"\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionchanged:: 6.0\n\nThe default value of ``junit_family`` option will change to ``xunit2`` in pytest 6.0, which\nis an update of the old ``xunit1`` format and is supported by default in modern tools\nthat manipulate this type of file (for example, Jenkins, Azure Pipelines, etc.).\n\nUsers are recommended to try the new ``xunit2`` format and see if their tooling that consumes the JUnit\nXML file supports it.\n\nTo use the new format, update your configuration file:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        junit_family = \"xunit2\"\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        junit_family = xunit2\n\nIf you discover that your tooling does not support the new format, and want to keep using the\nlegacy version, set the option to ``legacy`` instead:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        junit_family = \"legacy\"\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        junit_family = legacy\n\nBy using ``legacy`` you will keep using the legacy/xunit1 format when upgrading to\npytest 6.0, where the default format will be ``xunit2``.\n\nIn order to let users know about the transition, pytest will issue a warning in case\nthe ``--junit-xml`` option is given in the command line but ``junit_family`` is not explicitly\nconfigured in ``pytest.ini``.\n\nServices known to support the ``xunit2`` format:\n\n* `Jenkins <https://www.jenkins.io/>`__ with the `JUnit <https://plugins.jenkins.io/junit>`__ plugin.\n* `Azure Pipelines <https://azure.microsoft.com/en-us/services/devops/pipelines>`__.\n\nNode Construction changed to ``Node.from_parent``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionchanged:: 6.0\n\nThe construction of nodes now should use the named constructor ``from_parent``.\nThis limitation in api surface intends to enable better/simpler refactoring of the collection tree.\n\nThis means that instead of :code:`MyItem(name=\"foo\", parent=collector, obj=42)`\none now has to invoke :code:`MyItem.from_parent(collector, name=\"foo\")`.\n\nPlugins that wish to support older versions of pytest and suppress the warning can use\n`hasattr` to check if `from_parent` exists in that version:\n\n.. code-block:: python\n\n    def pytest_pycollect_makeitem(collector, name, obj):\n        if hasattr(MyItem, \"from_parent\"):\n            item = MyItem.from_parent(collector, name=\"foo\")\n            item.obj = 42\n            return item\n        else:\n            return MyItem(name=\"foo\", parent=collector, obj=42)\n\nNote that ``from_parent`` should only be called with keyword arguments for the parameters.\n\n\n``pytest.fixture`` arguments are keyword only\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 6.0\n\nPassing arguments to pytest.fixture() as positional arguments has been removed - pass them by keyword instead.\n\n``funcargnames`` alias for ``fixturenames``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 6.0\n\nThe ``FixtureRequest``, ``Metafunc``, and ``Function`` classes track the names of\ntheir associated fixtures, with the aptly-named ``fixturenames`` attribute.\n\nPrior to pytest 2.3, this attribute was named ``funcargnames``, and we have kept\nthat as an alias since.  It is finally due for removal, as it is often confusing\nin places where we or plugin authors must distinguish between fixture names and\nnames supplied by non-fixture things such as ``pytest.mark.parametrize``.\n\n\n.. _pytest.config global deprecated:\n\n``pytest.config`` global\n~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 5.0\n\nThe ``pytest.config`` global object is deprecated.  Instead use\n``request.config`` (via the ``request`` fixture) or if you are a plugin author\nuse the ``pytest_configure(config)`` hook. Note that many hooks can also access\nthe ``config`` object indirectly, through ``session.config`` or ``item.config`` for example.\n\n\n.. _`raises message deprecated`:\n\n``\"message\"`` parameter of ``pytest.raises``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 5.0\n\nIt is a common mistake to think this parameter will match the exception message, while in fact\nit only serves to provide a custom message in case the ``pytest.raises`` check fails. To prevent\nusers from making this mistake, and because it is believed to be little used, pytest is\ndeprecating it without providing an alternative for the moment.\n\nIf you have a valid use case for this parameter, consider that to obtain the same results\nyou can just call ``pytest.fail`` manually at the end of the ``with`` statement.\n\nFor example:\n\n.. code-block:: python\n\n    with pytest.raises(TimeoutError, message=\"Client got unexpected message\"):\n        wait_for(websocket.recv(), 0.5)\n\n\nBecomes:\n\n.. code-block:: python\n\n    with pytest.raises(TimeoutError):\n        wait_for(websocket.recv(), 0.5)\n        pytest.fail(\"Client got unexpected message\")\n\n\nIf you still have concerns about this deprecation and future removal, please comment on\n:issue:`3974`.\n\n\n.. _raises-warns-exec:\n\n``raises`` / ``warns`` with a string as the second argument\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 5.0\n\nUse the context manager form of these instead.  When necessary, invoke ``exec``\ndirectly.\n\nExample:\n\n.. code-block:: python\n\n    pytest.raises(ZeroDivisionError, \"1 / 0\")\n    pytest.raises(SyntaxError, \"a $ b\")\n\n    pytest.warns(DeprecationWarning, \"my_function()\")\n    pytest.warns(SyntaxWarning, \"assert(1, 2)\")\n\nBecomes:\n\n.. code-block:: python\n\n    with pytest.raises(ZeroDivisionError):\n        1 / 0\n    with pytest.raises(SyntaxError):\n        exec(\"a $ b\")  # exec is required for invalid syntax\n\n    with pytest.warns(DeprecationWarning):\n        my_function()\n    with pytest.warns(SyntaxWarning):\n        exec(\"assert(1, 2)\")  # exec is used to avoid a top-level warning\n\n\n\n\nUsing ``Class`` in custom Collectors\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nUsing objects named ``\"Class\"`` as a way to customize the type of nodes that are collected in ``Collector``\nsubclasses has been deprecated. Users instead should use ``pytest_pycollect_makeitem`` to customize node types during\ncollection.\n\nThis issue should affect only advanced plugins who create new collection types, so if you see this warning\nmessage please contact the authors so they can change the code.\n\n\n.. _marks in pytest.parametrize deprecated:\n\nmarks in ``pytest.mark.parametrize``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nApplying marks to values of a ``pytest.mark.parametrize`` call is now deprecated. For example:\n\n.. code-block:: python\n\n    @pytest.mark.parametrize(\n        \"a, b\",\n        [\n            (3, 9),\n            pytest.mark.xfail(reason=\"flaky\")(6, 36),\n            (10, 100),\n            (20, 200),\n            (40, 400),\n            (50, 500),\n        ],\n    )\n    def test_foo(a, b): ...\n\nThis code applies the ``pytest.mark.xfail(reason=\"flaky\")`` mark to the ``(6, 36)`` value of the above parametrization\ncall.\n\nThis was considered hard to read and understand, and also its implementation presented problems to the code preventing\nfurther internal improvements in the marks architecture.\n\nTo update the code, use ``pytest.param``:\n\n.. code-block:: python\n\n    @pytest.mark.parametrize(\n        \"a, b\",\n        [\n            (3, 9),\n            pytest.param(6, 36, marks=pytest.mark.xfail(reason=\"flaky\")),\n            (10, 100),\n            (20, 200),\n            (40, 400),\n            (50, 500),\n        ],\n    )\n    def test_foo(a, b): ...\n\n\n.. _pytest_funcarg__ prefix deprecated:\n\n``pytest_funcarg__`` prefix\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nIn very early pytest versions fixtures could be defined using the ``pytest_funcarg__`` prefix:\n\n.. code-block:: python\n\n    def pytest_funcarg__data():\n        return SomeData()\n\nSwitch over to the ``@pytest.fixture`` decorator:\n\n.. code-block:: python\n\n    @pytest.fixture\n    def data():\n        return SomeData()\n\n\n\n[pytest] section in setup.cfg files\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\n``[pytest]`` sections in ``setup.cfg`` files should now be named ``[tool:pytest]``\nto avoid conflicts with other distutils commands.\n\n\n.. _metafunc.addcall deprecated:\n\nMetafunc.addcall\n~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\n``Metafunc.addcall`` was a precursor to the current parametrized mechanism. Users should use\n:meth:`pytest.Metafunc.parametrize` instead.\n\nExample:\n\n.. code-block:: python\n\n    def pytest_generate_tests(metafunc):\n        metafunc.addcall({\"i\": 1}, id=\"1\")\n        metafunc.addcall({\"i\": 2}, id=\"2\")\n\nBecomes:\n\n.. code-block:: python\n\n    def pytest_generate_tests(metafunc):\n        metafunc.parametrize(\"i\", [1, 2], ids=[\"1\", \"2\"])\n\n\n.. _cached_setup deprecated:\n\n``cached_setup``\n~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\n``request.cached_setup`` was the precursor of the setup/teardown mechanism available to fixtures.\n\nExample:\n\n.. code-block:: python\n\n    @pytest.fixture\n    def db_session():\n        return request.cached_setup(\n            setup=Session.create, teardown=lambda session: session.close(), scope=\"module\"\n        )\n\nThis should be updated to make use of standard fixture mechanisms:\n\n.. code-block:: python\n\n    @pytest.fixture(scope=\"module\")\n    def db_session():\n        session = Session.create()\n        yield session\n        session.close()\n\n\nYou can consult :std:doc:`funcarg comparison section in the docs <funcarg_compare>` for\nmore information.\n\n\n.. _pytest_plugins in non-top-level conftest files deprecated:\n\npytest_plugins in non-top-level conftest files\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nDefining :globalvar:`pytest_plugins` is now deprecated in non-top-level conftest.py\nfiles because they will activate referenced plugins *globally*, which is surprising because for all other pytest\nfeatures ``conftest.py`` files are only *active* for tests at or below it.\n\n\n.. _config.warn and node.warn deprecated:\n\n``Config.warn`` and ``Node.warn``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nThose methods were part of the internal pytest warnings system, but since ``3.8`` pytest is using the builtin warning\nsystem for its own warnings, so those two functions are now deprecated.\n\n``Config.warn`` should be replaced by calls to the standard ``warnings.warn``, example:\n\n.. code-block:: python\n\n    config.warn(\"C1\", \"some warning\")\n\nBecomes:\n\n.. code-block:: python\n\n    warnings.warn(pytest.PytestWarning(\"some warning\"))\n\n``Node.warn`` now supports two signatures:\n\n* ``node.warn(PytestWarning(\"some message\"))``: is now the **recommended** way to call this function.\n  The warning instance must be a PytestWarning or subclass.\n\n* ``node.warn(\"CI\", \"some message\")``: this code/message form has been **removed** and should be converted to the warning instance form above.\n\n.. _record_xml_property deprecated:\n\nrecord_xml_property\n~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nThe ``record_xml_property`` fixture is now deprecated in favor of the more generic ``record_property``, which\ncan be used by other consumers (for example ``pytest-html``) to obtain custom information about the test run.\n\nThis is just a matter of renaming the fixture as the API is the same:\n\n.. code-block:: python\n\n    def test_foo(record_xml_property): ...\n\nChange to:\n\n.. code-block:: python\n\n    def test_foo(record_property): ...\n\n\n.. _passing command-line string to pytest.main deprecated:\n\nPassing command-line string to ``pytest.main()``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nPassing a command-line string to ``pytest.main()`` is deprecated:\n\n.. code-block:: python\n\n    pytest.main(\"-v -s\")\n\nPass a list instead:\n\n.. code-block:: python\n\n    pytest.main([\"-v\", \"-s\"])\n\n\nBy passing a string, users expect that pytest will interpret that command-line using the shell rules they are working\non (for example ``bash`` or ``Powershell``), but this is very hard/impossible to do in a portable way.\n\n\n.. _calling fixtures directly deprecated:\n\nCalling fixtures directly\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nCalling a fixture function directly, as opposed to request them in a test function, is deprecated.\n\nFor example:\n\n.. code-block:: python\n\n    @pytest.fixture\n    def cell():\n        return ...\n\n\n    @pytest.fixture\n    def full_cell():\n        cell = cell()\n        cell.make_full()\n        return cell\n\nThis is a great source of confusion to new users, which will often call the fixture functions and request them from test functions interchangeably, which breaks the fixture resolution model.\n\nIn those cases just request the function directly in the dependent fixture:\n\n.. code-block:: python\n\n    @pytest.fixture\n    def cell():\n        return ...\n\n\n    @pytest.fixture\n    def full_cell(cell):\n        cell.make_full()\n        return cell\n\nAlternatively if the fixture function is called multiple times inside a test (making it hard to apply the above pattern) or\nif you would like to make minimal changes to the code, you can create a fixture which calls the original function together\nwith the ``name`` parameter:\n\n.. code-block:: python\n\n    def cell():\n        return ...\n\n\n    @pytest.fixture(name=\"cell\")\n    def cell_fixture():\n        return cell()\n\n\n.. _internal classes accessed through node deprecated:\n\nInternal classes accessed through ``Node``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nAccess of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances now issue\nthis warning:\n\n.. code-block:: text\n\n    usage of Function.Module is deprecated, please use pytest.Module instead\n\nUsers should just ``import pytest`` and access those objects using the ``pytest`` module.\n\nThis has been documented as deprecated for years, but only now we are actually emitting deprecation warnings.\n\n``Node.get_marker``\n~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nAs part of a large :ref:`marker-revamp`, ``_pytest.nodes.Node.get_marker`` is removed. See\n:ref:`the documentation <update marker code>` on tips on how to update your code.\n\n\n``somefunction.markname``\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nAs part of a large :ref:`marker-revamp` we already deprecated using ``MarkInfo``\nthe only correct way to get markers of an element is via ``node.iter_markers(name)``.\n\n\n.. _pytest.namespace deprecated:\n\n``pytest_namespace``\n~~~~~~~~~~~~~~~~~~~~\n\n.. versionremoved:: 4.0\n\nThis hook is deprecated because it greatly complicates the pytest internals regarding configuration and initialization, making some\nbug fixes and refactorings impossible.\n\nExample of usage:\n\n.. code-block:: python\n\n    class MySymbol: ...\n\n\n    def pytest_namespace():\n        return {\"my_symbol\": MySymbol()}\n\n\nPlugin authors relying on this hook should instead require that users now import the plugin modules directly (with an appropriate public API).\n\nAs a stopgap measure, plugin authors may still inject their names into pytest's namespace, usually during ``pytest_configure``:\n\n.. code-block:: python\n\n    import pytest\n\n\n    def pytest_configure():\n        pytest.my_symbol = MySymbol()\n"
  },
  {
    "path": "doc/en/development_guide.rst",
    "content": "=================\nDevelopment Guide\n=================\n\nThe contributing guidelines are to be found :ref:`here <contributing>`.\nThe release procedure for pytest is documented on\n`GitHub <https://github.com/pytest-dev/pytest/blob/main/RELEASING.rst>`_.\n"
  },
  {
    "path": "doc/en/example/.ruff.toml",
    "content": "lint.ignore = [\"RUF059\"]\n"
  },
  {
    "path": "doc/en/example/assertion/failure_demo.py",
    "content": "from __future__ import annotations\n\nimport pytest\nfrom pytest import raises\n\n\ndef otherfunc(a, b):\n    assert a == b\n\n\ndef somefunc(x, y):\n    otherfunc(x, y)\n\n\ndef otherfunc_multi(a, b):\n    assert a == b\n\n\n@pytest.mark.parametrize(\"param1, param2\", [(3, 6)])\ndef test_generative(param1, param2):\n    assert param1 * 2 < param2\n\n\nclass TestFailing:\n    def test_simple(self):\n        def f():\n            return 42\n\n        def g():\n            return 43\n\n        assert f() == g()\n\n    def test_simple_multiline(self):\n        otherfunc_multi(42, 6 * 9)\n\n    def test_not(self):\n        def f():\n            return 42\n\n        assert not f()\n\n\nclass TestSpecialisedExplanations:\n    def test_eq_text(self):\n        assert \"spam\" == \"eggs\"\n\n    def test_eq_similar_text(self):\n        assert \"foo 1 bar\" == \"foo 2 bar\"\n\n    def test_eq_multiline_text(self):\n        assert \"foo\\nspam\\nbar\" == \"foo\\neggs\\nbar\"\n\n    def test_eq_long_text(self):\n        a = \"1\" * 100 + \"a\" + \"2\" * 100\n        b = \"1\" * 100 + \"b\" + \"2\" * 100\n        assert a == b\n\n    def test_eq_long_text_multiline(self):\n        a = \"1\\n\" * 100 + \"a\" + \"2\\n\" * 100\n        b = \"1\\n\" * 100 + \"b\" + \"2\\n\" * 100\n        assert a == b\n\n    def test_eq_list(self):\n        assert [0, 1, 2] == [0, 1, 3]\n\n    def test_eq_list_long(self):\n        a = [0] * 100 + [1] + [3] * 100\n        b = [0] * 100 + [2] + [3] * 100\n        assert a == b\n\n    def test_eq_dict(self):\n        assert {\"a\": 0, \"b\": 1, \"c\": 0} == {\"a\": 0, \"b\": 2, \"d\": 0}\n\n    def test_eq_set(self):\n        assert {0, 10, 11, 12} == {0, 20, 21}\n\n    def test_eq_longer_list(self):\n        assert [1, 2] == [1, 2, 3]\n\n    def test_in_list(self):\n        assert 1 in [0, 2, 3, 4, 5]\n\n    def test_not_in_text_multiline(self):\n        text = \"some multiline\\ntext\\nwhich\\nincludes foo\\nand a\\ntail\"\n        assert \"foo\" not in text\n\n    def test_not_in_text_single(self):\n        text = \"single foo line\"\n        assert \"foo\" not in text\n\n    def test_not_in_text_single_long(self):\n        text = \"head \" * 50 + \"foo \" + \"tail \" * 20\n        assert \"foo\" not in text\n\n    def test_not_in_text_single_long_term(self):\n        text = \"head \" * 50 + \"f\" * 70 + \"tail \" * 20\n        assert \"f\" * 70 not in text\n\n    def test_eq_dataclass(self):\n        from dataclasses import dataclass\n\n        @dataclass\n        class Foo:\n            a: int\n            b: str\n\n        left = Foo(1, \"b\")\n        right = Foo(1, \"c\")\n        assert left == right\n\n    def test_eq_attrs(self):\n        import attr\n\n        @attr.s\n        class Foo:\n            a = attr.ib()\n            b = attr.ib()\n\n        left = Foo(1, \"b\")\n        right = Foo(1, \"c\")\n        assert left == right\n\n\ndef test_attribute():\n    class Foo:\n        b = 1\n\n    i = Foo()\n    assert i.b == 2\n\n\ndef test_attribute_instance():\n    class Foo:\n        b = 1\n\n    assert Foo().b == 2\n\n\ndef test_attribute_failure():\n    class Foo:\n        def _get_b(self):\n            raise Exception(\"Failed to get attrib\")\n\n        b = property(_get_b)\n\n    i = Foo()\n    assert i.b == 2\n\n\ndef test_attribute_multiple():\n    class Foo:\n        b = 1\n\n    class Bar:\n        b = 2\n\n    assert Foo().b == Bar().b\n\n\ndef globf(x):\n    return x + 1\n\n\nclass TestRaises:\n    def test_raises(self):\n        s = \"qwe\"\n        raises(TypeError, int, s)\n\n    def test_raises_doesnt(self):\n        raises(OSError, int, \"3\")\n\n    def test_raise(self):\n        raise ValueError(\"demo error\")\n\n    def test_tupleerror(self):\n        a, b = [1]  # noqa: F841\n\n    def test_reinterpret_fails_with_print_for_the_fun_of_it(self):\n        items = [1, 2, 3]\n        print(f\"items is {items!r}\")\n        a, b = items.pop()\n\n    def test_some_error(self):\n        if namenotexi:  # noqa: F821\n            pass\n\n    def func1(self):\n        assert 41 == 42\n\n\n# thanks to Matthew Scott for this test\ndef test_dynamic_compile_shows_nicely():\n    import importlib.util\n    import sys\n\n    src = \"def foo():\\n assert 1 == 0\\n\"\n    name = \"abc-123\"\n    spec = importlib.util.spec_from_loader(name, loader=None)\n    module = importlib.util.module_from_spec(spec)\n    code = compile(src, name, \"exec\")\n    exec(code, module.__dict__)\n    sys.modules[name] = module\n    module.foo()\n\n\nclass TestMoreErrors:\n    def test_complex_error(self):\n        def f():\n            return 44\n\n        def g():\n            return 43\n\n        somefunc(f(), g())\n\n    def test_z1_unpack_error(self):\n        items = []\n        a, b = items\n\n    def test_z2_type_error(self):\n        items = 3\n        a, b = items\n\n    def test_startswith(self):\n        s = \"123\"\n        g = \"456\"\n        assert s.startswith(g)\n\n    def test_startswith_nested(self):\n        def f():\n            return \"123\"\n\n        def g():\n            return \"456\"\n\n        assert f().startswith(g())\n\n    def test_global_func(self):\n        assert isinstance(globf(42), float)\n\n    def test_instance(self):\n        self.x = 6 * 7\n        assert self.x != 42\n\n    def test_compare(self):\n        assert globf(10) < 5\n\n    def test_try_finally(self):\n        x = 1\n        try:\n            assert x == 0\n        finally:\n            x = 0\n\n\nclass TestCustomAssertMsg:\n    def test_single_line(self):\n        class A:\n            a = 1\n\n        b = 2\n        assert A.a == b, \"A.a appears not to be b\"\n\n    def test_multiline(self):\n        class A:\n            a = 1\n\n        b = 2\n        assert A.a == b, (\n            \"A.a appears not to be b\\nor does not appear to be b\\none of those\"\n        )\n\n    def test_custom_repr(self):\n        class JSON:\n            a = 1\n\n            def __repr__(self):\n                return \"This is JSON\\n{\\n  'foo': 'bar'\\n}\"\n\n        a = JSON()\n        b = 2\n        assert a.a == b, a\n"
  },
  {
    "path": "doc/en/example/assertion/global_testmodule_config/conftest.py",
    "content": "from __future__ import annotations\n\nimport os.path\n\nimport pytest\n\n\nmydir = os.path.dirname(__file__)\n\n\ndef pytest_runtest_setup(item):\n    if isinstance(item, pytest.Function):\n        if not item.fspath.relto(mydir):\n            return\n        mod = item.getparent(pytest.Module).obj\n        if hasattr(mod, \"hello\"):\n            print(f\"mod.hello {mod.hello!r}\")\n"
  },
  {
    "path": "doc/en/example/assertion/global_testmodule_config/test_hello_world.py",
    "content": "from __future__ import annotations\n\n\nhello = \"world\"\n\n\ndef test_func():\n    pass\n"
  },
  {
    "path": "doc/en/example/assertion/test_failures.py",
    "content": "from __future__ import annotations\n\nimport os.path\nimport shutil\n\n\nfailure_demo = os.path.join(os.path.dirname(__file__), \"failure_demo.py\")\npytest_plugins = (\"pytester\",)\n\n\ndef test_failure_demo_fails_properly(pytester):\n    target = pytester.path.joinpath(os.path.basename(failure_demo))\n    shutil.copy(failure_demo, target)\n    result = pytester.runpytest(target, syspathinsert=True)\n    result.stdout.fnmatch_lines([\"*44 failed*\"])\n    assert result.ret != 0\n"
  },
  {
    "path": "doc/en/example/assertion/test_setup_flow_example.py",
    "content": "from __future__ import annotations\n\n\ndef setup_module(module):\n    module.TestStateFullThing.classcount = 0\n\n\nclass TestStateFullThing:\n    def setup_class(cls):\n        cls.classcount += 1\n\n    def teardown_class(cls):\n        cls.classcount -= 1\n\n    def setup_method(self, method):\n        self.id = eval(method.__name__[5:])\n\n    def test_42(self):\n        assert self.classcount == 1\n        assert self.id == 42\n\n    def test_23(self):\n        assert self.classcount == 1\n        assert self.id == 23\n\n\ndef teardown_module(module):\n    assert module.TestStateFullThing.classcount == 0\n\n\n\"\"\" For this example the control flow happens as follows::\n    import test_setup_flow_example\n    setup_module(test_setup_flow_example)\n       setup_class(TestStateFullThing)\n           instance = TestStateFullThing()\n           setup_method(instance, instance.test_42)\n              instance.test_42()\n           setup_method(instance, instance.test_23)\n              instance.test_23()\n       teardown_class(TestStateFullThing)\n    teardown_module(test_setup_flow_example)\n\nNote that ``setup_class(TestStateFullThing)`` is called and not\n``TestStateFullThing.setup_class()`` which would require you\nto insert ``setup_class = classmethod(setup_class)`` to make\nyour setup function callable.\n\"\"\"\n"
  },
  {
    "path": "doc/en/example/attic.rst",
    "content": "\n.. _`accept example`:\n\nexample: specifying and selecting acceptance tests\n--------------------------------------------------------------\n\n.. sourcecode:: python\n\n    # ./conftest.py\n    def pytest_option(parser):\n        group = parser.getgroup(\"myproject\")\n        group.addoption(\n            \"-A\", dest=\"acceptance\", action=\"store_true\", help=\"run (slow) acceptance tests\"\n        )\n\n\n    def pytest_funcarg__accept(request):\n        return AcceptFixture(request)\n\n\n    class AcceptFixture:\n        def __init__(self, request):\n            if not request.config.getoption(\"acceptance\"):\n                pytest.skip(\"specify -A to run acceptance tests\")\n            self.tmpdir = request.config.mktemp(request.function.__name__, numbered=True)\n\n        def run(self, *cmd):\n            \"\"\"called by test code to execute an acceptance test.\"\"\"\n            self.tmpdir.chdir()\n            return subprocess.check_output(cmd).decode()\n\n\nand the actual test function example:\n\n.. sourcecode:: python\n\n    def test_some_acceptance_aspect(accept):\n        accept.tmpdir.mkdir(\"somesub\")\n        result = accept.run(\"ls\", \"-la\")\n        assert \"somesub\" in result\n\nIf you run this test without specifying a command line option\nthe test will get skipped with an appropriate message. Otherwise\nyou can start to add convenience and test support methods\nto your AcceptFixture and drive running of tools or\napplications and provide ways to do assertions about\nthe output.\n\n.. _`decorate a funcarg`:\n\nexample: decorating a funcarg in a test module\n--------------------------------------------------------------\n\nFor larger scale setups it's sometimes useful to decorate\na funcarg just for a particular test module.  We can\nextend the `accept example`_ by putting this in our test module:\n\n.. sourcecode:: python\n\n    def pytest_funcarg__accept(request):\n        # call the next factory (living in our conftest.py)\n        arg = request.getfuncargvalue(\"accept\")\n        # create a special layout in our tempdir\n        arg.tmpdir.mkdir(\"special\")\n        return arg\n\n\n    class TestSpecialAcceptance:\n        def test_sometest(self, accept):\n            assert accept.tmpdir.join(\"special\").check()\n\nOur module level factory will be invoked first and it can\nask its request object to call the next factory and then\ndecorate its result.  This mechanism allows us to stay\nignorant of how/where the function argument is provided -\nin our example from a `conftest plugin`_.\n\nSide note: the temporary directories used here are instances of\nthe `py.path.local`_ class which provides many of the os.path\nmethods in a convenient way.\n\n.. _`py.path.local`: ../path.html#local\n.. _`conftest plugin`: customize.html#conftestplugin\n"
  },
  {
    "path": "doc/en/example/conftest.py",
    "content": "from __future__ import annotations\n\n\ncollect_ignore = [\"nonpython\", \"customdirectory\"]\n"
  },
  {
    "path": "doc/en/example/customdirectory/conftest.py",
    "content": "# content of conftest.py\nfrom __future__ import annotations\n\nimport json\n\nimport pytest\n\n\nclass ManifestDirectory(pytest.Directory):\n    def collect(self):\n        # The standard pytest behavior is to loop over all `test_*.py` files and\n        # call `pytest_collect_file` on each file. This collector instead reads\n        # the `manifest.json` file and only calls `pytest_collect_file` for the\n        # files defined there.\n        manifest_path = self.path / \"manifest.json\"\n        manifest = json.loads(manifest_path.read_text(encoding=\"utf-8\"))\n        ihook = self.ihook\n        for file in manifest[\"files\"]:\n            yield from ihook.pytest_collect_file(\n                file_path=self.path / file, parent=self\n            )\n\n\n@pytest.hookimpl\ndef pytest_collect_directory(path, parent):\n    # Use our custom collector for directories containing a `manifest.json` file.\n    if path.joinpath(\"manifest.json\").is_file():\n        return ManifestDirectory.from_parent(parent=parent, path=path)\n    # Otherwise fallback to the standard behavior.\n    return None\n"
  },
  {
    "path": "doc/en/example/customdirectory/pytest.ini",
    "content": ""
  },
  {
    "path": "doc/en/example/customdirectory/tests/manifest.json",
    "content": "{\n    \"files\": [\n        \"test_first.py\",\n        \"test_second.py\"\n    ]\n}\n"
  },
  {
    "path": "doc/en/example/customdirectory/tests/test_first.py",
    "content": "# content of test_first.py\nfrom __future__ import annotations\n\n\ndef test_1():\n    pass\n"
  },
  {
    "path": "doc/en/example/customdirectory/tests/test_second.py",
    "content": "# content of test_second.py\nfrom __future__ import annotations\n\n\ndef test_2():\n    pass\n"
  },
  {
    "path": "doc/en/example/customdirectory/tests/test_third.py",
    "content": "# content of test_third.py\nfrom __future__ import annotations\n\n\ndef test_3():\n    pass\n"
  },
  {
    "path": "doc/en/example/customdirectory.rst",
    "content": ".. _`custom directory collectors`:\n\nUsing a custom directory collector\n====================================================\n\nBy default, pytest collects directories using :class:`pytest.Package`, for directories with ``__init__.py`` files,\nand :class:`pytest.Dir` for other directories.\nIf you want to customize how a directory is collected, you can write your own :class:`pytest.Directory` collector,\nand use :hook:`pytest_collect_directory` to hook it up.\n\n.. _`directory manifest plugin`:\n\nA basic example for a directory manifest file\n--------------------------------------------------------------\n\nSuppose you want to customize how collection is done on a per-directory basis.\nHere is an example ``conftest.py`` plugin that allows directories to contain a ``manifest.json`` file,\nwhich defines how the collection should be done for the directory.\nIn this example, only a simple list of files is supported,\nhowever you can imagine adding other keys, such as exclusions and globs.\n\n.. include:: customdirectory/conftest.py\n    :literal:\n\nYou can create a ``manifest.json`` file and some test files:\n\n.. include:: customdirectory/tests/manifest.json\n    :literal:\n\n.. include:: customdirectory/tests/test_first.py\n    :literal:\n\n.. include:: customdirectory/tests/test_second.py\n    :literal:\n\n.. include:: customdirectory/tests/test_third.py\n    :literal:\n\nAnd you can now execute the test specification:\n\n.. code-block:: pytest\n\n    customdirectory $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project/customdirectory\n    configfile: pytest.ini\n    collected 2 items\n\n    tests/test_first.py .                                                [ 50%]\n    tests/test_second.py .                                               [100%]\n\n    ============================ 2 passed in 0.12s =============================\n\n.. regendoc:wipe\n\nNotice how ``test_three.py`` was not executed, because it is not listed in the manifest.\n\nYou can verify that your custom collector appears in the collection tree:\n\n.. code-block:: pytest\n\n    customdirectory $ pytest --collect-only\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project/customdirectory\n    configfile: pytest.ini\n    collected 2 items\n\n    <Dir customdirectory>\n      <ManifestDirectory tests>\n        <Module test_first.py>\n          <Function test_1>\n        <Module test_second.py>\n          <Function test_2>\n\n    ======================== 2 tests collected in 0.12s ========================\n"
  },
  {
    "path": "doc/en/example/fixtures/test_fixtures_order_autouse.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef order():\n    return []\n\n\n@pytest.fixture\ndef a(order):\n    order.append(\"a\")\n\n\n@pytest.fixture\ndef b(a, order):\n    order.append(\"b\")\n\n\n@pytest.fixture(autouse=True)\ndef c(b, order):\n    order.append(\"c\")\n\n\n@pytest.fixture\ndef d(b, order):\n    order.append(\"d\")\n\n\n@pytest.fixture\ndef e(d, order):\n    order.append(\"e\")\n\n\n@pytest.fixture\ndef f(e, order):\n    order.append(\"f\")\n\n\n@pytest.fixture\ndef g(f, c, order):\n    order.append(\"g\")\n\n\ndef test_order_and_g(g, order):\n    assert order == [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"]\n"
  },
  {
    "path": "doc/en/example/fixtures/test_fixtures_order_autouse_multiple_scopes.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture(scope=\"class\")\ndef order():\n    return []\n\n\n@pytest.fixture(scope=\"class\", autouse=True)\ndef c1(order):\n    order.append(\"c1\")\n\n\n@pytest.fixture(scope=\"class\")\ndef c2(order):\n    order.append(\"c2\")\n\n\n@pytest.fixture(scope=\"class\")\ndef c3(order, c1):\n    order.append(\"c3\")\n\n\nclass TestClassWithC1Request:\n    def test_order(self, order, c1, c3):\n        assert order == [\"c1\", \"c3\"]\n\n\nclass TestClassWithoutC1Request:\n    def test_order(self, order, c2):\n        assert order == [\"c1\", \"c2\"]\n"
  },
  {
    "path": "doc/en/example/fixtures/test_fixtures_order_autouse_temp_effects.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef order():\n    return []\n\n\n@pytest.fixture\ndef c1(order):\n    order.append(\"c1\")\n\n\n@pytest.fixture\ndef c2(order):\n    order.append(\"c2\")\n\n\nclass TestClassWithAutouse:\n    @pytest.fixture(autouse=True)\n    def c3(self, order, c2):\n        order.append(\"c3\")\n\n    def test_req(self, order, c1):\n        assert order == [\"c2\", \"c3\", \"c1\"]\n\n    def test_no_req(self, order):\n        assert order == [\"c2\", \"c3\"]\n\n\nclass TestClassWithoutAutouse:\n    def test_req(self, order, c1):\n        assert order == [\"c1\"]\n\n    def test_no_req(self, order):\n        assert order == []\n"
  },
  {
    "path": "doc/en/example/fixtures/test_fixtures_order_dependencies.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef order():\n    return []\n\n\n@pytest.fixture\ndef a(order):\n    order.append(\"a\")\n\n\n@pytest.fixture\ndef b(a, order):\n    order.append(\"b\")\n\n\n@pytest.fixture\ndef c(b, order):\n    order.append(\"c\")\n\n\n@pytest.fixture\ndef d(c, b, order):\n    order.append(\"d\")\n\n\n@pytest.fixture\ndef e(d, b, order):\n    order.append(\"e\")\n\n\n@pytest.fixture\ndef f(e, order):\n    order.append(\"f\")\n\n\n@pytest.fixture\ndef g(f, c, order):\n    order.append(\"g\")\n\n\ndef test_order(g, order):\n    assert order == [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\"]\n"
  },
  {
    "path": "doc/en/example/fixtures/test_fixtures_order_scope.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture(scope=\"session\")\ndef order():\n    return []\n\n\n@pytest.fixture\ndef func(order):\n    order.append(\"function\")\n\n\n@pytest.fixture(scope=\"class\")\ndef cls(order):\n    order.append(\"class\")\n\n\n@pytest.fixture(scope=\"module\")\ndef mod(order):\n    order.append(\"module\")\n\n\n@pytest.fixture(scope=\"package\")\ndef pack(order):\n    order.append(\"package\")\n\n\n@pytest.fixture(scope=\"session\")\ndef sess(order):\n    order.append(\"session\")\n\n\nclass TestClass:\n    def test_order(self, func, cls, mod, pack, sess, order):\n        assert order == [\"session\", \"package\", \"module\", \"class\", \"function\"]\n"
  },
  {
    "path": "doc/en/example/fixtures/test_fixtures_request_different_scope.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef order():\n    return []\n\n\n@pytest.fixture\ndef outer(order, inner):\n    order.append(\"outer\")\n\n\nclass TestOne:\n    @pytest.fixture\n    def inner(self, order):\n        order.append(\"one\")\n\n    def test_order(self, order, outer):\n        assert order == [\"one\", \"outer\"]\n\n\nclass TestTwo:\n    @pytest.fixture\n    def inner(self, order):\n        order.append(\"two\")\n\n    def test_order(self, order, outer):\n        assert order == [\"two\", \"outer\"]\n"
  },
  {
    "path": "doc/en/example/index.rst",
    "content": "\n.. _examples:\n\nExamples and customization tricks\n=================================\n\nHere is a (growing) list of examples. :ref:`Contact <contact>` us if you\nneed more examples or have questions. Also take a look at the\n:ref:`comprehensive documentation <toc>` which contains many example\nsnippets as well.  Also, `pytest on stackoverflow.com\n<http://stackoverflow.com/search?q=pytest>`_ often comes with example\nanswers.\n\nFor basic examples, see\n\n- :ref:`get-started` for basic introductory examples\n- :ref:`assert` for basic assertion examples\n- :ref:`Fixtures <fixtures>` for basic fixture/setup examples\n- :ref:`parametrize` for basic test function parametrization\n- :ref:`unittest` for basic unittest integration\n\nThe following examples aim at various use cases you might encounter.\n\n.. toctree::\n   :maxdepth: 2\n\n   reportingdemo\n   simple\n   parametrize\n   markers\n   special\n   pythoncollection\n   nonpython\n   customdirectory\n"
  },
  {
    "path": "doc/en/example/markers.rst",
    "content": "\n.. _`mark examples`:\n\nWorking with custom markers\n=================================================\n\nHere are some examples using the :ref:`mark` mechanism.\n\n.. _`mark run`:\n\nMarking test functions and selecting them for a run\n----------------------------------------------------\n\nYou can \"mark\" a test function with custom metadata like this:\n\n.. code-block:: python\n\n    # content of test_server.py\n\n    import pytest\n\n\n    @pytest.mark.webtest\n    def test_send_http():\n        pass  # perform some webtest test for your app\n\n\n    @pytest.mark.device(serial=\"123\")\n    def test_something_quick():\n        pass\n\n\n    @pytest.mark.device(serial=\"abc\")\n    def test_another():\n        pass\n\n\n    class TestClass:\n        def test_method(self):\n            pass\n\n\n\nYou can then restrict a test run to only run tests marked with ``webtest``:\n\n.. code-block:: pytest\n\n    $ pytest -v -m webtest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 4 items / 3 deselected / 1 selected\n\n    test_server.py::test_send_http PASSED                                [100%]\n\n    ===================== 1 passed, 3 deselected in 0.12s ======================\n\nOr the inverse, running all tests except the webtest ones:\n\n.. code-block:: pytest\n\n    $ pytest -v -m \"not webtest\"\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 4 items / 1 deselected / 3 selected\n\n    test_server.py::test_something_quick PASSED                          [ 33%]\n    test_server.py::test_another PASSED                                  [ 66%]\n    test_server.py::TestClass::test_method PASSED                        [100%]\n\n    ===================== 3 passed, 1 deselected in 0.12s ======================\n\n.. _`marker_keyword_expression_example`:\n\nAdditionally, you can restrict a test run to only run tests matching one or multiple marker\nkeyword arguments, e.g. to run only tests marked with ``device`` and the specific ``serial=\"123\"``:\n\n.. code-block:: pytest\n\n    $ pytest -v -m \"device(serial='123')\"\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 4 items / 3 deselected / 1 selected\n\n    test_server.py::test_something_quick PASSED                          [100%]\n\n    ===================== 1 passed, 3 deselected in 0.12s ======================\n\n.. note:: Only keyword argument matching is supported in marker expressions.\n\n.. note:: Only :class:`int`, (unescaped) :class:`str`, :class:`bool` & :data:`None` values are supported in marker expressions.\n\nSelecting tests based on their node ID\n--------------------------------------\n\nYou can provide one or more :ref:`node IDs <node-id>` as positional\narguments to select only specified tests. This makes it easy to select\ntests based on their module, class, method, or function name:\n\n.. code-block:: pytest\n\n    $ pytest -v test_server.py::TestClass::test_method\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 1 item\n\n    test_server.py::TestClass::test_method PASSED                        [100%]\n\n    ============================ 1 passed in 0.12s =============================\n\nYou can also select on the class:\n\n.. code-block:: pytest\n\n    $ pytest -v test_server.py::TestClass\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 1 item\n\n    test_server.py::TestClass::test_method PASSED                        [100%]\n\n    ============================ 1 passed in 0.12s =============================\n\nOr select multiple nodes:\n\n.. code-block:: pytest\n\n    $ pytest -v test_server.py::TestClass test_server.py::test_send_http\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 2 items\n\n    test_server.py::TestClass::test_method PASSED                        [ 50%]\n    test_server.py::test_send_http PASSED                                [100%]\n\n    ============================ 2 passed in 0.12s =============================\n\n.. _node-id:\n\n.. note::\n\n    Node IDs are of the form ``module.py::class::method`` or\n    ``module.py::function``.  Node IDs control which tests are\n    collected, so ``module.py::class`` will select all test methods\n    on the class.  Nodes are also created for each parameter of a\n    parametrized fixture or test, so selecting a parametrized test\n    must include the parameter value, e.g.\n    ``module.py::function[param]``.\n\n    Node IDs for failing tests are displayed in the test summary info\n    when running pytest with the ``-rf`` option.  You can also\n    construct Node IDs from the output of ``pytest --collect-only``.\n\nUsing ``-k expr`` to select tests based on their name\n-------------------------------------------------------\n\n.. versionadded:: 2.0/2.3.4\n\nYou can use the :option:`-k` command line option to specify an expression\nwhich implements a substring match on the test names instead of the\nexact match on markers that :option:`-m` provides.  This makes it easy to\nselect tests based on their names:\n\n.. versionchanged:: 5.4\n\nThe expression matching is now case-insensitive.\n\n.. code-block:: pytest\n\n    $ pytest -v -k http  # running with the above defined example module\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 4 items / 3 deselected / 1 selected\n\n    test_server.py::test_send_http PASSED                                [100%]\n\n    ===================== 1 passed, 3 deselected in 0.12s ======================\n\nAnd you can also run all tests except the ones that match the keyword:\n\n.. code-block:: pytest\n\n    $ pytest -k \"not send_http\" -v\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 4 items / 1 deselected / 3 selected\n\n    test_server.py::test_something_quick PASSED                          [ 33%]\n    test_server.py::test_another PASSED                                  [ 66%]\n    test_server.py::TestClass::test_method PASSED                        [100%]\n\n    ===================== 3 passed, 1 deselected in 0.12s ======================\n\nOr to select \"http\" and \"quick\" tests:\n\n.. code-block:: pytest\n\n    $ pytest -k \"http or quick\" -v\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 4 items / 2 deselected / 2 selected\n\n    test_server.py::test_send_http PASSED                                [ 50%]\n    test_server.py::test_something_quick PASSED                          [100%]\n\n    ===================== 2 passed, 2 deselected in 0.12s ======================\n\nYou can use ``and``, ``or``, ``not`` and parentheses.\n\n\nIn addition to the test's name, :option:`-k` also matches the names of the test's parents (usually, the name of the file and class it's in),\nattributes set on the test function, markers applied to it or its parents and any :attr:`extra keywords <_pytest.nodes.Node.extra_keyword_matches>`\nexplicitly added to it or its parents.\n\n\nRegistering markers\n-------------------------------------\n\n\n\n.. ini-syntax for custom markers:\n\nRegistering markers for your test suite is simple:\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    [pytest]\n    markers = [\"webtest: mark a test as a webtest.\", \"slow: mark test as slow.\"]\n\nMultiple custom markers can be registered, by defining each one in its own line, as shown in above example.\n\nYou can ask which markers exist for your test suite - the list includes our just defined ``webtest`` and ``slow`` markers:\n\n.. code-block:: pytest\n\n    $ pytest --markers\n    @pytest.mark.webtest: mark a test as a webtest.\n\n    @pytest.mark.slow: mark test as slow.\n\n    @pytest.mark.filterwarnings(warning): add a warning filter to the given test. see https://docs.pytest.org/en/stable/how-to/capture-warnings.html#pytest-mark-filterwarnings\n\n    @pytest.mark.skip(reason=None): skip the given test function with an optional reason. Example: skip(reason=\"no way of currently testing this\") skips the test.\n\n    @pytest.mark.skipif(condition, ..., *, reason=...): skip the given test function if any of the conditions evaluate to True. Example: skipif(sys.platform == 'win32') skips the test if we are on the win32 platform. See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-skipif\n\n    @pytest.mark.xfail(condition, ..., *, reason=..., run=True, raises=None, strict=strict_xfail): mark the test function as an expected failure if any of the conditions evaluate to True. Optionally specify a reason for better reporting and run=False if you don't even want to execute the test function. If only specific exception(s) are expected, you can list them in raises, and if the test fails in other ways, it will be reported as a true failure. See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-xfail\n\n    @pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. argvalues generally needs to be a list of values if argnames specifies only one name or a list of tuples of values if argnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would lead to two calls of the decorated test function, one with arg1=1 and another with arg1=2.see https://docs.pytest.org/en/stable/how-to/parametrize.html for more info and examples.\n\n    @pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see https://docs.pytest.org/en/stable/explanation/fixtures.html#usefixtures\n\n    @pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible. DEPRECATED, use @pytest.hookimpl(tryfirst=True) instead.\n\n    @pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible. DEPRECATED, use @pytest.hookimpl(trylast=True) instead.\n\n\nFor an example on how to add and work with markers from a plugin, see\n:ref:`adding a custom marker from a plugin`.\n\n.. note::\n\n    It is recommended to explicitly register markers so that:\n\n    * There is one place in your test suite defining your markers\n\n    * Asking for existing markers via ``pytest --markers`` gives good output\n\n    * Typos in function markers are treated as an error if you use the :confval:`strict_markers` configuration option.\n\n.. _`scoped-marking`:\n\nMarking whole classes or modules\n----------------------------------------------------\n\nYou may use ``pytest.mark`` decorators with classes to apply markers to all of\nits test methods:\n\n.. code-block:: python\n\n    # content of test_mark_classlevel.py\n    import pytest\n\n\n    @pytest.mark.webtest\n    class TestClass:\n        def test_startup(self):\n            pass\n\n        def test_startup_and_more(self):\n            pass\n\nThis is equivalent to directly applying the decorator to the\ntwo test functions.\n\nTo apply marks at the module level, use the :globalvar:`pytestmark` global variable::\n\n    import pytest\n    pytestmark = pytest.mark.webtest\n\nor multiple markers::\n\n    pytestmark = [pytest.mark.webtest, pytest.mark.slowtest]\n\n\nDue to legacy reasons, before class decorators were introduced, it is possible to set the\n:globalvar:`pytestmark` attribute on a test class like this:\n\n.. code-block:: python\n\n    import pytest\n\n\n    class TestClass:\n        pytestmark = pytest.mark.webtest\n\n.. _`marking individual tests when using parametrize`:\n\nMarking individual tests when using parametrize\n-----------------------------------------------\n\nWhen using parametrize, applying a mark will make it apply\nto each individual test. However it is also possible to\napply a marker to an individual test instance:\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.mark.foo\n    @pytest.mark.parametrize(\n        (\"n\", \"expected\"), [(1, 2), pytest.param(1, 3, marks=pytest.mark.bar), (2, 3)]\n    )\n    def test_increment(n, expected):\n        assert n + 1 == expected\n\nIn this example the mark \"foo\" will apply to each of the three\ntests, whereas the \"bar\" mark is only applied to the second test.\nSkip and xfail marks can also be applied in this way, see :ref:`skip/xfail with parametrize`.\n\n.. _`adding a custom marker from a plugin`:\n\nCustom marker and command line option to control test runs\n----------------------------------------------------------\n\n.. regendoc:wipe\n\nPlugins can provide custom markers and implement specific behaviour\nbased on it. This is a self-contained example which adds a command\nline option and a parametrized test function marker to run tests\nspecified via named environments:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n    import pytest\n\n\n    def pytest_addoption(parser):\n        parser.addoption(\n            \"-E\",\n            action=\"store\",\n            metavar=\"NAME\",\n            help=\"only run tests matching the environment NAME.\",\n        )\n\n\n    def pytest_configure(config):\n        # register an additional marker\n        config.addinivalue_line(\n            \"markers\", \"env(name): mark test to run only on named environment\"\n        )\n\n\n    def pytest_runtest_setup(item):\n        envnames = [mark.args[0] for mark in item.iter_markers(name=\"env\")]\n        if envnames:\n            if item.config.getoption(\"-E\") not in envnames:\n                pytest.skip(f\"test requires env in {envnames!r}\")\n\nA test file using this local plugin:\n\n.. code-block:: python\n\n    # content of test_someenv.py\n\n    import pytest\n\n\n    @pytest.mark.env(\"stage1\")\n    def test_basic_db_operation():\n        pass\n\nand an example invocation specifying a different environment than what\nthe test needs:\n\n.. code-block:: pytest\n\n    $ pytest -E stage2\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_someenv.py s                                                    [100%]\n\n    ============================ 1 skipped in 0.12s ============================\n\nand here is one that specifies exactly the environment needed:\n\n.. code-block:: pytest\n\n    $ pytest -E stage1\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_someenv.py .                                                    [100%]\n\n    ============================ 1 passed in 0.12s =============================\n\nThe :option:`--markers` option always gives you a list of available markers:\n\n.. code-block:: pytest\n\n    $ pytest --markers\n    @pytest.mark.env(name): mark test to run only on named environment\n\n    @pytest.mark.filterwarnings(warning): add a warning filter to the given test. see https://docs.pytest.org/en/stable/how-to/capture-warnings.html#pytest-mark-filterwarnings\n\n    @pytest.mark.skip(reason=None): skip the given test function with an optional reason. Example: skip(reason=\"no way of currently testing this\") skips the test.\n\n    @pytest.mark.skipif(condition, ..., *, reason=...): skip the given test function if any of the conditions evaluate to True. Example: skipif(sys.platform == 'win32') skips the test if we are on the win32 platform. See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-skipif\n\n    @pytest.mark.xfail(condition, ..., *, reason=..., run=True, raises=None, strict=strict_xfail): mark the test function as an expected failure if any of the conditions evaluate to True. Optionally specify a reason for better reporting and run=False if you don't even want to execute the test function. If only specific exception(s) are expected, you can list them in raises, and if the test fails in other ways, it will be reported as a true failure. See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-xfail\n\n    @pytest.mark.parametrize(argnames, argvalues): call a test function multiple times passing in different arguments in turn. argvalues generally needs to be a list of values if argnames specifies only one name or a list of tuples of values if argnames specifies multiple names. Example: @parametrize('arg1', [1,2]) would lead to two calls of the decorated test function, one with arg1=1 and another with arg1=2.see https://docs.pytest.org/en/stable/how-to/parametrize.html for more info and examples.\n\n    @pytest.mark.usefixtures(fixturename1, fixturename2, ...): mark tests as needing all of the specified fixtures. see https://docs.pytest.org/en/stable/explanation/fixtures.html#usefixtures\n\n    @pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible. DEPRECATED, use @pytest.hookimpl(tryfirst=True) instead.\n\n    @pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible. DEPRECATED, use @pytest.hookimpl(trylast=True) instead.\n\n\n.. _`passing callables to custom markers`:\n\nPassing a callable to custom markers\n--------------------------------------------\n\n.. regendoc:wipe\n\nBelow is the config file that will be used in the next examples:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import sys\n\n\n    def pytest_runtest_setup(item):\n        for marker in item.iter_markers(name=\"my_marker\"):\n            print(marker)\n            sys.stdout.flush()\n\nA custom marker can have its argument set, i.e. ``args`` and ``kwargs`` properties, defined by either invoking it as a callable or using ``pytest.mark.MARKER_NAME.with_args``. These two methods achieve the same effect most of the time.\n\nHowever, if there is a callable as the single positional argument with no keyword arguments, using the ``pytest.mark.MARKER_NAME(c)`` will not pass ``c`` as a positional argument but decorate ``c`` with the custom marker (see :ref:`MarkDecorator <mark>`). Fortunately, ``pytest.mark.MARKER_NAME.with_args`` comes to the rescue:\n\n.. code-block:: python\n\n    # content of test_custom_marker.py\n    import pytest\n\n\n    def hello_world(*args, **kwargs):\n        return \"Hello World\"\n\n\n    @pytest.mark.my_marker.with_args(hello_world)\n    def test_with_args():\n        pass\n\nThe output is as follows:\n\n.. code-block:: pytest\n\n    $ pytest -q -s\n    Mark(name='my_marker', args=(<function hello_world at 0xdeadbeef0001>,), kwargs={})\n    .\n    1 passed in 0.12s\n\nWe can see that the custom marker has its argument set extended with the function ``hello_world``. This is the key difference between creating a custom marker as a callable, which invokes ``__call__`` behind the scenes, and using ``with_args``.\n\n\nReading markers which were set from multiple places\n----------------------------------------------------\n\n.. versionadded: 2.2.2\n\n.. regendoc:wipe\n\nIf you are heavily using markers in your test suite you may encounter the case where a marker is applied several times to a test function.  From plugin\ncode you can read over all such settings.  Example:\n\n.. code-block:: python\n\n    # content of test_mark_three_times.py\n    import pytest\n\n    pytestmark = pytest.mark.glob(\"module\", x=1)\n\n\n    @pytest.mark.glob(\"class\", x=2)\n    class TestClass:\n        @pytest.mark.glob(\"function\", x=3)\n        def test_something(self):\n            pass\n\nHere we have the marker \"glob\" applied three times to the same\ntest function.  From a conftest file we can read it like this:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import sys\n\n\n    def pytest_runtest_setup(item):\n        for mark in item.iter_markers(name=\"glob\"):\n            print(f\"glob args={mark.args} kwargs={mark.kwargs}\")\n            sys.stdout.flush()\n\nLet's run this without capturing output and see what we get:\n\n.. code-block:: pytest\n\n    $ pytest -q -s\n    glob args=('function',) kwargs={'x': 3}\n    glob args=('class',) kwargs={'x': 2}\n    glob args=('module',) kwargs={'x': 1}\n    .\n    1 passed in 0.12s\n\nMarking platform specific tests with pytest\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nConsider you have a test suite which marks tests for particular platforms,\nnamely ``pytest.mark.darwin``, ``pytest.mark.win32`` etc. and you\nalso have tests that run on all platforms and have no specific\nmarker.  If you now want to have a way to only run the tests\nfor your particular platform, you could use the following plugin:\n\n.. code-block:: python\n\n    # content of conftest.py\n    #\n    import sys\n\n    import pytest\n\n    ALL = set(\"darwin linux win32\".split())\n\n\n    def pytest_runtest_setup(item):\n        supported_platforms = ALL.intersection(mark.name for mark in item.iter_markers())\n        plat = sys.platform\n        if supported_platforms and plat not in supported_platforms:\n            pytest.skip(f\"cannot run on platform {plat}\")\n\nthen tests will be skipped if they were specified for a different platform.\nLet's do a little test file to show how this looks like:\n\n.. code-block:: python\n\n    # content of test_plat.py\n\n    import pytest\n\n\n    @pytest.mark.darwin\n    def test_if_apple_is_evil():\n        pass\n\n\n    @pytest.mark.linux\n    def test_if_linux_works():\n        pass\n\n\n    @pytest.mark.win32\n    def test_if_win32_crashes():\n        pass\n\n\n    def test_runs_everywhere():\n        pass\n\nthen you will see two tests skipped and two executed tests as expected:\n\n.. code-block:: pytest\n\n    $ pytest -rs # this option reports skip reasons\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 4 items\n\n    test_plat.py s.s.                                                    [100%]\n\n    ========================= short test summary info ==========================\n    SKIPPED [2] conftest.py:13: cannot run on platform linux\n    ======================= 2 passed, 2 skipped in 0.12s =======================\n\nNote that if you specify a platform via the marker-command line option like this:\n\n.. code-block:: pytest\n\n    $ pytest -m linux\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 4 items / 3 deselected / 1 selected\n\n    test_plat.py .                                                       [100%]\n\n    ===================== 1 passed, 3 deselected in 0.12s ======================\n\nthen the unmarked-tests will not be run.  It is thus a way to restrict the run to the specific tests.\n\nAutomatically adding markers based on test names\n--------------------------------------------------------\n\n.. regendoc:wipe\n\nIf you have a test suite where test function names indicate a certain\ntype of test, you can implement a hook that automatically defines\nmarkers so that you can use the :option:`-m` option with it. Let's look\nat this test module:\n\n.. code-block:: python\n\n    # content of test_module.py\n\n\n    def test_interface_simple():\n        assert 0\n\n\n    def test_interface_complex():\n        assert 0\n\n\n    def test_event_simple():\n        assert 0\n\n\n    def test_something_else():\n        assert 0\n\nWe want to dynamically define two markers and can do it in a\n``conftest.py`` plugin:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n    import pytest\n\n\n    def pytest_collection_modifyitems(items):\n        for item in items:\n            if \"interface\" in item.nodeid:\n                item.add_marker(pytest.mark.interface)\n            elif \"event\" in item.nodeid:\n                item.add_marker(pytest.mark.event)\n\nWe can now use the ``-m option`` to select one set:\n\n.. code-block:: pytest\n\n    $ pytest -m interface --tb=short\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 4 items / 2 deselected / 2 selected\n\n    test_module.py FF                                                    [100%]\n\n    ================================= FAILURES =================================\n    __________________________ test_interface_simple ___________________________\n    test_module.py:4: in test_interface_simple\n        assert 0\n    E   assert 0\n    __________________________ test_interface_complex __________________________\n    test_module.py:8: in test_interface_complex\n        assert 0\n    E   assert 0\n    ========================= short test summary info ==========================\n    FAILED test_module.py::test_interface_simple - assert 0\n    FAILED test_module.py::test_interface_complex - assert 0\n    ===================== 2 failed, 2 deselected in 0.12s ======================\n\nor to select both \"event\" and \"interface\" tests:\n\n.. code-block:: pytest\n\n    $ pytest -m \"interface or event\" --tb=short\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 4 items / 1 deselected / 3 selected\n\n    test_module.py FFF                                                   [100%]\n\n    ================================= FAILURES =================================\n    __________________________ test_interface_simple ___________________________\n    test_module.py:4: in test_interface_simple\n        assert 0\n    E   assert 0\n    __________________________ test_interface_complex __________________________\n    test_module.py:8: in test_interface_complex\n        assert 0\n    E   assert 0\n    ____________________________ test_event_simple _____________________________\n    test_module.py:12: in test_event_simple\n        assert 0\n    E   assert 0\n    ========================= short test summary info ==========================\n    FAILED test_module.py::test_interface_simple - assert 0\n    FAILED test_module.py::test_interface_complex - assert 0\n    FAILED test_module.py::test_event_simple - assert 0\n    ===================== 3 failed, 1 deselected in 0.12s ======================\n"
  },
  {
    "path": "doc/en/example/multipython.py",
    "content": "\"\"\"Module containing a parametrized tests testing cross-python serialization\nvia the pickle module.\"\"\"\n\nfrom __future__ import annotations\n\nimport shutil\nimport subprocess\nimport textwrap\n\nimport pytest\n\n\npythonlist = [\"python3.11\", \"python3.12\", \"python3.13\"]\n\n\n@pytest.fixture(params=pythonlist)\ndef python1(request, tmp_path):\n    picklefile = tmp_path / \"data.pickle\"\n    return Python(request.param, picklefile)\n\n\n@pytest.fixture(params=pythonlist)\ndef python2(request, python1):\n    return Python(request.param, python1.picklefile)\n\n\nclass Python:\n    def __init__(self, version, picklefile):\n        self.pythonpath = shutil.which(version)\n        if not self.pythonpath:\n            pytest.skip(f\"{version!r} not found\")\n        self.picklefile = picklefile\n\n    def dumps(self, obj):\n        dumpfile = self.picklefile.with_name(\"dump.py\")\n        dumpfile.write_text(\n            textwrap.dedent(\n                rf\"\"\"\n                import pickle\n                f = open({str(self.picklefile)!r}, 'wb')\n                s = pickle.dump({obj!r}, f, protocol=2)\n                f.close()\n                \"\"\"\n            )\n        )\n        subprocess.run((self.pythonpath, str(dumpfile)), check=True)\n\n    def load_and_is_true(self, expression):\n        loadfile = self.picklefile.with_name(\"load.py\")\n        loadfile.write_text(\n            textwrap.dedent(\n                rf\"\"\"\n                import pickle\n                f = open({str(self.picklefile)!r}, 'rb')\n                obj = pickle.load(f)\n                f.close()\n                res = eval({expression!r})\n                if not res:\n                    raise SystemExit(1)\n                \"\"\"\n            )\n        )\n        print(loadfile)\n        subprocess.run((self.pythonpath, str(loadfile)), check=True)\n\n\n@pytest.mark.parametrize(\"obj\", [42, {}, {1: 3}])\ndef test_basic_objects(python1, python2, obj):\n    python1.dumps(obj)\n    python2.load_and_is_true(f\"obj == {obj}\")\n"
  },
  {
    "path": "doc/en/example/nonpython/__init__.py",
    "content": ""
  },
  {
    "path": "doc/en/example/nonpython/conftest.py",
    "content": "# content of conftest.py\nfrom __future__ import annotations\n\nimport pytest\n\n\ndef pytest_collect_file(parent, file_path):\n    if file_path.suffix == \".yaml\" and file_path.name.startswith(\"test\"):\n        return YamlFile.from_parent(parent, path=file_path)\n\n\nclass YamlFile(pytest.File):\n    def collect(self):\n        # We need a yaml parser, e.g. PyYAML.\n        import yaml\n\n        raw = yaml.safe_load(self.path.open(encoding=\"utf-8\"))\n        for name, spec in sorted(raw.items()):\n            yield YamlItem.from_parent(self, name=name, spec=spec)\n\n\nclass YamlItem(pytest.Item):\n    def __init__(self, *, spec, **kwargs):\n        super().__init__(**kwargs)\n        self.spec = spec\n\n    def runtest(self):\n        for name, value in sorted(self.spec.items()):\n            # Some custom test execution (dumb example follows).\n            if name != value:\n                raise YamlException(self, name, value)\n\n    def repr_failure(self, excinfo):\n        \"\"\"Called when self.runtest() raises an exception.\"\"\"\n        if isinstance(excinfo.value, YamlException):\n            return \"\\n\".join(\n                [\n                    \"usecase execution failed\",\n                    \"   spec failed: {1!r}: {2!r}\".format(*excinfo.value.args),\n                    \"   no further details known at this point.\",\n                ]\n            )\n        return super().repr_failure(excinfo)\n\n    def reportinfo(self):\n        return self.path, 0, f\"usecase: {self.name}\"\n\n\nclass YamlException(Exception):\n    \"\"\"Custom exception for error reporting.\"\"\"\n"
  },
  {
    "path": "doc/en/example/nonpython/test_simple.yaml",
    "content": "# test_simple.yaml\nok:\n    sub1: sub1\n\nhello:\n    world: world\n    some: other\n"
  },
  {
    "path": "doc/en/example/nonpython.rst",
    "content": "\n.. _`non-python tests`:\n\nWorking with non-python tests\n====================================================\n\n.. _`yaml plugin`:\n\nA basic example for specifying tests in Yaml files\n--------------------------------------------------------------\n\n.. _`pytest-yamlwsgi`: https://pypi.org/project/pytest-yamlwsgi/\n\nHere is an example ``conftest.py`` (extracted from Ali Afshar's special purpose `pytest-yamlwsgi`_ plugin).   This ``conftest.py`` will  collect ``test*.yaml`` files and will execute the yaml-formatted content as custom tests:\n\n.. include:: nonpython/conftest.py\n    :literal:\n\nYou can create a simple example file:\n\n.. include:: nonpython/test_simple.yaml\n    :literal:\n\nand if you installed :pypi:`PyYAML` or a compatible YAML-parser you can\nnow execute the test specification:\n\n.. code-block:: pytest\n\n    nonpython $ pytest test_simple.yaml\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project/nonpython\n    collected 2 items\n\n    test_simple.yaml F.                                                  [100%]\n\n    ================================= FAILURES =================================\n    ______________________________ usecase: hello ______________________________\n    usecase execution failed\n       spec failed: 'some': 'other'\n       no further details known at this point.\n    ========================= short test summary info ==========================\n    FAILED test_simple.yaml::hello - usecase execution failed\n    ======================= 1 failed, 1 passed in 0.12s ========================\n\n.. regendoc:wipe\n\nYou get one dot for the passing ``sub1: sub1`` check and one failure.\nObviously in the above ``conftest.py`` you'll want to implement a more\ninteresting interpretation of the yaml-values.  You can easily write\nyour own domain specific testing language this way.\n\n.. note::\n\n    ``repr_failure(excinfo)`` is called for representing test failures.\n    If you create custom collection nodes you can return an error\n    representation string of your choice.  It\n    will be reported as a (red) string.\n\n``reportinfo()`` is used for representing the test location and is also\nconsulted when reporting in ``verbose`` mode. It should return a tuple\n``(path, lineno, description)``, where:\n\n* ``path`` is the path shown in reports (usually ``self.path`` or ``self.fspath``).\n* ``lineno`` is a zero-based line number, or ``0`` when no specific line applies.\n* ``description`` is a short label shown for the collected item:\n\n.. code-block:: pytest\n\n    nonpython $ pytest -v\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project/nonpython\n    collecting ... collected 2 items\n\n    test_simple.yaml::hello FAILED                                       [ 50%]\n    test_simple.yaml::ok PASSED                                          [100%]\n\n    ================================= FAILURES =================================\n    ______________________________ usecase: hello ______________________________\n    usecase execution failed\n       spec failed: 'some': 'other'\n       no further details known at this point.\n    ========================= short test summary info ==========================\n    FAILED test_simple.yaml::hello - usecase execution failed\n    ======================= 1 failed, 1 passed in 0.12s ========================\n\n.. regendoc:wipe\n\nWhile developing your custom test collection and execution it's also\ninteresting to just look at the collection tree:\n\n.. code-block:: pytest\n\n    nonpython $ pytest --collect-only\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project/nonpython\n    collected 2 items\n\n    <Package nonpython>\n      <YamlFile test_simple.yaml>\n        <YamlItem hello>\n        <YamlItem ok>\n\n    ======================== 2 tests collected in 0.12s ========================\n"
  },
  {
    "path": "doc/en/example/parametrize.rst",
    "content": "\n.. _paramexamples:\n\nParametrizing tests\n=================================================\n\n``pytest`` allows you to easily parametrize test functions.\nFor basic docs, see :ref:`parametrize-basics`.\n\nIn the following we provide some examples using\nthe builtin mechanisms.\n\nGenerating parameters combinations, depending on command line\n----------------------------------------------------------------------------\n\n.. regendoc:wipe\n\nLet's say we want to execute a test with different computation\nparameters and the parameter range shall be determined by a command\nline argument.  Let's first write a simple (do-nothing) computation test:\n\n.. code-block:: python\n\n    # content of test_compute.py\n\n\n    def test_compute(param1):\n        assert param1 < 4\n\nNow we add a test configuration like this:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n\n    def pytest_addoption(parser):\n        parser.addoption(\"--all\", action=\"store_true\", help=\"run all combinations\")\n\n\n    def pytest_generate_tests(metafunc):\n        if \"param1\" in metafunc.fixturenames:\n            if metafunc.config.getoption(\"all\"):\n                end = 5\n            else:\n                end = 2\n            metafunc.parametrize(\"param1\", range(end))\n\nThis means that we only run 2 tests if we do not pass ``--all``:\n\n.. code-block:: pytest\n\n    $ pytest -q test_compute.py\n    ..                                                                   [100%]\n    2 passed in 0.12s\n\nWe run only two computations, so we see two dots.\nlet's run the full monty:\n\n.. code-block:: pytest\n\n    $ pytest -q --all\n    ....F                                                                [100%]\n    ================================= FAILURES =================================\n    _____________________________ test_compute[4] ______________________________\n\n    param1 = 4\n\n        def test_compute(param1):\n    >       assert param1 < 4\n    E       assert 4 < 4\n\n    test_compute.py:4: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_compute.py::test_compute[4] - assert 4 < 4\n    1 failed, 4 passed in 0.12s\n\nAs expected when running the full range of ``param1`` values\nwe'll get an error on the last one.\n\n\nDifferent options for test IDs\n------------------------------------\n\npytest will build a string that is the test ID for each set of values in a\nparametrized test. These IDs can be used with :option:`-k` to select specific cases\nto run, and they will also identify the specific case when one is failing.\nRunning pytest with :option:`--collect-only` will show the generated IDs.\n\nNumbers, strings, booleans and None will have their usual string representation\nused in the test ID. For other objects, pytest will make a string based on\nthe argument name:\n\n.. code-block:: python\n\n    # content of test_time.py\n\n    from datetime import datetime, timedelta\n\n    import pytest\n\n    testdata = [\n        (datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1)),\n        (datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1)),\n    ]\n\n\n    @pytest.mark.parametrize(\"a,b,expected\", testdata)\n    def test_timedistance_v0(a, b, expected):\n        diff = a - b\n        assert diff == expected\n\n\n    @pytest.mark.parametrize(\"a,b,expected\", testdata, ids=[\"forward\", \"backward\"])\n    def test_timedistance_v1(a, b, expected):\n        diff = a - b\n        assert diff == expected\n\n\n    def idfn(val):\n        if isinstance(val, (datetime,)):\n            # note this wouldn't show any hours/minutes/seconds\n            return val.strftime(\"%Y%m%d\")\n\n\n    @pytest.mark.parametrize(\"a,b,expected\", testdata, ids=idfn)\n    def test_timedistance_v2(a, b, expected):\n        diff = a - b\n        assert diff == expected\n\n\n    @pytest.mark.parametrize(\n        \"a,b,expected\",\n        [\n            pytest.param(\n                datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1), id=\"forward\"\n            ),\n            pytest.param(\n                datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1), id=\"backward\"\n            ),\n        ],\n    )\n    def test_timedistance_v3(a, b, expected):\n        diff = a - b\n        assert diff == expected\n\nIn ``test_timedistance_v0``, we let pytest generate the test IDs.\n\nIn ``test_timedistance_v1``, we specified ``ids`` as a list of strings which were\nused as the test IDs. These are succinct, but can be a pain to maintain.\n\nIn ``test_timedistance_v2``, we specified ``ids`` as a function that can generate a\nstring representation to make part of the test ID. So our ``datetime`` values use the\nlabel generated by ``idfn``, but because we didn't generate a label for ``timedelta``\nobjects, they are still using the default pytest representation:\n\n.. code-block:: pytest\n\n    $ pytest test_time.py --collect-only\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 8 items\n\n    <Dir parametrize.rst-212>\n      <Module test_time.py>\n        <Function test_timedistance_v0[a0-b0-expected0]>\n        <Function test_timedistance_v0[a1-b1-expected1]>\n        <Function test_timedistance_v1[forward]>\n        <Function test_timedistance_v1[backward]>\n        <Function test_timedistance_v2[20011212-20011211-expected0]>\n        <Function test_timedistance_v2[20011211-20011212-expected1]>\n        <Function test_timedistance_v3[forward]>\n        <Function test_timedistance_v3[backward]>\n\n    ======================== 8 tests collected in 0.12s ========================\n\nIn ``test_timedistance_v3``, we used ``pytest.param`` to specify the test IDs\ntogether with the actual data, instead of listing them separately.\n\nA quick port of \"testscenarios\"\n------------------------------------\n\nHere is a quick port to run tests configured with :pypi:`testscenarios`,\nan add-on from Robert Collins for the standard unittest framework. We\nonly have to work a bit to construct the correct arguments for pytest's\n:py:func:`Metafunc.parametrize <pytest.Metafunc.parametrize>`:\n\n.. code-block:: python\n\n    # content of test_scenarios.py\n\n\n    def pytest_generate_tests(metafunc):\n        idlist = []\n        argvalues = []\n        for scenario in metafunc.cls.scenarios:\n            idlist.append(scenario[0])\n            items = scenario[1].items()\n            argnames = [x[0] for x in items]\n            argvalues.append([x[1] for x in items])\n        metafunc.parametrize(argnames, argvalues, ids=idlist, scope=\"class\")\n\n\n    scenario1 = (\"basic\", {\"attribute\": \"value\"})\n    scenario2 = (\"advanced\", {\"attribute\": \"value2\"})\n\n\n    class TestSampleWithScenarios:\n        scenarios = [scenario1, scenario2]\n\n        def test_demo1(self, attribute):\n            assert isinstance(attribute, str)\n\n        def test_demo2(self, attribute):\n            assert isinstance(attribute, str)\n\nthis is a fully self-contained example which you can run with:\n\n.. code-block:: pytest\n\n    $ pytest test_scenarios.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 4 items\n\n    test_scenarios.py ....                                               [100%]\n\n    ============================ 4 passed in 0.12s =============================\n\nIf you just collect tests you'll also nicely see 'advanced' and 'basic' as variants for the test function:\n\n.. code-block:: pytest\n\n    $ pytest --collect-only test_scenarios.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 4 items\n\n    <Dir parametrize.rst-212>\n      <Module test_scenarios.py>\n        <Class TestSampleWithScenarios>\n          <Function test_demo1[basic]>\n          <Function test_demo2[basic]>\n          <Function test_demo1[advanced]>\n          <Function test_demo2[advanced]>\n\n    ======================== 4 tests collected in 0.12s ========================\n\nNote that we told ``metafunc.parametrize()`` that your scenario values\nshould be considered class-scoped.  With pytest-2.3 this leads to a\nresource-based ordering.\n\nDeferring the setup of parametrized resources\n---------------------------------------------------\n\n.. regendoc:wipe\n\nThe parametrization of test functions happens at collection\ntime.  It is a good idea to setup expensive resources like DB\nconnections or subprocess only when the actual test is run.\nHere is a simple example how you can achieve that. This test\nrequires a ``db`` object fixture:\n\n.. code-block:: python\n\n    # content of test_backends.py\n\n    import pytest\n\n\n    def test_db_initialized(db):\n        # a dummy test\n        if db.__class__.__name__ == \"DB2\":\n            pytest.fail(\"deliberately failing for demo purposes\")\n\nWe can now add a test configuration that generates two invocations of\nthe ``test_db_initialized`` function and also implements a factory that\ncreates a database object for the actual test invocations:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import pytest\n\n\n    def pytest_generate_tests(metafunc):\n        if \"db\" in metafunc.fixturenames:\n            metafunc.parametrize(\"db\", [\"d1\", \"d2\"], indirect=True)\n\n\n    class DB1:\n        \"one database object\"\n\n\n    class DB2:\n        \"alternative database object\"\n\n\n    @pytest.fixture\n    def db(request):\n        if request.param == \"d1\":\n            return DB1()\n        elif request.param == \"d2\":\n            return DB2()\n        else:\n            raise ValueError(\"invalid internal test config\")\n\nLet's first see how it looks like at collection time:\n\n.. code-block:: pytest\n\n    $ pytest test_backends.py --collect-only\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 2 items\n\n    <Dir parametrize.rst-212>\n      <Module test_backends.py>\n        <Function test_db_initialized[d1]>\n        <Function test_db_initialized[d2]>\n\n    ======================== 2 tests collected in 0.12s ========================\n\nAnd then when we run the test:\n\n.. code-block:: pytest\n\n    $ pytest -q test_backends.py\n    .F                                                                   [100%]\n    ================================= FAILURES =================================\n    _________________________ test_db_initialized[d2] __________________________\n\n    db = <conftest.DB2 object at 0xdeadbeef0001>\n\n        def test_db_initialized(db):\n            # a dummy test\n            if db.__class__.__name__ == \"DB2\":\n    >           pytest.fail(\"deliberately failing for demo purposes\")\n    E           Failed: deliberately failing for demo purposes\n\n    test_backends.py:8: Failed\n    ========================= short test summary info ==========================\n    FAILED test_backends.py::test_db_initialized[d2] - Failed: deliberately f...\n    1 failed, 1 passed in 0.12s\n\nThe first invocation with ``db == \"DB1\"`` passed while the second with ``db == \"DB2\"`` failed.  Our ``db`` fixture function has instantiated each of the DB values during the setup phase while the ``pytest_generate_tests`` generated two according calls to the ``test_db_initialized`` during the collection phase.\n\nIndirect parametrization\n---------------------------------------------------\n\nUsing the ``indirect=True`` parameter when parametrizing a test allows one to\nparametrize a test with a fixture receiving the values before passing them to a\ntest:\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.fixture\n    def fixt(request):\n        return request.param * 3\n\n\n    @pytest.mark.parametrize(\"fixt\", [\"a\", \"b\"], indirect=True)\n    def test_indirect(fixt):\n        assert len(fixt) == 3\n\nThis can be used, for example, to do more expensive setup at test run time in\nthe fixture, rather than having to run those setup steps at collection time.\n\n.. regendoc:wipe\n\nApply indirect on particular arguments\n---------------------------------------------------\n\nVery often parametrization uses more than one argument name. There is opportunity to apply ``indirect``\nparameter on particular arguments. It can be done by passing list or tuple of\narguments' names to ``indirect``. In the example below there is a function ``test_indirect`` which uses\ntwo fixtures: ``x`` and ``y``. Here we give to indirect the list, which contains the name of the\nfixture ``x``. The indirect parameter will be applied to this argument only, and the value ``a``\nwill be passed to respective fixture function:\n\n.. code-block:: python\n\n    # content of test_indirect_list.py\n\n    import pytest\n\n\n    @pytest.fixture(scope=\"function\")\n    def x(request):\n        return request.param * 3\n\n\n    @pytest.fixture(scope=\"function\")\n    def y(request):\n        return request.param * 2\n\n\n    @pytest.mark.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\"])\n    def test_indirect(x, y):\n        assert x == \"aaa\"\n        assert y == \"b\"\n\nThe result of this test will be successful:\n\n.. code-block:: pytest\n\n    $ pytest -v test_indirect_list.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 1 item\n\n    test_indirect_list.py::test_indirect[a-b] PASSED                     [100%]\n\n    ============================ 1 passed in 0.12s =============================\n\n.. regendoc:wipe\n\nParametrizing test methods through per-class configuration\n--------------------------------------------------------------\n\n.. _`unittest parametrizer`: https://github.com/testing-cabal/unittest-ext/blob/master/params.py\n\n\nHere is an example ``pytest_generate_tests`` function implementing a\nparametrization scheme similar to Michael Foord's `unittest\nparametrizer`_ but in a lot less code:\n\n.. code-block:: python\n\n    # content of ./test_parametrize.py\n    import pytest\n\n\n    def pytest_generate_tests(metafunc):\n        # called once per each test function\n        funcarglist = metafunc.cls.params[metafunc.function.__name__]\n        argnames = sorted(funcarglist[0])\n        metafunc.parametrize(\n            argnames, [[funcargs[name] for name in argnames] for funcargs in funcarglist]\n        )\n\n\n    class TestClass:\n        # a map specifying multiple argument sets for a test method\n        params = {\n            \"test_equals\": [dict(a=1, b=2), dict(a=3, b=3)],\n            \"test_zerodivision\": [dict(a=1, b=0)],\n        }\n\n        def test_equals(self, a, b):\n            assert a == b\n\n        def test_zerodivision(self, a, b):\n            with pytest.raises(ZeroDivisionError):\n                a / b\n\nOur test generator looks up a class-level definition which specifies which\nargument sets to use for each test function.  Let's run it:\n\n.. code-block:: pytest\n\n    $ pytest -q\n    F..                                                                  [100%]\n    ================================= FAILURES =================================\n    ________________________ TestClass.test_equals[1-2] ________________________\n\n    self = <test_parametrize.TestClass object at 0xdeadbeef0002>, a = 1, b = 2\n\n        def test_equals(self, a, b):\n    >       assert a == b\n    E       assert 1 == 2\n\n    test_parametrize.py:21: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_parametrize.py::TestClass::test_equals[1-2] - assert 1 == 2\n    1 failed, 2 passed in 0.12s\n\nParametrization with multiple fixtures\n--------------------------------------\n\nHere is a stripped down real-life example of using parametrized\ntesting for testing serialization of objects between different python\ninterpreters.  We define a ``test_basic_objects`` function which\nis to be run with different sets of arguments for its three arguments:\n\n* ``python1``: first python interpreter, run to pickle-dump an object to a file\n* ``python2``: second interpreter, run to pickle-load an object from a file\n* ``obj``: object to be dumped/loaded\n\n.. literalinclude:: multipython.py\n\nRunning it results in some skips if we don't have all the python interpreters installed and otherwise runs all combinations (3 interpreters times 3 interpreters times 3 objects to serialize/deserialize):\n\n.. code-block:: pytest\n\n   . $ pytest -rs -q multipython.py\n   ssssssssssss......sss......                                          [100%]\n   ========================= short test summary info ==========================\n   SKIPPED [15] multipython.py:67: 'python3.11' not found\n   12 passed, 15 skipped in 0.12s\n\nParametrization of optional implementations/imports\n---------------------------------------------------\n\nIf you want to compare the outcomes of several implementations of a given\nAPI, you can write test functions that receive the already imported implementations\nand get skipped in case the implementation is not importable/available.  Let's\nsay we have a \"base\" implementation and the other (possibly optimized ones)\nneed to provide similar results:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n    import pytest\n\n\n    @pytest.fixture(scope=\"session\")\n    def basemod(request):\n        return pytest.importorskip(\"base\")\n\n\n    @pytest.fixture(scope=\"session\", params=[\"opt1\", \"opt2\"])\n    def optmod(request):\n        return pytest.importorskip(request.param)\n\nAnd then a base implementation of a simple function:\n\n.. code-block:: python\n\n    # content of base.py\n    def func1():\n        return 1\n\nAnd an optimized version:\n\n.. code-block:: python\n\n    # content of opt1.py\n    def func1():\n        return 1.0001\n\nAnd finally a little test module:\n\n.. code-block:: python\n\n    # content of test_module.py\n\n\n    def test_func1(basemod, optmod):\n        assert round(basemod.func1(), 3) == round(optmod.func1(), 3)\n\n\nIf you run this with reporting for skips enabled:\n\n.. code-block:: pytest\n\n    $ pytest -rs test_module.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 2 items\n\n    test_module.py .s                                                    [100%]\n\n    ========================= short test summary info ==========================\n    SKIPPED [1] test_module.py:3: could not import 'opt2': No module named 'opt2'\n    ======================= 1 passed, 1 skipped in 0.12s =======================\n\nYou'll see that we don't have an ``opt2`` module and thus the second test run\nof our ``test_func1`` was skipped.  A few notes:\n\n- the fixture functions in the ``conftest.py`` file are \"session-scoped\" because we\n  don't need to import more than once\n\n- if you have multiple test functions and a skipped import, you will see\n  the ``[1]`` count increasing in the report\n\n- you can put :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>` style\n  parametrization on the test functions to parametrize input/output\n  values as well.\n\n\nSet marks or test ID for individual parametrized test\n--------------------------------------------------------------------\n\nUse ``pytest.param`` to apply marks or set test ID to individual parametrized test.\nFor example:\n\n.. code-block:: python\n\n    # content of test_pytest_param_example.py\n    import pytest\n\n\n    @pytest.mark.parametrize(\n        \"test_input,expected\",\n        [\n            (\"3+5\", 8),\n            pytest.param(\"1+7\", 8, marks=pytest.mark.basic),\n            pytest.param(\"2+4\", 6, marks=pytest.mark.basic, id=\"basic_2+4\"),\n            pytest.param(\n                \"6*9\", 42, marks=[pytest.mark.basic, pytest.mark.xfail], id=\"basic_6*9\"\n            ),\n        ],\n    )\n    def test_eval(test_input, expected):\n        assert eval(test_input) == expected\n\nIn this example, we have 4 parametrized tests. Except for the first test,\nwe mark the rest three parametrized tests with the custom marker ``basic``,\nand for the fourth test we also use the built-in mark ``xfail`` to indicate this\ntest is expected to fail. For explicitness, we set test ids for some tests.\n\nThen run ``pytest`` with verbose mode and with only the ``basic`` marker:\n\n.. code-block:: pytest\n\n    $ pytest -v -m basic\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 24 items / 21 deselected / 3 selected\n\n    test_pytest_param_example.py::test_eval[1+7-8] PASSED                [ 33%]\n    test_pytest_param_example.py::test_eval[basic_2+4] PASSED            [ 66%]\n    test_pytest_param_example.py::test_eval[basic_6*9] XFAIL             [100%]\n\n    =============== 2 passed, 21 deselected, 1 xfailed in 0.12s ================\n\nAs the result:\n\n- Four tests were collected\n- One test was deselected because it doesn't have the ``basic`` mark.\n- Three tests with the ``basic`` mark were selected.\n- The test ``test_eval[1+7-8]`` passed, but the name is autogenerated and confusing.\n- The test ``test_eval[basic_2+4]`` passed.\n- The test ``test_eval[basic_6*9]`` was expected to fail and did fail.\n\n.. _`parametrizing_conditional_raising`:\n\nParametrizing conditional raising\n--------------------------------------------------------------------\n\nUse :func:`pytest.raises` with the\n:ref:`pytest.mark.parametrize ref` decorator to write parametrized tests\nin which some tests raise exceptions and others do not.\n\n``contextlib.nullcontext`` can be used to test cases that are not expected to\nraise exceptions but that should result in some value. The value is given as the\n``enter_result`` parameter, which will be available as the ``with`` statement’s\ntarget (``e`` in the example below).\n\nFor example:\n\n.. code-block:: python\n\n    from contextlib import nullcontext\n\n    import pytest\n\n\n    @pytest.mark.parametrize(\n        \"example_input,expectation\",\n        [\n            (3, nullcontext(2)),\n            (2, nullcontext(3)),\n            (1, nullcontext(6)),\n            (0, pytest.raises(ZeroDivisionError)),\n        ],\n    )\n    def test_division(example_input, expectation):\n        \"\"\"Test how much I know division.\"\"\"\n        with expectation as e:\n            assert (6 / example_input) == e\n\nIn the example above, the first three test cases should run without any\nexceptions, while the fourth should raise a ``ZeroDivisionError`` exception,\nwhich is expected by pytest.\n"
  },
  {
    "path": "doc/en/example/pythoncollection.py",
    "content": "# run this with $ pytest --collect-only test_collectonly.py\n#\nfrom __future__ import annotations\n\n\ndef test_function():\n    pass\n\n\nclass TestClass:\n    def test_method(self):\n        pass\n\n    def test_anothermethod(self):\n        pass\n"
  },
  {
    "path": "doc/en/example/pythoncollection.rst",
    "content": "Changing standard (Python) test discovery\n===============================================\n\nIgnore paths during test collection\n-----------------------------------\n\nYou can easily ignore certain test directories and modules during collection\nby passing the :option:`--ignore=path` option on the cli. ``pytest`` allows multiple\n``--ignore`` options. Example:\n\n.. code-block:: text\n\n    tests/\n    |-- example\n    |   |-- test_example_01.py\n    |   |-- test_example_02.py\n    |   '-- test_example_03.py\n    |-- foobar\n    |   |-- test_foobar_01.py\n    |   |-- test_foobar_02.py\n    |   '-- test_foobar_03.py\n    '-- hello\n        '-- world\n            |-- test_world_01.py\n            |-- test_world_02.py\n            '-- test_world_03.py\n\nNow if you invoke ``pytest`` with ``--ignore=tests/foobar/test_foobar_03.py --ignore=tests/hello/``,\nyou will see that ``pytest`` only collects test-modules, which do not match the patterns specified:\n\n.. code-block:: pytest\n\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y\n    rootdir: $REGENDOC_TMPDIR, inifile:\n    collected 5 items\n\n    tests/example/test_example_01.py .                                   [ 20%]\n    tests/example/test_example_02.py .                                   [ 40%]\n    tests/example/test_example_03.py .                                   [ 60%]\n    tests/foobar/test_foobar_01.py .                                     [ 80%]\n    tests/foobar/test_foobar_02.py .                                     [100%]\n\n    ========================= 5 passed in 0.02 seconds =========================\n\nThe :option:`--ignore-glob` option allows to ignore test file paths based on Unix shell-style wildcards.\nIf you want to exclude test-modules that end with ``_01.py``, execute ``pytest`` with :option:`--ignore-glob='*_01.py'`.\n\nDeselect tests during test collection\n-------------------------------------\n\nTests can individually be deselected during collection by passing the :option:`--deselect=item` option.\nFor example, say ``tests/foobar/test_foobar_01.py`` contains ``test_a`` and ``test_b``.\nYou can run all of the tests within ``tests/`` *except* for ``tests/foobar/test_foobar_01.py::test_a``\nby invoking ``pytest`` with ``--deselect=tests/foobar/test_foobar_01.py::test_a``.\n``pytest`` allows multiple ``--deselect`` options.\n\n.. _duplicate-paths:\n\nKeeping duplicate paths specified from command line\n----------------------------------------------------\n\nDefault behavior of ``pytest`` is to ignore duplicate paths specified from the command line.\nExample:\n\n.. code-block:: pytest\n\n    pytest path_a path_a\n\n    ...\n    collected 1 item\n    ...\n\nJust collect tests once.\n\nTo collect duplicate tests, use the :option:`--keep-duplicates` option on the cli.\nExample:\n\n.. code-block:: pytest\n\n    pytest --keep-duplicates path_a path_a\n\n    ...\n    collected 2 items\n    ...\n\n\nChanging directory recursion\n-----------------------------------------------------\n\nYou can set the :confval:`norecursedirs` option in a configuration file:\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    [pytest]\n    norecursedirs = [\".svn\", \"_build\", \"tmp*\"]\n\nThis would tell ``pytest`` to not recurse into typical subversion or sphinx-build directories or into any ``tmp`` prefixed directory.\n\n.. _`change naming conventions`:\n\nChanging naming conventions\n-----------------------------------------------------\n\nYou can configure different naming conventions by setting\nthe :confval:`python_files`, :confval:`python_classes` and\n:confval:`python_functions` in your :ref:`configuration file <config file formats>`.\nHere is an example:\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    # Example 1: have pytest look for \"check\" instead of \"test\"\n    [pytest]\n    python_files = [\"check_*.py\"]\n    python_classes = [\"Check\"]\n    python_functions = [\"*_check\"]\n\nThis would make ``pytest`` look for tests in files that match the ``check_*\n.py`` glob-pattern, ``Check`` prefixes in classes, and functions and methods\nthat match ``*_check``. For example, if we have:\n\n.. code-block:: python\n\n    # content of check_myapp.py\n    class CheckMyApp:\n        def simple_check(self):\n            pass\n\n        def complex_check(self):\n            pass\n\nThe test collection would look like this:\n\n.. code-block:: pytest\n\n    $ pytest --collect-only\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    configfile: pytest.toml\n    collected 2 items\n\n    <Dir pythoncollection.rst-213>\n      <Module check_myapp.py>\n        <Class CheckMyApp>\n          <Function simple_check>\n          <Function complex_check>\n\n    ======================== 2 tests collected in 0.12s ========================\n\nYou can check for multiple glob patterns by adding a space between the patterns:\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    # Example 2: have pytest look for files with \"test\" and \"example\"\n    [pytest]\n    python_files = [\"test_*.py\", \"example_*.py\"]\n\n.. note::\n\n   the ``python_functions`` and ``python_classes`` options have no effect\n   for ``unittest.TestCase`` test discovery because pytest delegates\n   discovery of test case methods to unittest code.\n\nInterpreting cmdline arguments as Python packages\n-----------------------------------------------------\n\nYou can use the :option:`--pyargs` option to make ``pytest`` try\ninterpreting arguments as python package names, deriving\ntheir file system path and then running the test. For\nexample if you have unittest2 installed you can type:\n\n.. code-block:: bash\n\n    pytest --pyargs unittest2.test.test_skipping -q\n\nwhich would run the respective test module.  Like with\nother options, through a configuration file and the :confval:`addopts` option you\ncan make this change more permanently:\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    [pytest]\n    addopts = [\"--pyargs\"]\n\nNow a simple invocation of ``pytest NAME`` will check\nif NAME exists as an importable package/module and otherwise\ntreat it as a filesystem path.\n\nFinding out what is collected\n-----------------------------------------------\n\nYou can always peek at the collection tree without running tests like this:\n\n.. code-block:: pytest\n\n    . $ pytest --collect-only pythoncollection.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    configfile: pytest.toml\n    collected 3 items\n\n    <Dir pythoncollection.rst-213>\n      <Dir CWD>\n        <Module pythoncollection.py>\n          <Function test_function>\n          <Class TestClass>\n            <Function test_method>\n            <Function test_anothermethod>\n\n    ======================== 3 tests collected in 0.12s ========================\n\n.. _customizing-test-collection:\n\nCustomizing test collection\n---------------------------\n\n.. regendoc:wipe\n\nYou can easily instruct ``pytest`` to discover tests from every Python file:\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    [pytest]\n    python_files = [\"*.py\"]\n\nHowever, many projects will have a ``setup.py`` which they don't want to be\nimported. Moreover, there may be files only importable by a specific python\nversion. For such cases you can dynamically define files to be ignored by\nlisting them in a ``conftest.py`` file:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import sys\n\n    collect_ignore = [\"setup.py\"]\n    if sys.version_info[0] > 2:\n        collect_ignore.append(\"pkg/module_py2.py\")\n\nand then if you have a module file like this:\n\n.. code-block:: python\n\n    # content of pkg/module_py2.py\n    def test_only_on_python2():\n        try:\n            assert 0\n        except Exception, e:\n            pass\n\nand a ``setup.py`` dummy file like this:\n\n.. code-block:: python\n\n    # content of setup.py\n    0 / 0  # will raise exception if imported\n\nIf you run with a Python 2 interpreter then you will find the one test and will\nleave out the ``setup.py`` file:\n\n.. code-block:: pytest\n\n    #$ pytest --collect-only\n    ====== test session starts ======\n    platform linux2 -- Python 2.7.10, pytest-2.9.1, py-1.4.31, pluggy-0.3.1\n    rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini\n    collected 1 items\n    <Module 'pkg/module_py2.py'>\n      <Function 'test_only_on_python2'>\n\n    ====== 1 tests found in 0.04 seconds ======\n\nIf you run with a Python 3 interpreter both the one test and the ``setup.py``\nfile will be left out:\n\n.. code-block:: pytest\n\n    $ pytest --collect-only\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    configfile: pytest.toml\n    collected 0 items\n\n    ======================= no tests collected in 0.12s ========================\n\nIt's also possible to ignore files based on Unix shell-style wildcards by adding\npatterns to :globalvar:`collect_ignore_glob`.\n\nThe following example ``conftest.py`` ignores the file ``setup.py`` and in\naddition all files that end with ``*_py2.py`` when executed with a Python 3\ninterpreter:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import sys\n\n    collect_ignore = [\"setup.py\"]\n    if sys.version_info[0] > 2:\n        collect_ignore_glob = [\"*_py2.py\"]\n\nSince Pytest 2.6, users can prevent pytest from discovering classes that start\nwith ``Test`` by setting a boolean ``__test__`` attribute to ``False``.\n\n.. code-block:: python\n\n    # Will not be discovered as a test\n    class TestClass:\n        __test__ = False\n\n.. note::\n\n   If you are working with abstract test classes and want to avoid manually setting\n   the ``__test__`` attribute for subclasses, you can use a mixin class to handle\n   this automatically. For example:\n\n   .. code-block:: python\n\n       # Mixin to handle abstract test classes\n       class NotATest:\n           def __init_subclass__(cls):\n               cls.__test__ = NotATest not in cls.__bases__\n\n\n       # Abstract test class\n       class AbstractTest(NotATest):\n           pass\n\n\n       # Subclass that will be collected as a test\n       class RealTest(AbstractTest):\n           def test_example(self):\n               assert 1 + 1 == 2\n\n   This approach ensures that subclasses of abstract test classes are automatically\n   collected without needing to explicitly set the ``__test__`` attribute.\n"
  },
  {
    "path": "doc/en/example/reportingdemo.rst",
    "content": ".. _`tbreportdemo`:\n\nDemo of Python failure reports with pytest\n==========================================\n\nHere is a nice run of several failures and how ``pytest`` presents things:\n\n.. code-block:: pytest\n\n    assertion $ pytest failure_demo.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project/assertion\n    collected 44 items\n\n    failure_demo.py FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF         [100%]\n\n    ================================= FAILURES =================================\n    ___________________________ test_generative[3-6] ___________________________\n\n    param1 = 3, param2 = 6\n\n        @pytest.mark.parametrize(\"param1, param2\", [(3, 6)])\n        def test_generative(param1, param2):\n    >       assert param1 * 2 < param2\n    E       assert (3 * 2) < 6\n\n    failure_demo.py:21: AssertionError\n    _________________________ TestFailing.test_simple __________________________\n\n    self = <failure_demo.TestFailing object at 0xdeadbeef0001>\n\n        def test_simple(self):\n            def f():\n                return 42\n\n            def g():\n                return 43\n\n    >       assert f() == g()\n    E       assert 42 == 43\n    E        +  where 42 = <function TestFailing.test_simple.<locals>.f at 0xdeadbeef0002>()\n    E        +  and   43 = <function TestFailing.test_simple.<locals>.g at 0xdeadbeef0003>()\n\n    failure_demo.py:32: AssertionError\n    ____________________ TestFailing.test_simple_multiline _____________________\n\n    self = <failure_demo.TestFailing object at 0xdeadbeef0004>\n\n        def test_simple_multiline(self):\n    >       otherfunc_multi(42, 6 * 9)\n\n    failure_demo.py:35:\n    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\n    a = 42, b = 54\n\n        def otherfunc_multi(a, b):\n    >       assert a == b\n    E       assert 42 == 54\n\n    failure_demo.py:16: AssertionError\n    ___________________________ TestFailing.test_not ___________________________\n\n    self = <failure_demo.TestFailing object at 0xdeadbeef0005>\n\n        def test_not(self):\n            def f():\n                return 42\n\n    >       assert not f()\n    E       assert not 42\n    E        +  where 42 = <function TestFailing.test_not.<locals>.f at 0xdeadbeef0006>()\n\n    failure_demo.py:41: AssertionError\n    _________________ TestSpecialisedExplanations.test_eq_text _________________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0007>\n\n        def test_eq_text(self):\n    >       assert \"spam\" == \"eggs\"\n    E       AssertionError: assert 'spam' == 'eggs'\n    E\n    E         - eggs\n    E         + spam\n\n    failure_demo.py:46: AssertionError\n    _____________ TestSpecialisedExplanations.test_eq_similar_text _____________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0008>\n\n        def test_eq_similar_text(self):\n    >       assert \"foo 1 bar\" == \"foo 2 bar\"\n    E       AssertionError: assert 'foo 1 bar' == 'foo 2 bar'\n    E\n    E         - foo 2 bar\n    E         ?     ^\n    E         + foo 1 bar\n    E         ?     ^\n\n    failure_demo.py:49: AssertionError\n    ____________ TestSpecialisedExplanations.test_eq_multiline_text ____________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0009>\n\n        def test_eq_multiline_text(self):\n    >       assert \"foo\\nspam\\nbar\" == \"foo\\neggs\\nbar\"\n    E       AssertionError: assert 'foo\\nspam\\nbar' == 'foo\\neggs\\nbar'\n    E\n    E           foo\n    E         - eggs\n    E         + spam\n    E           bar\n\n    failure_demo.py:52: AssertionError\n    ______________ TestSpecialisedExplanations.test_eq_long_text _______________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000a>\n\n        def test_eq_long_text(self):\n            a = \"1\" * 100 + \"a\" + \"2\" * 100\n            b = \"1\" * 100 + \"b\" + \"2\" * 100\n    >       assert a == b\n    E       AssertionError: assert '111111111111...2222222222222' == '111111111111...2222222222222'\n    E\n    E         Skipping 90 identical leading characters in diff, use -v to show\n    E         Skipping 91 identical trailing characters in diff, use -v to show\n    E         - 1111111111b222222222\n    E         ?           ^\n    E         + 1111111111a222222222\n    E         ?           ^\n\n    failure_demo.py:57: AssertionError\n    _________ TestSpecialisedExplanations.test_eq_long_text_multiline __________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000b>\n\n        def test_eq_long_text_multiline(self):\n            a = \"1\\n\" * 100 + \"a\" + \"2\\n\" * 100\n            b = \"1\\n\" * 100 + \"b\" + \"2\\n\" * 100\n    >       assert a == b\n    E       AssertionError: assert '1\\n1\\n1\\n1\\n...n2\\n2\\n2\\n2\\n' == '1\\n1\\n1\\n1\\n...n2\\n2\\n2\\n2\\n'\n    E\n    E         Skipping 190 identical leading characters in diff, use -v to show\n    E         Skipping 191 identical trailing characters in diff, use -v to show\n    E           1\n    E           1\n    E           1\n    E           1...\n    E\n    E         ...Full output truncated (7 lines hidden), use '-vv' to show\n\n    failure_demo.py:62: AssertionError\n    _________________ TestSpecialisedExplanations.test_eq_list _________________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000c>\n\n        def test_eq_list(self):\n    >       assert [0, 1, 2] == [0, 1, 3]\n    E       assert [0, 1, 2] == [0, 1, 3]\n    E\n    E         At index 2 diff: 2 != 3\n    E         Use -v to get more diff\n\n    failure_demo.py:65: AssertionError\n    ______________ TestSpecialisedExplanations.test_eq_list_long _______________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000d>\n\n        def test_eq_list_long(self):\n            a = [0] * 100 + [1] + [3] * 100\n            b = [0] * 100 + [2] + [3] * 100\n    >       assert a == b\n    E       assert [0, 0, 0, 0, 0, 0, ...] == [0, 0, 0, 0, 0, 0, ...]\n    E\n    E         At index 100 diff: 1 != 2\n    E         Use -v to get more diff\n\n    failure_demo.py:70: AssertionError\n    _________________ TestSpecialisedExplanations.test_eq_dict _________________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000e>\n\n        def test_eq_dict(self):\n    >       assert {\"a\": 0, \"b\": 1, \"c\": 0} == {\"a\": 0, \"b\": 2, \"d\": 0}\n    E       AssertionError: assert {'a': 0, 'b': 1, 'c': 0} == {'a': 0, 'b': 2, 'd': 0}\n    E\n    E         Omitting 1 identical items, use -vv to show\n    E         Differing items:\n    E         {'b': 1} != {'b': 2}\n    E         Left contains 1 more item:\n    E         {'c': 0}\n    E         Right contains 1 more item:\n    E         {'d': 0}\n    E         Use -v to get more diff\n\n    failure_demo.py:73: AssertionError\n    _________________ TestSpecialisedExplanations.test_eq_set __________________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef000f>\n\n        def test_eq_set(self):\n    >       assert {0, 10, 11, 12} == {0, 20, 21}\n    E       assert {0, 10, 11, 12} == {0, 20, 21}\n    E\n    E         Extra items in the left set:\n    E         10\n    E         11\n    E         12\n    E         Extra items in the right set:\n    E         20\n    E         21\n    E         Use -v to get more diff\n\n    failure_demo.py:76: AssertionError\n    _____________ TestSpecialisedExplanations.test_eq_longer_list ______________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0010>\n\n        def test_eq_longer_list(self):\n    >       assert [1, 2] == [1, 2, 3]\n    E       assert [1, 2] == [1, 2, 3]\n    E\n    E         Right contains one more item: 3\n    E         Use -v to get more diff\n\n    failure_demo.py:79: AssertionError\n    _________________ TestSpecialisedExplanations.test_in_list _________________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0011>\n\n        def test_in_list(self):\n    >       assert 1 in [0, 2, 3, 4, 5]\n    E       assert 1 in [0, 2, 3, 4, 5]\n\n    failure_demo.py:82: AssertionError\n    __________ TestSpecialisedExplanations.test_not_in_text_multiline __________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0012>\n\n        def test_not_in_text_multiline(self):\n            text = \"some multiline\\ntext\\nwhich\\nincludes foo\\nand a\\ntail\"\n    >       assert \"foo\" not in text\n    E       AssertionError: assert 'foo' not in 'some multil...nand a\\ntail'\n    E\n    E         'foo' is contained here:\n    E           some multiline\n    E           text\n    E           which\n    E           includes foo\n    E         ?          +++\n    E           and a\n    E           tail\n\n    failure_demo.py:86: AssertionError\n    ___________ TestSpecialisedExplanations.test_not_in_text_single ____________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0013>\n\n        def test_not_in_text_single(self):\n            text = \"single foo line\"\n    >       assert \"foo\" not in text\n    E       AssertionError: assert 'foo' not in 'single foo line'\n    E\n    E         'foo' is contained here:\n    E           single foo line\n    E         ?        +++\n\n    failure_demo.py:90: AssertionError\n    _________ TestSpecialisedExplanations.test_not_in_text_single_long _________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0014>\n\n        def test_not_in_text_single_long(self):\n            text = \"head \" * 50 + \"foo \" + \"tail \" * 20\n    >       assert \"foo\" not in text\n    E       AssertionError: assert 'foo' not in 'head head h...l tail tail '\n    E\n    E         'foo' is contained here:\n    E           head head foo tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail\n    E         ?           +++\n\n    failure_demo.py:94: AssertionError\n    ______ TestSpecialisedExplanations.test_not_in_text_single_long_term _______\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0015>\n\n        def test_not_in_text_single_long_term(self):\n            text = \"head \" * 50 + \"f\" * 70 + \"tail \" * 20\n    >       assert \"f\" * 70 not in text\n    E       AssertionError: assert 'fffffffffff...ffffffffffff' not in 'head head h...l tail tail '\n    E\n    E         'ffffffffffffffffff...fffffffffffffffffff' is contained here:\n    E           head head fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffftail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail\n    E         ?           ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n    failure_demo.py:98: AssertionError\n    ______________ TestSpecialisedExplanations.test_eq_dataclass _______________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0016>\n\n        def test_eq_dataclass(self):\n            from dataclasses import dataclass\n\n            @dataclass\n            class Foo:\n                a: int\n                b: str\n\n            left = Foo(1, \"b\")\n            right = Foo(1, \"c\")\n    >       assert left == right\n    E       AssertionError: assert TestSpecialis...oo(a=1, b='b') == TestSpecialis...oo(a=1, b='c')\n    E\n    E         Omitting 1 identical items, use -vv to show\n    E         Differing attributes:\n    E         ['b']\n    E\n    E         Drill down into differing attribute b:\n    E           b: 'b' != 'c'\n    E           - c\n    E           + b\n\n    failure_demo.py:110: AssertionError\n    ________________ TestSpecialisedExplanations.test_eq_attrs _________________\n\n    self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef0017>\n\n        def test_eq_attrs(self):\n            import attr\n\n            @attr.s\n            class Foo:\n                a = attr.ib()\n                b = attr.ib()\n\n            left = Foo(1, \"b\")\n            right = Foo(1, \"c\")\n    >       assert left == right\n    E       AssertionError: assert Foo(a=1, b='b') == Foo(a=1, b='c')\n    E\n    E         Omitting 1 identical items, use -vv to show\n    E         Differing attributes:\n    E         ['b']\n    E\n    E         Drill down into differing attribute b:\n    E           b: 'b' != 'c'\n    E           - c\n    E           + b\n\n    failure_demo.py:122: AssertionError\n    ______________________________ test_attribute ______________________________\n\n        def test_attribute():\n            class Foo:\n                b = 1\n\n            i = Foo()\n    >       assert i.b == 2\n    E       assert 1 == 2\n    E        +  where 1 = <failure_demo.test_attribute.<locals>.Foo object at 0xdeadbeef0018>.b\n\n    failure_demo.py:130: AssertionError\n    _________________________ test_attribute_instance __________________________\n\n        def test_attribute_instance():\n            class Foo:\n                b = 1\n\n    >       assert Foo().b == 2\n    E       AssertionError: assert 1 == 2\n    E        +  where 1 = <failure_demo.test_attribute_instance.<locals>.Foo object at 0xdeadbeef0019>.b\n    E        +    where <failure_demo.test_attribute_instance.<locals>.Foo object at 0xdeadbeef0019> = <class 'failure_demo.test_attribute_instance.<locals>.Foo'>()\n\n    failure_demo.py:137: AssertionError\n    __________________________ test_attribute_failure __________________________\n\n        def test_attribute_failure():\n            class Foo:\n                def _get_b(self):\n                    raise Exception(\"Failed to get attrib\")\n\n                b = property(_get_b)\n\n            i = Foo()\n    >       assert i.b == 2\n                   ^^^\n\n    failure_demo.py:148:\n    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\n    self = <failure_demo.test_attribute_failure.<locals>.Foo object at 0xdeadbeef001a>\n\n        def _get_b(self):\n    >       raise Exception(\"Failed to get attrib\")\n    E       Exception: Failed to get attrib\n\n    failure_demo.py:143: Exception\n    _________________________ test_attribute_multiple __________________________\n\n        def test_attribute_multiple():\n            class Foo:\n                b = 1\n\n            class Bar:\n                b = 2\n\n    >       assert Foo().b == Bar().b\n    E       AssertionError: assert 1 == 2\n    E        +  where 1 = <failure_demo.test_attribute_multiple.<locals>.Foo object at 0xdeadbeef001b>.b\n    E        +    where <failure_demo.test_attribute_multiple.<locals>.Foo object at 0xdeadbeef001b> = <class 'failure_demo.test_attribute_multiple.<locals>.Foo'>()\n    E        +  and   2 = <failure_demo.test_attribute_multiple.<locals>.Bar object at 0xdeadbeef001c>.b\n    E        +    where <failure_demo.test_attribute_multiple.<locals>.Bar object at 0xdeadbeef001c> = <class 'failure_demo.test_attribute_multiple.<locals>.Bar'>()\n\n    failure_demo.py:158: AssertionError\n    __________________________ TestRaises.test_raises __________________________\n\n    self = <failure_demo.TestRaises object at 0xdeadbeef001d>\n\n        def test_raises(self):\n            s = \"qwe\"\n    >       raises(TypeError, int, s)\n    E       ValueError: invalid literal for int() with base 10: 'qwe'\n\n    failure_demo.py:168: ValueError\n    ______________________ TestRaises.test_raises_doesnt _______________________\n\n    self = <failure_demo.TestRaises object at 0xdeadbeef001e>\n\n        def test_raises_doesnt(self):\n    >       raises(OSError, int, \"3\")\n    E       Failed: DID NOT RAISE <class 'OSError'>\n\n    failure_demo.py:171: Failed\n    __________________________ TestRaises.test_raise ___________________________\n\n    self = <failure_demo.TestRaises object at 0xdeadbeef001f>\n\n        def test_raise(self):\n    >       raise ValueError(\"demo error\")\n    E       ValueError: demo error\n\n    failure_demo.py:174: ValueError\n    ________________________ TestRaises.test_tupleerror ________________________\n\n    self = <failure_demo.TestRaises object at 0xdeadbeef0020>\n\n        def test_tupleerror(self):\n    >       a, b = [1]  # noqa: F841\n            ^^^^\n    E       ValueError: not enough values to unpack (expected 2, got 1)\n\n    failure_demo.py:177: ValueError\n    ______ TestRaises.test_reinterpret_fails_with_print_for_the_fun_of_it ______\n\n    self = <failure_demo.TestRaises object at 0xdeadbeef0021>\n\n        def test_reinterpret_fails_with_print_for_the_fun_of_it(self):\n            items = [1, 2, 3]\n            print(f\"items is {items!r}\")\n    >       a, b = items.pop()\n            ^^^^\n    E       TypeError: cannot unpack non-iterable int object\n\n    failure_demo.py:182: TypeError\n    --------------------------- Captured stdout call ---------------------------\n    items is [1, 2, 3]\n    ________________________ TestRaises.test_some_error ________________________\n\n    self = <failure_demo.TestRaises object at 0xdeadbeef0022>\n\n        def test_some_error(self):\n    >       if namenotexi:  # noqa: F821\n               ^^^^^^^^^^\n    E       NameError: name 'namenotexi' is not defined\n\n    failure_demo.py:185: NameError\n    ____________________ test_dynamic_compile_shows_nicely _____________________\n\n        def test_dynamic_compile_shows_nicely():\n            import importlib.util\n            import sys\n\n            src = \"def foo():\\n assert 1 == 0\\n\"\n            name = \"abc-123\"\n            spec = importlib.util.spec_from_loader(name, loader=None)\n            module = importlib.util.module_from_spec(spec)\n            code = compile(src, name, \"exec\")\n            exec(code, module.__dict__)\n            sys.modules[name] = module\n    >       module.foo()\n\n    failure_demo.py:204:\n    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\n    >   ???\n    E   AssertionError\n\n    abc-123:2: AssertionError\n    ____________________ TestMoreErrors.test_complex_error _____________________\n\n    self = <failure_demo.TestMoreErrors object at 0xdeadbeef0023>\n\n        def test_complex_error(self):\n            def f():\n                return 44\n\n            def g():\n                return 43\n\n    >       somefunc(f(), g())\n\n    failure_demo.py:215:\n    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n    failure_demo.py:12: in somefunc\n        otherfunc(x, y)\n    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\n    a = 44, b = 43\n\n        def otherfunc(a, b):\n    >       assert a == b\n    E       assert 44 == 43\n\n    failure_demo.py:8: AssertionError\n    ___________________ TestMoreErrors.test_z1_unpack_error ____________________\n\n    self = <failure_demo.TestMoreErrors object at 0xdeadbeef0024>\n\n        def test_z1_unpack_error(self):\n            items = []\n    >       a, b = items\n            ^^^^\n    E       ValueError: not enough values to unpack (expected 2, got 0)\n\n    failure_demo.py:219: ValueError\n    ____________________ TestMoreErrors.test_z2_type_error _____________________\n\n    self = <failure_demo.TestMoreErrors object at 0xdeadbeef0025>\n\n        def test_z2_type_error(self):\n            items = 3\n    >       a, b = items\n            ^^^^\n    E       TypeError: cannot unpack non-iterable int object\n\n    failure_demo.py:223: TypeError\n    ______________________ TestMoreErrors.test_startswith ______________________\n\n    self = <failure_demo.TestMoreErrors object at 0xdeadbeef0026>\n\n        def test_startswith(self):\n            s = \"123\"\n            g = \"456\"\n    >       assert s.startswith(g)\n    E       AssertionError: assert False\n    E        +  where False = <built-in method startswith of str object at 0xdeadbeef0027>('456')\n    E        +    where <built-in method startswith of str object at 0xdeadbeef0027> = '123'.startswith\n\n    failure_demo.py:228: AssertionError\n    __________________ TestMoreErrors.test_startswith_nested ___________________\n\n    self = <failure_demo.TestMoreErrors object at 0xdeadbeef0028>\n\n        def test_startswith_nested(self):\n            def f():\n                return \"123\"\n\n            def g():\n                return \"456\"\n\n    >       assert f().startswith(g())\n    E       AssertionError: assert False\n    E        +  where False = <built-in method startswith of str object at 0xdeadbeef0027>('456')\n    E        +    where <built-in method startswith of str object at 0xdeadbeef0027> = '123'.startswith\n    E        +      where '123' = <function TestMoreErrors.test_startswith_nested.<locals>.f at 0xdeadbeef0029>()\n    E        +    and   '456' = <function TestMoreErrors.test_startswith_nested.<locals>.g at 0xdeadbeef002a>()\n\n    failure_demo.py:237: AssertionError\n    _____________________ TestMoreErrors.test_global_func ______________________\n\n    self = <failure_demo.TestMoreErrors object at 0xdeadbeef002b>\n\n        def test_global_func(self):\n    >       assert isinstance(globf(42), float)\n    E       assert False\n    E        +  where False = isinstance(43, float)\n    E        +    where 43 = globf(42)\n\n    failure_demo.py:240: AssertionError\n    _______________________ TestMoreErrors.test_instance _______________________\n\n    self = <failure_demo.TestMoreErrors object at 0xdeadbeef002c>\n\n        def test_instance(self):\n            self.x = 6 * 7\n    >       assert self.x != 42\n    E       assert 42 != 42\n    E        +  where 42 = <failure_demo.TestMoreErrors object at 0xdeadbeef002c>.x\n\n    failure_demo.py:244: AssertionError\n    _______________________ TestMoreErrors.test_compare ________________________\n\n    self = <failure_demo.TestMoreErrors object at 0xdeadbeef002d>\n\n        def test_compare(self):\n    >       assert globf(10) < 5\n    E       assert 11 < 5\n    E        +  where 11 = globf(10)\n\n    failure_demo.py:247: AssertionError\n    _____________________ TestMoreErrors.test_try_finally ______________________\n\n    self = <failure_demo.TestMoreErrors object at 0xdeadbeef002e>\n\n        def test_try_finally(self):\n            x = 1\n            try:\n    >           assert x == 0\n    E           assert 1 == 0\n\n    failure_demo.py:252: AssertionError\n    ___________________ TestCustomAssertMsg.test_single_line ___________________\n\n    self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef002f>\n\n        def test_single_line(self):\n            class A:\n                a = 1\n\n            b = 2\n    >       assert A.a == b, \"A.a appears not to be b\"\n    E       AssertionError: A.a appears not to be b\n    E       assert 1 == 2\n    E        +  where 1 = <class 'failure_demo.TestCustomAssertMsg.test_single_line.<locals>.A'>.a\n\n    failure_demo.py:263: AssertionError\n    ____________________ TestCustomAssertMsg.test_multiline ____________________\n\n    self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef0030>\n\n        def test_multiline(self):\n            class A:\n                a = 1\n\n            b = 2\n    >       assert A.a == b, (\n                \"A.a appears not to be b\\nor does not appear to be b\\none of those\"\n            )\n    E       AssertionError: A.a appears not to be b\n    E         or does not appear to be b\n    E         one of those\n    E       assert 1 == 2\n    E        +  where 1 = <class 'failure_demo.TestCustomAssertMsg.test_multiline.<locals>.A'>.a\n\n    failure_demo.py:270: AssertionError\n    ___________________ TestCustomAssertMsg.test_custom_repr ___________________\n\n    self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef0031>\n\n        def test_custom_repr(self):\n            class JSON:\n                a = 1\n\n                def __repr__(self):\n                    return \"This is JSON\\n{\\n  'foo': 'bar'\\n}\"\n\n            a = JSON()\n            b = 2\n    >       assert a.a == b, a\n    E       AssertionError: This is JSON\n    E         {\n    E           'foo': 'bar'\n    E         }\n    E       assert 1 == 2\n    E        +  where 1 = This is JSON\\n{\\n  'foo': 'bar'\\n}.a\n\n    failure_demo.py:283: AssertionError\n    ========================= short test summary info ==========================\n    FAILED failure_demo.py::test_generative[3-6] - assert (3 * 2) < 6\n    FAILED failure_demo.py::TestFailing::test_simple - assert 42 == 43\n    FAILED failure_demo.py::TestFailing::test_simple_multiline - assert 42 == 54\n    FAILED failure_demo.py::TestFailing::test_not - assert not 42\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_text - Asser...\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_similar_text\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_multiline_text\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_long_text - ...\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_long_text_multiline\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_list - asser...\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_list_long - ...\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_dict - Asser...\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_set - assert...\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_longer_list\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_in_list - asser...\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_not_in_text_multiline\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_not_in_text_single\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_not_in_text_single_long\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_not_in_text_single_long_term\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_dataclass - ...\n    FAILED failure_demo.py::TestSpecialisedExplanations::test_eq_attrs - Asse...\n    FAILED failure_demo.py::test_attribute - assert 1 == 2\n    FAILED failure_demo.py::test_attribute_instance - AssertionError: assert ...\n    FAILED failure_demo.py::test_attribute_failure - Exception: Failed to get...\n    FAILED failure_demo.py::test_attribute_multiple - AssertionError: assert ...\n    FAILED failure_demo.py::TestRaises::test_raises - ValueError: invalid lit...\n    FAILED failure_demo.py::TestRaises::test_raises_doesnt - Failed: DID NOT ...\n    FAILED failure_demo.py::TestRaises::test_raise - ValueError: demo error\n    FAILED failure_demo.py::TestRaises::test_tupleerror - ValueError: not eno...\n    FAILED failure_demo.py::TestRaises::test_reinterpret_fails_with_print_for_the_fun_of_it\n    FAILED failure_demo.py::TestRaises::test_some_error - NameError: name 'na...\n    FAILED failure_demo.py::test_dynamic_compile_shows_nicely - AssertionError\n    FAILED failure_demo.py::TestMoreErrors::test_complex_error - assert 44 == 43\n    FAILED failure_demo.py::TestMoreErrors::test_z1_unpack_error - ValueError...\n    FAILED failure_demo.py::TestMoreErrors::test_z2_type_error - TypeError: c...\n    FAILED failure_demo.py::TestMoreErrors::test_startswith - AssertionError:...\n    FAILED failure_demo.py::TestMoreErrors::test_startswith_nested - Assertio...\n    FAILED failure_demo.py::TestMoreErrors::test_global_func - assert False\n    FAILED failure_demo.py::TestMoreErrors::test_instance - assert 42 != 42\n    FAILED failure_demo.py::TestMoreErrors::test_compare - assert 11 < 5\n    FAILED failure_demo.py::TestMoreErrors::test_try_finally - assert 1 == 0\n    FAILED failure_demo.py::TestCustomAssertMsg::test_single_line - Assertion...\n    FAILED failure_demo.py::TestCustomAssertMsg::test_multiline - AssertionEr...\n    FAILED failure_demo.py::TestCustomAssertMsg::test_custom_repr - Assertion...\n    ============================ 44 failed in 0.12s ============================\n"
  },
  {
    "path": "doc/en/example/simple.rst",
    "content": "\n\nBasic patterns and examples\n==========================================================\n\nHow to change command line options defaults\n-------------------------------------------\n\nIt can be tedious to type the same series of command line options\nevery time you use ``pytest``.  For example, if you always want to see\ndetailed info on skipped and xfailed tests, as well as have terser \"dot\"\nprogress output, you can write it into a configuration file:\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    [pytest]\n    addopts = [\"-ra\", \"-q\"]\n\nAlternatively, you can set a ``PYTEST_ADDOPTS`` environment variable to add command\nline options while the environment is in use:\n\n.. code-block:: bash\n\n    export PYTEST_ADDOPTS=\"-v\"\n\nHere's how the command-line is built in the presence of ``addopts`` or the environment variable:\n\n.. code-block:: text\n\n    <configuration file addopts> $PYTEST_ADDOPTS <extra command-line arguments>\n\nSo if the user executes in the command-line:\n\n.. code-block:: bash\n\n    pytest -m slow\n\nThe actual command line executed is:\n\n.. code-block:: bash\n\n    pytest -ra -q -v -m slow\n\nNote that as usual for other command-line applications, in case of conflicting options the last one wins, so the example\nabove will show verbose output because :option:`-v` overwrites :option:`-q`.\n\n\n.. _request example:\n\nPass different values to a test function, depending on command line options\n----------------------------------------------------------------------------\n\n.. regendoc:wipe\n\nSuppose we want to write a test that depends on a command line option.\nHere is a basic pattern to achieve this:\n\n.. code-block:: python\n\n    # content of test_sample.py\n    def test_answer(cmdopt):\n        if cmdopt == \"type1\":\n            print(\"first\")\n        elif cmdopt == \"type2\":\n            print(\"second\")\n        assert 0  # to see what was printed\n\n\nFor this to work we need to add a command line option and\nprovide the ``cmdopt`` through a :ref:`fixture function <fixture>`:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import pytest\n\n\n    def pytest_addoption(parser):\n        parser.addoption(\n            \"--cmdopt\", action=\"store\", default=\"type1\", help=\"my option: type1 or type2\"\n        )\n\n\n    @pytest.fixture\n    def cmdopt(request):\n        return request.config.getoption(\"--cmdopt\")\n\nLet's run this without supplying our new option:\n\n.. code-block:: pytest\n\n    $ pytest -q test_sample.py\n    F                                                                    [100%]\n    ================================= FAILURES =================================\n    _______________________________ test_answer ________________________________\n\n    cmdopt = 'type1'\n\n        def test_answer(cmdopt):\n            if cmdopt == \"type1\":\n                print(\"first\")\n            elif cmdopt == \"type2\":\n                print(\"second\")\n    >       assert 0  # to see what was printed\n            ^^^^^^^^\n    E       assert 0\n\n    test_sample.py:6: AssertionError\n    --------------------------- Captured stdout call ---------------------------\n    first\n    ========================= short test summary info ==========================\n    FAILED test_sample.py::test_answer - assert 0\n    1 failed in 0.12s\n\nAnd now with supplying a command line option:\n\n.. code-block:: pytest\n\n    $ pytest -q --cmdopt=type2\n    F                                                                    [100%]\n    ================================= FAILURES =================================\n    _______________________________ test_answer ________________________________\n\n    cmdopt = 'type2'\n\n        def test_answer(cmdopt):\n            if cmdopt == \"type1\":\n                print(\"first\")\n            elif cmdopt == \"type2\":\n                print(\"second\")\n    >       assert 0  # to see what was printed\n            ^^^^^^^^\n    E       assert 0\n\n    test_sample.py:6: AssertionError\n    --------------------------- Captured stdout call ---------------------------\n    second\n    ========================= short test summary info ==========================\n    FAILED test_sample.py::test_answer - assert 0\n    1 failed in 0.12s\n\nYou can see that the command line option arrived in our test.\n\nWe could add simple validation for the input by listing the choices:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import pytest\n\n\n    def pytest_addoption(parser):\n        parser.addoption(\n            \"--cmdopt\",\n            action=\"store\",\n            default=\"type1\",\n            help=\"my option: type1 or type2\",\n            choices=(\"type1\", \"type2\"),\n        )\n\nNow we'll get feedback on a bad argument:\n\n.. code-block:: pytest\n\n    $ pytest -q --cmdopt=type3\n    ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]\n    pytest: error: argument --cmdopt: invalid choice: 'type3' (choose from type1, type2)\n      inifile: None\n      rootdir: /home/sweet/project\n\n\nIf you need to provide more detailed error messages, you can use the\n``type`` parameter and raise :exc:`pytest.UsageError`:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import pytest\n\n\n    def type_checker(value):\n        msg = \"cmdopt must specify a numeric type as typeNNN\"\n        if not value.startswith(\"type\"):\n            raise pytest.UsageError(msg)\n        try:\n            int(value[4:])\n        except ValueError:\n            raise pytest.UsageError(msg)\n\n        return value\n\n\n    def pytest_addoption(parser):\n        parser.addoption(\n            \"--cmdopt\",\n            action=\"store\",\n            default=\"type1\",\n            help=\"my option: type1 or type2\",\n            type=type_checker,\n        )\n\nThis completes the basic pattern.  However, one often rather wants to\nprocess command line options outside of the test and rather pass in\ndifferent or more complex objects.\n\nDynamically adding command line options\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nThrough :confval:`addopts` you can statically add command line\noptions for your project.  You can also dynamically modify\nthe command line arguments before they get processed:\n\n.. code-block:: python\n\n    # installable external plugin\n    import sys\n\n\n    def pytest_load_initial_conftests(args):\n        if \"xdist\" in sys.modules:  # pytest-xdist plugin\n            import multiprocessing\n\n            num = max(multiprocessing.cpu_count() / 2, 1)\n            args[:] = [\"-n\", str(num)] + args\n\nIf you have the :pypi:`xdist plugin <pytest-xdist>` installed\nyou will now always perform test runs using a number\nof subprocesses close to your CPU. Running in an empty\ndirectory with the above conftest.py:\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 0 items\n\n    ========================== no tests ran in 0.12s ===========================\n\n.. _`excontrolskip`:\n\nControl skipping of tests according to command line option\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nHere is a ``conftest.py`` file adding a ``--runslow`` command\nline option to control skipping of ``pytest.mark.slow`` marked tests:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n    import pytest\n\n\n    def pytest_addoption(parser):\n        parser.addoption(\n            \"--runslow\", action=\"store_true\", default=False, help=\"run slow tests\"\n        )\n\n\n    def pytest_configure(config):\n        config.addinivalue_line(\"markers\", \"slow: mark test as slow to run\")\n\n\n    def pytest_collection_modifyitems(config, items):\n        if config.getoption(\"--runslow\"):\n            # --runslow given in cli: do not skip slow tests\n            return\n        skip_slow = pytest.mark.skip(reason=\"need --runslow option to run\")\n        for item in items:\n            if \"slow\" in item.keywords:\n                item.add_marker(skip_slow)\n\nWe can now write a test module like this:\n\n.. code-block:: python\n\n    # content of test_module.py\n    import pytest\n\n\n    def test_func_fast():\n        pass\n\n\n    @pytest.mark.slow\n    def test_func_slow():\n        pass\n\nand when running it will see a skipped \"slow\" test:\n\n.. code-block:: pytest\n\n    $ pytest -rs    # \"-rs\" means report details on the little 's'\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 2 items\n\n    test_module.py .s                                                    [100%]\n\n    ========================= short test summary info ==========================\n    SKIPPED [1] test_module.py:8: need --runslow option to run\n    ======================= 1 passed, 1 skipped in 0.12s =======================\n\nOr run it including the ``slow`` marked test:\n\n.. code-block:: pytest\n\n    $ pytest --runslow\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 2 items\n\n    test_module.py ..                                                    [100%]\n\n    ============================ 2 passed in 0.12s =============================\n\n.. _`__tracebackhide__`:\n\nWriting well integrated assertion helpers\n-----------------------------------------\n\n.. regendoc:wipe\n\nIf you have a test helper function called from a test you can\nuse the ``pytest.fail`` marker to fail a test with a certain message.\nThe test support function will not show up in the traceback if you\nset the ``__tracebackhide__`` option somewhere in the helper function.\nExample:\n\n.. code-block:: python\n\n    # content of test_checkconfig.py\n    import pytest\n\n\n    def checkconfig(x):\n        __tracebackhide__ = True\n        if not hasattr(x, \"config\"):\n            pytest.fail(f\"not configured: {x}\")\n\n\n    def test_something():\n        checkconfig(42)\n\nThe ``__tracebackhide__`` setting influences ``pytest`` showing\nof tracebacks: the ``checkconfig`` function will not be shown\nunless the :option:`--full-trace` command line option is specified.\nLet's run our little function:\n\n.. code-block:: pytest\n\n    $ pytest -q test_checkconfig.py\n    F                                                                    [100%]\n    ================================= FAILURES =================================\n    ______________________________ test_something ______________________________\n\n        def test_something():\n    >       checkconfig(42)\n    E       Failed: not configured: 42\n\n    test_checkconfig.py:11: Failed\n    ========================= short test summary info ==========================\n    FAILED test_checkconfig.py::test_something - Failed: not configured: 42\n    1 failed in 0.12s\n\nIf you only want to hide certain exceptions, you can set ``__tracebackhide__``\nto a callable which gets the ``ExceptionInfo`` object. You can for example use\nthis to make sure unexpected exception types aren't hidden:\n\n.. code-block:: python\n\n    import operator\n\n    import pytest\n\n\n    class ConfigException(Exception):\n        pass\n\n\n    def checkconfig(x):\n        __tracebackhide__ = operator.methodcaller(\"errisinstance\", ConfigException)\n        if not hasattr(x, \"config\"):\n            raise ConfigException(f\"not configured: {x}\")\n\n\n    def test_something():\n        checkconfig(42)\n\nThis will avoid hiding the exception traceback on unrelated exceptions (i.e.\nbugs in assertion helpers).\n\n\nDetect if running from within a pytest run\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nUsually it is a bad idea to make application code\nbehave differently if called from a test.  But if you\nabsolutely must find out if your application code is\nrunning from a test you can do this:\n\n.. code-block:: python\n\n    import os\n\n\n    if os.environ.get(\"PYTEST_VERSION\") is not None:\n        # Things you want to do if your code is called by pytest.\n        ...\n    else:\n        # Things you want to do if your code is not called by pytest.\n        ...\n\n\nAdding info to test report header\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nIt's easy to present extra information in a ``pytest`` run:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n\n    def pytest_report_header(config):\n        return \"project deps: mylib-1.1\"\n\nwhich will add the string to the test header accordingly:\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    project deps: mylib-1.1\n    rootdir: /home/sweet/project\n    collected 0 items\n\n    ========================== no tests ran in 0.12s ===========================\n\n.. regendoc:wipe\n\nIt is also possible to return a list of strings which will be considered as several\nlines of information. You may consider ``config.getoption('verbose')`` in order to\ndisplay more information if applicable:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n\n    def pytest_report_header(config):\n        if config.get_verbosity() > 0:\n            return [\"info1: did you know that ...\", \"did you?\"]\n\nwhich will add info only when run with \"--v\":\n\n.. code-block:: pytest\n\n    $ pytest -v\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    info1: did you know that ...\n    did you?\n    rootdir: /home/sweet/project\n    collecting ... collected 0 items\n\n    ========================== no tests ran in 0.12s ===========================\n\nand nothing when run plainly:\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 0 items\n\n    ========================== no tests ran in 0.12s ===========================\n\nProfiling test duration\n--------------------------\n\n.. regendoc:wipe\n\n.. versionadded: 2.2\n\nIf you have a slow running large test suite you might want to find\nout which tests are the slowest. Let's make an artificial test suite:\n\n.. code-block:: python\n\n    # content of test_some_are_slow.py\n    import time\n\n\n    def test_funcfast():\n        time.sleep(0.1)\n\n\n    def test_funcslow1():\n        time.sleep(0.2)\n\n\n    def test_funcslow2():\n        time.sleep(0.3)\n\nNow we can profile which test functions execute the slowest:\n\n.. code-block:: pytest\n\n    $ pytest --durations=3\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 3 items\n\n    test_some_are_slow.py ...                                            [100%]\n\n    =========================== slowest 3 durations ============================\n    0.30s call     test_some_are_slow.py::test_funcslow2\n    0.20s call     test_some_are_slow.py::test_funcslow1\n    0.10s call     test_some_are_slow.py::test_funcfast\n    ============================ 3 passed in 0.12s =============================\n\nIncremental testing - test steps\n---------------------------------------------------\n\n.. regendoc:wipe\n\nSometimes you may have a testing situation which consists of a series\nof test steps.  If one step fails it makes no sense to execute further\nsteps as they are all expected to fail anyway and their tracebacks\nadd no insight.  Here is a simple ``conftest.py`` file which introduces\nan ``incremental`` marker which is to be used on classes:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n    import pytest\n\n    # store history of failures per test class name and per index in parametrize (if parametrize used)\n    _test_failed_incremental: dict[str, dict[tuple[int, ...], str]] = {}\n\n\n    def pytest_runtest_makereport(item, call):\n        if \"incremental\" in item.keywords:\n            # incremental marker is used\n            if call.excinfo is not None:\n                # the test has failed\n                # retrieve the class name of the test\n                cls_name = str(item.cls)\n                # retrieve the index of the test (if parametrize is used in combination with incremental)\n                parametrize_index = (\n                    tuple(item.callspec.indices.values())\n                    if hasattr(item, \"callspec\")\n                    else ()\n                )\n                # retrieve the name of the test function\n                test_name = item.originalname or item.name\n                # store in _test_failed_incremental the original name of the failed test\n                _test_failed_incremental.setdefault(cls_name, {}).setdefault(\n                    parametrize_index, test_name\n                )\n\n\n    def pytest_runtest_setup(item):\n        if \"incremental\" in item.keywords:\n            # retrieve the class name of the test\n            cls_name = str(item.cls)\n            # check if a previous test has failed for this class\n            if cls_name in _test_failed_incremental:\n                # retrieve the index of the test (if parametrize is used in combination with incremental)\n                parametrize_index = (\n                    tuple(item.callspec.indices.values())\n                    if hasattr(item, \"callspec\")\n                    else ()\n                )\n                # retrieve the name of the first test function to fail for this class name and index\n                test_name = _test_failed_incremental[cls_name].get(parametrize_index, None)\n                # if name found, test has failed for the combination of class name & test name\n                if test_name is not None:\n                    pytest.xfail(f\"previous test failed ({test_name})\")\n\n\nThese two hook implementations work together to abort incremental-marked\ntests in a class.  Here is a test module example:\n\n.. code-block:: python\n\n    # content of test_step.py\n\n    import pytest\n\n\n    @pytest.mark.incremental\n    class TestUserHandling:\n        def test_login(self):\n            pass\n\n        def test_modification(self):\n            assert 0\n\n        def test_deletion(self):\n            pass\n\n\n    def test_normal():\n        pass\n\nIf we run this:\n\n.. code-block:: pytest\n\n    $ pytest -rx\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 4 items\n\n    test_step.py .Fx.                                                    [100%]\n\n    ================================= FAILURES =================================\n    ____________________ TestUserHandling.test_modification ____________________\n\n    self = <test_step.TestUserHandling object at 0xdeadbeef0001>\n\n        def test_modification(self):\n    >       assert 0\n    E       assert 0\n\n    test_step.py:11: AssertionError\n    ========================= short test summary info ==========================\n    XFAIL test_step.py::TestUserHandling::test_deletion - previous test failed (test_modification)\n    ================== 1 failed, 2 passed, 1 xfailed in 0.12s ==================\n\nWe'll see that ``test_deletion`` was not executed because ``test_modification``\nfailed.  It is reported as an \"expected failure\".\n\n\nPackage/Directory-level fixtures (setups)\n-------------------------------------------------------\n\nIf you have nested test directories, you can have per-directory fixture scopes\nby placing fixture functions in a ``conftest.py`` file in that directory.\nYou can use all types of fixtures including :ref:`autouse fixtures\n<autouse fixtures>` which are the equivalent of xUnit's setup/teardown\nconcept.  It's however recommended to have explicit fixture references in your\ntests or test classes rather than relying on implicitly executing\nsetup/teardown functions, especially if they are far away from the actual tests.\n\nHere is an example for making a ``db`` fixture available in a directory:\n\n.. code-block:: python\n\n    # content of a/conftest.py\n    import pytest\n\n\n    class DB:\n        pass\n\n\n    @pytest.fixture(scope=\"package\")\n    def db():\n        return DB()\n\nand then a test module in that directory:\n\n.. code-block:: python\n\n    # content of a/test_db.py\n    def test_a1(db):\n        assert 0, db  # to show value\n\nanother test module:\n\n.. code-block:: python\n\n    # content of a/test_db2.py\n    def test_a2(db):\n        assert 0, db  # to show value\n\nand then a module in a sister directory which will not see\nthe ``db`` fixture:\n\n.. code-block:: python\n\n    # content of b/test_error.py\n    def test_root(db):  # no db here, will error out\n        pass\n\nWe can run this:\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 7 items\n\n    a/test_db.py F                                                       [ 14%]\n    a/test_db2.py F                                                      [ 28%]\n    b/test_error.py E                                                    [ 42%]\n    test_step.py .Fx.                                                    [100%]\n\n    ================================== ERRORS ==================================\n    _______________________ ERROR at setup of test_root ________________________\n    file /home/sweet/project/b/test_error.py, line 1\n      def test_root(db):  # no db here, will error out\n    E       fixture 'db' not found\n    >       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, capteesys, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, subtests, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory\n    >       use 'pytest --fixtures [testpath]' for help on them.\n\n    /home/sweet/project/b/test_error.py:1\n    ================================= FAILURES =================================\n    _________________________________ test_a1 __________________________________\n\n    db = <conftest.DB object at 0xdeadbeef0002>\n\n        def test_a1(db):\n    >       assert 0, db  # to show value\n            ^^^^^^^^^^^^\n    E       AssertionError: <conftest.DB object at 0xdeadbeef0002>\n    E       assert 0\n\n    a/test_db.py:2: AssertionError\n    _________________________________ test_a2 __________________________________\n\n    db = <conftest.DB object at 0xdeadbeef0002>\n\n        def test_a2(db):\n    >       assert 0, db  # to show value\n            ^^^^^^^^^^^^\n    E       AssertionError: <conftest.DB object at 0xdeadbeef0002>\n    E       assert 0\n\n    a/test_db2.py:2: AssertionError\n    ____________________ TestUserHandling.test_modification ____________________\n\n    self = <test_step.TestUserHandling object at 0xdeadbeef0003>\n\n        def test_modification(self):\n    >       assert 0\n    E       assert 0\n\n    test_step.py:11: AssertionError\n    ========================= short test summary info ==========================\n    FAILED a/test_db.py::test_a1 - AssertionError: <conftest.DB object at 0x7...\n    FAILED a/test_db2.py::test_a2 - AssertionError: <conftest.DB object at 0x...\n    FAILED test_step.py::TestUserHandling::test_modification - assert 0\n    ERROR b/test_error.py::test_root\n    ============= 3 failed, 2 passed, 1 xfailed, 1 error in 0.12s ==============\n\nThe two test modules in the ``a`` directory see the same ``db`` fixture instance\nwhile the one test in the sister-directory ``b`` doesn't see it.  We could of course\nalso define a ``db`` fixture in that sister directory's ``conftest.py`` file.\nNote that each fixture is only instantiated if there is a test actually needing\nit (unless you use \"autouse\" fixtures which are always executed ahead of the first test\nexecuting).\n\n\nPost-process test reports / failures\n---------------------------------------\n\nIf you want to postprocess test reports and need access to the executing\nenvironment you can implement a hook that gets called when the test\n\"report\" object is about to be created.  Here we write out all failing\ntest calls and also access a fixture (if it was used by the test) in\ncase you want to query/look at it during your post processing.  In our\ncase we just write some information out to a ``failures`` file:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n    import os.path\n\n    import pytest\n\n\n    @pytest.hookimpl(wrapper=True, tryfirst=True)\n    def pytest_runtest_makereport(item, call):\n        # execute all other hooks to obtain the report object\n        rep = yield\n\n        # we only look at actual failing test calls, not setup/teardown\n        if rep.when == \"call\" and rep.failed:\n            mode = \"a\" if os.path.exists(\"failures\") else \"w\"\n            with open(\"failures\", mode, encoding=\"utf-8\") as f:\n                # let's also access a fixture for the fun of it\n                if \"tmp_path\" in item.fixturenames:\n                    extra = \" ({})\".format(item.funcargs[\"tmp_path\"])\n                else:\n                    extra = \"\"\n\n                f.write(rep.nodeid + extra + \"\\n\")\n\n        return rep\n\n\nif you then have failing tests:\n\n.. code-block:: python\n\n    # content of test_module.py\n    def test_fail1(tmp_path):\n        assert 0\n\n\n    def test_fail2():\n        assert 0\n\nand run them:\n\n.. code-block:: pytest\n\n    $ pytest test_module.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 2 items\n\n    test_module.py FF                                                    [100%]\n\n    ================================= FAILURES =================================\n    ________________________________ test_fail1 ________________________________\n\n    tmp_path = PosixPath('PYTEST_TMPDIR/test_fail10')\n\n        def test_fail1(tmp_path):\n    >       assert 0\n    E       assert 0\n\n    test_module.py:2: AssertionError\n    ________________________________ test_fail2 ________________________________\n\n        def test_fail2():\n    >       assert 0\n    E       assert 0\n\n    test_module.py:6: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_module.py::test_fail1 - assert 0\n    FAILED test_module.py::test_fail2 - assert 0\n    ============================ 2 failed in 0.12s =============================\n\nyou will have a \"failures\" file which contains the failing test ids:\n\n.. code-block:: bash\n\n    $ cat failures\n    test_module.py::test_fail1 (PYTEST_TMPDIR/test_fail10)\n    test_module.py::test_fail2\n\nMaking test result information available in fixtures\n-----------------------------------------------------------\n\n.. regendoc:wipe\n\nIf you want to make test result reports available in fixture finalizers\nhere is a little example implemented via a local plugin:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import pytest\n    from pytest import StashKey, CollectReport\n\n    phase_report_key = StashKey[dict[str, CollectReport]]()\n\n\n    @pytest.hookimpl(wrapper=True, tryfirst=True)\n    def pytest_runtest_makereport(item, call):\n        # execute all other hooks to obtain the report object\n        rep = yield\n\n        # store test results for each phase of a call, which can\n        # be \"setup\", \"call\", \"teardown\"\n        item.stash.setdefault(phase_report_key, {})[rep.when] = rep\n\n        return rep\n\n\n    @pytest.fixture\n    def something(request):\n        yield\n        # request.node is an \"item\" because we use the default\n        # \"function\" scope\n        report = request.node.stash[phase_report_key]\n        if report[\"setup\"].failed:\n            print(\"setting up a test failed\", request.node.nodeid)\n        elif report[\"setup\"].skipped:\n            print(\"setting up a test skipped\", request.node.nodeid)\n        elif (\"call\" not in report) or report[\"call\"].failed:\n            print(\"executing test failed or skipped\", request.node.nodeid)\n\n\nif you then have failing tests:\n\n.. code-block:: python\n\n    # content of test_module.py\n\n    import pytest\n\n\n    @pytest.fixture\n    def other():\n        assert 0\n\n\n    def test_setup_fails(something, other):\n        pass\n\n\n    def test_call_fails(something):\n        assert 0\n\n\n    def test_fail2():\n        assert 0\n\nand run it:\n\n.. code-block:: pytest\n\n    $ pytest -s test_module.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 3 items\n\n    test_module.py Esetting up a test failed test_module.py::test_setup_fails\n    Fexecuting test failed or skipped test_module.py::test_call_fails\n    F\n\n    ================================== ERRORS ==================================\n    ____________________ ERROR at setup of test_setup_fails ____________________\n\n        @pytest.fixture\n        def other():\n    >       assert 0\n    E       assert 0\n\n    test_module.py:7: AssertionError\n    ================================= FAILURES =================================\n    _____________________________ test_call_fails ______________________________\n\n    something = None\n\n        def test_call_fails(something):\n    >       assert 0\n    E       assert 0\n\n    test_module.py:15: AssertionError\n    ________________________________ test_fail2 ________________________________\n\n        def test_fail2():\n    >       assert 0\n    E       assert 0\n\n    test_module.py:19: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_module.py::test_call_fails - assert 0\n    FAILED test_module.py::test_fail2 - assert 0\n    ERROR test_module.py::test_setup_fails - assert 0\n    ======================== 2 failed, 1 error in 0.12s ========================\n\nYou'll see that the fixture finalizers could use the precise reporting\ninformation.\n\n.. _pytest current test env:\n\n``PYTEST_CURRENT_TEST`` environment variable\n--------------------------------------------\n\n\n\nSometimes a test session might get stuck and there might be no easy way to figure out\nwhich test got stuck, for example if pytest was run in quiet mode (:option:`-q`) or you don't have access to the console\noutput. This is particularly a problem if the problem happens only sporadically, the famous \"flaky\" kind of tests.\n\n``pytest`` sets the :envvar:`PYTEST_CURRENT_TEST` environment variable when running tests, which can be inspected\nby process monitoring utilities or libraries like :pypi:`psutil` to discover which test got stuck if necessary:\n\n.. code-block:: python\n\n    import psutil\n\n    for pid in psutil.pids():\n        environ = psutil.Process(pid).environ()\n        if \"PYTEST_CURRENT_TEST\" in environ:\n            print(f'pytest process {pid} running: {environ[\"PYTEST_CURRENT_TEST\"]}')\n\nDuring the test session pytest will set ``PYTEST_CURRENT_TEST`` to the current test\n:ref:`nodeid <nodeids>` and the current stage, which can be ``setup``, ``call``,\nor ``teardown``.\n\nFor example, when running a single test function named ``test_foo`` from ``foo_module.py``,\n``PYTEST_CURRENT_TEST`` will be set to:\n\n#. ``foo_module.py::test_foo (setup)``\n#. ``foo_module.py::test_foo (call)``\n#. ``foo_module.py::test_foo (teardown)``\n\nIn that order.\n\n.. note::\n\n    The contents of ``PYTEST_CURRENT_TEST`` is meant to be human readable and the actual format\n    can be changed between releases (even bug fixes) so it shouldn't be relied on for scripting\n    or automation.\n\n.. _freezing-pytest:\n\nFreezing pytest\n---------------\n\nIf you freeze your application using a tool like\n`PyInstaller <https://pyinstaller.readthedocs.io>`_\nin order to distribute it to your end-users, it is a good idea to also package\nyour test runner and run your tests using the frozen application. This way packaging\nerrors such as dependencies not being included into the executable can be detected early\nwhile also allowing you to send test files to users so they can run them in their\nmachines, which can be useful to obtain more information about a hard to reproduce bug.\n\nFortunately recent ``PyInstaller`` releases already have a custom hook\nfor pytest, but if you are using another tool to freeze executables\nsuch as ``cx_freeze`` or ``py2exe``, you can use ``pytest.freeze_includes()``\nto obtain the full list of internal pytest modules. How to configure the tools\nto find the internal modules varies from tool to tool, however.\n\nInstead of freezing the pytest runner as a separate executable, you can make\nyour frozen program work as the pytest runner by some clever\nargument handling during program startup. This allows you to\nhave a single executable, which is usually more convenient.\nPlease note that the mechanism for plugin discovery used by pytest (:ref:`entry\npoints <pip-installable plugins>`) doesn't work with frozen executables so pytest\ncan't find any third party plugins automatically. To include third party plugins\nlike ``pytest-timeout`` they must be imported explicitly and passed on to pytest.main.\n\n.. code-block:: python\n\n    # contents of app_main.py\n    import sys\n\n    import pytest_timeout  # Third party plugin\n\n    if len(sys.argv) > 1 and sys.argv[1] == \"--pytest\":\n        import pytest\n\n        sys.exit(pytest.main(sys.argv[2:], plugins=[pytest_timeout]))\n    else:\n        # normal application execution: at this point argv can be parsed\n        # by your argument-parsing library of choice as usual\n        ...\n\n\nThis allows you to execute tests using the frozen\napplication with standard ``pytest`` command-line options:\n\n.. code-block:: bash\n\n    ./app_main --pytest --verbose --tb=long --junit=xml=results.xml test-suite/\n"
  },
  {
    "path": "doc/en/example/special.rst",
    "content": "A session-fixture which can look at all collected tests\n----------------------------------------------------------------\n\nA session-scoped fixture effectively has access to all\ncollected test items.  Here is an example of a fixture\nfunction which walks all collected tests and looks\nif their test class defines a ``callme`` method and\ncalls it:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n    import pytest\n\n\n    @pytest.fixture(scope=\"session\", autouse=True)\n    def callattr_ahead_of_alltests(request):\n        print(\"callattr_ahead_of_alltests called\")\n        seen = {None}\n        session = request.node\n        for item in session.items:\n            cls = item.getparent(pytest.Class)\n            if cls not in seen:\n                if hasattr(cls.obj, \"callme\"):\n                    cls.obj.callme()\n                seen.add(cls)\n\ntest classes may now define a ``callme`` method which\nwill be called ahead of running any tests:\n\n.. code-block:: python\n\n    # content of test_module.py\n\n\n    class TestHello:\n        @classmethod\n        def callme(cls):\n            print(\"callme called!\")\n\n        def test_method1(self):\n            print(\"test_method1 called\")\n\n        def test_method2(self):\n            print(\"test_method2 called\")\n\n\n    class TestOther:\n        @classmethod\n        def callme(cls):\n            print(\"callme other called\")\n\n        def test_other(self):\n            print(\"test other\")\n\n\n    # works with unittest as well ...\n    import unittest\n\n\n    class SomeTest(unittest.TestCase):\n        @classmethod\n        def callme(self):\n            print(\"SomeTest callme called\")\n\n        def test_unit1(self):\n            print(\"test_unit1 method called\")\n\nIf you run this without output capturing:\n\n.. code-block:: pytest\n\n    $ pytest -q -s test_module.py\n    callattr_ahead_of_alltests called\n    callme called!\n    callme other called\n    SomeTest callme called\n    test_method1 called\n    .test_method2 called\n    .test other\n    .test_unit1 method called\n    .\n    4 passed in 0.12s\n"
  },
  {
    "path": "doc/en/example/xfail_demo.py",
    "content": "from __future__ import annotations\n\nimport pytest\n\n\nxfail = pytest.mark.xfail\n\n\n@xfail\ndef test_hello():\n    assert 0\n\n\n@xfail(run=False)\ndef test_hello2():\n    assert 0\n\n\n@xfail(\"hasattr(os, 'sep')\")\ndef test_hello3():\n    assert 0\n\n\n@xfail(reason=\"bug 110\")\ndef test_hello4():\n    assert 0\n\n\n@xfail('pytest.__version__[0] != \"17\"')\ndef test_hello5():\n    assert 0\n\n\ndef test_hello6():\n    pytest.xfail(\"reason\")\n\n\n@xfail(raises=IndexError)\ndef test_hello7():\n    x = []\n    x[1] = 1\n"
  },
  {
    "path": "doc/en/explanation/anatomy.rst",
    "content": ".. _test-anatomy:\n\nAnatomy of a test\n=================\n\nIn the simplest terms, a test is meant to look at the result of a particular\nbehavior, and make sure that result aligns with what you would expect.\nBehavior is not something that can be empirically measured, which is why writing\ntests can be challenging.\n\n\"Behavior\" is the way in which some system **acts in response** to a particular\nsituation and/or stimuli. But exactly *how* or *why* something is done is not\nquite as important as *what* was done.\n\nYou can think of a test as being broken down into four steps:\n\n1. **Arrange**\n2. **Act**\n3. **Assert**\n4. **Cleanup**\n\n**Arrange** is where we prepare everything for our test. This means pretty\nmuch everything except for the \"**act**\". It's lining up the dominoes so that\nthe **act** can do its thing in one, state-changing step. This can mean\npreparing objects, starting/killing services, entering records into a database,\nor even things like defining a URL to query, generating some credentials for a\nuser that doesn't exist yet, or just waiting for some process to finish.\n\n**Act** is the singular, state-changing action that kicks off the **behavior**\nwe want to test. This behavior is what carries out the changing of the state of\nthe system under test (SUT), and it's the resulting changed state that we can\nlook at to make a judgement about the behavior. This typically takes the form of\na function/method call.\n\n**Assert** is where we look at that resulting state and check if it looks how\nwe'd expect after the dust has settled. It's where we gather evidence to say the\nbehavior does or does not align with what we expect. The ``assert`` in our test\nis where we take that measurement/observation and apply our judgement to it. If\nsomething should be green, we'd say ``assert thing == \"green\"``.\n\n**Cleanup** is where the test picks up after itself, so other tests aren't being\naccidentally influenced by it.\n\nAt its core, the test is ultimately the **act** and **assert** steps, with the\n**arrange** step only providing the context. **Behavior** exists between **act**\nand **assert**.\n"
  },
  {
    "path": "doc/en/explanation/ci.rst",
    "content": ".. _`ci-pipelines`:\n\nCI Pipelines\n============\n\nRationale\n---------\n\nThe goal of testing in a CI pipeline is different from testing locally. Indeed,\nyou can quickly edit some code and run your tests again on your computer, but\nit is not possible with CI pipelines. They run on a separate server and are\ntriggered by specific actions.\n\nFrom that observation, pytest can detect when it is in a CI environment and\nadapt some of its behaviours.\n\nHow CI is detected\n------------------\n\nPytest knows it is in a CI environment when either one of these environment variables is set to a non-empty value:\n\n* :envvar:`CI`: used by many CI systems.\n* :envvar:`BUILD_NUMBER`: used by Jenkins.\n\nEffects on CI\n-------------\n\nFor now, the effects on pytest of being in a CI environment are limited.\n\nWhen a CI environment is detected, the output of the short test summary info is no longer truncated to the terminal size i.e. the entire message will be shown.\n\n  .. code-block:: python\n\n        # content of test_ci.py\n        import pytest\n\n\n        def test_db_initialized():\n            pytest.fail(\n                \"deliberately failing for demo purpose, Lorem ipsum dolor sit amet, \"\n                \"consectetur adipiscing elit. Cras facilisis, massa in suscipit \"\n                \"dignissim, mauris lacus molestie nisi, quis varius metus nulla ut ipsum.\"\n            )\n\n\nRunning this locally, without any extra options, will output:\n\n  .. code-block:: pytest\n\n     $ pytest test_ci.py\n     ...\n     ========================= short test summary info ==========================\n     FAILED test_ci.py::test_db_initialized - Failed: deliberately f...\n\n*(Note the truncated text)*\n\n\nWhile running this on CI will output:\n\n  .. code-block:: pytest\n\n     $ export CI=true\n     $ pytest test_ci.py\n     ...\n     ========================= short test summary info ==========================\n     FAILED test_ci.py::test_db_initialized - Failed: deliberately failing\n     for demo purpose, Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras\n     facilisis, massa in suscipit dignissim, mauris lacus molestie nisi, quis varius\n     metus nulla ut ipsum.\n"
  },
  {
    "path": "doc/en/explanation/fixtures.rst",
    "content": ".. _about-fixtures:\n\nAbout fixtures\n===============\n\n.. seealso:: :ref:`how-to-fixtures`\n.. seealso:: :ref:`Fixtures reference <reference-fixtures>`\n\npytest fixtures are designed to be explicit, modular and scalable.\n\nWhat fixtures are\n-----------------\n\nIn testing, a `fixture <https://en.wikipedia.org/wiki/Test_fixture#Software>`_\nprovides a defined, reliable and consistent context for the tests. This could\ninclude environment (for example a database configured with known parameters)\nor content (such as a dataset).\n\nFixtures define the steps and data that constitute the *arrange* phase of a\ntest (see :ref:`test-anatomy`). In pytest, they are functions you define that\nserve this purpose. They can also be used to define a test's *act* phase; this\nis a powerful technique for designing more complex tests.\n\nThe services, state, or other operating environments set up by fixtures are\naccessed by test functions through arguments. For each fixture used by a test\nfunction there is typically a parameter (named after the fixture) in the test\nfunction's definition.\n\nWe can tell pytest that a particular function is a fixture by decorating it with\n:py:func:`@pytest.fixture <pytest.fixture>`. Here's a simple example of\nwhat a fixture in pytest might look like:\n\n.. code-block:: python\n\n    import pytest\n\n\n    class Fruit:\n        def __init__(self, name):\n            self.name = name\n\n        def __eq__(self, other):\n            return self.name == other.name\n\n\n    @pytest.fixture\n    def my_fruit():\n        return Fruit(\"apple\")\n\n\n    @pytest.fixture\n    def fruit_basket(my_fruit):\n        return [Fruit(\"banana\"), my_fruit]\n\n\n    def test_my_fruit_in_basket(my_fruit, fruit_basket):\n        assert my_fruit in fruit_basket\n\nTests don't have to be limited to a single fixture, either. They can depend on\nas many fixtures as you want, and fixtures can use other fixtures, as well. This\nis where pytest's fixture system really shines.\n\n\nImprovements over xUnit-style setup/teardown functions\n-----------------------------------------------------------\n\npytest fixtures offer dramatic improvements over the classic xUnit\nstyle of setup/teardown functions:\n\n* fixtures have explicit names and are activated by declaring their use\n  from test functions, modules, classes or whole projects.\n\n* fixtures are implemented in a modular manner, as each fixture name\n  triggers a *fixture function* which can itself use other fixtures.\n\n* fixture management scales from simple unit to complex\n  functional testing, allowing to parametrize fixtures and tests according\n  to configuration and component options, or to reuse fixtures\n  across function, class, module or whole test session scopes.\n\n* teardown logic can be easily, and safely managed, no matter how many fixtures\n  are used, without the need to carefully handle errors by hand or micromanage\n  the order that cleanup steps are added.\n\nIn addition, pytest continues to support :ref:`xunitsetup`.  You can mix\nboth styles, moving incrementally from classic to new style, as you\nprefer.  You can also start out from existing :ref:`unittest.TestCase\nstyle <unittest.TestCase>`.\n\n\n\nFixture errors\n--------------\n\npytest does its best to put all the fixtures for a given test in a linear order\nso that it can see which fixture happens first, second, third, and so on. If an\nearlier fixture has a problem, though, and raises an exception, pytest will stop\nexecuting fixtures for that test and mark the test as having an error.\n\nWhen a test is marked as having an error, it doesn't mean the test failed,\nthough. It just means the test couldn't even be attempted because one of the\nthings it depends on had a problem.\n\nThis is one reason why it's a good idea to cut out as many unnecessary\ndependencies as possible for a given test. That way a problem in something\nunrelated isn't causing us to have an incomplete picture of what may or may not\nhave issues.\n\nHere's a quick example to help explain:\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.fixture\n    def order():\n        return []\n\n\n    @pytest.fixture\n    def append_first(order):\n        order.append(1)\n\n\n    @pytest.fixture\n    def append_second(order, append_first):\n        order.extend([2])\n\n\n    @pytest.fixture(autouse=True)\n    def append_third(order, append_second):\n        order += [3]\n\n\n    def test_order(order):\n        assert order == [1, 2, 3]\n\n\nIf, for whatever reason, ``order.append(1)`` had a bug and it raises an exception,\nwe wouldn't be able to know if ``order.extend([2])`` or ``order += [3]`` would\nalso have problems. After ``append_first`` throws an exception, pytest won't run\nany more fixtures for ``test_order``, and it won't even try to run\n``test_order`` itself. The only things that would've run would be ``order`` and\n``append_first``.\n\n\nSharing test data\n-----------------\n\nIf you want to make test data from files available to your tests, a good way\nto do this is by loading these data in a fixture for use by your tests.\nThis makes use of the automatic caching mechanisms of pytest.\n\nAnother good approach is by adding the data files in the ``tests`` directory.\nThere are also community plugins available to help to manage this aspect of\ntesting, e.g. :pypi:`pytest-datadir` and :pypi:`pytest-datafiles`.\n\n.. _fixtures-signal-cleanup:\n\nA note about fixture cleanup\n----------------------------\n\npytest does not do any special processing for :data:`SIGTERM <signal.SIGTERM>` and\n``SIGQUIT`` signals (:data:`SIGINT <signal.SIGINT>` is handled naturally\nby the Python runtime via :class:`KeyboardInterrupt`), so fixtures that manage external resources which are important\nto be cleared when the Python process is terminated (by those signals) might leak resources.\n\nThe reason pytest does not handle those signals to perform fixture cleanup is that signal handlers are global,\nand changing them might interfere with the code under execution.\n\nIf fixtures in your suite need special care regarding termination in those scenarios,\nsee :issue:`this comment <5243#issuecomment-491522595>` in the issue\ntracker for a possible workaround.\n"
  },
  {
    "path": "doc/en/explanation/flaky.rst",
    "content": "\nFlaky tests\n-----------\n\nA \"flaky\" test is one that exhibits intermittent or sporadic failure, that seems to have non-deterministic behaviour. Sometimes it passes, sometimes it fails, and it's not clear why. This page discusses pytest features that can help and other general strategies for identifying, fixing or mitigating them.\n\nWhy flaky tests are a problem\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFlaky tests are particularly troublesome when a continuous integration (CI) server is being used, so that all tests must pass before a new code change can be merged. If the test result is not a reliable signal -- that a test failure means the code change broke the test -- developers can become mistrustful of the test results, which can lead to overlooking genuine failures. It is also a source of wasted time as developers must re-run test suites and investigate spurious failures.\n\n\nPotential root causes\n^^^^^^^^^^^^^^^^^^^^^\n\nSystem state\n~~~~~~~~~~~~\n\nBroadly speaking, a flaky test indicates that the test relies on some system state that is not being appropriately controlled - the test environment is not sufficiently isolated. Higher level tests are more likely to be flaky as they rely on more state.\n\nFlaky tests sometimes appear when a test suite is run in parallel (such as use of `pytest-xdist`_). This can indicate a test is reliant on test ordering.\n\n-  Perhaps a different test is failing to clean up after itself and leaving behind data which causes the flaky test to fail.\n- The flaky test is reliant on data from a previous test that doesn't clean up after itself, and in parallel runs that previous test is not always present\n- Tests that modify global state typically cannot be run in parallel.\n\n\nOverly strict assertion\n~~~~~~~~~~~~~~~~~~~~~~~\n\nOverly strict assertions can cause problems with floating point comparison as well as timing issues. :func:`pytest.approx` is useful here.\n\nThread safety\n~~~~~~~~~~~~~\n\npytest is single-threaded, executing its tests always in the same thread, sequentially, never spawning any threads itself.\n\nEven in case of plugins which run tests in parallel, for example `pytest-xdist`_, usually work by spawning multiple *processes* and running tests in batches, without using multiple threads.\n\nIt is of course possible (and common) for tests and fixtures to spawn threads themselves as part of their testing workflow (for example, a fixture that starts a server thread in the background, or a test which executes production code that spawns threads), but some care must be taken:\n\n* Make sure to eventually wait on any spawned threads -- for example at the end of a test, or during the teardown of a fixture.\n* Avoid using primitives provided by pytest (:func:`pytest.warns`, :func:`pytest.raises`, etc) from multiple threads, as they are not thread-safe.\n\nIf your test suite uses threads and you are seeing flaky test results, do not discount the possibility that the test is implicitly using global state in pytest itself.\n\nRelated features\n^^^^^^^^^^^^^^^^\n\nXfail strict\n~~~~~~~~~~~~\n\n:ref:`pytest.mark.xfail ref` with ``strict=False`` can be used to mark a test so that its failure does not cause the whole build to break. This could be considered like a manual quarantine, and is rather dangerous to use permanently.\n\n\nPYTEST_CURRENT_TEST\n~~~~~~~~~~~~~~~~~~~\n\n:envvar:`PYTEST_CURRENT_TEST` may be useful for figuring out \"which test got stuck\".\nSee :ref:`pytest current test env` for more details.\n\n\nPlugins\n~~~~~~~\n\nRerunning any failed tests can mitigate the negative effects of flaky tests by giving them additional chances to pass, so that the overall build does not fail. Several pytest plugins support this:\n\n* `pytest-rerunfailures <https://github.com/pytest-dev/pytest-rerunfailures>`_\n* `pytest-replay <https://github.com/ESSS/pytest-replay>`_: This plugin helps to reproduce locally crashes or flaky tests observed during CI runs.\n* `pytest-flakefinder <https://github.com/dropbox/pytest-flakefinder>`_ - `blog post <https://blogs.dropbox.com/tech/2016/03/open-sourcing-pytest-tools/>`_\n\nPlugins to deliberately randomize tests can help expose tests with state problems:\n\n* `pytest-random-order <https://github.com/jbasko/pytest-random-order>`_\n* `pytest-randomly <https://github.com/pytest-dev/pytest-randomly>`_\n\n\nOther general strategies\n^^^^^^^^^^^^^^^^^^^^^^^^\n\nSplit up test suites\n~~~~~~~~~~~~~~~~~~~~\n\nIt can be common to split a single test suite into two, such as unit vs integration, and only use the unit test suite as a CI gate. This also helps keep build times manageable as high level tests tend to be slower. However, it means it does become possible for code that breaks the build to be merged, so extra vigilance is needed for monitoring the integration test results.\n\n\nVideo/screenshot on failure\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nFor UI tests these are important for understanding what the state of the UI was when the test failed. pytest-splinter can be used with plugins like pytest-bdd and can `save a screenshot on test failure <https://pytest-splinter.readthedocs.io/en/latest/#automatic-screenshots-on-test-failure>`_, which can help to isolate the cause.\n\n\nDelete or rewrite the test\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIf the functionality is covered by other tests, perhaps the test can be removed. If not, perhaps it can be rewritten at a lower level which will remove the flakiness or make its source more apparent.\n\n\nQuarantine\n~~~~~~~~~~\n\nMark Lapierre discusses the `Pros and Cons of Quarantined Tests <https://dev.to/mlapierre/pros-and-cons-of-quarantined-tests-2emj>`_ in a post from 2018.\n\n\n\nCI tools that rerun on failure\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAzure Pipelines (the Azure cloud CI/CD tool, formerly Visual Studio Team Services or VSTS) has a feature to `identify flaky tests <https://docs.microsoft.com/en-us/previous-versions/azure/devops/2017/dec-11-vsts?view=tfs-2017#identify-flaky-tests>`_ and rerun failed tests.\n\n\n\nResearch\n^^^^^^^^\n\nThis is a limited list, please submit an issue or pull request to expand it!\n\n* Gao, Zebao, Yalan Liang, Myra B. Cohen, Atif M. Memon, and Zhen Wang. \"Making system user interactive tests repeatable: When and what should we control?.\" In *Software Engineering (ICSE), 2015 IEEE/ACM 37th IEEE International Conference on*, vol. 1, pp. 55-65. IEEE, 2015.  `PDF <http://www.cs.umd.edu/~atif/pubs/gao-icse15.pdf>`__\n* Palomba, Fabio, and Andy Zaidman. \"Does refactoring of test smells induce fixing flaky tests?.\" In *Software Maintenance and Evolution (ICSME), 2017 IEEE International Conference on*, pp. 1-12. IEEE, 2017. `PDF in Google Drive <https://drive.google.com/file/d/10HdcCQiuQVgW3yYUJD-TSTq1NbYEprl0/view>`__\n* Bell, Jonathan, Owolabi Legunsen, Michael Hilton, Lamyaa Eloussi, Tifany Yung, and Darko Marinov. \"DeFlaker: Automatically detecting flaky tests.\" In *Proceedings of the 2018 International Conference on Software Engineering*. 2018. `PDF <https://www.jonbell.net/icse18-deflaker.pdf#section-Research>`__\n* Dutta, Saikat and Shi, August and Choudhary, Rutvik and Zhang, Zhekun and Jain, Aryaman and Misailovic, Sasa. \"Detecting flaky tests in probabilistic and machine learning applications.\" In *Proceedings of the 29th ACM SIGSOFT International Symposium on Software Testing and Analysis (ISSTA)*, pp. 211-224. ACM, 2020. `PDF <https://www.cs.cornell.edu/~saikatd/papers/flash-issta20.pdf>`__\n* Habchi, Sarra and Haben, Guillaume and Sohn, Jeongju and Franci, Adriano and Papadakis, Mike and Cordy, Maxime and Le Traon, Yves. \"What Made This Test Flake? Pinpointing Classes Responsible for Test Flakiness.\" In Proceedings of the 38th IEEE International Conference on Software Maintenance and Evolution (ICSME), IEEE, 2022. `PDF <https://arxiv.org/abs/2207.10143>`__\n* Lamprou, Sokrates. \"Non-deterministic tests and where to find them: Empirically investigating the relationship between flaky tests and test smells by examining test order dependency.\" Bachelor thesis, Department of Computer and Information Science, Linköping University, 2022. LIU-IDA/LITH-EX-G–19/056–SE. `PDF <https://www.diva-portal.org/smash/get/diva2:1713691/FULLTEXT01.pdf>`__\n* Leinen, Fabian and Elsner, Daniel and Pretschner, Alexander and Stahlbauer, Andreas and Sailer, Michael and Jürgens, Elmar. \"Cost of Flaky Tests in Continuous Integration: An Industrial Case Study.\" Technical University of Munich and CQSE GmbH, Munich, Germany, 2023. `PDF <https://mediatum.ub.tum.de/doc/1730194/1730194.pdf>`__\n\nResources\n^^^^^^^^^\n\n* `Eradicating Non-Determinism in Tests <https://martinfowler.com/articles/nonDeterminism.html>`_ by Martin Fowler, 2011\n* `No more flaky tests on the Go team <https://www.thoughtworks.com/insights/blog/no-more-flaky-tests-go-team>`_ by Pavan Sudarshan, 2012\n* `The Build That Cried Broken: Building Trust in your Continuous Integration Tests <https://www.youtube.com/embed/VotJqV4n8ig>`_ talk (video) by `Angie Jones <https://angiejones.tech/>`_ at SeleniumConf Austin 2017\n* `Test and Code Podcast: Flaky Tests and How to Deal with Them <https://testandcode.com/50>`_ by Brian Okken and Anthony Shaw, 2018\n* Microsoft:\n\n  * `How we approach testing VSTS to enable continuous delivery <https://blogs.msdn.microsoft.com/bharry/2017/06/28/testing-in-a-cloud-delivery-cadence/>`_ by Brian Harry MS, 2017\n  * `Eliminating Flaky Tests <https://docs.microsoft.com/en-us/azure/devops/learn/devops-at-microsoft/eliminating-flaky-tests>`_ blog and talk (video) by Munil Shah, 2017\n\n* Google:\n\n  * `Flaky Tests at Google and How We Mitigate Them <https://testing.googleblog.com/2016/05/flaky-tests-at-google-and-how-we.html>`_ by John Micco, 2016\n  * `Where do Google's flaky tests come from? <https://testing.googleblog.com/2017/04/where-do-our-flaky-tests-come-from.html>`_  by Jeff Listfield, 2017\n\n* Dropbox:\n  * `Athena: Our automated build health management system <https://dropbox.tech/infrastructure/athena-our-automated-build-health-management-system>`_ by Utsav Shah, 2019\n  * `How To Manage Flaky Tests in your CI Workflows <https://mill-build.org/blog/4-flaky-tests.html>`_ by Li Haoyi, 2025\n\n* Uber:\n  * `Handling Flaky Unit Tests in Java <https://www.uber.com/blog/handling-flaky-tests-java/>`_ by Uber Engineering, 2021\n  * `Flaky Tests Overhaul at Uber <https://www.uber.com/blog/flaky-tests-overhaul/>`_ by Uber Engineering, 2024\n\n.. _pytest-xdist: https://github.com/pytest-dev/pytest-xdist\n"
  },
  {
    "path": "doc/en/explanation/goodpractices.rst",
    "content": ".. highlight:: python\n.. _`goodpractices`:\n\nGood Integration Practices\n=================================================\n\nInstall package with pip\n-------------------------------------------------\n\nFor development, we recommend you use :mod:`venv` for virtual environments and\n:doc:`pip:index` for installing your application and any dependencies,\nas well as the ``pytest`` package itself.\nThis ensures your code and dependencies are isolated from your system Python installation.\n\nCreate a ``pyproject.toml`` file in the root of your repository as described in\n:doc:`packaging:tutorials/packaging-projects`.\nThe first few lines should look like this:\n\n.. code-block:: toml\n\n    [build-system]\n    requires = [\"hatchling\"]\n    build-backend = \"hatchling.build\"\n\n    [project]\n    name = \"PACKAGENAME\"\n    version = \"PACKAGEVERSION\"\n\nwhere ``PACKAGENAME`` and ``PACKAGEVERSION`` are the name and version of your package respectively.\n\nYou can then install your package in \"editable\" mode by running from the same directory:\n\n.. code-block:: bash\n\n    pip install -e .\n\nwhich lets you change your source code (both tests and application) and rerun tests at will.\n\n.. _`test discovery`:\n.. _`Python test discovery`:\n\nConventions for Python test discovery\n-------------------------------------------------\n\n``pytest`` implements the following standard test discovery:\n\n* If no arguments are specified then collection starts from :confval:`testpaths`\n  (if configured) or the current directory. Alternatively, command line arguments\n  can be used in any combination of directories, file names or node ids.\n* Recurse into directories, unless they match :confval:`norecursedirs`.\n* In those directories, search for ``test_*.py`` or ``*_test.py`` files, imported by their `test package name`_.\n* From those files, collect test items:\n\n  * ``test`` prefixed test functions or methods outside of class.\n  * ``test`` prefixed test functions or methods inside ``Test`` prefixed test classes (without an ``__init__`` method). Methods decorated with ``@staticmethod`` and ``@classmethods`` are also considered.\n\nFor examples of how to customize your test discovery :doc:`/example/pythoncollection`.\n\nWithin Python modules, ``pytest`` also discovers tests using the standard\n:ref:`unittest.TestCase <unittest.TestCase>` subclassing technique.\n\n\n.. _`test layout`:\n\nChoosing a test layout\n----------------------\n\n``pytest`` supports two common test layouts:\n\nTests outside application code\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nPutting tests into an extra directory outside your actual application code\nmight be useful if you have many functional tests or for other reasons want\nto keep tests separate from actual application code (often a good idea):\n\n.. code-block:: text\n\n    pyproject.toml\n    src/\n        mypkg/\n            __init__.py\n            app.py\n            view.py\n    tests/\n        test_app.py\n        test_view.py\n        ...\n\nThis has the following benefits:\n\n* Your tests can run against an installed version after executing ``pip install .``.\n* Your tests can run against the local copy with an editable install after executing ``pip install --editable .``.\n\nFor new projects, we recommend to use ``importlib`` :ref:`import mode <import-modes>`\n(see which-import-mode_ for a detailed explanation).\nTo this end, add the following to your configuration file:\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    [pytest]\n    addopts = [\"--import-mode=importlib\"]\n\n.. _src-layout:\n\nGenerally, but especially if you use the default import mode ``prepend``,\nit is **strongly** suggested to use a ``src`` layout.\nHere, your application root package resides in a sub-directory of your root,\ni.e. ``src/mypkg/`` instead of ``mypkg``.\n\nThis layout prevents a lot of common pitfalls and has many benefits,\nwhich are better explained in this excellent `blog post`_ by Ionel Cristian Mărieș.\n\n.. _blog post: https://blog.ionelmc.ro/2014/05/25/python-packaging/#the-structure>\n\n.. note::\n\n    If you do not use an editable install and use the ``src`` layout as above you need to extend the Python's\n    search path for module files to execute the tests against the local copy directly. You can do it in an\n    ad-hoc manner by setting the ``PYTHONPATH`` environment variable:\n\n    .. code-block:: bash\n\n       PYTHONPATH=src pytest\n\n    or in a permanent manner by using the :confval:`pythonpath` configuration variable and adding the\n    following to your configuration file:\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            pythonpath = [\"src\"]\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            pythonpath = src\n\n.. note::\n\n    If you do not use an editable install and do not use the ``src`` layout (``mypkg`` directly in the root\n    directory) you can rely on the fact that Python by default puts the current directory in ``sys.path`` to\n    import your package and run ``python -m pytest`` to execute the tests against the local copy directly.\n\n    See :ref:`pytest vs python -m pytest` for more information about the difference between calling ``pytest`` and\n    ``python -m pytest``.\n\n.. seealso::\n\n    :doc:`packaging:discussions/src-layout-vs-flat-layout`\n        The Python Packaging User Guide discusses the trade-offs between the ``src`` layout and ``flat`` layout.\n\nTests as part of application code\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nInlining test directories into your application package\nis useful if you have direct relation between tests and application modules and\nwant to distribute them along with your application:\n\n.. code-block:: text\n\n    pyproject.toml\n    [src/]mypkg/\n        __init__.py\n        app.py\n        view.py\n        tests/\n            __init__.py\n            test_app.py\n            test_view.py\n            ...\n\nIn this scheme, it is easy to run your tests using the :option:`--pyargs` option:\n\n.. code-block:: bash\n\n    pytest --pyargs mypkg\n\n``pytest`` will discover where ``mypkg`` is installed and collect tests from there.\n\nNote that this layout also works in conjunction with the ``src`` layout mentioned in the previous section.\n\n\n.. note::\n\n    You can use namespace packages (PEP420) for your application\n    but pytest will still perform `test package name`_ discovery based on the\n    presence of ``__init__.py`` files.  If you use one of the\n    two recommended file system layouts above but leave away the ``__init__.py``\n    files from your directories, it should just work.  From\n    \"inlined tests\", however, you will need to use absolute imports for\n    getting at your application code.\n\n.. _`test package name`:\n\n.. note::\n\n    In ``prepend`` and ``append`` import-modes, if pytest finds a ``\"a/b/test_module.py\"``\n    test file while recursing into the filesystem it determines the import name\n    as follows:\n\n    * determine ``basedir``: this is the first \"upward\" (towards the root)\n      directory not containing an ``__init__.py``.  If e.g. both ``a``\n      and ``b`` contain an ``__init__.py`` file then the parent directory\n      of ``a`` will become the ``basedir``.\n\n    * perform ``sys.path.insert(0, basedir)`` to make the test module\n      importable under the fully qualified import name.\n\n    * ``import a.b.test_module`` where the path is determined\n      by converting path separators ``/`` into \".\" characters.  This means\n      you must follow the convention of having directory and file\n      names map directly to the import names.\n\n    The reason for this somewhat evolved importing technique is\n    that in larger projects multiple test modules might import\n    from each other and thus deriving a canonical import name helps\n    to avoid surprises such as a test module getting imported twice.\n\n    With :option:`--import-mode=importlib` things are less convoluted because\n    pytest doesn't need to change ``sys.path``, making things much less\n    surprising.\n\n\n.. _which-import-mode:\n\nChoosing an import mode\n^^^^^^^^^^^^^^^^^^^^^^^\n\nFor historical reasons, pytest defaults to the ``prepend`` :ref:`import mode <import-modes>`\ninstead of the ``importlib`` import mode we recommend for new projects.\nThe reason lies in the way the ``prepend`` mode works:\n\nSince there are no packages to derive a full package name from,\n``pytest`` will import your test files as *top-level* modules.\nThe test files in the first example (:ref:`src layout <src-layout>`) would be imported as\n``test_app`` and ``test_view`` top-level modules by adding ``tests/`` to ``sys.path``.\n\nThis results in a drawback compared to the import mode ``importlib``:\nyour test files must have **unique names**.\n\nIf you need to have test modules with the same name,\nas a workaround you might add ``__init__.py`` files to your ``tests`` directory and subdirectories,\nchanging them to packages:\n\n.. code-block:: text\n\n    pyproject.toml\n    mypkg/\n        ...\n    tests/\n        __init__.py\n        foo/\n            __init__.py\n            test_view.py\n        bar/\n            __init__.py\n            test_view.py\n\nNow pytest will load the modules as ``tests.foo.test_view`` and ``tests.bar.test_view``,\nallowing you to have modules with the same name.\nBut now this introduces a subtle problem:\nin order to load the test modules from the ``tests`` directory,\npytest prepends the root of the repository to ``sys.path``,\nwhich adds the side-effect that now ``mypkg`` is also importable.\n\nThis is problematic if you are using a tool like tox_ to test your package in a virtual environment,\nbecause you want to test the *installed* version of your package,\nnot the local code from the repository.\n\nThe ``importlib`` import mode does not have any of the drawbacks above,\nbecause ``sys.path`` is not changed when importing test modules.\n\n\n.. _`buildout`: http://www.buildout.org/en/latest/\n\n.. _`use tox`:\n\ntox\n---\n\nOnce you are done with your work and want to make sure that your actual\npackage passes all tests you may want to look into :doc:`tox <tox:index>`, the\nvirtualenv test automation tool.\n``tox`` helps you to setup virtualenv environments with pre-defined\ndependencies and then executing a pre-configured test command with\noptions.  It will run tests against the installed package and not\nagainst your source code checkout, helping to detect packaging\nglitches.\n\nDo not run via setuptools\n-------------------------\n\nIntegration with setuptools is **not recommended**,\ni.e. you should not be using ``python setup.py test`` or ``pytest-runner``,\nand may stop working in the future.\n\nThis is deprecated since it depends on deprecated features of setuptools\nand relies on features that break security mechanisms in pip.\nFor example 'setup_requires' and 'tests_require' bypass ``pip --require-hashes``.\nFor more information and migration instructions,\nsee the `pytest-runner notice <https://github.com/pytest-dev/pytest-runner#deprecation-notice>`_.\nSee also `pypa/setuptools#1684 <https://github.com/pypa/setuptools/issues/1684>`_.\n\nsetuptools intends to\n`remove the test command <https://github.com/pypa/setuptools/issues/931>`_.\n\nChecking with flake8-pytest-style\n---------------------------------\n\nIn order to ensure that pytest is being used correctly in your project,\nit can be helpful to use the `flake8-pytest-style <https://github.com/m-burst/flake8-pytest-style>`_ flake8 plugin.\n\nflake8-pytest-style checks for common mistakes and coding style violations in pytest code,\nsuch as incorrect use of fixtures, test function names, and markers.\nBy using this plugin, you can catch these errors early in the development process\nand ensure that your pytest code is consistent and easy to maintain.\n\nA list of the lints detected by flake8-pytest-style can be found on its `PyPI page <https://pypi.org/project/flake8-pytest-style/>`_.\n\n.. note::\n\n    flake8-pytest-style is not an official pytest project. Some of the rules enforce certain style choices, such as using `@pytest.fixture()` over `@pytest.fixture`, but you can configure the plugin to fit your preferred style.\n\n.. _`strict mode`:\n\nUsing pytest's strict mode\n--------------------------\n\n.. versionadded:: 9.0\n\nPytest contains a set of configuration options that make it more strict.\nThe options are off by default for compatibility or other reasons,\nbut you should enable them if you can.\n\nYou can enable all of the strictness options at once by setting the :confval:`strict` configuration option:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        strict = true\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        strict = true\n\nSee the :confval:`strict` documentation for the options it enables and their effect.\n\nIf pytest adds new strictness options in the future, they will also be enabled in strict mode.\nTherefore, you should only enable strict mode if you use a pinned/locked version of pytest,\nor if you want to proactively adopt new strictness options as they are added.\nIf you don't want to automatically pick up new options, you can enable options individually:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        strict_config = true\n        strict_markers = true\n        strict_parametrization_ids = true\n        strict_xfail = true\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        strict_config = true\n        strict_markers = true\n        strict_parametrization_ids = true\n        strict_xfail = true\n\nIf you want to use strict mode but are having trouble with a specific option, you can turn it off individually:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        strict = true\n        strict_parametrization_ids = false\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        strict = true\n        strict_parametrization_ids = false\n"
  },
  {
    "path": "doc/en/explanation/index.rst",
    "content": ":orphan:\n\n.. _explanation:\n\nExplanation\n================\n\n.. toctree::\n   :maxdepth: 1\n\n   anatomy\n   fixtures\n   goodpractices\n   pythonpath\n   types\n   ci\n   flaky\n"
  },
  {
    "path": "doc/en/explanation/pythonpath.rst",
    "content": ".. _pythonpath:\n\npytest import mechanisms and ``sys.path``/``PYTHONPATH``\n========================================================\n\n.. _`import-modes`:\n\nImport modes\n------------\n\npytest as a testing framework needs to import test modules and ``conftest.py`` files for execution.\n\nImporting files in Python is a non-trivial process, so aspects of the\nimport process can be controlled through the :option:`--import-mode` command-line flag, which can assume\nthese values:\n\n.. _`import-mode-prepend`:\n\n* ``prepend`` (default): The directory path containing each module will be inserted into the *beginning*\n  of :py:data:`sys.path` if not already there, and then imported with\n  the :func:`importlib.import_module <importlib.import_module>` function.\n\n  It is highly recommended to arrange your test modules as packages by adding ``__init__.py`` files to your directories\n  containing tests. This will make the tests part of a proper Python package, allowing pytest to resolve their full\n  name (for example ``tests.core.test_core`` for ``test_core.py`` inside the ``tests.core`` package).\n\n  If the test directory tree is not arranged as packages, then each test file needs to have a unique name\n  compared to the other test files, otherwise pytest will raise an error if it finds two tests with the same name.\n\n  This is the classic mechanism, dating back from the time Python 2 was still supported.\n\n.. _`import-mode-append`:\n\n* ``append``: the directory containing each module is appended to the end of :py:data:`sys.path` if not already\n  there, and imported with :func:`importlib.import_module <importlib.import_module>`.\n\n  This better allows users to run test modules against installed versions of a package even if the\n  package under test has the same import root. For example:\n\n  ::\n\n        testing/__init__.py\n        testing/test_pkg_under_test.py\n        pkg_under_test/\n\n  the tests will run against the installed version\n  of ``pkg_under_test`` when :option:`--import-mode=append` is used whereas\n  with ``prepend``, they would pick up the local version. This kind of confusion is why\n  we advocate for using :ref:`src-layouts <src-layout>`.\n\n  Same as ``prepend``, requires test module names to be unique when the test directory tree is\n  not arranged in packages, because the modules will be put in :py:data:`sys.modules` after importing.\n\n.. _`import-mode-importlib`:\n\n* ``importlib``: this mode uses more fine control mechanisms provided by :mod:`importlib` to import test modules, without changing :py:data:`sys.path`.\n\n  Advantages of this mode:\n\n  * pytest will not change :py:data:`sys.path` at all.\n  * Test module names do not need to be unique -- pytest will generate a unique name automatically based on the ``rootdir``.\n\n  Disadvantages:\n\n  * Test modules can't import each other.\n  * Testing utility modules in the tests directories (for example a ``tests.helpers`` module containing test-related functions/classes)\n    are not importable. The recommendation in this case is to place testing utility modules together with the application/library\n    code, for example ``app.testing.helpers``.\n\n    Important: by \"test utility modules\", we mean functions/classes which are imported by\n    other tests directly; this does not include fixtures, which should be placed in ``conftest.py`` files, along\n    with the test modules, and are discovered automatically by pytest.\n\n  It works like this:\n\n  1. Given a certain module path, for example ``tests/core/test_models.py``, derives a canonical name\n     like ``tests.core.test_models`` and tries to import it.\n\n     For non-test modules, this will work if they are accessible via :py:data:`sys.path`. So\n     for example, ``.env/lib/site-packages/app/core.py`` will be importable as ``app.core``.\n     This happens when plugins import non-test modules (for example doctesting).\n\n     If this step succeeds, the module is returned.\n\n     For test modules, unless they are reachable from :py:data:`sys.path`, this step will fail.\n\n  2. If the previous step fails, we import the module directly using ``importlib`` facilities, which lets us import it without\n     changing :py:data:`sys.path`.\n\n     Because Python requires the module to also be available in :py:data:`sys.modules`, pytest derives a unique name for it based\n     on its relative location from the ``rootdir``, and adds the module to :py:data:`sys.modules`.\n\n     For example, ``tests/core/test_models.py`` will end up being imported as the module ``tests.core.test_models``.\n\n  .. versionadded:: 6.0\n\n.. note::\n\n    Initially we intended to make ``importlib`` the default in future releases, however it is clear now that\n    it has its own set of drawbacks so the default will remain ``prepend`` for the foreseeable future.\n\n.. note::\n\n    By default, pytest will not attempt to resolve namespace packages automatically, but that can\n    be changed via the :confval:`consider_namespace_packages` configuration variable.\n\n.. seealso::\n\n    The :confval:`pythonpath` configuration variable.\n\n    The :confval:`consider_namespace_packages` configuration variable.\n\n    :ref:`test layout`.\n\n\n``prepend`` and ``append`` import modes scenarios\n-------------------------------------------------\n\nHere's a list of scenarios when using ``prepend`` or ``append`` import modes where pytest needs to\nchange :py:data:`sys.path` in order to import test modules or ``conftest.py`` files, and the issues users\nmight encounter because of that.\n\nTest modules / ``conftest.py`` files inside packages\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nConsider this file and directory layout::\n\n    root/\n    |- foo/\n       |- __init__.py\n       |- conftest.py\n       |- bar/\n          |- __init__.py\n          |- tests/\n             |- __init__.py\n             |- test_foo.py\n\n\nWhen executing:\n\n.. code-block:: bash\n\n    pytest root/\n\npytest will find ``foo/bar/tests/test_foo.py`` and realize it is part of a package given that\nthere's an ``__init__.py`` file in the same directory. It will then search upwards until it can find the\nlast directory which still contains an ``__init__.py`` file in order to find the package *root* (in\nthis case ``foo/``). To load the module, it will insert ``root/``  to the front of\n:py:data:`sys.path` (if not there already) in order to load\n``test_foo.py`` as the *module* ``foo.bar.tests.test_foo``.\n\nThe same logic applies to the ``conftest.py`` file: it will be imported as ``foo.conftest`` module.\n\nPreserving the full package name is important when tests live in a package to avoid problems\nand allow test modules to have duplicated names. This is also discussed in detail in\n:ref:`test discovery`.\n\nStandalone test modules / ``conftest.py`` files\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nConsider this file and directory layout::\n\n    root/\n    |- foo/\n       |- conftest.py\n       |- bar/\n          |- tests/\n             |- test_foo.py\n\n\nWhen executing:\n\n.. code-block:: bash\n\n    pytest root/\n\npytest will find ``foo/bar/tests/test_foo.py`` and realize it is NOT part of a package given that\nthere's no ``__init__.py`` file in the same directory. It will then add ``root/foo/bar/tests`` to\n:py:data:`sys.path` in order to import ``test_foo.py`` as the *module* ``test_foo``. The same is done\nwith the ``conftest.py`` file by adding ``root/foo`` to :py:data:`sys.path` to import it as ``conftest``.\n\nFor this reason this layout cannot have test modules with the same name, as they all will be\nimported in the global import namespace.\n\nThis is also discussed in detail in :ref:`test discovery`.\n\n.. _`pytest vs python -m pytest`:\n\nInvoking ``pytest`` versus ``python -m pytest``\n-----------------------------------------------\n\nRunning pytest with ``pytest [...]`` instead of ``python -m pytest [...]`` yields nearly\nequivalent behaviour, except that the latter will add the current directory to :py:data:`sys.path`, which\nis standard ``python`` behavior.\n\nSee also :ref:`invoke-python`.\n"
  },
  {
    "path": "doc/en/explanation/types.rst",
    "content": ".. _types:\n\nTyping in pytest\n================\n\n.. note::\n    This page assumes the reader is familiar with Python's typing system and its advantages.\n\n    For more information, refer to `Python's Typing Documentation <https://docs.python.org/3/library/typing.html>`_.\n\nWhy type tests?\n---------------\n\nTyping tests provides significant advantages:\n\n- **Readability:** Clearly defines expected inputs and outputs, improving readability, especially in complex or parameterized tests.\n\n- **Refactoring:** This is the main benefit in typing tests, as it will greatly help with refactoring, letting the type checker point out the necessary changes in both production and tests, without needing to run the full test suite.\n\nFor production code, typing also helps catching some bugs that might not be caught by tests at all (regardless of coverage), for example:\n\n.. code-block:: python\n\n    def get_caption(target: int, items: list[tuple[int, str]]) -> str:\n        for value, caption in items:\n            if value == target:\n                return caption\n\n\nThe type checker will correctly error out that the function might return `None`, however even a full coverage test suite might miss that case:\n\n.. code-block:: python\n\n    def test_get_caption() -> None:\n        assert get_caption(10, [(1, \"foo\"), (10, \"bar\")]) == \"bar\"\n\n\nNote the code above has 100% coverage, but the bug is not caught (of course the example is \"obvious\", but serves to illustrate the point).\n\n\n\nUsing typing in test suites\n---------------------------\n\nTo type fixtures in pytest, just add normal types to the fixture functions -- there is nothing special that needs to be done just because of the `fixture` decorator.\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.fixture\n    def sample_fixture() -> int:\n        return 38\n\nIn the same manner, the fixtures passed to test functions need be annotated with the fixture's return type:\n\n.. code-block:: python\n\n    def test_sample_fixture(sample_fixture: int) -> None:\n        assert sample_fixture == 38\n\nFrom the POV of the type checker, it does not matter that `sample_fixture` is actually a fixture managed by pytest, all it matters to it is that `sample_fixture` is a parameter of type `int`.\n\n\nThe same logic applies to :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`:\n\n.. code-block:: python\n\n\n    @pytest.mark.parametrize(\"input_value, expected_output\", [(1, 2), (5, 6), (10, 11)])\n    def test_increment(input_value: int, expected_output: int) -> None:\n        assert input_value + 1 == expected_output\n\n\nThe same logic applies when typing fixture functions which receive other fixtures:\n\n.. code-block:: python\n\n    @pytest.fixture\n    def mock_env_user(monkeypatch: pytest.MonkeyPatch) -> None:\n        monkeypatch.setenv(\"USER\", \"TestingUser\")\n\n\nConclusion\n----------\n\nIncorporating typing into pytest tests enhances **clarity**, improves **debugging** and **maintenance**, and ensures **type safety**.\nThese practices lead to a **robust**, **readable**, and **easily maintainable** test suite that is better equipped to handle future changes with minimal risk of errors.\n"
  },
  {
    "path": "doc/en/funcarg_compare.rst",
    "content": ":orphan:\n\n.. _`funcargcompare`:\n\npytest-2.3: reasoning for fixture/funcarg evolution\n=============================================================\n\n**Target audience**: Reading this document requires basic knowledge of\npython testing, xUnit setup methods and the (previous) basic pytest\nfuncarg mechanism, see :ref:`historical funcargs and pytest.funcargs`.\nIf you are new to pytest, then you can simply ignore this\nsection and read the other sections.\n\nShortcomings of the previous ``pytest_funcarg__`` mechanism\n--------------------------------------------------------------\n\nThe pre pytest-2.3 funcarg mechanism calls a factory each time a\nfuncarg for a test function is required.  If a factory wants to\nreuse a resource across different scopes, it often used\nthe ``request.cached_setup()`` helper to manage caching of\nresources.  Here is a basic example of how we could implement\na per-session Database object:\n\n.. code-block:: python\n\n    # content of conftest.py\n    class Database:\n        def __init__(self):\n            print(\"database instance created\")\n\n        def destroy(self):\n            print(\"database instance destroyed\")\n\n\n    def pytest_funcarg__db(request):\n        return request.cached_setup(\n            setup=DataBase, teardown=lambda db: db.destroy, scope=\"session\"\n        )\n\nThere are several limitations and difficulties with this approach:\n\n1. Scoping funcarg resource creation is not straightforward, instead one must\n   understand the intricate cached_setup() method mechanics.\n\n2. parametrizing the \"db\" resource is not straightforward:\n   you need to apply a \"parametrize\" decorator or implement a\n   :hook:`pytest_generate_tests` hook\n   calling :py:func:`~pytest.Metafunc.parametrize` which\n   performs parametrization at the places where the resource\n   is used.  Moreover, you need to modify the factory to use an\n   ``extrakey`` parameter containing ``request.param`` to the\n   ``Request.cached_setup`` call.\n\n3. Multiple parametrized session-scoped resources will be active\n   at the same time, making it hard for them to affect global state\n   of the application under test.\n\n4. there is no way you can make use of funcarg factories\n   in xUnit setup methods.\n\n5. A non-parametrized fixture function cannot use a parametrized\n   funcarg resource if it isn't stated in the test function signature.\n\nAll of these limitations are addressed with pytest-2.3 and its\nimproved :ref:`fixture mechanism <fixture>`.\n\n\nDirect scoping of fixture/funcarg factories\n--------------------------------------------------------\n\nInstead of calling cached_setup() with a cache scope, you can use the\n:ref:`@pytest.fixture <pytest.fixture>` decorator and directly state\nthe scope:\n\n.. code-block:: python\n\n    @pytest.fixture(scope=\"session\")\n    def db(request):\n        # factory will only be invoked once per session -\n        db = DataBase()\n        request.addfinalizer(db.destroy)  # destroy when session is finished\n        return db\n\nThis factory implementation does not need to call ``cached_setup()`` anymore\nbecause it will only be invoked once per session.  Moreover, the\n``request.addfinalizer()`` registers a finalizer according to the specified\nresource scope on which the factory function is operating.\n\n\nDirect parametrization of funcarg resource factories\n----------------------------------------------------------\n\nPreviously, funcarg factories could not directly cause parametrization.\nYou needed to specify a ``@parametrize`` decorator on your test function\nor implement a :hook:`pytest_generate_tests` hook to perform\nparametrization, i.e. calling a test multiple times with different value\nsets.  pytest-2.3 introduces a decorator for use on the factory itself:\n\n.. code-block:: python\n\n    @pytest.fixture(params=[\"mysql\", \"pg\"])\n    def db(request): ...  # use request.param\n\nHere the factory will be invoked twice (with the respective \"mysql\"\nand \"pg\" values set as ``request.param`` attributes) and all of\nthe tests requiring \"db\" will run twice as well.  The \"mysql\" and\n\"pg\" values will also be used for reporting the test-invocation variants.\n\nThis new way of parametrizing funcarg factories should in many cases\nallow to reuse already written factories because effectively\n``request.param`` was already used when test functions/classes were\nparametrized via\n:py:func:`metafunc.parametrize(indirect=True) <pytest.Metafunc.parametrize>` calls.\n\nOf course it's perfectly fine to combine parametrization and scoping:\n\n.. code-block:: python\n\n    @pytest.fixture(scope=\"session\", params=[\"mysql\", \"pg\"])\n    def db(request):\n        if request.param == \"mysql\":\n            db = MySQL()\n        elif request.param == \"pg\":\n            db = PG()\n        request.addfinalizer(db.destroy)  # destroy when session is finished\n        return db\n\nThis would execute all tests requiring the per-session \"db\" resource twice,\nreceiving the values created by the two respective invocations to the\nfactory function.\n\n\nNo ``pytest_funcarg__`` prefix when using @fixture decorator\n-------------------------------------------------------------------\n\nWhen using the ``@fixture`` decorator the name of the function\ndenotes the name under which the resource can be accessed as a function\nargument:\n\n.. code-block:: python\n\n    @pytest.fixture()\n    def db(request): ...\n\nThe name under which the funcarg resource can be requested is ``db``.\n\nYou can still use the \"old\" non-decorator way of specifying funcarg factories\naka:\n\n.. code-block:: python\n\n    def pytest_funcarg__db(request): ...\n\n\nBut it is then not possible to define scoping and parametrization.\nIt is thus recommended to use the factory decorator.\n\n\nsolving per-session setup / autouse fixtures\n--------------------------------------------------------------\n\npytest for a long time offered a pytest_configure and a pytest_sessionstart\nhook which are often used to setup global resources.  This suffers from\nseveral problems:\n\n1. in distributed testing the managing process would setup test resources\n   that are never needed because it only coordinates the test run\n   activities of the worker processes.\n\n2. if you only perform a collection (with \"--collect-only\")\n   resource-setup will still be executed.\n\n3. If a pytest_sessionstart is contained in some subdirectories\n   conftest.py file, it will not be called.  This stems from the\n   fact that this hook is actually used for reporting, in particular\n   the test-header with platform/custom information.\n\nMoreover, it was not easy to define a scoped setup from plugins or\nconftest files other than to implement a ``pytest_runtest_setup()`` hook\nand caring for scoping/caching yourself.  And it's virtually impossible\nto do this with parametrization as ``pytest_runtest_setup()`` is called\nduring test execution and parametrization happens at collection time.\n\nIt follows that pytest_configure/session/runtest_setup are often not\nappropriate for implementing common fixture needs.  Therefore,\npytest-2.3 introduces :ref:`autouse fixtures` which fully\nintegrate with the generic :ref:`fixture mechanism <fixture>`\nand obsolete many prior uses of pytest hooks.\n\nfuncargs/fixture discovery now happens at collection time\n---------------------------------------------------------------------\n\nSince pytest-2.3, discovery of fixture/funcarg factories are taken care of\nat collection time.  This is more efficient especially for large test suites.\nMoreover, a call to \"pytest --collect-only\" should be able to in the future\nshow a lot of setup-information and thus presents a nice method to get an\noverview of fixture management in your project.\n\n.. _`compatibility notes`:\n\n.. _`funcargscompat`:\n\nConclusion and compatibility notes\n---------------------------------------------------------\n\n**funcargs** were originally introduced to pytest-2.0.  In pytest-2.3\nthe mechanism was extended and refined and is now described as\nfixtures:\n\n* previously funcarg factories were specified with a special\n  ``pytest_funcarg__NAME`` prefix instead of using the\n  ``@pytest.fixture`` decorator.\n\n* Factories received a ``request`` object which managed caching through\n  ``request.cached_setup()`` calls and allowed using other funcargs via\n  ``request.getfuncargvalue()`` calls.  These intricate APIs made it hard\n  to do proper parametrization and implement resource caching. The\n  new :py:func:`pytest.fixture` decorator allows to declare the scope\n  and let pytest figure things out for you.\n\n* if you used parametrization and funcarg factories which made use of\n  ``request.cached_setup()`` it is recommended to invest a few minutes\n  and simplify your fixture function code to use the :ref:`@pytest.fixture`\n  decorator instead.  This will also allow to take advantage of\n  the automatic per-resource grouping of tests.\n"
  },
  {
    "path": "doc/en/funcargs.rst",
    "content": "\n=======================================================\nfuncargs: resource injection and parametrization\n=======================================================\n\npytest-2.3 introduces major refinements to fixture management\nof which the funcarg mechanism introduced with pytest-2.0 remains\na core part.  The documentation has been refactored as well\nand you can read on here:\n\n- :ref:`fixtures`\n- :ref:`parametrize`\n- :ref:`funcargcompare`\n"
  },
  {
    "path": "doc/en/getting-started.rst",
    "content": ".. _get-started:\n\nGet Started\n===================================\n\n.. _`getstarted`:\n.. _`installation`:\n\nInstall ``pytest``\n----------------------------------------\n\n1. Run the following command in your command line:\n\n.. code-block:: bash\n\n    pip install -U pytest\n\n2. Check that you installed the correct version:\n\n.. code-block:: bash\n\n    $ pytest --version\n    pytest 9.0.2\n\n.. _`simpletest`:\n\nCreate your first test\n----------------------------------------------------------\n\nCreate a new file called ``test_sample.py``, containing a function, and a test:\n\n.. code-block:: python\n\n    # content of test_sample.py\n    def func(x):\n        return x + 1\n\n\n    def test_answer():\n        assert func(3) == 5\n\nThe test\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_sample.py F                                                     [100%]\n\n    ================================= FAILURES =================================\n    _______________________________ test_answer ________________________________\n\n        def test_answer():\n    >       assert func(3) == 5\n    E       assert 4 == 5\n    E        +  where 4 = func(3)\n\n    test_sample.py:6: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_sample.py::test_answer - assert 4 == 5\n    ============================ 1 failed in 0.12s =============================\n\nThe ``[100%]`` refers to the overall progress of running all test cases. After it finishes, pytest then shows a failure report because ``func(3)`` does not return ``5``.\n\n.. note::\n\n    You can use the ``assert`` statement to verify test expectations. pytest’s :ref:`Advanced assertion introspection <python:assert>` will intelligently report intermediate values of the assert expression so you can avoid the many names :ref:`of JUnit legacy methods <testcase-objects>`.\n\nRun multiple tests\n----------------------------------------------------------\n\n``pytest`` will run all files of the form ``test_*.py`` or ``*_test.py`` in the current directory and its subdirectories. More generally, it follows :ref:`standard test discovery rules <test discovery>`.\n\n\nAssert that a certain exception is raised\n--------------------------------------------------------------\n\nUse the :ref:`raises <assertraises>` helper to assert that some code raises an exception:\n\n.. code-block:: python\n\n    # content of test_sysexit.py\n    import pytest\n\n\n    def f():\n        raise SystemExit(1)\n\n\n    def test_mytest():\n        with pytest.raises(SystemExit):\n            f()\n\nExecute the test function with “quiet” reporting mode:\n\n.. code-block:: pytest\n\n    $ pytest -q test_sysexit.py\n    .                                                                    [100%]\n    1 passed in 0.12s\n\n.. note::\n\n    The ``-q/--quiet`` flag keeps the output brief in this and following examples.\n\nSee :ref:`assertraises` for specifying more details about the expected exception.\n\nGroup multiple tests in a class\n--------------------------------------------------------------\n\n.. regendoc:wipe\n\nOnce you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a class containing more than one test:\n\n.. code-block:: python\n\n    # content of test_class.py\n    class TestClass:\n        def test_one(self):\n            x = \"this\"\n            assert \"h\" in x\n\n        def test_two(self):\n            x = \"hello\"\n            assert hasattr(x, \"check\")\n\n``pytest`` discovers all tests following its :ref:`Conventions for Python test discovery <test discovery>`, so it finds both ``test_`` prefixed functions. There is no need to subclass anything, but make sure to prefix your class with ``Test`` otherwise the class will be skipped. We can simply run the module by passing its filename:\n\n.. code-block:: pytest\n\n    $ pytest -q test_class.py\n    .F                                                                   [100%]\n    ================================= FAILURES =================================\n    ____________________________ TestClass.test_two ____________________________\n\n    self = <test_class.TestClass object at 0xdeadbeef0001>\n\n        def test_two(self):\n            x = \"hello\"\n    >       assert hasattr(x, \"check\")\n    E       AssertionError: assert False\n    E        +  where False = hasattr('hello', 'check')\n\n    test_class.py:8: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_class.py::TestClass::test_two - AssertionError: assert False\n    1 failed, 1 passed in 0.12s\n\nThe first test passed and the second failed. You can easily see the intermediate values in the assertion to help you understand the reason for the failure.\n\nGrouping tests in classes can be beneficial for the following reasons:\n\n * Test organization\n * Sharing fixtures for tests only in that particular class\n * Applying marks at the class level and having them implicitly apply to all tests\n\nSomething to be aware of when grouping tests inside classes is that each test has a unique instance of the class.\nHaving each test share the same class instance would be very detrimental to test isolation and would promote poor test practices.\nThis is outlined below:\n\n.. regendoc:wipe\n\n.. code-block:: python\n\n    # content of test_class_demo.py\n    class TestClassDemoInstance:\n        value = 0\n\n        def test_one(self):\n            self.value = 1\n            assert self.value == 1\n\n        def test_two(self):\n            assert self.value == 1\n\n\n.. code-block:: pytest\n\n    $ pytest -k TestClassDemoInstance -q\n    .F                                                                   [100%]\n    ================================= FAILURES =================================\n    ______________________ TestClassDemoInstance.test_two ______________________\n\n    self = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef0002>\n\n        def test_two(self):\n    >       assert self.value == 1\n    E       assert 0 == 1\n    E        +  where 0 = <test_class_demo.TestClassDemoInstance object at 0xdeadbeef0002>.value\n\n    test_class_demo.py:9: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_class_demo.py::TestClassDemoInstance::test_two - assert 0 == 1\n    1 failed, 1 passed in 0.12s\n\nNote that attributes added at class level are *class attributes*, so they will be shared between tests.\n\nCompare floating-point values with pytest.approx\n--------------------------------------------------------------\n\n``pytest`` also provides a number of utilities to make writing tests easier.\nFor example, you can use :func:`pytest.approx` to compare floating-point\nvalues that may have small rounding errors:\n\n.. code-block:: python\n\n    # content of test_approx.py\n    import pytest\n\n\n    def test_sum():\n        assert (0.1 + 0.2) == pytest.approx(0.3)\n\nThis avoids the need for manual tolerance checks or using\n``math.isclose`` and works with scalars, lists, and NumPy arrays.\n\n\nRequest a unique temporary directory for functional tests\n--------------------------------------------------------------\n\n``pytest`` provides :std:doc:`Builtin fixtures/function arguments <builtin>` to request arbitrary resources, like a unique temporary directory:\n\n.. code-block:: python\n\n    # content of test_tmp_path.py\n    def test_needsfiles(tmp_path):\n        print(tmp_path)\n        assert 0\n\nList the name ``tmp_path`` in the test function signature and ``pytest`` will lookup and call a fixture factory to create the resource before performing the test function call. Before the test runs, ``pytest`` creates a unique-per-test-invocation temporary directory:\n\n.. code-block:: pytest\n\n    $ pytest -q test_tmp_path.py\n    F                                                                    [100%]\n    ================================= FAILURES =================================\n    _____________________________ test_needsfiles ______________________________\n\n    tmp_path = PosixPath('PYTEST_TMPDIR/test_needsfiles0')\n\n        def test_needsfiles(tmp_path):\n            print(tmp_path)\n    >       assert 0\n    E       assert 0\n\n    test_tmp_path.py:3: AssertionError\n    --------------------------- Captured stdout call ---------------------------\n    PYTEST_TMPDIR/test_needsfiles0\n    ========================= short test summary info ==========================\n    FAILED test_tmp_path.py::test_needsfiles - assert 0\n    1 failed in 0.12s\n\nMore info on temporary directory handling is available at :ref:`Temporary directories and files <tmp_path handling>`.\n\nFind out what kind of builtin :ref:`pytest fixtures <fixtures>` exist with the command:\n\n.. code-block:: bash\n\n    pytest --fixtures   # shows builtin and custom fixtures\n\nNote that this command omits fixtures with leading ``_`` unless the :option:`-v` option is added.\n\nContinue reading\n-------------------------------------\n\nCheck out additional pytest resources to help you customize tests for your unique workflow:\n\n* \":ref:`usage`\" for command line invocation examples\n* \":ref:`existingtestsuite`\" for working with preexisting tests\n* \":ref:`mark`\" for information on the ``pytest.mark`` mechanism\n* \":ref:`fixtures`\" for providing a functional baseline to your tests\n* \":ref:`plugins`\" for managing and writing plugins\n* \":ref:`goodpractices`\" for virtualenv and test layouts\n"
  },
  {
    "path": "doc/en/historical-notes.rst",
    "content": "Historical Notes\n================\n\nThis page lists features or behavior from previous versions of pytest which have changed over the years. They are\nkept here as a historical note so users looking at old code can find documentation related to them.\n\n\n.. _marker-revamp:\n\nMarker revamp and iteration\n---------------------------\n\n.. versionchanged:: 3.6\n\npytest's marker implementation traditionally worked by simply updating the ``__dict__`` attribute of functions to cumulatively add markers. As a result, markers would unintentionally be passed along class hierarchies in surprising ways. Further, the API for retrieving them was inconsistent, as markers from parameterization would be stored differently than markers applied using the ``@pytest.mark`` decorator and markers added via ``node.add_marker``.\n\nThis state of things made it technically next to impossible to use data from markers correctly without having a deep understanding of the internals, leading to subtle and hard to understand bugs in more advanced usages.\n\nDepending on how a marker got declared/changed one would get either a ``MarkerInfo`` which might contain markers from sibling classes,\n``MarkDecorators`` when marks came from parameterization or from a ``node.add_marker`` call, discarding prior marks. Also ``MarkerInfo`` acts like a single mark, when it in fact represents a merged view on multiple marks with the same name.\n\nOn top of that markers were not accessible in the same way for modules, classes, and functions/methods.\nIn fact, markers were only accessible in functions, even if they were declared on classes/modules.\n\nA new API to access markers has been introduced in pytest 3.6 in order to solve the problems with\nthe initial design, providing the :func:`_pytest.nodes.Node.iter_markers` method to iterate over\nmarkers in a consistent manner and reworking the internals, which solved a great deal of problems\nwith the initial design.\n\n\n.. _update marker code:\n\nUpdating code\n~~~~~~~~~~~~~\n\nThe old ``Node.get_marker(name)`` function is considered deprecated because it returns an internal ``MarkerInfo`` object\nwhich contains the merged name, ``*args`` and ``**kwargs`` of all the markers which apply to that node.\n\nIn general there are two scenarios on how markers should be handled:\n\n1. Marks overwrite each other. Order matters but you only want to think of your mark as a single item. E.g.\n``log_level('info')`` at a module level can be overwritten by ``log_level('debug')`` for a specific test.\n\n    In this case, use ``Node.get_closest_marker(name)``:\n\n    .. code-block:: python\n\n        # replace this:\n        marker = item.get_marker(\"log_level\")\n        if marker:\n            level = marker.args[0]\n\n        # by this:\n        marker = item.get_closest_marker(\"log_level\")\n        if marker:\n            level = marker.args[0]\n\n2. Marks compose in an additive manner. E.g. ``skipif(condition)`` marks mean you just want to evaluate all of them,\norder doesn't even matter. You probably want to think of your marks as a set here.\n\n   In this case iterate over each mark and handle their ``*args`` and ``**kwargs`` individually.\n\n   .. code-block:: python\n\n        # replace this\n        skipif = item.get_marker(\"skipif\")\n        if skipif:\n            for condition in skipif.args:\n                # eval condition\n                ...\n\n        # by this:\n        for skipif in item.iter_markers(\"skipif\"):\n            condition = skipif.args[0]\n            # eval condition\n\n\nIf you are unsure or have any questions, please consider opening\n:issue:`an issue <new>`.\n\nRelated issues\n~~~~~~~~~~~~~~\n\nHere is a non-exhaustive list of issues fixed by the new implementation:\n\n* Marks don't pick up nested classes (:issue:`199`).\n\n* Markers stain on all related classes (:issue:`568`).\n\n* Combining marks - args and kwargs calculation (:issue:`2897`).\n\n* ``request.node.get_marker('name')`` returns ``None`` for markers applied in classes (:issue:`902`).\n\n* Marks applied in parametrize are stored as markdecorator (:issue:`2400`).\n\n* Fix marker interaction in a backward incompatible way (:issue:`1670`).\n\n* Refactor marks to get rid of the current \"marks transfer\" mechanism (:issue:`2363`).\n\n* Introduce FunctionDefinition node, use it in generate_tests (:issue:`2522`).\n\n* Remove named marker attributes and collect markers in items (:issue:`891`).\n\n* skipif mark from parametrize hides module level skipif mark (:issue:`1540`).\n\n* skipif + parametrize not skipping tests (:issue:`1296`).\n\n* Marker transfer incompatible with inheritance (:issue:`535`).\n\nMore details can be found in the :pr:`original PR <3317>`.\n\n.. note::\n\n    in a future major release of pytest we will introduce class based markers,\n    at which point markers will no longer be limited to instances of :py:class:`~pytest.Mark`.\n\n\ncache plugin integrated into the core\n-------------------------------------\n\n\n\nThe functionality of the :ref:`core cache <cache>` plugin was previously distributed\nas a third party plugin named ``pytest-cache``.  The core plugin\nis compatible regarding command line options and API usage except that you\ncan only store/receive data between test runs that is json-serializable.\n\n.. _historical funcargs and pytest.funcargs:\n\nfuncargs and ``pytest_funcarg__``\n---------------------------------\n\n\n\nIn versions prior to 2.3 there was no ``@pytest.fixture`` marker\nand you had to use a magic ``pytest_funcarg__NAME`` prefix\nfor the fixture factory.  This remains and will remain supported\nbut is not anymore advertised as the primary means of declaring fixture\nfunctions.\n\n\n``@pytest.yield_fixture`` decorator\n-----------------------------------\n\n\n\nPrior to version 2.10, in order to use a ``yield`` statement to execute teardown code one\nhad to mark a fixture using the ``yield_fixture`` marker. From 2.10 onward, normal\nfixtures can use ``yield`` directly so the ``yield_fixture`` decorator is no longer needed\nand considered deprecated.\n\n\n``[pytest]`` header in ``setup.cfg``\n------------------------------------\n\n\n\nPrior to 3.0, the supported section name was ``[pytest]``. Due to how\nthis may collide with some distutils commands, the recommended\nsection name for ``setup.cfg`` files is now ``[tool:pytest]``.\n\nNote that for ``pytest.ini`` and ``tox.ini`` files the section\nname is ``[pytest]``.\n\n\nApplying marks to ``@pytest.mark.parametrize`` parameters\n---------------------------------------------------------\n\n\n\nPrior to version 3.1 the supported mechanism for marking values\nused the syntax:\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.mark.parametrize(\n        \"test_input,expected\", [(\"3+5\", 8), (\"2+4\", 6), pytest.mark.xfail((\"6*9\", 42))]\n    )\n    def test_eval(test_input, expected):\n        assert eval(test_input) == expected\n\n\nThis was an initial hack to support the feature but soon was demonstrated to be incomplete,\nbroken for passing functions or applying multiple marks with the same name but different parameters.\n\nThe old syntax is planned to be removed in pytest-4.0.\n\n\n``@pytest.mark.parametrize`` argument names as a tuple\n------------------------------------------------------\n\n\n\nIn versions prior to 2.4 one needed to specify the argument\nnames as a tuple.  This remains valid but the simpler ``\"name1,name2,...\"``\ncomma-separated-string syntax is now advertised first because\nit's easier to write and produces less line noise.\n\n\nsetup: is now an \"autouse fixture\"\n----------------------------------\n\n\n\nDuring development prior to the pytest-2.3 release the name\n``pytest.setup`` was used but before the release it was renamed\nand moved to become part of the general fixture mechanism,\nnamely :ref:`autouse fixtures`\n\n\n.. _string conditions:\n\nConditions as strings instead of booleans\n-----------------------------------------\n\n\n\nPrior to pytest-2.4 the only way to specify skipif/xfail conditions was\nto use strings:\n\n.. code-block:: python\n\n    import sys\n\n\n    @pytest.mark.skipif(\"sys.version_info >= (3,3)\")\n    def test_function(): ...\n\nDuring test function setup the skipif condition is evaluated by calling\n``eval('sys.version_info >= (3,0)', namespace)``.  The namespace contains\nall the module globals, and ``os`` and ``sys`` as a minimum.\n\nSince pytest-2.4 :ref:`boolean conditions <condition booleans>` are considered preferable\nbecause markers can then be freely imported between test modules.\nWith strings you need to import not only the marker but all variables\nused by the marker, which violates encapsulation.\n\nThe reason for specifying the condition as a string was that ``pytest`` can\nreport a summary of skip conditions based purely on the condition string.\nWith conditions as booleans you are required to specify a ``reason`` string.\n\nNote that string conditions will remain fully supported and you are free\nto use them if you have no need for cross-importing markers.\n\nThe evaluation of a condition string in ``pytest.mark.skipif(conditionstring)``\nor ``pytest.mark.xfail(conditionstring)`` takes place in a namespace\ndictionary which is constructed as follows:\n\n* the namespace is initialized by putting the ``sys`` and ``os`` modules\n  and the pytest ``config`` object into it.\n\n* updated with the module globals of the test function for which the\n  expression is applied.\n\nThe pytest ``config`` object allows you to skip based on a test\nconfiguration value which you might have added:\n\n.. code-block:: python\n\n    @pytest.mark.skipif(\"not config.getvalue('db')\")\n    def test_function(): ...\n\nThe equivalent with \"boolean conditions\" using ``request.config`` is:\n\n.. code-block:: python\n\n    @pytest.fixture(autouse=True)\n    def skip_if_no_db(request):\n        if not request.config.getoption(\"--db\", default=False):\n            pytest.skip(\"--db was not specified\")\n\n\n    def test_function():\n        pass\n\n.. note::\n\n    ``pytest.config`` was removed in pytest 5.0. Use ``request.config``\n    (via the ``request`` fixture) or the ``pytestconfig`` fixture instead.\n    See :ref:`pytest.config global deprecated` for details.\n\n``pytest.set_trace()``\n----------------------\n\n\n\nPrevious to version 2.4 to set a break point in code one needed to use ``pytest.set_trace()``:\n\n.. code-block:: python\n\n    import pytest\n\n\n    def test_function():\n        ...\n        pytest.set_trace()  # invoke PDB debugger and tracing\n\n\nThis is no longer needed and one can use the native ``import pdb;pdb.set_trace()`` call directly.\n\nFor more details see :ref:`breakpoints`.\n\n\"compat\" properties\n-------------------\n\n\n\nAccess of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances has long\nbeen documented as deprecated, but started to emit warnings from pytest ``3.9`` and onward.\n\nUsers should just ``import pytest`` and access those objects using the ``pytest`` module.\n"
  },
  {
    "path": "doc/en/history.rst",
    "content": "History\n=======\n\npytest has a long and interesting history. The `first commit\n<https://github.com/pytest-dev/pytest/commit/5992a8ef21424d7571305a8d7e2a3431ee7e1e23>`__\nin this repository is from January 2007, and even that commit alone already\ntells a lot: The repository originally was from the :pypi:`py`\nlibrary (later split off to pytest), and it\noriginally was a SVN revision, migrated to Mercurial, and finally migrated to\ngit.\n\nHowever, the commit says “create the new development trunk” and is\nalready quite big: *435 files changed, 58640 insertions(+)*. This is because\npytest originally was born as part of `PyPy <https://www.pypy.org/>`__, to make\nit easier to write tests for it. Here's how it evolved from there to its own\nproject:\n\n\n-  Late 2002 / early 2003, `PyPy was\n   born <https://morepypy.blogspot.com/2018/09/the-first-15-years-of-pypy.html>`__.\n-  Like that blog post mentioned, from very early on, there was a big\n   focus on testing. There were various ``testsupport`` files on top of\n   unittest.py, and as early as June 2003, Holger Krekel (:user:`hpk42`)\n   `refactored <https://mail.python.org/pipermail/pypy-dev/2003-June/000787.html>`__\n   its test framework to clean things up (``pypy.tool.test``, but still\n   on top of ``unittest.py``, with nothing pytest-like yet).\n-  In December 2003, there was `another\n   iteration <https://foss.heptapod.net/pypy/pypy/-/commit/02752373e1b29d89c6bb0a97e5f940caa22bdd63>`__\n   at improving their testing situation, by Stefan Schwarzer, called\n   ``pypy.tool.newtest``.\n-  However, it didn’t seem to be around for long, as around June/July\n   2004, efforts started on a thing called ``utest``, offering plain\n   assertions. This seems like the start of something pytest-like, but\n   unfortunately, it's unclear where the test runner's code was at the time.\n   The closest thing still around is `this\n   file <https://foss.heptapod.net/pypy/pypy/-/commit/0735f9ed287ec20950a7dd0a16fc10810d4f6847>`__,\n   but that doesn’t seem like a complete test runner at all. What can be seen\n   is that there were `various\n   efforts <https://foss.heptapod.net/pypy/pypy/-/commits/branch/default?utf8=%E2%9C%93&search=utest>`__\n   by Laura Creighton and Samuele Pedroni (:user:`pedronis`) at automatically\n   converting existing tests to the new ``utest`` framework.\n-  Around the same time, for Europython 2004, @hpk42 `started a\n   project <http://web.archive.org/web/20041020215353/http://codespeak.net/svn/user/hpk/talks/std-talk.txt>`__\n   originally called “std”, intended to be a “complementary standard\n   library” - already laying out the principles behind what later became\n   pytest:\n\n       -  current “batteries included” are very useful, but\n\n          -  some of them are written in a pretty much java-like style,\n             especially the unittest-framework\n          -  […]\n          -  the best API is one that doesn’t exist\n\n       […]\n\n       -  a testing package should require as few boilerplate code as\n          possible and offer much flexibility\n       -  it should provide premium quality tracebacks and debugging aid\n\n       […]\n\n       -  first of all … forget about limited “assertXYZ APIs” and use the\n          real thing, e.g.::\n\n              assert x == y\n\n       -  this works with plain python but you get unhelpful “assertion\n          failed” errors with no information\n\n       -  std.utest (magic!) actually reinterprets the assertion expression\n          and offers detailed information about underlying values\n\n-  In September 2004, the ``py-dev`` mailinglist gets born, which `is\n   now <https://mail.python.org/pipermail/pytest-dev/>`__ ``pytest-dev``,\n   but thankfully with all the original archives still intact.\n\n-  Around September/October 2004, the ``std`` project `was renamed\n   <https://mail.python.org/pipermail/pypy-dev/2004-September/001565.html>`__ to\n   ``py`` and ``std.utest`` became ``py.test``. This is also the first time the\n   `entire source\n   code <https://foss.heptapod.net/pypy/pypy/-/commit/42cf50c412026028e20acd23d518bd92e623ac11>`__,\n   seems to be available, with much of the API still being around today:\n\n   -  ``py.path.local``, which is being phased out of pytest (in favour of\n      pathlib) some 16-17 years later\n   -  The idea of the collection tree, including ``Collector``,\n      ``FSCollector``, ``Directory``, ``PyCollector``, ``Module``,\n      ``Class``\n   -  Arguments like ``-x`` / ``--exitfirst``, ``-l`` /\n      ``--showlocals``, ``--fulltrace``, ``--pdb``, ``-S`` /\n      ``--nocapture`` (``-s`` / ``--capture=off`` today),\n      ``--collectonly`` (``--collect-only`` today)\n\n-  In the same month, the ``py`` library `gets split off\n   <https://foss.heptapod.net/pypy/pypy/-/commit/6bdafe9203ad92eb259270b267189141c53bce33>`__\n   from ``PyPy``\n\n-  It seemed to get rather quiet for a while, and little seemed to happen\n   between October 2004 (removing ``py`` from PyPy) and January\n   2007 (first commit in the now-pytest repository). However, there were\n   various discussions about features/ideas on the mailinglist, and\n   :pypi:`a couple of releases <py/0.8.0-alpha2/#history>` every\n   couple of months:\n\n   -  March 2006: py 0.8.0-alpha2\n   -  May 2007: py 0.9.0\n   -  March 2008: py 0.9.1 (first release to be found `in the pytest\n      changelog <https://github.com/pytest-dev/pytest/blob/main/doc/en/changelog.rst#091>`__!)\n   -  August 2008: py 0.9.2\n\n-  In August 2009, py 1.0.0 was released, `introducing a lot of\n   fundamental\n   features <https://holgerkrekel.net/2009/08/04/pylib-1-0-0-released-the-testing-with-python-innovations-continue/>`__:\n\n   -  funcargs/fixtures\n   -  A `plugin\n      architecture <http://web.archive.org/web/20090629032718/https://codespeak.net/py/dist/test/extend.html>`__\n      which still looks very much the same today!\n   -  Various `default\n      plugins <http://web.archive.org/web/20091005181132/https://codespeak.net/py/dist/test/plugin/index.html>`__,\n      including\n      `monkeypatch <http://web.archive.org/web/20091012022829/http://codespeak.net/py/dist/test/plugin/how-to/monkeypatch.html>`__\n\n-  Even back there, the\n   `FAQ <http://web.archive.org/web/20091005222413/http://codespeak.net/py/dist/faq.html>`__\n   said:\n\n       Clearly, [a second standard library] was ambitious and the naming has\n       maybe haunted the project rather than helping it. There may be a\n       project name change and possibly a split up into different projects\n       sometime.\n\n   and that finally happened in November 2010, when pytest 2.0.0 `was\n   released <https://mail.python.org/pipermail/pytest-dev/2010-November/001687.html>`__\n   as a package separate from ``py`` (but still called ``py.test``).\n\n-  In August 2016, pytest 3.0.0 :std:ref:`was released <release-3.0.0>`,\n   which adds ``pytest`` (rather than ``py.test``) as the recommended\n   command-line entry point\n\nDue to this history, it's difficult to answer the question when pytest was started.\nIt depends what point should really be seen as the start of it all. One\npossible interpretation is to  pick Europython 2004, i.e. around June/July\n2004.\n"
  },
  {
    "path": "doc/en/how-to/assert.rst",
    "content": ".. _`assert`:\n\nHow to write and report assertions in tests\n==================================================\n\n.. _`assert with the assert statement`:\n\nAsserting with the ``assert`` statement\n---------------------------------------------------------\n\n``pytest`` allows you to use the standard Python ``assert`` for verifying\nexpectations and values in Python tests.  For example, you can write the\nfollowing:\n\n.. code-block:: python\n\n    # content of test_assert1.py\n    def f():\n        return 3\n\n\n    def test_function():\n        assert f() == 4\n\nto assert that your function returns a certain value. If this assertion fails\nyou will see the return value of the function call:\n\n.. code-block:: pytest\n\n    $ pytest test_assert1.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_assert1.py F                                                    [100%]\n\n    ================================= FAILURES =================================\n    ______________________________ test_function _______________________________\n\n        def test_function():\n    >       assert f() == 4\n    E       assert 3 == 4\n    E        +  where 3 = f()\n\n    test_assert1.py:6: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_assert1.py::test_function - assert 3 == 4\n    ============================ 1 failed in 0.12s =============================\n\n``pytest`` has support for showing the values of the most common subexpressions\nincluding calls, attributes, comparisons, and binary and unary\noperators. (See :ref:`tbreportdemo`).  This allows you to use the\nidiomatic python constructs without boilerplate code while not losing\nintrospection information.\n\nIf a message is specified with the assertion like this:\n\n.. code-block:: python\n\n    assert a % 2 == 0, \"value was odd, should be even\"\n\nit is printed alongside the assertion introspection in the traceback.\n\nSee :ref:`assert-details` for more information on assertion introspection.\n\n.. _`assertraises`:\n\nAssertions about approximate equality\n-------------------------------------\n\nWhen comparing floating point values (or arrays of floats), small rounding\nerrors are common. Instead of using ``assert abs(a - b) < tol`` or\n``numpy.isclose``, you can use :func:`pytest.approx`:\n\n.. code-block:: python\n\n    import pytest\n    import numpy as np\n\n\n    def test_floats():\n        assert (0.1 + 0.2) == pytest.approx(0.3)\n\n\n    def test_arrays():\n        a = np.array([1.0, 2.0, 3.0])\n        b = np.array([0.9999, 2.0001, 3.0])\n        assert a == pytest.approx(b)\n\n``pytest.approx`` works with scalars, lists, dictionaries, and NumPy arrays.\nIt also supports comparisons involving NaNs.\n\nSee :func:`pytest.approx` for details.\n\nAssertions about expected exceptions\n------------------------------------------\n\nIn order to write assertions about raised exceptions, you can use\n:func:`pytest.raises` as a context manager like this:\n\n.. code-block:: python\n\n    import pytest\n\n\n    def test_zero_division():\n        with pytest.raises(ZeroDivisionError):\n            1 / 0\n\nand if you need to have access to the actual exception info you may use:\n\n.. code-block:: python\n\n    def test_recursion_depth():\n        with pytest.raises(RuntimeError) as excinfo:\n\n            def f():\n                f()\n\n            f()\n        assert \"maximum recursion\" in str(excinfo.value)\n\n``excinfo`` is an :class:`~pytest.ExceptionInfo` instance, which is a wrapper around\nthe actual exception raised.  The main attributes of interest are\n``.type``, ``.value`` and ``.traceback``.\n\nNote that ``pytest.raises`` will match the exception type or any subclasses (like the standard ``except`` statement).\nIf you want to check if a block of code is raising an exact exception type, you need to check that explicitly:\n\n\n.. code-block:: python\n\n    def test_foo_not_implemented():\n        def foo():\n            raise NotImplementedError\n\n        with pytest.raises(RuntimeError) as excinfo:\n            foo()\n        assert excinfo.type is RuntimeError\n\nThe :func:`pytest.raises` call will succeed, even though the function raises :class:`NotImplementedError`, because\n:class:`NotImplementedError` is a subclass of :class:`RuntimeError`; however the following `assert` statement will\ncatch the problem.\n\nMatching exception messages\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can pass a ``match`` keyword parameter to the context-manager to test\nthat a regular expression matches on the string representation of an exception\n(similar to the ``TestCase.assertRaisesRegex`` method from ``unittest``):\n\n.. code-block:: python\n\n    import pytest\n\n\n    def myfunc():\n        raise ValueError(\"Exception 123 raised\")\n\n\n    def test_match():\n        with pytest.raises(ValueError, match=r\".* 123 .*\"):\n            myfunc()\n\nNotes:\n\n* The ``match`` parameter is matched with the :func:`re.search`\n  function, so in the above example ``match='123'`` would have worked as well.\n* The ``match`` parameter also matches against `PEP-678 <https://peps.python.org/pep-0678/>`__ ``__notes__``.\n\n\n.. _`assert-matching-exception-groups`:\n\nAssertions about expected exception groups\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen expecting a :exc:`BaseExceptionGroup` or :exc:`ExceptionGroup` you can use :class:`pytest.RaisesGroup`:\n\n.. code-block:: python\n\n    def test_exception_in_group():\n        with pytest.RaisesGroup(ValueError):\n            raise ExceptionGroup(\"group msg\", [ValueError(\"value msg\")])\n        with pytest.RaisesGroup(ValueError, TypeError):\n            raise ExceptionGroup(\"msg\", [ValueError(\"foo\"), TypeError(\"bar\")])\n\n\nIt accepts a ``match`` parameter, that checks against the group message, and a ``check`` parameter that takes an arbitrary callable which it passes the group to, and only succeeds if the callable returns ``True``.\n\n.. code-block:: python\n\n    def test_raisesgroup_match_and_check():\n        with pytest.RaisesGroup(BaseException, match=\"my group msg\"):\n            raise BaseExceptionGroup(\"my group msg\", [KeyboardInterrupt()])\n        with pytest.RaisesGroup(\n            Exception, check=lambda eg: isinstance(eg.__cause__, ValueError)\n        ):\n            raise ExceptionGroup(\"\", [TypeError()]) from ValueError()\n\nIt is strict about structure and unwrapped exceptions, unlike :ref:`except* <except_star>`, so you might want to set the ``flatten_subgroups`` and/or ``allow_unwrapped`` parameters.\n\n.. code-block:: python\n\n    def test_structure():\n        with pytest.RaisesGroup(pytest.RaisesGroup(ValueError)):\n            raise ExceptionGroup(\"\", (ExceptionGroup(\"\", (ValueError(),)),))\n        with pytest.RaisesGroup(ValueError, flatten_subgroups=True):\n            raise ExceptionGroup(\"1st group\", [ExceptionGroup(\"2nd group\", [ValueError()])])\n        with pytest.RaisesGroup(ValueError, allow_unwrapped=True):\n            raise ValueError\n\nTo specify more details about the contained exception you can use :class:`pytest.RaisesExc`\n\n.. code-block:: python\n\n    def test_raises_exc():\n        with pytest.RaisesGroup(pytest.RaisesExc(ValueError, match=\"foo\")):\n            raise ExceptionGroup(\"\", (ValueError(\"foo\")))\n\nThey both supply a method :meth:`pytest.RaisesGroup.matches` :meth:`pytest.RaisesExc.matches` if you want to do matching outside of using it as a :external+python:std:ref:`context manager <context-managers>`. This can be helpful when checking ``.__context__`` or ``.__cause__``.\n\n.. code-block:: python\n\n    def test_matches():\n        exc = ValueError()\n        exc_group = ExceptionGroup(\"\", [exc])\n        if RaisesGroup(ValueError).matches(exc_group):\n            ...\n        # helpful error is available in `.fail_reason` if it fails to match\n        r = RaisesExc(ValueError)\n        assert r.matches(e), r.fail_reason\n\nCheck the documentation on :class:`pytest.RaisesGroup` and :class:`pytest.RaisesExc` for more details and examples.\n\n``ExceptionInfo.group_contains()``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. warning::\n\n   This helper makes it easy to check for the presence of specific exceptions, but it is very bad for checking that the group does *not* contain *any other exceptions*. So this will pass:\n\n    .. code-block:: python\n\n       class EXTREMELYBADERROR(BaseException):\n           \"\"\"This is a very bad error to miss\"\"\"\n\n\n       def test_for_value_error():\n           with pytest.raises(ExceptionGroup) as excinfo:\n               excs = [ValueError()]\n               if very_unlucky():\n                   excs.append(EXTREMELYBADERROR())\n               raise ExceptionGroup(\"\", excs)\n           # This passes regardless of if there's other exceptions.\n           assert excinfo.group_contains(ValueError)\n           # You can't simply list all exceptions you *don't* want to get here.\n\n\n   There is no good way of using :func:`excinfo.group_contains() <pytest.ExceptionInfo.group_contains>` to ensure you're not getting *any* other exceptions than the one you expected.\n   You should instead use :class:`pytest.RaisesGroup`, see :ref:`assert-matching-exception-groups`.\n\nYou can also use the :func:`excinfo.group_contains() <pytest.ExceptionInfo.group_contains>`\nmethod to test for exceptions returned as part of an :class:`ExceptionGroup`:\n\n.. code-block:: python\n\n    def test_exception_in_group():\n        with pytest.raises(ExceptionGroup) as excinfo:\n            raise ExceptionGroup(\n                \"Group message\",\n                [\n                    RuntimeError(\"Exception 123 raised\"),\n                ],\n            )\n        assert excinfo.group_contains(RuntimeError, match=r\".* 123 .*\")\n        assert not excinfo.group_contains(TypeError)\n\nThe optional ``match`` keyword parameter works the same way as for\n:func:`pytest.raises`.\n\nBy default ``group_contains()`` will recursively search for a matching\nexception at any level of nested ``ExceptionGroup`` instances. You can\nspecify a ``depth`` keyword parameter if you only want to match an\nexception at a specific level; exceptions contained directly in the top\n``ExceptionGroup`` would match ``depth=1``.\n\n.. code-block:: python\n\n    def test_exception_in_group_at_given_depth():\n        with pytest.raises(ExceptionGroup) as excinfo:\n            raise ExceptionGroup(\n                \"Group message\",\n                [\n                    RuntimeError(),\n                    ExceptionGroup(\n                        \"Nested group\",\n                        [\n                            TypeError(),\n                        ],\n                    ),\n                ],\n            )\n        assert excinfo.group_contains(RuntimeError, depth=1)\n        assert excinfo.group_contains(TypeError, depth=2)\n        assert not excinfo.group_contains(RuntimeError, depth=2)\n        assert not excinfo.group_contains(TypeError, depth=1)\n\nAlternate `pytest.raises` form (legacy)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere is an alternate form of :func:`pytest.raises` where you pass\na function that will be executed, along with ``*args`` and ``**kwargs``. :func:`pytest.raises`\nwill then execute the function with those arguments and assert that the given exception is raised:\n\n.. code-block:: python\n\n    def func(x):\n        if x <= 0:\n            raise ValueError(\"x needs to be larger than zero\")\n\n\n    pytest.raises(ValueError, func, x=-1)\n\nThe reporter will provide you with helpful output in case of failures such as *no\nexception* or *wrong exception*.\n\nThis form was the original :func:`pytest.raises` API, developed before the ``with`` statement was\nadded to the Python language. Nowadays, this form is rarely used, with the context-manager form (using ``with``)\nbeing considered more readable.\nNonetheless, this form is fully supported and not deprecated in any way.\n\nxfail mark and pytest.raises\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIt is also possible to specify a ``raises`` argument to\n:ref:`pytest.mark.xfail <pytest.mark.xfail ref>`, which checks that the test is failing in a more\nspecific way than just having any exception raised:\n\n.. code-block:: python\n\n    def f():\n        raise IndexError()\n\n\n    @pytest.mark.xfail(raises=IndexError)\n    def test_f():\n        f()\n\n\nThis will only \"xfail\" if the test fails by raising ``IndexError`` or subclasses.\n\n* Using :ref:`pytest.mark.xfail <pytest.mark.xfail ref>` with the ``raises`` parameter is probably better for something\n  like documenting unfixed bugs (where the test describes what \"should\" happen) or bugs in dependencies.\n\n* Using :func:`pytest.raises` is likely to be better for cases where you are\n  testing exceptions your own code is deliberately raising, which is the majority of cases.\n\nYou can also use :class:`pytest.RaisesGroup`:\n\n.. code-block:: python\n\n    def f():\n        raise ExceptionGroup(\"\", [IndexError()])\n\n\n    @pytest.mark.xfail(raises=RaisesGroup(IndexError))\n    def test_f():\n        f()\n\n\n.. _`assertwarns`:\n\nAssertions about expected warnings\n-----------------------------------------\n\n\n\nYou can check that code raises a particular warning using\n:ref:`pytest.warns <warns>`.\n\n\n.. _newreport:\n\nMaking use of context-sensitive comparisons\n-------------------------------------------------\n\n\n\n``pytest`` has rich support for providing context-sensitive information\nwhen it encounters comparisons.  For example:\n\n.. code-block:: python\n\n    # content of test_assert2.py\n    def test_set_comparison():\n        set1 = set(\"1308\")\n        set2 = set(\"8035\")\n        assert set1 == set2\n\nif you run this module:\n\n.. code-block:: pytest\n\n    $ pytest test_assert2.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_assert2.py F                                                    [100%]\n\n    ================================= FAILURES =================================\n    ___________________________ test_set_comparison ____________________________\n\n        def test_set_comparison():\n            set1 = set(\"1308\")\n            set2 = set(\"8035\")\n    >       assert set1 == set2\n    E       AssertionError: assert {'0', '1', '3', '8'} == {'0', '3', '5', '8'}\n    E\n    E         Extra items in the left set:\n    E         '1'\n    E         Extra items in the right set:\n    E         '5'\n    E         Use -v to get more diff\n\n    test_assert2.py:4: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_assert2.py::test_set_comparison - AssertionError: assert {'0'...\n    ============================ 1 failed in 0.12s =============================\n\nSpecial comparisons are done for a number of cases:\n\n* comparing long strings: a context diff is shown\n* comparing long sequences: first failing indices\n* comparing dicts: different entries\n\nIn string context diffs, lines prefixed with ``-`` come from the left-hand side\nof ``assert left == right``, while lines prefixed with ``+`` come from the\nright-hand side.\n\nSee the :ref:`reporting demo <tbreportdemo>` for many more examples.\n\nDefining your own explanation for failed assertions\n---------------------------------------------------\n\nIt is possible to add your own detailed explanations by implementing\nthe ``pytest_assertrepr_compare`` hook.\n\n.. autofunction:: _pytest.hookspec.pytest_assertrepr_compare\n   :noindex:\n\nAs an example consider adding the following hook in a :ref:`conftest.py <conftest.py>`\nfile which provides an alternative explanation for ``Foo`` objects:\n\n.. code-block:: python\n\n   # content of conftest.py\n   from test_foocompare import Foo\n\n\n   def pytest_assertrepr_compare(op, left, right):\n       if isinstance(left, Foo) and isinstance(right, Foo) and op == \"==\":\n           return [\n               \"Comparing Foo instances:\",\n               f\"   vals: {left.val} != {right.val}\",\n           ]\n\nnow, given this test module:\n\n.. code-block:: python\n\n   # content of test_foocompare.py\n   class Foo:\n       def __init__(self, val):\n           self.val = val\n\n       def __eq__(self, other):\n           return self.val == other.val\n\n\n   def test_compare():\n       f1 = Foo(1)\n       f2 = Foo(2)\n       assert f1 == f2\n\nyou can run the test module and get the custom output defined in\nthe conftest file:\n\n.. code-block:: pytest\n\n   $ pytest -q test_foocompare.py\n   F                                                                    [100%]\n   ================================= FAILURES =================================\n   _______________________________ test_compare _______________________________\n\n       def test_compare():\n           f1 = Foo(1)\n           f2 = Foo(2)\n   >       assert f1 == f2\n   E       assert Comparing Foo instances:\n   E            vals: 1 != 2\n\n   test_foocompare.py:12: AssertionError\n   ========================= short test summary info ==========================\n   FAILED test_foocompare.py::test_compare - assert Comparing Foo instances:\n   1 failed in 0.12s\n\n.. _`return-not-none`:\n\nReturning non-None value in test functions\n------------------------------------------\n\nA :class:`pytest.PytestReturnNotNoneWarning` is emitted when a test function returns a value other than ``None``.\n\nThis helps prevent a common mistake made by beginners who assume that returning a ``bool`` (e.g., ``True`` or ``False``) will determine whether a test passes or fails.\n\nExample:\n\n.. code-block:: python\n\n    @pytest.mark.parametrize(\n        [\"a\", \"b\", \"result\"],\n        [\n            [1, 2, 5],\n            [2, 3, 8],\n            [5, 3, 18],\n        ],\n    )\n    def test_foo(a, b, result):\n        return foo(a, b) == result  # Incorrect usage, do not do this.\n\nSince pytest ignores return values, it might be surprising that the test will never fail based on the returned value.\n\nThe correct fix is to replace the ``return`` statement with an ``assert``:\n\n.. code-block:: python\n\n    @pytest.mark.parametrize(\n        [\"a\", \"b\", \"result\"],\n        [\n            [1, 2, 5],\n            [2, 3, 8],\n            [5, 3, 18],\n        ],\n    )\n    def test_foo(a, b, result):\n        assert foo(a, b) == result\n\n\n\n\n.. _assert-details:\n.. _`assert introspection`:\n\nAssertion introspection details\n-------------------------------\n\n\nReporting details about a failing assertion is achieved by rewriting assert\nstatements before they are run.  Rewritten assert statements put introspection\ninformation into the assertion failure message.  ``pytest`` only rewrites test\nmodules directly discovered by its test collection process, so **asserts in\nsupporting modules which are not themselves test modules will not be rewritten**.\n\nYou can manually enable assertion rewriting for an imported module by calling\n:ref:`register_assert_rewrite <assertion-rewriting>`\nbefore you import it (a good place to do that is in your root ``conftest.py``).\n\nFor further information, Benjamin Peterson wrote up `Behind the scenes of pytest's new assertion rewriting <http://pybites.blogspot.com/2011/07/behind-scenes-of-pytests-new-assertion.html>`_.\n\nAssertion rewriting caches files on disk\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``pytest`` will write back the rewritten modules to disk for caching. You can disable\nthis behavior (for example to avoid leaving stale ``.pyc`` files around in projects that\nmove files around a lot) by adding this to the top of your ``conftest.py`` file:\n\n.. code-block:: python\n\n   import sys\n\n   sys.dont_write_bytecode = True\n\nNote that you still get the benefits of assertion introspection, the only change is that\nthe ``.pyc`` files won't be cached on disk.\n\nAdditionally, rewriting will silently skip caching if it cannot write new ``.pyc`` files,\ne.g. in a read-only filesystem or a zipfile.\n\n\nDisabling assert rewriting\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``pytest`` rewrites test modules on import by using an import\nhook to write new ``pyc`` files. Most of the time this works transparently.\nHowever, if you are working with the import machinery yourself, the import hook may\ninterfere.\n\nIf this is the case you have two options:\n\n* Disable rewriting for a specific module by adding the string\n  ``PYTEST_DONT_REWRITE`` to its docstring.\n\n* Disable rewriting for all modules by using :option:`--assert=plain`.\n"
  },
  {
    "path": "doc/en/how-to/bash-completion.rst",
    "content": "\n.. _bash_completion:\n\nHow to set up bash completion\n=============================\n\nWhen using bash as your shell, ``pytest`` can use argcomplete\n(https://kislyuk.github.io/argcomplete/) for auto-completion.\nFor this ``argcomplete`` needs to be installed **and** enabled.\n\nInstall argcomplete using:\n\n.. code-block:: bash\n\n    sudo pip install 'argcomplete>=0.5.7'\n\nFor global activation of all argcomplete enabled python applications run:\n\n.. code-block:: bash\n\n    sudo activate-global-python-argcomplete\n\nFor permanent (but not global) ``pytest`` activation, use:\n\n.. code-block:: bash\n\n    register-python-argcomplete pytest >> ~/.bashrc\n\nFor one-time activation of argcomplete for ``pytest`` only, use:\n\n.. code-block:: bash\n\n    eval \"$(register-python-argcomplete pytest)\"\n"
  },
  {
    "path": "doc/en/how-to/cache.rst",
    "content": ".. _`cache_provider`:\n.. _cache:\n\n\nHow to re-run failed tests and maintain state between test runs\n===============================================================\n\n\n\nUsage\n---------\n\nThe plugin provides two command line options to rerun failures from the\nlast ``pytest`` invocation:\n\n* :option:`--lf, --last-failed <--lf>` - to only re-run the failures.\n* :option:`--ff, --failed-first <--ff>` - to run the failures first and then the rest of\n  the tests.\n\nFor cleanup (usually not needed), a :option:`--cache-clear` option allows to remove\nall cross-session cache contents ahead of a test run.\n\nOther plugins may access the `config.cache`_ object to set/get\n**json encodable** values between ``pytest`` invocations.\n\n.. note::\n\n    This plugin is enabled by default, but can be disabled if needed: see\n    :ref:`cmdunregister` (the internal name for this plugin is\n    ``cacheprovider``).\n\n\nRerunning only failures or failures first\n-----------------------------------------------\n\nFirst, let's create 50 test invocations of which only 2 fail:\n\n.. code-block:: python\n\n    # content of test_50.py\n    import pytest\n\n\n    @pytest.mark.parametrize(\"i\", range(50))\n    def test_num(i):\n        if i in (17, 25):\n            pytest.fail(\"bad luck\")\n\nIf you run this for the first time you will see two failures:\n\n.. code-block:: pytest\n\n    $ pytest -q\n    .................F.......F........................                   [100%]\n    ================================= FAILURES =================================\n    _______________________________ test_num[17] _______________________________\n\n    i = 17\n\n        @pytest.mark.parametrize(\"i\", range(50))\n        def test_num(i):\n            if i in (17, 25):\n    >           pytest.fail(\"bad luck\")\n    E           Failed: bad luck\n\n    test_50.py:7: Failed\n    _______________________________ test_num[25] _______________________________\n\n    i = 25\n\n        @pytest.mark.parametrize(\"i\", range(50))\n        def test_num(i):\n            if i in (17, 25):\n    >           pytest.fail(\"bad luck\")\n    E           Failed: bad luck\n\n    test_50.py:7: Failed\n    ========================= short test summary info ==========================\n    FAILED test_50.py::test_num[17] - Failed: bad luck\n    FAILED test_50.py::test_num[25] - Failed: bad luck\n    2 failed, 48 passed in 0.12s\n\nIf you then run it with :option:`--lf`:\n\n.. code-block:: pytest\n\n    $ pytest --lf\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 2 items\n    run-last-failure: rerun previous 2 failures\n\n    test_50.py FF                                                        [100%]\n\n    ================================= FAILURES =================================\n    _______________________________ test_num[17] _______________________________\n\n    i = 17\n\n        @pytest.mark.parametrize(\"i\", range(50))\n        def test_num(i):\n            if i in (17, 25):\n    >           pytest.fail(\"bad luck\")\n    E           Failed: bad luck\n\n    test_50.py:7: Failed\n    _______________________________ test_num[25] _______________________________\n\n    i = 25\n\n        @pytest.mark.parametrize(\"i\", range(50))\n        def test_num(i):\n            if i in (17, 25):\n    >           pytest.fail(\"bad luck\")\n    E           Failed: bad luck\n\n    test_50.py:7: Failed\n    ========================= short test summary info ==========================\n    FAILED test_50.py::test_num[17] - Failed: bad luck\n    FAILED test_50.py::test_num[25] - Failed: bad luck\n    ============================ 2 failed in 0.12s =============================\n\nYou have run only the two failing tests from the last run, while the 48 passing\ntests have not been run (\"deselected\").\n\nNow, if you run with the :option:`--ff` option, all tests will be run but the first\nprevious failures will be executed first (as can be seen from the series\nof ``FF`` and dots):\n\n.. code-block:: pytest\n\n    $ pytest --ff\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 50 items\n    run-last-failure: rerun previous 2 failures first\n\n    test_50.py FF................................................        [100%]\n\n    ================================= FAILURES =================================\n    _______________________________ test_num[17] _______________________________\n\n    i = 17\n\n        @pytest.mark.parametrize(\"i\", range(50))\n        def test_num(i):\n            if i in (17, 25):\n    >           pytest.fail(\"bad luck\")\n    E           Failed: bad luck\n\n    test_50.py:7: Failed\n    _______________________________ test_num[25] _______________________________\n\n    i = 25\n\n        @pytest.mark.parametrize(\"i\", range(50))\n        def test_num(i):\n            if i in (17, 25):\n    >           pytest.fail(\"bad luck\")\n    E           Failed: bad luck\n\n    test_50.py:7: Failed\n    ========================= short test summary info ==========================\n    FAILED test_50.py::test_num[17] - Failed: bad luck\n    FAILED test_50.py::test_num[25] - Failed: bad luck\n    ======================= 2 failed, 48 passed in 0.12s =======================\n\n.. _`config.cache`:\n\nNew :option:`--nf, --new-first <--nf>` option: run new tests first followed by the rest\nof the tests, in both cases tests are also sorted by the file modified time,\nwith more recent files coming first.\n\nBehavior when no tests failed in the last run\n---------------------------------------------\n\nThe :option:`--lfnf, --last-failed-no-failures <--lfnf>` option governs the behavior of :option:`--last-failed`.\nDetermines whether to execute tests when there are no previously (known)\nfailures or when no cached ``lastfailed`` data was found.\n\nThere are two options:\n\n* ``all``:  when there are no known test failures, runs all tests (the full test suite). This is the default.\n* ``none``: when there are no known test failures, just emits a message stating this and exit successfully.\n\nExample:\n\n.. code-block:: bash\n\n    pytest --last-failed --last-failed-no-failures all    # runs the full test suite (default behavior)\n    pytest --last-failed --last-failed-no-failures none   # runs no tests and exits successfully\n\nThe new config.cache object\n--------------------------------\n\n.. regendoc:wipe\n\nPlugins or conftest.py support code can get a cached value using the\npytest ``config`` object.  Here is a basic example plugin which\nimplements a :ref:`fixture <fixture>` which reuses previously created state\nacross pytest invocations:\n\n.. code-block:: python\n\n    # content of test_caching.py\n    import pytest\n\n\n    def expensive_computation():\n        print(\"running expensive computation...\")\n\n\n    @pytest.fixture\n    def mydata(pytestconfig):\n        val = pytestconfig.cache.get(\"example/value\", None)\n        if val is None:\n            expensive_computation()\n            val = 42\n            pytestconfig.cache.set(\"example/value\", val)\n        return val\n\n\n    def test_function(mydata):\n        assert mydata == 23\n\nIf you run this command for the first time, you can see the print statement:\n\n.. code-block:: pytest\n\n    $ pytest -q\n    F                                                                    [100%]\n    ================================= FAILURES =================================\n    ______________________________ test_function _______________________________\n\n    mydata = 42\n\n        def test_function(mydata):\n    >       assert mydata == 23\n    E       assert 42 == 23\n\n    test_caching.py:19: AssertionError\n    -------------------------- Captured stdout setup ---------------------------\n    running expensive computation...\n    ========================= short test summary info ==========================\n    FAILED test_caching.py::test_function - assert 42 == 23\n    1 failed in 0.12s\n\nIf you run it a second time, the value will be retrieved from\nthe cache and nothing will be printed:\n\n.. code-block:: pytest\n\n    $ pytest -q\n    F                                                                    [100%]\n    ================================= FAILURES =================================\n    ______________________________ test_function _______________________________\n\n    mydata = 42\n\n        def test_function(mydata):\n    >       assert mydata == 23\n    E       assert 42 == 23\n\n    test_caching.py:19: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_caching.py::test_function - assert 42 == 23\n    1 failed in 0.12s\n\nSee the :fixture:`config.cache fixture <cache>` for more details.\n\n\nInspecting Cache content\n------------------------\n\nYou can always peek at the content of the cache using the\n:option:`--cache-show` command line option:\n\n.. code-block:: pytest\n\n    $ pytest --cache-show\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    cachedir: /home/sweet/project/.pytest_cache\n    --------------------------- cache values for '*' ---------------------------\n    cache/lastfailed contains:\n      {'test_caching.py::test_function': True}\n    cache/nodeids contains:\n      ['test_caching.py::test_function']\n    example/value contains:\n      42\n\n    ========================== no tests ran in 0.12s ===========================\n\n:option:`--cache-show` takes an optional argument to specify a glob pattern for\nfiltering:\n\n.. code-block:: pytest\n\n    $ pytest --cache-show example/*\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    cachedir: /home/sweet/project/.pytest_cache\n    ----------------------- cache values for 'example/*' -----------------------\n    example/value contains:\n      42\n\n    ========================== no tests ran in 0.12s ===========================\n\nClearing Cache content\n----------------------\n\nYou can instruct pytest to clear all cache files and values\nby adding the :option:`--cache-clear` option like this:\n\n.. code-block:: bash\n\n    pytest --cache-clear\n\nThis is recommended for invocations from Continuous Integration\nservers where isolation and correctness is more important\nthan speed.\n\n\n.. _cache stepwise:\n\nStepwise\n--------\n\nAs an alternative to :option:`--lf` :option:`-x`, especially for cases where you expect a large part of the test suite will fail, :option:`--sw, --stepwise <--sw>` allows you to fix them one at a time. The test suite will run until the first failure and then stop. At the next invocation, tests will continue from the last failing test and then run until the next failing test. You may use the :option:`--stepwise-skip` option to ignore one failing test and stop the test execution on the second failing test instead. This is useful if you get stuck on a failing test and just want to ignore it until later.  Providing ``--stepwise-skip`` will also enable ``--stepwise`` implicitly.\n"
  },
  {
    "path": "doc/en/how-to/capture-stdout-stderr.rst",
    "content": "\n.. _`captures`:\n\nHow to capture stdout/stderr output\n=========================================================\n\nPytest intercepts stdout and stderr as configured by the :option:`--capture=`\ncommand-line argument or by using fixtures. The ``--capture=`` flag configures\nreporting, whereas the fixtures offer more granular control and allow\ninspection of output during testing. The reports can be customized with the\n:option:`-r` flag.\n\nDefault stdout/stderr/stdin capturing behaviour\n---------------------------------------------------------\n\nDuring test execution any output sent to ``stdout`` and ``stderr`` is\ncaptured.  If a test or a setup method fails its according captured\noutput will usually be shown along with the failure traceback. (This\nbehavior can be configured by the :option:`--show-capture` command-line option).\n\nIn addition, ``stdin`` is set to a \"null\" object which will\nfail on attempts to read from it because it is rarely desired\nto wait for interactive input when running automated tests.\n\nBy default capturing is done by intercepting writes to low level\nfile descriptors.  This allows capturing output from simple\nprint statements as well as output from a subprocess started by\na test.\n\n.. _capture-method:\n\nSetting capturing methods or disabling capturing\n-------------------------------------------------\n\nThere are three ways in which ``pytest`` can perform capturing:\n\n* ``fd`` (file descriptor) level capturing (default): All writes going to the\n  operating system file descriptors 1 and 2 will be captured.\n\n* ``sys`` level capturing: Only writes to Python files ``sys.stdout``\n  and ``sys.stderr`` will be captured.  No capturing of writes to\n  filedescriptors is performed.\n\n* ``tee-sys`` capturing: Python writes to ``sys.stdout`` and ``sys.stderr``\n  will be captured, however the writes will also be passed-through to\n  the actual ``sys.stdout`` and ``sys.stderr``. This allows output to be\n  'live printed' and captured for plugin use, such as junitxml (new in pytest 5.4).\n\n.. _`disable capturing`:\n\nYou can influence output capturing mechanisms from the command line:\n\n.. code-block:: bash\n\n    pytest -s                  # disable all capturing\n    pytest --capture=sys       # replace sys.stdout/stderr with in-mem files\n    pytest --capture=fd        # also point filedescriptors 1 and 2 to temp file\n    pytest --capture=tee-sys   # combines 'sys' and '-s', capturing sys.stdout/stderr\n                               # and passing it along to the actual sys.stdout/stderr\n\n.. _printdebugging:\n\nUsing print statements for debugging\n---------------------------------------------------\n\nOne primary benefit of the default capturing of stdout/stderr output\nis that you can use print statements for debugging:\n\n.. code-block:: python\n\n    # content of test_module.py\n\n\n    def setup_function(function):\n        print(\"setting up\", function)\n\n\n    def test_func1():\n        assert True\n\n\n    def test_func2():\n        assert False\n\nand running this module will show you precisely the output\nof the failing function and hide the other one:\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 2 items\n\n    test_module.py .F                                                    [100%]\n\n    ================================= FAILURES =================================\n    ________________________________ test_func2 ________________________________\n\n        def test_func2():\n    >       assert False\n    E       assert False\n\n    test_module.py:12: AssertionError\n    -------------------------- Captured stdout setup ---------------------------\n    setting up <function test_func2 at 0xdeadbeef0001>\n    ========================= short test summary info ==========================\n    FAILED test_module.py::test_func2 - assert False\n    ======================= 1 failed, 1 passed in 0.12s ========================\n\n.. _accessing-captured-output:\n\nAccessing captured output from a test function\n---------------------------------------------------\n\nThe :fixture:`capsys`, :fixture:`capteesys`, :fixture:`capsysbinary`, :fixture:`capfd`, and :fixture:`capfdbinary`\nfixtures allow access to ``stdout``/``stderr`` output created during test execution.\n\nHere is an example test function that performs some output related checks:\n\n.. code-block:: python\n\n    def test_myoutput(capsys):  # or use \"capfd\" for fd-level\n        print(\"hello\")\n        sys.stderr.write(\"world\\n\")\n        captured = capsys.readouterr()\n        assert captured.out == \"hello\\n\"\n        assert captured.err == \"world\\n\"\n        print(\"next\")\n        captured = capsys.readouterr()\n        assert captured.out == \"next\\n\"\n\nThe ``readouterr()`` call snapshots the output so far -\nand capturing will be continued.  After the test\nfunction finishes the original streams will\nbe restored.  Using :fixture:`capsys` this way frees your\ntest from having to care about setting/resetting\noutput streams and also interacts well with pytest's\nown per-test capturing.\n\nThe return value of ``readouterr()`` is a ``namedtuple`` with two attributes, ``out`` and ``err``.\n\nIf the code under test writes non-textual data (``bytes``), you can capture this using\nthe :fixture:`capsysbinary` fixture which instead returns ``bytes`` from\nthe ``readouterr`` method.\n\nIf you want to capture at the file descriptor level you can use\nthe :fixture:`capfd` fixture which offers the exact\nsame interface but allows to also capture output from\nlibraries or subprocesses that directly write to operating\nsystem level output streams (FD1 and FD2). Similarly to :fixture:`capsysbinary`, :fixture:`capfdbinary` can be\nused to capture ``bytes`` at the file descriptor level.\n\n\nTo temporarily disable capture within a test, the capture fixtures\nhave a ``disabled()`` method that can be used\nas a context manager, disabling capture inside the ``with`` block:\n\n.. code-block:: python\n\n    def test_disabling_capturing(capsys):\n        print(\"this output is captured\")\n        with capsys.disabled():\n            print(\"output not captured, going directly to sys.stdout\")\n        print(\"this output is also captured\")\n\n.. note::\n\n   When a capture fixture such as :fixture:`capsys` or :fixture:`capfd` is used,\n   it takes precedence over the global capturing configuration set via\n   command-line options such as ``-s`` or ``--capture=no``.\n\n   This means that output produced within a test using a capture fixture will\n   still be captured and available via ``readouterr()``, even if global capturing\n   is disabled.\n"
  },
  {
    "path": "doc/en/how-to/capture-warnings.rst",
    "content": ".. _`warnings`:\n\nHow to capture warnings\n=======================\n\n\n\nStarting from version ``3.1``, pytest now automatically catches warnings during test execution\nand displays them at the end of the session:\n\n.. code-block:: python\n\n    # content of test_show_warnings.py\n    import warnings\n\n\n    def api_v1():\n        warnings.warn(UserWarning(\"api v1, should use functions from v2\"))\n        return 1\n\n\n    def test_one():\n        assert api_v1() == 1\n\nRunning pytest now produces this output:\n\n.. code-block:: pytest\n\n    $ pytest test_show_warnings.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_show_warnings.py .                                              [100%]\n\n    ============================= warnings summary =============================\n    test_show_warnings.py::test_one\n      /home/sweet/project/test_show_warnings.py:5: UserWarning: api v1, should use functions from v2\n        warnings.warn(UserWarning(\"api v1, should use functions from v2\"))\n\n    -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html\n    ======================= 1 passed, 1 warning in 0.12s =======================\n\n.. _`controlling-warnings`:\n\nControlling warnings\n--------------------\n\nSimilar to Python's `warning filter`_ and :option:`-W option <python:-W>` flag, pytest provides\nits own ``-W`` flag to control which warnings are ignored, displayed, or turned into\nerrors. See the `warning filter`_ documentation for more\nadvanced use-cases.\n\n.. _`warning filter`: https://docs.python.org/3/library/warnings.html#warning-filter\n\nThis code sample shows how to treat any ``UserWarning`` category class of warning\nas an error:\n\n.. code-block:: pytest\n\n    $ pytest -q test_show_warnings.py -W error::UserWarning\n    F                                                                    [100%]\n    ================================= FAILURES =================================\n    _________________________________ test_one _________________________________\n\n        def test_one():\n    >       assert api_v1() == 1\n                   ^^^^^^^^\n\n    test_show_warnings.py:10:\n    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\n        def api_v1():\n    >       warnings.warn(UserWarning(\"api v1, should use functions from v2\"))\n    E       UserWarning: api v1, should use functions from v2\n\n    test_show_warnings.py:5: UserWarning\n    ========================= short test summary info ==========================\n    FAILED test_show_warnings.py::test_one - UserWarning: api v1, should use ...\n    1 failed in 0.12s\n\nThe same option can be set in the configuration file using the\n:confval:`filterwarnings` configuration option. For example, the configuration below will ignore all\nuser warnings and specific deprecation warnings matching a regex, but will transform\nall other warnings into errors.\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        filterwarnings = [\n            'error',\n            'ignore::UserWarning',\n            # Note the use of single quote below to denote \"raw\" strings in TOML.\n            'ignore:function ham\\(\\) is deprecated:DeprecationWarning',\n        ]\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        filterwarnings =\n            error\n            ignore::UserWarning\n            ignore:function ham\\(\\) is deprecated:DeprecationWarning\n\n\nWhen a warning matches more than one option in the list, the action for the last matching option\nis performed.\n\n\n.. note::\n\n    The ``-W`` flag and the :confval:`filterwarnings` configuration option use warning filters that are\n    similar in structure, but each configuration option interprets its filter\n    differently. For example, *message* in ``filterwarnings`` is a string containing a\n    regular expression that the start of the warning message must match,\n    case-insensitively, while *message* in ``-W`` is a literal string that the start of\n    the warning message must contain (case-insensitively), ignoring any whitespace at\n    the start or end of message. Consult the `warning filter`_ documentation for more\n    details.\n\n\n.. _`filterwarnings`:\n\n``@pytest.mark.filterwarnings``\n-------------------------------\n\n\n\nYou can use the :ref:`@pytest.mark.filterwarnings <pytest.mark.filterwarnings ref>` mark to add warning filters to specific test items,\nallowing you to have finer control of which warnings should be captured at test, class or\neven module level:\n\n.. code-block:: python\n\n    import warnings\n\n\n    def api_v1():\n        warnings.warn(UserWarning(\"api v1, should use functions from v2\"))\n        return 1\n\n\n    @pytest.mark.filterwarnings(\"ignore:api v1\")\n    def test_one():\n        assert api_v1() == 1\n\n\nYou can specify multiple filters with separate decorators:\n\n.. code-block:: python\n\n    # Ignore \"api v1\" warnings, but fail on all other warnings\n    @pytest.mark.filterwarnings(\"ignore:api v1\")\n    @pytest.mark.filterwarnings(\"error\")\n    def test_one():\n        assert api_v1() == 1\n\nYou can also pass multiple filters to a single mark by providing multiple arguments:\n\n.. code-block:: python\n\n    # Later arguments take precedence, matching warnings.filterwarnings behavior.\n    @pytest.mark.filterwarnings(\"error\", \"ignore:api v1\")\n    def test_one():\n        assert api_v1() == 1\n\n.. important::\n\n    Regarding decorator order and filter precedence:\n    it's important to remember that decorators are evaluated in reverse order,\n    so you have to list the warning filters in the reverse order\n    compared to traditional :py:func:`warnings.filterwarnings` and :option:`-W option <python:-W>` usage.\n    This means in practice that filters from earlier :ref:`@pytest.mark.filterwarnings <pytest.mark.filterwarnings ref>` decorators\n    take precedence over filters from later decorators, as illustrated in the example above.\n\n\nFilters applied using a mark take precedence over filters passed on the command line or configured\nby the :confval:`filterwarnings` configuration option.\n\nYou may apply a filter to all tests of a class by using the :ref:`filterwarnings <pytest.mark.filterwarnings ref>` mark as a class\ndecorator or to all tests in a module by setting the :globalvar:`pytestmark` variable:\n\n.. code-block:: python\n\n    # turns all warnings into errors for this module\n    pytestmark = pytest.mark.filterwarnings(\"error\")\n\n\n.. note::\n\n    If you want to apply multiple filters\n    (by assigning a list of :ref:`filterwarnings <pytest.mark.filterwarnings ref>` mark to :globalvar:`pytestmark`),\n    you must use the traditional :py:func:`warnings.filterwarnings` ordering approach (later filters take precedence),\n    which is the reverse of the decorator approach mentioned above.\n\n\n*Credits go to Florian Schulze for the reference implementation in the* `pytest-warnings`_\n*plugin.*\n\n.. _`pytest-warnings`: https://github.com/fschulze/pytest-warnings\n\nDisabling warnings summary\n--------------------------\n\nAlthough not recommended, you can use the :option:`--disable-warnings` command-line option to suppress the\nwarning summary entirely from the test run output.\n\nDisabling warning capture entirely\n----------------------------------\n\nThis plugin is enabled by default but can be disabled entirely in your configuration file with:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        addopts = [\"-p\", \"no:warnings\"]\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        addopts = -p no:warnings\n\nOr passing ``-p no:warnings`` in the command-line. This might be useful if your test suite handles warnings\nusing an external system.\n\n\n.. _`deprecation-warnings`:\n\nDeprecationWarning and PendingDeprecationWarning\n------------------------------------------------\n\nBy default pytest will display ``DeprecationWarning`` and ``PendingDeprecationWarning`` warnings from\nuser code and third-party libraries, as recommended by :pep:`565`.\nThis helps users keep their code modern and avoid breakages when deprecated warnings are effectively removed.\n\nHowever, in the specific case where users capture any type of warnings in their test, either with\n:func:`pytest.warns`, :func:`pytest.deprecated_call` or using the :fixture:`recwarn` fixture,\nno warning will be displayed at all.\n\nSometimes it is useful to hide some specific deprecation warnings that happen in code that you have no control over\n(such as third-party libraries), in which case you might use the warning filters options (configuration or marks) to ignore\nthose warnings.\n\nFor example:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        filterwarnings = [\n            'ignore:.*U.*mode is deprecated:DeprecationWarning',\n        ]\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        filterwarnings =\n            ignore:.*U.*mode is deprecated:DeprecationWarning\n\n\nThis will ignore all warnings of type ``DeprecationWarning`` where the start of the message matches\nthe regular expression ``\".*U.*mode is deprecated\"``.\n\nSee :ref:`@pytest.mark.filterwarnings <filterwarnings>` and\n:ref:`Controlling warnings <controlling-warnings>` for more examples.\n\n.. note::\n\n    If warnings are configured at the interpreter level, using\n    the :envvar:`python:PYTHONWARNINGS` environment variable or the\n    ``-W`` command-line option, pytest will not configure any filters by default.\n\n    Also pytest doesn't follow :pep:`565` suggestion of resetting all warning filters because\n    it might break test suites that configure warning filters themselves\n    by calling :func:`warnings.simplefilter` (see :issue:`2430` for an example of that).\n\n\n.. _`ensuring a function triggers a deprecation warning`:\n\n.. _ensuring_function_triggers:\n\nEnsuring code triggers a deprecation warning\n--------------------------------------------\n\nYou can also use :func:`pytest.deprecated_call` for checking\nthat a certain function call triggers a ``DeprecationWarning``, ``PendingDeprecationWarning`` or\n``FutureWarning``:\n\n.. code-block:: python\n\n    import pytest\n\n\n    def test_myfunction_deprecated():\n        with pytest.deprecated_call():\n            myfunction(17)\n\nThis test will fail if ``myfunction`` does not issue a deprecation warning\nwhen called with a ``17`` argument.\n\n\n\n\n.. _`asserting warnings`:\n\n.. _assertwarnings:\n\n.. _`asserting warnings with the warns function`:\n\n.. _warns:\n\nAsserting warnings with the warns function\n------------------------------------------\n\nYou can check that code raises a particular warning using :func:`pytest.warns`,\nwhich works in a similar manner to :ref:`raises <assertraises>` (except that\n:ref:`raises <assertraises>` does not capture all exceptions, only the\n``expected_exception``):\n\n.. code-block:: python\n\n    import warnings\n\n    import pytest\n\n\n    def test_warning():\n        with pytest.warns(UserWarning):\n            warnings.warn(\"my warning\", UserWarning)\n\nThe test will fail if the warning in question is not raised. Use the keyword\nargument ``match`` to assert that the warning matches a text or regex.\nTo match a literal string that may contain regular expression metacharacters like ``(`` or ``.``, the pattern can\nfirst be escaped with ``re.escape``.\n\nSome examples:\n\n.. code-block:: pycon\n\n\n    >>> with warns(UserWarning, match=\"must be 0 or None\"):\n    ...     warnings.warn(\"value must be 0 or None\", UserWarning)\n    ...\n\n    >>> with warns(UserWarning, match=r\"must be \\d+$\"):\n    ...     warnings.warn(\"value must be 42\", UserWarning)\n    ...\n\n    >>> with warns(UserWarning, match=r\"must be \\d+$\"):\n    ...     warnings.warn(\"this is not here\", UserWarning)\n    ...\n    Traceback (most recent call last):\n      ...\n    Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...\n\n    >>> with warns(UserWarning, match=re.escape(\"issue with foo() func\")):\n    ...     warnings.warn(\"issue with foo() func\")\n    ...\n\nYou can also call :func:`pytest.warns` on a function or code string:\n\n.. code-block:: python\n\n    pytest.warns(expected_warning, func, *args, **kwargs)\n    pytest.warns(expected_warning, \"func(*args, **kwargs)\")\n\nThe function also returns a list of all raised warnings (as\n``warnings.WarningMessage`` objects), which you can query for\nadditional information:\n\n.. code-block:: python\n\n    with pytest.warns(RuntimeWarning) as record:\n        warnings.warn(\"another warning\", RuntimeWarning)\n\n    # check that only one warning was raised\n    assert len(record) == 1\n    # check that the message matches\n    assert record[0].message.args[0] == \"another warning\"\n\nAlternatively, you can examine raised warnings in detail using the\n:fixture:`recwarn` fixture (see :ref:`below <recwarn>`).\n\n\nThe :fixture:`recwarn` fixture automatically ensures to reset the warnings\nfilter at the end of the test, so no global state is leaked.\n\n.. _`recording warnings`:\n\n.. _recwarn:\n\nRecording warnings\n------------------\n\nYou can record raised warnings either using the :func:`pytest.warns` context manager or with\nthe :fixture:`recwarn` fixture.\n\nTo record with :func:`pytest.warns` without asserting anything about the warnings,\npass no arguments as the expected warning type and it will default to a generic Warning:\n\n.. code-block:: python\n\n    with pytest.warns() as record:\n        warnings.warn(\"user\", UserWarning)\n        warnings.warn(\"runtime\", RuntimeWarning)\n\n    assert len(record) == 2\n    assert str(record[0].message) == \"user\"\n    assert str(record[1].message) == \"runtime\"\n\nThe :fixture:`recwarn` fixture will record warnings for the whole function:\n\n.. code-block:: python\n\n    import warnings\n\n\n    def test_hello(recwarn):\n        warnings.warn(\"hello\", UserWarning)\n        assert len(recwarn) == 1\n        w = recwarn.pop(UserWarning)\n        assert issubclass(w.category, UserWarning)\n        assert str(w.message) == \"hello\"\n        assert w.filename\n        assert w.lineno\n\nBoth the :fixture:`recwarn` fixture and the :func:`pytest.warns` context manager return the same interface for recorded\nwarnings: a :class:`~_pytest.recwarn.WarningsRecorder` instance. To view the recorded warnings, you can\niterate over this instance, call ``len`` on it to get the number of recorded\nwarnings, or index into it to get a particular recorded warning.\n\n\n.. _`warns use cases`:\n\nAdditional use cases of warnings in tests\n-----------------------------------------\n\nHere are some use cases involving warnings that often come up in tests, and suggestions on how to deal with them:\n\n- To ensure that **at least one** of the indicated warnings is issued, use:\n\n.. code-block:: python\n\n    def test_warning():\n        with pytest.warns((RuntimeWarning, UserWarning)):\n            ...\n\n- To ensure that **only** certain warnings are issued, use:\n\n.. code-block:: python\n\n    def test_warning(recwarn):\n        ...\n        assert len(recwarn) == 1\n        user_warning = recwarn.pop(UserWarning)\n        assert issubclass(user_warning.category, UserWarning)\n\n-  To ensure that **no** warnings are emitted, use:\n\n.. code-block:: python\n\n    def test_warning():\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"error\")\n            ...\n\n- To suppress warnings, use:\n\n.. code-block:: python\n\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        ...\n\n\n.. _custom_failure_messages:\n\nCustom failure messages\n-----------------------\n\nRecording warnings provides an opportunity to produce custom test\nfailure messages for when no warnings are issued or other conditions\nare met.\n\n.. code-block:: python\n\n    def test():\n        with pytest.warns(Warning) as record:\n            f()\n            if not record:\n                pytest.fail(\"Expected a warning!\")\n\nIf no warnings are issued when calling ``f``, then ``not record`` will\nevaluate to ``True``.  You can then call :func:`pytest.fail` with a\ncustom error message.\n\n.. _internal-warnings:\n\nInternal pytest warnings\n------------------------\n\npytest may generate its own warnings in some situations, such as improper usage or deprecated features.\n\nFor example, pytest will emit a warning if it encounters a class that matches :confval:`python_classes` but also\ndefines an ``__init__`` constructor, as this prevents the class from being instantiated:\n\n.. code-block:: python\n\n    # content of test_pytest_warnings.py\n    class Test:\n        def __init__(self):\n            pass\n\n        def test_foo(self):\n            assert 1 == 1\n\n.. code-block:: pytest\n\n    $ pytest test_pytest_warnings.py -q\n\n    ============================= warnings summary =============================\n    test_pytest_warnings.py:1\n      /home/sweet/project/test_pytest_warnings.py:1: PytestCollectionWarning: cannot collect test class 'Test' because it has a __init__ constructor (from: test_pytest_warnings.py)\n        class Test:\n\n    -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html\n    1 warning in 0.12s\n\nThese warnings might be filtered using the same builtin mechanisms used to filter other types of warnings.\n\nPlease read our :ref:`backwards-compatibility` to learn how we proceed about deprecating and eventually removing\nfeatures.\n\nThe full list of warnings is listed in :ref:`the reference documentation <warnings ref>`.\n\n\n.. _`resource-warnings`:\n\nResource Warnings\n-----------------\n\nAdditional information of the source of a :class:`ResourceWarning` can be obtained when captured by pytest if\n:mod:`tracemalloc` module is enabled.\n\nOne convenient way to enable :mod:`tracemalloc` when running tests is to set the :envvar:`PYTHONTRACEMALLOC` to a large\nenough number of frames (say ``20``, but that number is application dependent).\n\nFor more information, consult the `Python Development Mode <https://docs.python.org/3/library/devmode.html>`__\nsection in the Python documentation.\n"
  },
  {
    "path": "doc/en/how-to/doctest.rst",
    "content": ".. _doctest:\n\nHow to run doctests\n=========================================================\n\nBy default, all files matching the ``test*.txt`` pattern will\nbe run through the python standard :mod:`doctest` module.  You\ncan change the pattern by issuing:\n\n.. code-block:: bash\n\n    pytest --doctest-glob=\"*.rst\"\n\non the command line. :option:`--doctest-glob` can be given multiple times in the command-line.\n\nIf you then have a text file like this:\n\n.. code-block:: text\n\n    # content of test_example.txt\n\n    hello this is a doctest\n    >>> x = 3\n    >>> x\n    3\n\nthen you can just invoke ``pytest`` directly:\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_example.txt .                                                   [100%]\n\n    ============================ 1 passed in 0.12s =============================\n\nBy default, pytest will collect ``test*.txt`` files looking for doctest directives, but you\ncan pass additional globs using the :option:`--doctest-glob` option (multi-allowed).\n\nIn addition to text files, you can also execute doctests directly from docstrings of your classes\nand functions, including from test modules:\n\n.. code-block:: python\n\n    # content of mymodule.py\n    def something():\n        \"\"\"a doctest in a docstring\n        >>> something()\n        42\n        \"\"\"\n        return 42\n\n.. code-block:: bash\n\n    $ pytest --doctest-modules\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 2 items\n\n    mymodule.py .                                                        [ 50%]\n    test_example.txt .                                                   [100%]\n\n    ============================ 2 passed in 0.12s =============================\n\nYou can make these changes permanent in your project by\nputting them into a configuration file like this:\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    [pytest]\n    addopts = [\"--doctest-modules\"]\n\nEncoding\n--------\n\nThe default encoding is **UTF-8**, but you can specify the encoding\nthat will be used for those doctest files using the\n:confval:`doctest_encoding` configuration option:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        doctest_encoding = \"latin1\"\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        doctest_encoding = latin1\n\n.. _using doctest options:\n\nUsing 'doctest' options\n-----------------------\n\nPython's standard :mod:`doctest` module provides some :ref:`options <python:option-flags-and-directives>`\nto configure the strictness of doctest tests. In pytest, you can enable those flags using the\nconfiguration file.\n\nFor example, to make pytest ignore trailing whitespaces and ignore\nlengthy exception stack traces you can just write:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        doctest_optionflags = [\"NORMALIZE_WHITESPACE\", \"IGNORE_EXCEPTION_DETAIL\"]\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        doctest_optionflags = NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL\n\nAlternatively, options can be enabled by an inline comment in the doc test\nitself:\n\n.. code-block:: rst\n\n    >>> something_that_raises()  # doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n    ValueError: ...\n\npytest also introduces new options:\n\n* ``ALLOW_UNICODE``: when enabled, the ``u`` prefix is stripped from unicode\n  strings in expected doctest output. This allows doctests to run in Python 2\n  and Python 3 unchanged.\n\n* ``ALLOW_BYTES``: similarly, the ``b`` prefix is stripped from byte strings\n  in expected doctest output.\n\n* ``NUMBER``: when enabled, floating-point numbers only need to match as far as\n  the precision you have written in the expected doctest output. The numbers are\n  compared using :func:`pytest.approx` with relative tolerance equal to the\n  precision. For example, the following output would only need to match to 2\n  decimal places when comparing ``3.14`` to\n  ``pytest.approx(math.pi, rel=10**-2)``::\n\n      >>> math.pi\n      3.14\n\n  If you wrote ``3.1416`` then the actual output would need to match to\n  approximately 4 decimal places; and so on.\n\n  This avoids false positives caused by limited floating-point precision, like\n  this::\n\n      Expected:\n          0.233\n      Got:\n          0.23300000000000001\n\n  ``NUMBER`` also supports lists of floating-point numbers -- in fact, it\n  matches floating-point numbers appearing anywhere in the output, even inside\n  a string! This means that it may not be appropriate to enable globally in\n  ``doctest_optionflags`` in your configuration file.\n\n  .. versionadded:: 5.1\n\n\nContinue on failure\n-------------------\n\nBy default, pytest would report only the first failure for a given doctest. If\nyou want to continue the test even when you have failures, do:\n\n.. code-block:: bash\n\n    pytest --doctest-modules --doctest-continue-on-failure\n\n\nOutput format\n-------------\n\nYou can change the diff output format on failure for your doctests\nby using one of the standard doctest module's format options\n(see :data:`python:doctest.REPORT_UDIFF`, :data:`python:doctest.REPORT_CDIFF`,\n:data:`python:doctest.REPORT_NDIFF`, :data:`python:doctest.REPORT_ONLY_FIRST_FAILURE`):\n\n.. code-block:: bash\n\n    pytest --doctest-modules --doctest-report none\n    pytest --doctest-modules --doctest-report udiff\n    pytest --doctest-modules --doctest-report cdiff\n    pytest --doctest-modules --doctest-report ndiff\n    pytest --doctest-modules --doctest-report only_first_failure\n\n\npytest-specific features\n------------------------\n\nSome features are provided to make writing doctests easier or with better integration with\nyour existing test suite. Keep in mind however that by using those features you will make\nyour doctests incompatible with the standard ``doctests`` module.\n\nUsing fixtures\n^^^^^^^^^^^^^^\n\nIt is possible to use fixtures using the ``getfixture`` helper:\n\n.. code-block:: text\n\n    # content of example.rst\n    >>> tmp = getfixture('tmp_path')\n    >>> ...\n    >>>\n\nNote that the fixture needs to be defined in a place visible by pytest, for example, a `conftest.py`\nfile or plugin; normal python files containing docstrings are not normally scanned for fixtures\nunless explicitly configured by :confval:`python_files`.\n\nAlso, the :ref:`usefixtures <usefixtures>` mark and fixtures marked as :ref:`autouse <autouse>` are supported\nwhen executing text doctest files.\n\n\n.. _`doctest_namespace`:\n\n'doctest_namespace' fixture\n^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe ``doctest_namespace`` fixture can be used to inject items into the\nnamespace in which your doctests run. It is intended to be used within\nyour own fixtures to provide the tests that use them with context.\n\n``doctest_namespace`` is a standard ``dict`` object into which you\nplace the objects you want to appear in the doctest namespace:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import pytest\n    import numpy\n\n\n    @pytest.fixture(autouse=True)\n    def add_np(doctest_namespace):\n        doctest_namespace[\"np\"] = numpy\n\nwhich can then be used in your doctests directly:\n\n.. code-block:: python\n\n    # content of numpy.py\n    def arange():\n        \"\"\"\n        >>> a = np.arange(10)\n        >>> len(a)\n        10\n        \"\"\"\n\nNote that like the normal ``conftest.py``, the fixtures are discovered in the directory tree conftest is in.\nMeaning that if you put your doctest with your source code, the relevant conftest.py needs to be in the same directory tree.\nFixtures will not be discovered in a sibling directory tree!\n\nSkipping tests\n^^^^^^^^^^^^^^\n\nFor the same reasons one might want to skip normal tests, it is also possible to skip\ntests inside doctests.\n\nTo skip a single check inside a doctest you can use the standard\n:data:`doctest.SKIP` directive:\n\n.. code-block:: python\n\n    def test_random(y):\n        \"\"\"\n        >>> random.random()  # doctest: +SKIP\n        0.156231223\n\n        >>> 1 + 1\n        2\n        \"\"\"\n\nThis will skip the first check, but not the second.\n\npytest also allows using the standard pytest functions :func:`pytest.skip` and\n:func:`pytest.xfail` inside doctests, which might be useful because you can\nthen skip/xfail tests based on external conditions:\n\n\n.. code-block:: text\n\n    >>> import sys, pytest\n    >>> if sys.platform.startswith('win'):\n    ...     pytest.skip('this doctest does not work on Windows')\n    ...\n    >>> import fcntl\n    >>> ...\n\nHowever using those functions is discouraged because it reduces the readability of the\ndocstring.\n\n.. note::\n\n    :func:`pytest.skip` and :func:`pytest.xfail` behave differently depending\n    if the doctests are in a Python file (in docstrings) or a text file containing\n    doctests intermingled with text:\n\n    * Python modules (docstrings): the functions only act in that specific docstring,\n      letting the other docstrings in the same module execute as normal.\n\n    * Text files: the functions will skip/xfail the checks for the rest of the entire\n      file.\n\n\nAlternatives\n------------\n\nWhile the built-in pytest support provides a good set of functionalities for using\ndoctests, if you use them extensively you might be interested in those external packages\nwhich add many more features, and include pytest integration:\n\n* `pytest-doctestplus <https://github.com/scientific-python/pytest-doctestplus>`__: provides\n  advanced doctest support and enables the testing of reStructuredText (\".rst\") files.\n\n* `Sybil <https://sybil.readthedocs.io>`__: provides a way to test examples in\n  your documentation by parsing them from the documentation source and evaluating\n  the parsed examples as part of your normal test run.\n"
  },
  {
    "path": "doc/en/how-to/existingtestsuite.rst",
    "content": ".. _existingtestsuite:\n\nHow to use pytest with an existing test suite\n==============================================\n\nPytest can be used with most existing test suites, but its\nbehavior differs from other test runners such as Python's\ndefault unittest framework.\n\nBefore using this section you will want to :ref:`install pytest <getstarted>`.\n\nRunning an existing test suite with pytest\n---------------------------------------------\n\nSay you want to contribute to an existing repository somewhere.\nAfter pulling the code into your development space using some\nflavor of version control and (optionally) setting up a virtualenv\nyou will want to run:\n\n.. code-block:: bash\n\n    cd <repository>\n    pip install -e .  # Environment dependent alternatives include\n                      # 'python setup.py develop' and 'conda develop'\n\nin your project root.  This will set up a symlink to your code in\nsite-packages, allowing you to edit your code while your tests\nrun against it as if it were installed.\n\nSetting up your project in development mode lets you avoid having to\nreinstall every time you want to run your tests, and is less brittle than\nmucking about with sys.path to point your tests at local code.\n\nAlso consider using :ref:`tox <use tox>`.\n"
  },
  {
    "path": "doc/en/how-to/failures.rst",
    "content": ".. _how-to-handle-failures:\n\nHow to handle test failures\n=============================\n\n.. _maxfail:\n\nStopping after the first (or N) failures\n---------------------------------------------------\n\nTo stop the testing process after the first (N) failures:\n\n.. code-block:: bash\n\n    pytest -x           # stop after first failure\n    pytest --maxfail=2  # stop after two failures\n\n\n.. _pdb-option:\n\nUsing :doc:`python:library/pdb` with pytest\n-------------------------------------------\n\nDropping to :doc:`pdb <python:library/pdb>` on failures\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nPython comes with a builtin Python debugger called :doc:`pdb <python:library/pdb>`.  ``pytest``\nallows one to drop into the :doc:`pdb <python:library/pdb>` prompt via a command line option:\n\n.. code-block:: bash\n\n    pytest --pdb\n\nThis will invoke the Python debugger on every failure (or KeyboardInterrupt).\nOften you might only want to do this for the first failing test to understand\na certain failure situation:\n\n.. code-block:: bash\n\n    pytest -x --pdb   # drop to PDB on first failure, then end test session\n    pytest --pdb --maxfail=3  # drop to PDB for first three failures\n\nNote that on any failure the exception information is stored on\n``sys.last_value``, ``sys.last_type`` and ``sys.last_traceback``. In\ninteractive use, this allows one to drop into postmortem debugging with\nany debug tool. One can also manually access the exception information,\nfor example::\n\n    >>> import sys\n    >>> sys.last_traceback.tb_lineno\n    42\n    >>> sys.last_value\n    AssertionError('assert result == \"ok\"',)\n\n\n.. _trace-option:\n\nDropping to :doc:`pdb <python:library/pdb>` at the start of a test\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n``pytest`` allows one to drop into the :doc:`pdb <python:library/pdb>` prompt immediately at the start of each test via a command line option:\n\n.. code-block:: bash\n\n    pytest --trace\n\nThis will invoke the Python debugger at the start of every test.\n\n.. _breakpoints:\n\nSetting breakpoints\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. versionadded: 2.4.0\n\nTo set a breakpoint in your code use the native Python ``import pdb;pdb.set_trace()`` call\nin your code and pytest automatically disables its output capture for that test:\n\n* Output capture in other tests is not affected.\n* Any prior test output that has already been captured and will be processed as\n  such.\n* Output capture gets resumed when ending the debugger session (via the\n  ``continue`` command).\n\n\n.. _`breakpoint-builtin`:\n\nUsing the builtin breakpoint function\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nPython 3.7 introduces a builtin ``breakpoint()`` function.\nPytest supports the use of ``breakpoint()`` with the following behaviours:\n\n - When ``breakpoint()`` is called and ``PYTHONBREAKPOINT`` is set to the default value, pytest will use the custom internal PDB trace UI instead of the system default ``Pdb``.\n - When tests are complete, the system will default back to the system ``Pdb`` trace UI.\n - With :option:`--pdb` passed to pytest, the custom internal Pdb trace UI is used with both ``breakpoint()`` and failed tests/unhandled exceptions.\n - :option:`--pdbcls` can be used to specify a custom debugger class.\n\n\n.. _faulthandler:\n\nFault Handler\n-------------\n\n.. versionadded:: 5.0\n\nThe :mod:`faulthandler` standard module\ncan be used to dump Python tracebacks on a segfault or after a timeout.\n\nThe module is automatically enabled for pytest runs, unless the ``-p no:faulthandler`` is given\non the command-line.\n\nAlso the :confval:`faulthandler_timeout=X<faulthandler_timeout>` configuration option can be used\nto dump the traceback of all threads if a test takes longer than ``X``\nseconds to finish.\n\n.. note::\n\n    This functionality has been integrated from the external\n    `pytest-faulthandler <https://github.com/pytest-dev/pytest-faulthandler>`__ plugin, with two\n    small differences:\n\n    * To disable it, use ``-p no:faulthandler`` instead of ``--no-faulthandler``: the former\n      can be used with any plugin, so it saves one option.\n\n    * The ``--faulthandler-timeout`` command-line option has become the\n      :confval:`faulthandler_timeout` configuration option. It can still be configured from\n      the command-line using ``-o faulthandler_timeout=X``.\n\n\n.. _unraisable:\n\nWarning about unraisable exceptions and unhandled thread exceptions\n-------------------------------------------------------------------\n\n.. versionadded:: 6.2\n\nUnhandled exceptions are exceptions that are raised in a situation in which\nthey cannot propagate to a caller. The most common case is an exception raised\nin a :meth:`__del__ <object.__del__>` implementation.\n\nUnhandled thread exceptions are exceptions raised in a :class:`~threading.Thread`\nbut not handled, causing the thread to terminate uncleanly.\n\nBoth types of exceptions are normally considered bugs, but may go unnoticed\nbecause they don't cause the program itself to crash. Pytest detects these\nconditions and issues a warning that is visible in the test run summary.\n\nThe plugins are automatically enabled for pytest runs, unless the\n``-p no:unraisableexception`` (for unraisable exceptions) and\n``-p no:threadexception`` (for thread exceptions) options are given on the\ncommand-line.\n\nThe warnings may be silenced selectively using the :ref:`pytest.mark.filterwarnings ref`\nmark. The warning categories are :class:`pytest.PytestUnraisableExceptionWarning` and\n:class:`pytest.PytestUnhandledThreadExceptionWarning`.\n"
  },
  {
    "path": "doc/en/how-to/fixtures.rst",
    "content": ".. _how-to-fixtures:\n\nHow to use fixtures\n====================\n\n.. seealso:: :ref:`about-fixtures`\n.. seealso:: :ref:`Fixtures reference <reference-fixtures>`\n\n\n\"Requesting\" fixtures\n---------------------\n\nAt a basic level, test functions request fixtures they require by declaring\nthem as arguments.\n\nWhen pytest goes to run a test, it looks at the parameters in that test\nfunction's signature, and then searches for fixtures that have the same names as\nthose parameters. Once pytest finds them, it runs those fixtures, captures what\nthey returned (if anything), and passes those objects into the test function as\narguments.\n\n\nQuick example\n^^^^^^^^^^^^^\n\n.. code-block:: python\n\n    import pytest\n\n\n    class Fruit:\n        def __init__(self, name):\n            self.name = name\n            self.cubed = False\n\n        def cube(self):\n            self.cubed = True\n\n\n    class FruitSalad:\n        def __init__(self, *fruit_bowl):\n            self.fruit = fruit_bowl\n            self._cube_fruit()\n\n        def _cube_fruit(self):\n            for fruit in self.fruit:\n                fruit.cube()\n\n\n    # Arrange\n    @pytest.fixture\n    def fruit_bowl():\n        return [Fruit(\"apple\"), Fruit(\"banana\")]\n\n\n    def test_fruit_salad(fruit_bowl):\n        # Act\n        fruit_salad = FruitSalad(*fruit_bowl)\n\n        # Assert\n        assert all(fruit.cubed for fruit in fruit_salad.fruit)\n\nIn this example, ``test_fruit_salad`` \"**requests**\" ``fruit_bowl`` (i.e.\n``def test_fruit_salad(fruit_bowl):``), and when pytest sees this, it will\nexecute the ``fruit_bowl`` fixture function and pass the object it returns into\n``test_fruit_salad`` as the ``fruit_bowl`` argument.\n\nHere's roughly\nwhat's happening if we were to do it by hand:\n\n.. code-block:: python\n\n    def fruit_bowl():\n        return [Fruit(\"apple\"), Fruit(\"banana\")]\n\n\n    def test_fruit_salad(fruit_bowl):\n        # Act\n        fruit_salad = FruitSalad(*fruit_bowl)\n\n        # Assert\n        assert all(fruit.cubed for fruit in fruit_salad.fruit)\n\n\n    # Arrange\n    bowl = fruit_bowl()\n    test_fruit_salad(fruit_bowl=bowl)\n\n\nFixtures can **request** other fixtures\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nOne of pytest's greatest strengths is its extremely flexible fixture system. It\nallows us to boil down complex requirements for tests into more simple and\norganized functions, where we only need to have each one describe the things\nthey are dependent on. We'll get more into this further down, but for now,\nhere's a quick example to demonstrate how fixtures can use other fixtures:\n\n.. code-block:: python\n\n    # contents of test_append.py\n    import pytest\n\n\n    # Arrange\n    @pytest.fixture\n    def first_entry():\n        return \"a\"\n\n\n    # Arrange\n    @pytest.fixture\n    def order(first_entry):\n        return [first_entry]\n\n\n    def test_string(order):\n        # Act\n        order.append(\"b\")\n\n        # Assert\n        assert order == [\"a\", \"b\"]\n\n\nNotice that this is the same example from above, but very little changed. The\nfixtures in pytest **request** fixtures just like tests. All the same\n**requesting** rules apply to fixtures that do for tests. Here's how this\nexample would work if we did it by hand:\n\n.. code-block:: python\n\n    def first_entry():\n        return \"a\"\n\n\n    def order(first_entry):\n        return [first_entry]\n\n\n    def test_string(order):\n        # Act\n        order.append(\"b\")\n\n        # Assert\n        assert order == [\"a\", \"b\"]\n\n\n    entry = first_entry()\n    the_list = order(first_entry=entry)\n    test_string(order=the_list)\n\nFixtures are reusable\n^^^^^^^^^^^^^^^^^^^^^\n\nOne of the things that makes pytest's fixture system so powerful, is that it\ngives us the ability to define a generic setup step that can be reused over and\nover, just like a normal function would be used. Two different tests can request\nthe same fixture and have pytest give each test their own result from that\nfixture.\n\nThis is extremely useful for making sure tests aren't affected by each other. We\ncan use this system to make sure each test gets its own fresh batch of data and\nis starting from a clean state so it can provide consistent, repeatable results.\n\nHere's an example of how this can come in handy:\n\n.. code-block:: python\n\n    # contents of test_append.py\n    import pytest\n\n\n    # Arrange\n    @pytest.fixture\n    def first_entry():\n        return \"a\"\n\n\n    # Arrange\n    @pytest.fixture\n    def order(first_entry):\n        return [first_entry]\n\n\n    def test_string(order):\n        # Act\n        order.append(\"b\")\n\n        # Assert\n        assert order == [\"a\", \"b\"]\n\n\n    def test_int(order):\n        # Act\n        order.append(2)\n\n        # Assert\n        assert order == [\"a\", 2]\n\n\nEach test here is being given its own copy of that ``list`` object,\nwhich means the ``order`` fixture is getting executed twice (the same\nis true for the ``first_entry`` fixture). If we were to do this by hand as\nwell, it would look something like this:\n\n.. code-block:: python\n\n    def first_entry():\n        return \"a\"\n\n\n    def order(first_entry):\n        return [first_entry]\n\n\n    def test_string(order):\n        # Act\n        order.append(\"b\")\n\n        # Assert\n        assert order == [\"a\", \"b\"]\n\n\n    def test_int(order):\n        # Act\n        order.append(2)\n\n        # Assert\n        assert order == [\"a\", 2]\n\n\n    entry = first_entry()\n    the_list = order(first_entry=entry)\n    test_string(order=the_list)\n\n    entry = first_entry()\n    the_list = order(first_entry=entry)\n    test_int(order=the_list)\n\nA test/fixture can **request** more than one fixture at a time\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nTests and fixtures aren't limited to **requesting** a single fixture at a time.\nThey can request as many as they like. Here's another quick example to\ndemonstrate:\n\n.. code-block:: python\n\n    # contents of test_append.py\n    import pytest\n\n\n    # Arrange\n    @pytest.fixture\n    def first_entry():\n        return \"a\"\n\n\n    # Arrange\n    @pytest.fixture\n    def second_entry():\n        return 2\n\n\n    # Arrange\n    @pytest.fixture\n    def order(first_entry, second_entry):\n        return [first_entry, second_entry]\n\n\n    # Arrange\n    @pytest.fixture\n    def expected_list():\n        return [\"a\", 2, 3.0]\n\n\n    def test_string(order, expected_list):\n        # Act\n        order.append(3.0)\n\n        # Assert\n        assert order == expected_list\n\nFixtures can be **requested** more than once per test (return values are cached)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFixtures can also be **requested** more than once during the same test, and\npytest won't execute them again for that test. This means we can **request**\nfixtures in multiple fixtures that are dependent on them (and even again in the\ntest itself) without those fixtures being executed more than once.\n\n.. code-block:: python\n\n    # contents of test_append.py\n    import pytest\n\n\n    # Arrange\n    @pytest.fixture\n    def first_entry():\n        return \"a\"\n\n\n    # Arrange\n    @pytest.fixture\n    def order():\n        return []\n\n\n    # Act\n    @pytest.fixture\n    def append_first(order, first_entry):\n        return order.append(first_entry)\n\n\n    def test_string_only(append_first, order, first_entry):\n        # Assert\n        assert order == [first_entry]\n\nIf a **requested** fixture was executed once for every time it was **requested**\nduring a test, then this test would fail because both ``append_first`` and\n``test_string_only`` would see ``order`` as an empty list (i.e. ``[]``), but\nsince the return value of ``order`` was cached (along with any side effects\nexecuting it may have had) after the first time it was called, both the test and\n``append_first`` were referencing the same object, and the test saw the effect\n``append_first`` had on that object.\n\n.. _`autouse`:\n.. _`autouse fixtures`:\n\nAutouse fixtures (fixtures you don't have to request)\n-----------------------------------------------------\n\nSometimes you may want to have a fixture (or even several) that you know all\nyour tests will depend on. \"Autouse\" fixtures are a convenient way to make all\ntests automatically **request** them. This can cut out a\nlot of redundant **requests**, and can even provide more advanced fixture usage\n(more on that further down).\n\nWe can make a fixture an autouse fixture by passing in ``autouse=True`` to the\nfixture's decorator. Here's a simple example for how they can be used:\n\n.. code-block:: python\n\n    # contents of test_append.py\n    import pytest\n\n\n    @pytest.fixture\n    def first_entry():\n        return \"a\"\n\n\n    @pytest.fixture\n    def order(first_entry):\n        return []\n\n\n    @pytest.fixture(autouse=True)\n    def append_first(order, first_entry):\n        return order.append(first_entry)\n\n\n    def test_string_only(order, first_entry):\n        assert order == [first_entry]\n\n\n    def test_string_and_int(order, first_entry):\n        order.append(2)\n        assert order == [first_entry, 2]\n\nIn this example, the ``append_first`` fixture is an autouse fixture. Because it\nhappens automatically, both tests are affected by it, even though neither test\n**requested** it. That doesn't mean they *can't* be **requested** though; just\nthat it isn't *necessary*.\n\n.. _smtpshared:\n\nScope: sharing fixtures across classes, modules, packages or session\n--------------------------------------------------------------------\n\n.. regendoc:wipe\n\nFixtures requiring network access depend on connectivity and are\nusually time-expensive to create.  Extending the previous example, we\ncan add a ``scope=\"module\"`` parameter to the\n:py:func:`@pytest.fixture <pytest.fixture>` invocation\nto cause a ``smtp_connection`` fixture function, responsible to create a connection to a preexisting SMTP server, to only be invoked\nonce per test *module* (the default is to invoke once per test *function*).\nMultiple test functions in a test module will thus\neach receive the same ``smtp_connection`` fixture instance, thus saving time.\nPossible values for ``scope`` are: ``function``, ``class``, ``module``, ``package`` or ``session``.\n\nThe next example puts the fixture function into a separate ``conftest.py`` file\nso that tests from multiple test modules in the directory can\naccess the fixture function:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import smtplib\n\n    import pytest\n\n\n    @pytest.fixture(scope=\"module\")\n    def smtp_connection():\n        return smtplib.SMTP(\"smtp.gmail.com\", 587, timeout=5)\n\n\n.. code-block:: python\n\n    # content of test_module.py\n\n\n    def test_ehlo(smtp_connection):\n        response, msg = smtp_connection.ehlo()\n        assert response == 250\n        assert b\"smtp.gmail.com\" in msg\n        assert 0  # for demo purposes\n\n\n    def test_noop(smtp_connection):\n        response, msg = smtp_connection.noop()\n        assert response == 250\n        assert 0  # for demo purposes\n\nHere, the ``test_ehlo`` needs the ``smtp_connection`` fixture value.  pytest\nwill discover and call the :py:func:`@pytest.fixture <pytest.fixture>`\nmarked ``smtp_connection`` fixture function.  Running the test looks like this:\n\n.. code-block:: pytest\n\n    $ pytest test_module.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 2 items\n\n    test_module.py FF                                                    [100%]\n\n    ================================= FAILURES =================================\n    ________________________________ test_ehlo _________________________________\n\n    smtp_connection = <smtplib.SMTP object at 0xdeadbeef0001>\n\n        def test_ehlo(smtp_connection):\n            response, msg = smtp_connection.ehlo()\n            assert response == 250\n            assert b\"smtp.gmail.com\" in msg\n    >       assert 0  # for demo purposes\n            ^^^^^^^^\n    E       assert 0\n\n    test_module.py:7: AssertionError\n    ________________________________ test_noop _________________________________\n\n    smtp_connection = <smtplib.SMTP object at 0xdeadbeef0001>\n\n        def test_noop(smtp_connection):\n            response, msg = smtp_connection.noop()\n            assert response == 250\n    >       assert 0  # for demo purposes\n            ^^^^^^^^\n    E       assert 0\n\n    test_module.py:13: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_module.py::test_ehlo - assert 0\n    FAILED test_module.py::test_noop - assert 0\n    ============================ 2 failed in 0.12s =============================\n\nYou see the two ``assert 0`` failing and more importantly you can also see\nthat the **exact same** ``smtp_connection`` object was passed into the\ntwo test functions because pytest shows the incoming argument values in the\ntraceback.  As a result, the two test functions using ``smtp_connection`` run\nas quick as a single one because they reuse the same instance.\n\nIf you decide that you rather want to have a session-scoped ``smtp_connection``\ninstance, you can simply declare it:\n\n.. code-block:: python\n\n    @pytest.fixture(scope=\"session\")\n    def smtp_connection():\n        # the returned fixture value will be shared for\n        # all tests requesting it\n        ...\n\n\nFixture scopes\n^^^^^^^^^^^^^^\n\nFixtures are created when first requested by a test, and are destroyed based on their ``scope``:\n\n* ``function``: the default scope, the fixture is destroyed at the end of the test.\n* ``class``: the fixture is destroyed during teardown of the last test in the class.\n* ``module``: the fixture is destroyed during teardown of the last test in the module.\n* ``package``: the fixture is destroyed during teardown of the last test in the package where the fixture is defined, including sub-packages and sub-directories within it.\n* ``session``: the fixture is destroyed at the end of the test session.\n\n.. note::\n\n    Pytest only caches one instance of a fixture at a time, which\n    means that when using a parametrized fixture, pytest may invoke a fixture more than once in\n    the given scope.\n\n.. _dynamic scope:\n\nDynamic scope\n^^^^^^^^^^^^^\n\n.. versionadded:: 5.2\n\nIn some cases, you might want to change the scope of the fixture without changing the code.\nTo do that, pass a callable to ``scope``. The callable must return a string with a valid scope\nand will be executed only once - during the fixture definition. It will be called with two\nkeyword arguments - ``fixture_name`` as a string and ``config`` with a configuration object.\n\nThis can be especially useful when dealing with fixtures that need time for setup, like spawning\na docker container. You can use the command-line argument to control the scope of the spawned\ncontainers for different environments. See the example below.\n\n.. code-block:: python\n\n    def determine_scope(fixture_name, config):\n        if config.getoption(\"--keep-containers\", None):\n            return \"session\"\n        return \"function\"\n\n\n    @pytest.fixture(scope=determine_scope)\n    def docker_container():\n        yield spawn_container()\n\n\n\n.. _`finalization`:\n\nTeardown/Cleanup (AKA Fixture finalization)\n-------------------------------------------\n\nWhen we run our tests, we'll want to make sure they clean up after themselves so\nthey don't mess with any other tests (and also so that we don't leave behind a\nmountain of test data to bloat the system). Fixtures in pytest offer a very\nuseful teardown system, which allows us to define the specific steps necessary\nfor each fixture to clean up after itself.\n\nThis system can be leveraged in two ways.\n\n.. _`yield fixtures`:\n\n1. ``yield`` fixtures (recommended)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. regendoc: wipe\n\n\"Yield\" fixtures ``yield`` instead of ``return``. With these\nfixtures, we can run some code and pass an object back to the requesting\nfixture/test, just like with the other fixtures. The only differences are:\n\n1. ``return`` is swapped out for ``yield``.\n2. Any teardown code for that fixture is placed *after* the ``yield``.\n\nOnce pytest figures out a linear order for the fixtures, it will run each one up\nuntil it returns or yields, and then move on to the next fixture in the list to\ndo the same thing.\n\nOnce the test is finished, pytest will go back down the list of fixtures, but in\nthe *reverse order*, taking each one that yielded, and running the code inside\nit that was *after* the ``yield`` statement.\n\nAs a simple example, consider this basic email module:\n\n.. code-block:: python\n\n    # content of emaillib.py\n    class MailAdminClient:\n        def create_user(self):\n            return MailUser()\n\n        def delete_user(self, user):\n            # do some cleanup\n            pass\n\n\n    class MailUser:\n        def __init__(self):\n            self.inbox = []\n\n        def send_email(self, email, other):\n            other.inbox.append(email)\n\n        def clear_mailbox(self):\n            self.inbox.clear()\n\n\n    class Email:\n        def __init__(self, subject, body):\n            self.subject = subject\n            self.body = body\n\nLet's say we want to test sending email from one user to another. We'll have to\nfirst make each user, then send the email from one user to the other, and\nfinally assert that the other user received that message in their inbox. If we\nwant to clean up after the test runs, we'll likely have to make sure the other\nuser's mailbox is emptied before deleting that user, otherwise the system may\ncomplain.\n\nHere's what that might look like:\n\n.. code-block:: python\n\n    # content of test_emaillib.py\n    from emaillib import Email, MailAdminClient\n\n    import pytest\n\n\n    @pytest.fixture\n    def mail_admin():\n        return MailAdminClient()\n\n\n    @pytest.fixture\n    def sending_user(mail_admin):\n        user = mail_admin.create_user()\n        yield user\n        mail_admin.delete_user(user)\n\n\n    @pytest.fixture\n    def receiving_user(mail_admin):\n        user = mail_admin.create_user()\n        yield user\n        user.clear_mailbox()\n        mail_admin.delete_user(user)\n\n\n    def test_email_received(sending_user, receiving_user):\n        email = Email(subject=\"Hey!\", body=\"How's it going?\")\n        sending_user.send_email(email, receiving_user)\n        assert email in receiving_user.inbox\n\nBecause ``receiving_user`` is the last fixture to run during setup, it's the first to run\nduring teardown.\n\nThere is a risk that even having the order right on the teardown side of things\ndoesn't guarantee a safe cleanup. That's covered in a bit more detail in\n:ref:`safe teardowns`.\n\n.. code-block:: pytest\n\n   $ pytest -q test_emaillib.py\n   .                                                                    [100%]\n   1 passed in 0.12s\n\nHandling errors for yield fixture\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nIf a yield fixture raises an exception before yielding, pytest won't try to run\nthe teardown code after that yield fixture's ``yield`` statement. But, for every\nfixture that has already run successfully for that test, pytest will still\nattempt to tear them down as it normally would.\n\n2. Adding finalizers directly\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nWhile yield fixtures are considered to be the cleaner and more straightforward\noption, there is another choice, and that is to add \"finalizer\" functions\ndirectly to the test's `request-context`_ object. It brings a similar result as\nyield fixtures, but requires a bit more verbosity.\n\nIn order to use this approach, we have to request the `request-context`_ object\n(just like we would request another fixture) in the fixture we need to add\nteardown code for, and then pass a callable, containing that teardown code, to\nits ``addfinalizer`` method.\n\nWe have to be careful though, because pytest will run that finalizer once it's\nbeen added, even if that fixture raises an exception after adding the finalizer.\nSo to make sure we don't run the finalizer code when we wouldn't need to, we\nwould only add the finalizer once the fixture would have done something that\nwe'd need to teardown.\n\nHere's how the previous example would look using the ``addfinalizer`` method:\n\n.. code-block:: python\n\n    # content of test_emaillib.py\n    from emaillib import Email, MailAdminClient\n\n    import pytest\n\n\n    @pytest.fixture\n    def mail_admin():\n        return MailAdminClient()\n\n\n    @pytest.fixture\n    def sending_user(mail_admin):\n        user = mail_admin.create_user()\n        yield user\n        mail_admin.delete_user(user)\n\n\n    @pytest.fixture\n    def receiving_user(mail_admin, request):\n        user = mail_admin.create_user()\n\n        def delete_user():\n            mail_admin.delete_user(user)\n\n        request.addfinalizer(delete_user)\n        return user\n\n\n    @pytest.fixture\n    def email(sending_user, receiving_user, request):\n        _email = Email(subject=\"Hey!\", body=\"How's it going?\")\n        sending_user.send_email(_email, receiving_user)\n\n        def empty_mailbox():\n            receiving_user.clear_mailbox()\n\n        request.addfinalizer(empty_mailbox)\n        return _email\n\n\n    def test_email_received(receiving_user, email):\n        assert email in receiving_user.inbox\n\n\nIt's a bit longer than yield fixtures and a bit more complex, but it\ndoes offer some nuances for when you're in a pinch.\n\n.. code-block:: pytest\n\n   $ pytest -q test_emaillib.py\n   .                                                                    [100%]\n   1 passed in 0.12s\n\nNote on finalizer order\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nFinalizers are executed in a first-in-last-out order.\nFor yield fixtures, the first teardown code to run is from the right-most fixture, i.e. the last test parameter.\n\n\n.. code-block:: python\n\n    # content of test_finalizers.py\n    import pytest\n\n\n    def test_bar(fix_w_yield1, fix_w_yield2):\n        print(\"test_bar\")\n\n\n    @pytest.fixture\n    def fix_w_yield1():\n        yield\n        print(\"after_yield_1\")\n\n\n    @pytest.fixture\n    def fix_w_yield2():\n        yield\n        print(\"after_yield_2\")\n\n\n.. code-block:: pytest\n\n    $ pytest -s test_finalizers.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_finalizers.py test_bar\n    .after_yield_2\n    after_yield_1\n\n\n    ============================ 1 passed in 0.12s =============================\n\nFor finalizers, the first fixture to run is last call to `request.addfinalizer`.\n\n.. code-block:: python\n\n    # content of test_finalizers.py\n    from functools import partial\n    import pytest\n\n\n    @pytest.fixture\n    def fix_w_finalizers(request):\n        request.addfinalizer(partial(print, \"finalizer_2\"))\n        request.addfinalizer(partial(print, \"finalizer_1\"))\n\n\n    def test_bar(fix_w_finalizers):\n        print(\"test_bar\")\n\n\n.. code-block:: pytest\n\n    $ pytest -s test_finalizers.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_finalizers.py test_bar\n    .finalizer_1\n    finalizer_2\n\n\n    ============================ 1 passed in 0.12s =============================\n\nThis is so because yield fixtures use `addfinalizer` behind the scenes: when the fixture executes, `addfinalizer` registers a function that resumes the generator, which in turn calls the teardown code.\n\n\n.. _`safe teardowns`:\n\nSafe teardowns\n--------------\n\nThe fixture system of pytest is *very* powerful, but it's still being run by a\ncomputer, so it isn't able to figure out how to safely teardown everything we\nthrow at it. If we aren't careful, an error in the wrong spot might leave stuff\nfrom our tests behind, and that can cause further issues pretty quickly.\n\nFor example, consider the following tests (based off of the mail example from\nabove):\n\n.. code-block:: python\n\n    # content of test_emaillib.py\n    from emaillib import Email, MailAdminClient\n\n    import pytest\n\n\n    @pytest.fixture\n    def setup():\n        mail_admin = MailAdminClient()\n        sending_user = mail_admin.create_user()\n        receiving_user = mail_admin.create_user()\n        email = Email(subject=\"Hey!\", body=\"How's it going?\")\n        sending_user.send_email(email, receiving_user)\n        yield receiving_user, email\n        receiving_user.clear_mailbox()\n        mail_admin.delete_user(sending_user)\n        mail_admin.delete_user(receiving_user)\n\n\n    def test_email_received(setup):\n        receiving_user, email = setup\n        assert email in receiving_user.inbox\n\nThis version is a lot more compact, but it's also harder to read, doesn't have a\nvery descriptive fixture name, and none of the fixtures can be reused easily.\n\nThere's also a more serious issue, which is that if any of those steps in the\nsetup raise an exception, none of the teardown code will run.\n\nOne option might be to go with the ``addfinalizer`` method instead of yield\nfixtures, but that might get pretty complex and difficult to maintain (and it\nwouldn't be compact anymore).\n\n.. code-block:: pytest\n\n   $ pytest -q test_emaillib.py\n   .                                                                    [100%]\n   1 passed in 0.12s\n\n.. _`safe fixture structure`:\n\nSafe fixture structure\n^^^^^^^^^^^^^^^^^^^^^^\n\nThe safest and simplest fixture structure requires limiting fixtures to only\nmaking one state-changing action each, and then bundling them together with\ntheir teardown code, as :ref:`the email examples above <yield fixtures>` showed.\n\nThe chance that a state-changing operation can fail but still modify state is\nnegligible, as most of these operations tend to be `transaction\n<https://en.wikipedia.org/wiki/Transaction_processing>`_-based (at least at the\nlevel of testing where state could be left behind). So if we make sure that any\nsuccessful state-changing action gets torn down by moving it to a separate\nfixture function and separating it from other, potentially failing\nstate-changing actions, then our tests will stand the best chance at leaving\nthe test environment the way they found it.\n\nFor an example, let's say we have a website with a login page, and we have\naccess to an admin API where we can generate users. For our test, we want to:\n\n1. Create a user through that admin API\n2. Launch a browser using Selenium\n3. Go to the login page of our site\n4. Log in as the user we created\n5. Assert that their name is in the header of the landing page\n\nWe wouldn't want to leave that user in the system, nor would we want to leave\nthat browser session running, so we'll want to make sure the fixtures that\ncreate those things clean up after themselves.\n\nHere's what that might look like:\n\n.. note::\n\n    For this example, certain fixtures (i.e. ``base_url`` and\n    ``admin_credentials``) are implied to exist elsewhere. So for now, let's\n    assume they exist, and we're just not looking at them.\n\n.. code-block:: python\n\n    from uuid import uuid4\n    from urllib.parse import urljoin\n\n    from selenium.webdriver import Chrome\n    import pytest\n\n    from src.utils.pages import LoginPage, LandingPage\n    from src.utils import AdminApiClient\n    from src.utils.data_types import User\n\n\n    @pytest.fixture\n    def admin_client(base_url, admin_credentials):\n        return AdminApiClient(base_url, **admin_credentials)\n\n\n    @pytest.fixture\n    def user(admin_client):\n        _user = User(name=\"Susan\", username=f\"testuser-{uuid4()}\", password=\"P4$$word\")\n        admin_client.create_user(_user)\n        yield _user\n        admin_client.delete_user(_user)\n\n\n    @pytest.fixture\n    def driver():\n        _driver = Chrome()\n        yield _driver\n        _driver.quit()\n\n\n    @pytest.fixture\n    def login(driver, base_url, user):\n        driver.get(urljoin(base_url, \"/login\"))\n        page = LoginPage(driver)\n        page.login(user)\n\n\n    @pytest.fixture\n    def landing_page(driver, login):\n        return LandingPage(driver)\n\n\n    def test_name_on_landing_page_after_login(landing_page, user):\n        assert landing_page.header == f\"Welcome, {user.name}!\"\n\nThe way the dependencies are laid out means it's unclear if the ``user``\nfixture would execute before the ``driver`` fixture. But that's ok, because\nthose are atomic operations, and so it doesn't matter which one runs first\nbecause the sequence of events for the test is still `linearizable\n<https://en.wikipedia.org/wiki/Linearizability>`_. But what *does* matter is\nthat, no matter which one runs first, if the one raises an exception while the\nother would not have, neither will have left anything behind. If ``driver``\nexecutes before ``user``, and ``user`` raises an exception, the driver will\nstill quit, and the user was never made. And if ``driver`` was the one to raise\nthe exception, then the driver would never have been started and the user would\nnever have been made.\n\n.. note:\n\n    While the ``user`` fixture doesn't *actually* need to happen before the\n    ``driver`` fixture, if we made ``driver`` request ``user``, it might save\n    some time in the event that making the user raises an exception, since it\n    won't bother trying to start the driver, which is a fairly expensive\n    operation.\n\n\nRunning multiple ``assert`` statements safely\n---------------------------------------------\n\nSometimes you may want to run multiple asserts after doing all that setup, which\nmakes sense as, in more complex systems, a single action can kick off multiple\nbehaviors. pytest has a convenient way of handling this and it combines a bunch\nof what we've gone over so far.\n\nAll that's needed is stepping up to a larger scope, then having the **act**\nstep defined as an autouse fixture, and finally, making sure all the fixtures\nare targeting that higher level scope.\n\nLet's pull :ref:`an example from above <safe fixture structure>`, and tweak it a\nbit. Let's say that in addition to checking for a welcome message in the header,\nwe also want to check for a sign out button, and a link to the user's profile.\n\nLet's take a look at how we can structure that so we can run multiple asserts\nwithout having to repeat all those steps again.\n\n.. note::\n\n    For this example, certain fixtures (i.e. ``base_url`` and\n    ``admin_credentials``) are implied to exist elsewhere. So for now, let's\n    assume they exist, and we're just not looking at them.\n\n.. code-block:: python\n\n    # contents of tests/end_to_end/test_login.py\n    from uuid import uuid4\n    from urllib.parse import urljoin\n\n    from selenium.webdriver import Chrome\n    import pytest\n\n    from src.utils.pages import LoginPage, LandingPage\n    from src.utils import AdminApiClient\n    from src.utils.data_types import User\n\n\n    @pytest.fixture(scope=\"class\")\n    def admin_client(base_url, admin_credentials):\n        return AdminApiClient(base_url, **admin_credentials)\n\n\n    @pytest.fixture(scope=\"class\")\n    def user(admin_client):\n        _user = User(name=\"Susan\", username=f\"testuser-{uuid4()}\", password=\"P4$$word\")\n        admin_client.create_user(_user)\n        yield _user\n        admin_client.delete_user(_user)\n\n\n    @pytest.fixture(scope=\"class\")\n    def driver():\n        _driver = Chrome()\n        yield _driver\n        _driver.quit()\n\n\n    @pytest.fixture(scope=\"class\")\n    def landing_page(driver, login):\n        return LandingPage(driver)\n\n\n    class TestLandingPageSuccess:\n        @pytest.fixture(scope=\"class\", autouse=True)\n        def login(self, driver, base_url, user):\n            driver.get(urljoin(base_url, \"/login\"))\n            page = LoginPage(driver)\n            page.login(user)\n\n        def test_name_in_header(self, landing_page, user):\n            assert landing_page.header == f\"Welcome, {user.name}!\"\n\n        def test_sign_out_button(self, landing_page):\n            assert landing_page.sign_out_button.is_displayed()\n\n        def test_profile_link(self, landing_page, user):\n            profile_href = urljoin(base_url, f\"/profile?id={user.profile_id}\")\n            assert landing_page.profile_link.get_attribute(\"href\") == profile_href\n\nNotice that the methods are only referencing ``self`` in the signature as a\nformality. No state is tied to the actual test class as it might be in the\n``unittest.TestCase`` framework. Everything is managed by the pytest fixture\nsystem.\n\nEach method only has to request the fixtures that it actually needs without\nworrying about order. This is because the **act** fixture is an autouse fixture,\nand it made sure all the other fixtures executed before it. There's no more\nchanges of state that need to take place, so the tests are free to make as many\nnon-state-changing queries as they want without risking stepping on the toes of\nthe other tests.\n\nThe ``login`` fixture is defined inside the class as well, because not every one\nof the other tests in the module will be expecting a successful login, and the **act** may need to\nbe handled a little differently for another test class. For example, if we\nwanted to write another test scenario around submitting bad credentials, we\ncould handle it by adding something like this to the test file:\n\n.. note:\n\n    It's assumed that the page object for this (i.e. ``LoginPage``) raises a\n    custom exception, ``BadCredentialsException``, when it recognizes text\n    signifying that on the login form after attempting to log in.\n\n.. code-block:: python\n\n    class TestLandingPageBadCredentials:\n        @pytest.fixture(scope=\"class\")\n        def faux_user(self, user):\n            _user = deepcopy(user)\n            _user.password = \"badpass\"\n            return _user\n\n        def test_raises_bad_credentials_exception(self, login_page, faux_user):\n            with pytest.raises(BadCredentialsException):\n                login_page.login(faux_user)\n\n\n.. _`request-context`:\n\nFixtures can introspect the requesting test context\n-------------------------------------------------------------\n\nFixture functions can accept the :py:class:`request <_pytest.fixtures.FixtureRequest>` object\nto introspect the \"requesting\" test function, class or module context.\nFurther extending the previous ``smtp_connection`` fixture example, let's\nread an optional server URL from the test module which uses our fixture:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import smtplib\n\n    import pytest\n\n\n    @pytest.fixture(scope=\"module\")\n    def smtp_connection(request):\n        server = getattr(request.module, \"smtpserver\", \"smtp.gmail.com\")\n        smtp_connection = smtplib.SMTP(server, 587, timeout=5)\n        yield smtp_connection\n        print(f\"finalizing {smtp_connection} ({server})\")\n        smtp_connection.close()\n\nWe use the ``request.module`` attribute to optionally obtain an\n``smtpserver`` attribute from the test module.  If we just execute\nagain, nothing much has changed:\n\n.. code-block:: pytest\n\n    $ pytest -s -q --tb=no test_module.py\n    FFfinalizing <smtplib.SMTP object at 0xdeadbeef0002> (smtp.gmail.com)\n\n    ========================= short test summary info ==========================\n    FAILED test_module.py::test_ehlo - assert 0\n    FAILED test_module.py::test_noop - assert 0\n    2 failed in 0.12s\n\nLet's quickly create another test module that actually sets the\nserver URL in its module namespace:\n\n.. code-block:: python\n\n    # content of test_anothersmtp.py\n\n    smtpserver = \"mail.python.org\"  # will be read by smtp fixture\n\n\n    def test_showhelo(smtp_connection):\n        assert 0, smtp_connection.helo()\n\nRunning it:\n\n.. code-block:: pytest\n\n    $ pytest -qq --tb=short test_anothersmtp.py\n    F                                                                    [100%]\n    ================================= FAILURES =================================\n    ______________________________ test_showhelo _______________________________\n    test_anothersmtp.py:6: in test_showhelo\n        assert 0, smtp_connection.helo()\n    E   AssertionError: (250, b'mail.python.org')\n    E   assert 0\n    ------------------------- Captured stdout teardown -------------------------\n    finalizing <smtplib.SMTP object at 0xdeadbeef0003> (mail.python.org)\n    ========================= short test summary info ==========================\n    FAILED test_anothersmtp.py::test_showhelo - AssertionError: (250, b'mail....\n\nvoila! The ``smtp_connection`` fixture function picked up our mail server name\nfrom the module namespace.\n\n.. _`using-markers`:\n\nUsing markers to pass data to fixtures\n-------------------------------------------------------------\n\nUsing the :py:class:`request <_pytest.fixtures.FixtureRequest>` object, a fixture can also access\nmarkers which are applied to a test function. This can be useful to pass data\ninto a fixture from a test:\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.fixture\n    def fixt(request):\n        marker = request.node.get_closest_marker(\"fixt_data\")\n        if marker is None:\n            # Handle missing marker in some way...\n            data = None\n        else:\n            data = marker.args[0]\n\n        # Do something with the data\n        return data\n\n\n    @pytest.mark.fixt_data(42)\n    def test_fixt(fixt):\n        assert fixt == 42\n\n.. _`fixture-factory`:\n\nFactories as fixtures\n-------------------------------------------------------------\n\nThe \"factory as fixture\" pattern can help in situations where the result\nof a fixture is needed multiple times in a single test. Instead of returning\ndata directly, the fixture instead returns a function which generates the data.\nThis function can then be called multiple times in the test.\n\nFactories can have parameters as needed:\n\n.. code-block:: python\n\n    @pytest.fixture\n    def make_customer_record():\n        def _make_customer_record(name):\n            return {\"name\": name, \"orders\": []}\n\n        return _make_customer_record\n\n\n    def test_customer_records(make_customer_record):\n        customer_1 = make_customer_record(\"Lisa\")\n        customer_2 = make_customer_record(\"Mike\")\n        customer_3 = make_customer_record(\"Meredith\")\n\nIf the data created by the factory requires managing, the fixture can take care of that:\n\n.. code-block:: python\n\n    @pytest.fixture\n    def make_customer_record():\n        created_records = []\n\n        def _make_customer_record(name):\n            record = models.Customer(name=name, orders=[])\n            created_records.append(record)\n            return record\n\n        yield _make_customer_record\n\n        for record in created_records:\n            record.destroy()\n\n\n    def test_customer_records(make_customer_record):\n        customer_1 = make_customer_record(\"Lisa\")\n        customer_2 = make_customer_record(\"Mike\")\n        customer_3 = make_customer_record(\"Meredith\")\n\n\n.. _`fixture-parametrize`:\n\nParametrizing fixtures\n-----------------------------------------------------------------\n\nFixture functions can be parametrized in which case they will be called\nmultiple times, each time executing the set of dependent tests, i.e. the\ntests that depend on this fixture.  Test functions usually do not need\nto be aware of their re-running.  Fixture parametrization helps to\nwrite exhaustive functional tests for components which themselves can be\nconfigured in multiple ways.\n\nExtending the previous example, we can flag the fixture to create two\n``smtp_connection`` fixture instances which will cause all tests using the fixture\nto run twice.  The fixture function gets access to each parameter\nthrough the special :py:class:`request <pytest.FixtureRequest>` object:\n\n.. code-block:: python\n\n    # content of conftest.py\n    import smtplib\n\n    import pytest\n\n\n    @pytest.fixture(scope=\"module\", params=[\"smtp.gmail.com\", \"mail.python.org\"])\n    def smtp_connection(request):\n        smtp_connection = smtplib.SMTP(request.param, 587, timeout=5)\n        yield smtp_connection\n        print(f\"finalizing {smtp_connection}\")\n        smtp_connection.close()\n\nThe main change is the declaration of ``params`` with\n:py:func:`@pytest.fixture <pytest.fixture>`, a list of values\nfor each of which the fixture function will execute and can access\na value via ``request.param``.  No test function code needs to change.\nSo let's just do another run:\n\n.. code-block:: pytest\n\n    $ pytest -q test_module.py\n    FFFF                                                                 [100%]\n    ================================= FAILURES =================================\n    ________________________ test_ehlo[smtp.gmail.com] _________________________\n\n    smtp_connection = <smtplib.SMTP object at 0xdeadbeef0004>\n\n        def test_ehlo(smtp_connection):\n            response, msg = smtp_connection.ehlo()\n            assert response == 250\n            assert b\"smtp.gmail.com\" in msg\n    >       assert 0  # for demo purposes\n            ^^^^^^^^\n    E       assert 0\n\n    test_module.py:7: AssertionError\n    ________________________ test_noop[smtp.gmail.com] _________________________\n\n    smtp_connection = <smtplib.SMTP object at 0xdeadbeef0004>\n\n        def test_noop(smtp_connection):\n            response, msg = smtp_connection.noop()\n            assert response == 250\n    >       assert 0  # for demo purposes\n            ^^^^^^^^\n    E       assert 0\n\n    test_module.py:13: AssertionError\n    ________________________ test_ehlo[mail.python.org] ________________________\n\n    smtp_connection = <smtplib.SMTP object at 0xdeadbeef0005>\n\n        def test_ehlo(smtp_connection):\n            response, msg = smtp_connection.ehlo()\n            assert response == 250\n    >       assert b\"smtp.gmail.com\" in msg\n    E       AssertionError: assert b'smtp.gmail.com' in b'mail.python.org\\nPIPELINING\\nSIZE 51200000\\nETRN\\nSTARTTLS\\nAUTH DIGEST-MD5 NTLM CRAM-MD5\\nENHANCEDSTATUSCODES\\n8BITMIME\\nDSN\\nSMTPUTF8\\nCHUNKING'\n\n    test_module.py:6: AssertionError\n    -------------------------- Captured stdout setup ---------------------------\n    finalizing <smtplib.SMTP object at 0xdeadbeef0004>\n    ________________________ test_noop[mail.python.org] ________________________\n\n    smtp_connection = <smtplib.SMTP object at 0xdeadbeef0005>\n\n        def test_noop(smtp_connection):\n            response, msg = smtp_connection.noop()\n            assert response == 250\n    >       assert 0  # for demo purposes\n            ^^^^^^^^\n    E       assert 0\n\n    test_module.py:13: AssertionError\n    ------------------------- Captured stdout teardown -------------------------\n    finalizing <smtplib.SMTP object at 0xdeadbeef0005>\n    ========================= short test summary info ==========================\n    FAILED test_module.py::test_ehlo[smtp.gmail.com] - assert 0\n    FAILED test_module.py::test_noop[smtp.gmail.com] - assert 0\n    FAILED test_module.py::test_ehlo[mail.python.org] - AssertionError: asser...\n    FAILED test_module.py::test_noop[mail.python.org] - assert 0\n    4 failed in 0.12s\n\nWe see that our two test functions each ran twice, against the different\n``smtp_connection`` instances.  Note also, that with the ``mail.python.org``\nconnection the second test fails in ``test_ehlo`` because a\ndifferent server string is expected than what arrived.\n\npytest will build a string that is the test ID for each fixture value\nin a parametrized fixture, e.g. ``test_ehlo[smtp.gmail.com]`` and\n``test_ehlo[mail.python.org]`` in the above examples.  These IDs can\nbe used with :option:`-k` to select specific cases to run, and they will\nalso identify the specific case when one is failing.  Running pytest\nwith :option:`--collect-only` will show the generated IDs.\n\nNumbers, strings, booleans and ``None`` will have their usual string\nrepresentation used in the test ID. For other objects, pytest will\nmake a string based on the argument name.  It is possible to customise\nthe string used in a test ID for a certain fixture value by using the\n``ids`` keyword argument:\n\n.. code-block:: python\n\n   # content of test_ids.py\n   import pytest\n\n\n   @pytest.fixture(params=[0, 1], ids=[\"spam\", \"ham\"])\n   def a(request):\n       return request.param\n\n\n   def test_a(a):\n       pass\n\n\n   def idfn(fixture_value):\n       if fixture_value == 0:\n           return \"eggs\"\n       else:\n           return None\n\n\n   @pytest.fixture(params=[0, 1], ids=idfn)\n   def b(request):\n       return request.param\n\n\n   def test_b(b):\n       pass\n\nThe above shows how ``ids`` can be either a list of strings to use or\na function which will be called with the fixture value and then\nhas to return a string to use.  In the latter case if the function\nreturns ``None`` then pytest's auto-generated ID will be used.\n\nRunning the above tests results in the following test IDs being used:\n\n.. code-block:: pytest\n\n   $ pytest --collect-only\n   =========================== test session starts ============================\n   platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n   rootdir: /home/sweet/project\n   collected 12 items\n\n   <Dir fixtures.rst-233>\n     <Module test_anothersmtp.py>\n       <Function test_showhelo[smtp.gmail.com]>\n       <Function test_showhelo[mail.python.org]>\n     <Module test_emaillib.py>\n       <Function test_email_received>\n     <Module test_finalizers.py>\n       <Function test_bar>\n     <Module test_ids.py>\n       <Function test_a[spam]>\n       <Function test_a[ham]>\n       <Function test_b[eggs]>\n       <Function test_b[1]>\n     <Module test_module.py>\n       <Function test_ehlo[smtp.gmail.com]>\n       <Function test_noop[smtp.gmail.com]>\n       <Function test_ehlo[mail.python.org]>\n       <Function test_noop[mail.python.org]>\n\n   ======================= 12 tests collected in 0.12s ========================\n\n.. _`fixture-parametrize-marks`:\n\nUsing marks with parametrized fixtures\n--------------------------------------\n\n:func:`pytest.param` can be used to apply marks in values sets of parametrized fixtures in the same way\nthat they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`.\n\nExample:\n\n.. code-block:: python\n\n    # content of test_fixture_marks.py\n    import pytest\n\n\n    @pytest.fixture(params=[0, 1, pytest.param(2, marks=pytest.mark.skip)])\n    def data_set(request):\n        return request.param\n\n\n    def test_data(data_set):\n        pass\n\nRunning this test will *skip* the invocation of ``data_set`` with value ``2``:\n\n.. code-block:: pytest\n\n    $ pytest test_fixture_marks.py -v\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 3 items\n\n    test_fixture_marks.py::test_data[0] PASSED                           [ 33%]\n    test_fixture_marks.py::test_data[1] PASSED                           [ 66%]\n    test_fixture_marks.py::test_data[2] SKIPPED (unconditional skip)     [100%]\n\n    ======================= 2 passed, 1 skipped in 0.12s =======================\n\n.. _`interdependent fixtures`:\n\nModularity: using fixtures from a fixture function\n----------------------------------------------------------\n\nIn addition to using fixtures in test functions, fixture functions\ncan use other fixtures themselves.  This contributes to a modular design\nof your fixtures and allows reuse of framework-specific fixtures across\nmany projects.  As a simple example, we can extend the previous example\nand instantiate an object ``app`` where we stick the already defined\n``smtp_connection`` resource into it:\n\n.. code-block:: python\n\n    # content of test_appsetup.py\n\n    import pytest\n\n\n    class App:\n        def __init__(self, smtp_connection):\n            self.smtp_connection = smtp_connection\n\n\n    @pytest.fixture(scope=\"module\")\n    def app(smtp_connection):\n        return App(smtp_connection)\n\n\n    def test_smtp_connection_exists(app):\n        assert app.smtp_connection\n\nHere we declare an ``app`` fixture which receives the previously defined\n``smtp_connection`` fixture and instantiates an ``App`` object with it.  Let's run it:\n\n.. code-block:: pytest\n\n    $ pytest -v test_appsetup.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 2 items\n\n    test_appsetup.py::test_smtp_connection_exists[smtp.gmail.com] PASSED [ 50%]\n    test_appsetup.py::test_smtp_connection_exists[mail.python.org] PASSED [100%]\n\n    ============================ 2 passed in 0.12s =============================\n\nDue to the parametrization of ``smtp_connection``, the test will run twice with two\ndifferent ``App`` instances and respective smtp servers.  There is no\nneed for the ``app`` fixture to be aware of the ``smtp_connection``\nparametrization because pytest will fully analyse the fixture dependency graph.\n\nNote that the ``app`` fixture has a scope of ``module`` and uses a\nmodule-scoped ``smtp_connection`` fixture.  The example would still work if\n``smtp_connection`` was cached on a ``session`` scope: it is fine for fixtures to use\n\"broader\" scoped fixtures but not the other way round:\nA session-scoped fixture could not use a module-scoped one in a\nmeaningful way.\n\n\n.. _`automatic per-resource grouping`:\n\nAutomatic grouping of tests by fixture instances\n----------------------------------------------------------\n\n.. regendoc: wipe\n\npytest minimizes the number of active fixtures during test runs.\nIf you have a parametrized fixture, then all the tests using it will\nfirst execute with one instance and then finalizers are called\nbefore the next fixture instance is created.  Among other things,\nthis eases testing of applications which create and use global state.\n\nThe following example uses two parametrized fixtures, one of which is\nscoped on a per-module basis, and all the functions perform ``print`` calls\nto show the setup/teardown flow:\n\n.. code-block:: python\n\n    # content of test_module.py\n    import pytest\n\n\n    @pytest.fixture(scope=\"module\", params=[\"mod1\", \"mod2\"])\n    def modarg(request):\n        param = request.param\n        print(\"  SETUP modarg\", param)\n        yield param\n        print(\"  TEARDOWN modarg\", param)\n\n\n    @pytest.fixture(scope=\"function\", params=[1, 2])\n    def otherarg(request):\n        param = request.param\n        print(\"  SETUP otherarg\", param)\n        yield param\n        print(\"  TEARDOWN otherarg\", param)\n\n\n    def test_0(otherarg):\n        print(\"  RUN test0 with otherarg\", otherarg)\n\n\n    def test_1(modarg):\n        print(\"  RUN test1 with modarg\", modarg)\n\n\n    def test_2(otherarg, modarg):\n        print(f\"  RUN test2 with otherarg {otherarg} and modarg {modarg}\")\n\n\nLet's run the tests in verbose mode and with looking at the print-output:\n\n.. code-block:: pytest\n\n    $ pytest -v -s test_module.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y -- $PYTHON_PREFIX/bin/python\n    cachedir: .pytest_cache\n    rootdir: /home/sweet/project\n    collecting ... collected 8 items\n\n    test_module.py::test_0[1]   SETUP otherarg 1\n      RUN test0 with otherarg 1\n    PASSED  TEARDOWN otherarg 1\n\n    test_module.py::test_0[2]   SETUP otherarg 2\n      RUN test0 with otherarg 2\n    PASSED  TEARDOWN otherarg 2\n\n    test_module.py::test_1[mod1]   SETUP modarg mod1\n      RUN test1 with modarg mod1\n    PASSED\n    test_module.py::test_2[mod1-1]   SETUP otherarg 1\n      RUN test2 with otherarg 1 and modarg mod1\n    PASSED  TEARDOWN otherarg 1\n\n    test_module.py::test_2[mod1-2]   SETUP otherarg 2\n      RUN test2 with otherarg 2 and modarg mod1\n    PASSED  TEARDOWN otherarg 2\n\n    test_module.py::test_1[mod2]   TEARDOWN modarg mod1\n      SETUP modarg mod2\n      RUN test1 with modarg mod2\n    PASSED\n    test_module.py::test_2[mod2-1]   SETUP otherarg 1\n      RUN test2 with otherarg 1 and modarg mod2\n    PASSED  TEARDOWN otherarg 1\n\n    test_module.py::test_2[mod2-2]   SETUP otherarg 2\n      RUN test2 with otherarg 2 and modarg mod2\n    PASSED  TEARDOWN otherarg 2\n      TEARDOWN modarg mod2\n\n\n    ============================ 8 passed in 0.12s =============================\n\nYou can see that the parametrized module-scoped ``modarg`` resource caused an\nordering of test execution that led to the fewest possible \"active\" resources.\nThe finalizer for the ``mod1`` parametrized resource was executed before the\n``mod2`` resource was setup.\n\nIn particular notice that test_0 is completely independent and finishes first.\nThen test_1 is executed with ``mod1``, then test_2 with ``mod1``, then test_1\nwith ``mod2`` and finally test_2 with ``mod2``.\n\nThe ``otherarg`` parametrized resource (having function scope) was set up before\nand torn down after every test that used it.\n\n\n.. _`usefixtures`:\n\nUse fixtures in classes and modules with ``usefixtures``\n--------------------------------------------------------\n\n.. regendoc:wipe\n\nSometimes test functions do not directly need access to a fixture object.\nFor example, tests may require to operate with an empty directory as the\ncurrent working directory but otherwise do not care for the concrete\ndirectory.  Here is how you can use the standard :mod:`tempfile`\nand pytest fixtures to\nachieve it.  We separate the creation of the fixture into a :file:`conftest.py`\nfile:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n    import os\n    import tempfile\n\n    import pytest\n\n\n    @pytest.fixture\n    def cleandir():\n        with tempfile.TemporaryDirectory() as newpath:\n            old_cwd = os.getcwd()\n            os.chdir(newpath)\n            yield\n            os.chdir(old_cwd)\n\nand declare its use in a test module via a ``usefixtures`` marker:\n\n.. code-block:: python\n\n    # content of test_setenv.py\n    import os\n\n    import pytest\n\n\n    @pytest.mark.usefixtures(\"cleandir\")\n    class TestDirectoryInit:\n        def test_cwd_starts_empty(self):\n            assert os.listdir(os.getcwd()) == []\n            with open(\"myfile\", \"w\", encoding=\"utf-8\") as f:\n                f.write(\"hello\")\n\n        def test_cwd_again_starts_empty(self):\n            assert os.listdir(os.getcwd()) == []\n\nDue to the ``usefixtures`` marker, the ``cleandir`` fixture\nwill be required for the execution of each test method, just as if\nyou specified a \"cleandir\" function argument to each of them.  Let's run it\nto verify our fixture is activated and the tests pass:\n\n.. code-block:: pytest\n\n    $ pytest -q\n    ..                                                                   [100%]\n    2 passed in 0.12s\n\nYou can specify multiple fixtures like this:\n\n.. code-block:: python\n\n    @pytest.mark.usefixtures(\"cleandir\", \"anotherfixture\")\n    def test(): ...\n\nand you may specify fixture usage at the test module level using :globalvar:`pytestmark`:\n\n.. code-block:: python\n\n    pytestmark = pytest.mark.usefixtures(\"cleandir\")\n\n\nIt is also possible to put fixtures required by all tests in your project\ninto a configuration file:\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    [pytest]\n    usefixtures = [\"cleandir\"]\n\n.. warning::\n\n    ``@pytest.mark.usefixtures`` cannot be used on **fixture functions**. For example,\n    this is an error:\n\n    .. code-block:: python\n\n        @pytest.mark.usefixtures(\"my_other_fixture\")\n        @pytest.fixture\n        def my_fixture_that_sadly_wont_use_my_other_fixture(): ...\n\n.. _`override fixtures`:\n\nOverriding fixtures on various levels\n-------------------------------------\n\nIn a relatively large test suite, you may want to *override* a fixture, to augment\nor change its behavior inside of certain test modules or directories.\n\nOverride a fixture on a directory (conftest) level\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGiven the tests file structure is:\n\n::\n\n    tests/\n        conftest.py\n            # content of tests/conftest.py\n            import pytest\n\n            @pytest.fixture\n            def username():\n                return 'username'\n\n        test_something.py\n            # content of tests/test_something.py\n            def test_username(username):\n                assert username == 'username'\n\n        subdir/\n            conftest.py\n                # content of tests/subdir/conftest.py\n                import pytest\n\n                @pytest.fixture\n                def username(username):\n                    return 'overridden-' + username\n\n            test_something_else.py\n                # content of tests/subdir/test_something_else.py\n                def test_username(username):\n                    assert username == 'overridden-username'\n\nAs you can see, a fixture with the same name can be overridden for a certain test directory level.\nNote that the ``base`` or ``super`` fixture can be accessed from the ``overriding``\nfixture easily - used in the example above.\n\nOverride a fixture on a test module level\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGiven the tests file structure is:\n\n::\n\n    tests/\n        conftest.py\n            # content of tests/conftest.py\n            import pytest\n\n            @pytest.fixture\n            def username():\n                return 'username'\n\n        test_something.py\n            # content of tests/test_something.py\n            import pytest\n\n            @pytest.fixture\n            def username(username):\n                return 'overridden-' + username\n\n            def test_username(username):\n                assert username == 'overridden-username'\n\n        test_something_else.py\n            # content of tests/test_something_else.py\n            import pytest\n\n            @pytest.fixture\n            def username(username):\n                return 'overridden-else-' + username\n\n            def test_username(username):\n                assert username == 'overridden-else-username'\n\nIn the example above, a fixture with the same name can be overridden for a certain test module.\n\n\nOverride a fixture with direct test parametrization\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGiven the tests file structure is:\n\n::\n\n    tests/\n        conftest.py\n            # content of tests/conftest.py\n            import pytest\n\n            @pytest.fixture\n            def username():\n                return 'username'\n\n            @pytest.fixture\n            def other_username(username):\n                return 'other-' + username\n\n        test_something.py\n            # content of tests/test_something.py\n            import pytest\n\n            @pytest.mark.parametrize('username', ['directly-overridden-username'])\n            def test_username(username):\n                assert username == 'directly-overridden-username'\n\n            @pytest.mark.parametrize('username', ['directly-overridden-username-other'])\n            def test_username_other(other_username):\n                assert other_username == 'other-directly-overridden-username-other'\n\nIn the example above, a fixture value is overridden by the test parameter value. Note that the value of the fixture\ncan be overridden this way even if the test doesn't use it directly (doesn't mention it in the function prototype).\n\n\nOverride a parametrized fixture with non-parametrized one and vice versa\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGiven the tests file structure is:\n\n::\n\n    tests/\n        conftest.py\n            # content of tests/conftest.py\n            import pytest\n\n            @pytest.fixture(params=['one', 'two', 'three'])\n            def parametrized_username(request):\n                return request.param\n\n            @pytest.fixture\n            def non_parametrized_username(request):\n                return 'username'\n\n        test_something.py\n            # content of tests/test_something.py\n            import pytest\n\n            @pytest.fixture\n            def parametrized_username():\n                return 'overridden-username'\n\n            @pytest.fixture(params=['one', 'two', 'three'])\n            def non_parametrized_username(request):\n                return request.param\n\n            def test_username(parametrized_username):\n                assert parametrized_username == 'overridden-username'\n\n            def test_parametrized_username(non_parametrized_username):\n                assert non_parametrized_username in ['one', 'two', 'three']\n\n        test_something_else.py\n            # content of tests/test_something_else.py\n            def test_username(parametrized_username):\n                assert parametrized_username in ['one', 'two', 'three']\n\n            def test_username(non_parametrized_username):\n                assert non_parametrized_username == 'username'\n\nIn the example above, a parametrized fixture is overridden with a non-parametrized version, and\na non-parametrized fixture is overridden with a parametrized version for certain test module.\nThe same applies for the test directory level obviously.\n\n\nUsing fixtures from other projects\n----------------------------------\n\nUsually projects that provide pytest support will use :ref:`entry points <pip-installable plugins>`,\nso just installing those projects into an environment will make those fixtures available for use.\n\nIn case you want to use fixtures from a project that does not use entry points, you can\ndefine :globalvar:`pytest_plugins` in your top ``conftest.py`` file to register that module\nas a plugin.\n\nSuppose you have some fixtures in ``mylibrary.fixtures`` and you want to reuse them into your\n``app/tests`` directory.\n\nAll you need to do is to define :globalvar:`pytest_plugins` in ``app/tests/conftest.py``\npointing to that module.\n\n.. code-block:: python\n\n    pytest_plugins = \"mylibrary.fixtures\"\n\nThis effectively registers ``mylibrary.fixtures`` as a plugin, making all its fixtures and\nhooks available to tests in ``app/tests``.\n\n.. note::\n\n    Sometimes users will *import* fixtures from other projects for use, however this is not\n    recommended: importing fixtures into a module will register them in pytest\n    as *defined* in that module.\n\n    This has minor consequences, such as appearing multiple times in ``pytest --help``,\n    but it is not **recommended** because this behavior might change/stop working\n    in future versions.\n"
  },
  {
    "path": "doc/en/how-to/index.rst",
    "content": ":orphan:\n\n.. _how-to:\n\nHow-to guides\n================\n\nCore pytest functionality\n-------------------------\n\n.. toctree::\n   :maxdepth: 1\n\n   usage\n   assert\n   fixtures\n   mark\n   parametrize\n   subtests\n   tmp_path\n   monkeypatch\n   doctest\n   cache\n\nTest output and outcomes\n----------------------------\n\n.. toctree::\n   :maxdepth: 1\n\n   failures\n   output\n   logging\n   capture-stdout-stderr\n   capture-warnings\n   skipping\n\nPlugins\n----------------------------\n\n.. toctree::\n   :maxdepth: 1\n\n   plugins\n   writing_plugins\n   writing_hook_functions\n\npytest and other test systems\n-----------------------------\n\n.. toctree::\n   :maxdepth: 1\n\n   existingtestsuite\n   unittest\n   xunit_setup\n\npytest development environment\n------------------------------\n\n.. toctree::\n   :maxdepth: 1\n\n   bash-completion\n"
  },
  {
    "path": "doc/en/how-to/logging.rst",
    "content": ".. _logging:\n\nHow to manage logging\n---------------------\n\npytest captures log messages of level ``WARNING`` or above automatically and displays them in their own section\nfor each failed test in the same manner as captured stdout and stderr.\n\nRunning without options:\n\n.. code-block:: bash\n\n    pytest\n\nShows failed tests like so:\n\n.. code-block:: pytest\n\n    ----------------------- Captured stdlog call ----------------------\n    test_reporting.py    26 WARNING  text going to logger\n    ----------------------- Captured stdout call ----------------------\n    text going to stdout\n    ----------------------- Captured stderr call ----------------------\n    text going to stderr\n    ==================== 2 failed in 0.02 seconds =====================\n\nBy default each captured log message shows the module, line number, log level\nand message.\n\nIf desired the log and date format can be specified to\nanything that the logging module supports by passing specific formatting options:\n\n.. code-block:: bash\n\n    pytest --log-format=\"%(asctime)s %(levelname)s %(message)s\" \\\n            --log-date-format=\"%Y-%m-%d %H:%M:%S\"\n\nShows failed tests like so:\n\n.. code-block:: pytest\n\n    ----------------------- Captured stdlog call ----------------------\n    2010-04-10 14:48:44 WARNING text going to logger\n    ----------------------- Captured stdout call ----------------------\n    text going to stdout\n    ----------------------- Captured stderr call ----------------------\n    text going to stderr\n    ==================== 2 failed in 0.02 seconds =====================\n\nThese options can also be customized through a configuration file:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        log_format = \"%(asctime)s %(levelname)s %(message)s\"\n        log_date_format = \"%Y-%m-%d %H:%M:%S\"\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        log_format = %(asctime)s %(levelname)s %(message)s\n        log_date_format = %Y-%m-%d %H:%M:%S\n\nSpecific loggers can be disabled via :option:`--log-disable={logger_name}`.\nThis argument can be passed multiple times:\n\n.. code-block:: bash\n\n    pytest --log-disable=main --log-disable=testing\n\nFurther it is possible to disable reporting of captured content (stdout,\nstderr and logs) on failed tests completely with:\n\n.. code-block:: bash\n\n    pytest --show-capture=no\n\n\ncaplog fixture\n^^^^^^^^^^^^^^\n\nInside tests it is possible to change the log level for the captured log\nmessages.  This is supported by the ``caplog`` fixture:\n\n.. code-block:: python\n\n    def test_foo(caplog):\n        caplog.set_level(logging.INFO)\n\nBy default the level is set on the root logger,\nhowever as a convenience it is also possible to set the log level of any\nlogger:\n\n.. code-block:: python\n\n    def test_foo(caplog):\n        caplog.set_level(logging.CRITICAL, logger=\"root.baz\")\n\nThe log levels set are restored automatically at the end of the test.\n\nIt is also possible to use a context manager to temporarily change the log\nlevel inside a ``with`` block:\n\n.. code-block:: python\n\n    def test_bar(caplog):\n        with caplog.at_level(logging.INFO):\n            pass\n\nAgain, by default the level of the root logger is affected but the level of any\nlogger can be changed instead with:\n\n.. code-block:: python\n\n    def test_bar(caplog):\n        with caplog.at_level(logging.CRITICAL, logger=\"root.baz\"):\n            pass\n\nLastly all the logs sent to the logger during the test run are made available on\nthe fixture in the form of both the ``logging.LogRecord`` instances and the final log text.\nThis is useful for when you want to assert on the contents of a message:\n\n.. code-block:: python\n\n    def test_baz(caplog):\n        func_under_test()\n        for record in caplog.records:\n            assert record.levelname != \"CRITICAL\"\n        assert \"wally\" not in caplog.text\n\nFor all the available attributes of the log records see the\n``logging.LogRecord`` class.\n\nYou can also resort to ``record_tuples`` if all you want to do is to ensure,\nthat certain messages have been logged under a given logger name with a given\nseverity and message:\n\n.. code-block:: python\n\n    def test_foo(caplog):\n        logging.getLogger().info(\"boo %s\", \"arg\")\n\n        assert caplog.record_tuples == [(\"root\", logging.INFO, \"boo arg\")]\n\nYou can call ``caplog.clear()`` to reset the captured log records in a test:\n\n.. code-block:: python\n\n    def test_something_with_clearing_records(caplog):\n        some_method_that_creates_log_records()\n        caplog.clear()\n        your_test_method()\n        assert [\"Foo\"] == [rec.message for rec in caplog.records]\n\n\nThe ``caplog.records`` attribute contains records from the current stage only, so\ninside the ``setup`` phase it contains only setup logs, same with the ``call`` and\n``teardown`` phases.\n\nTo access logs from other stages, use the ``caplog.get_records(when)`` method. As an example,\nif you want to make sure that tests which use a certain fixture never log any warnings, you can inspect\nthe records for the ``setup`` and ``call`` stages during teardown like so:\n\n.. code-block:: python\n\n    @pytest.fixture\n    def window(caplog):\n        window = create_window()\n        yield window\n        for when in (\"setup\", \"call\"):\n            messages = [\n                x.message for x in caplog.get_records(when) if x.levelno == logging.WARNING\n            ]\n            if messages:\n                pytest.fail(f\"warning messages encountered during testing: {messages}\")\n\n\n\nThe full API is available at :class:`pytest.LogCaptureFixture`.\n\n.. warning::\n\n    The ``caplog`` fixture adds a handler to the root logger to capture logs. If the root logger is\n    modified during a test, for example with ``logging.config.dictConfig``, this handler may be\n    removed and cause no logs to be captured. To avoid this, ensure that any root logger configuration\n    only adds to the existing handlers.\n\n\n.. _live_logs:\n\nLive Logs\n^^^^^^^^^\n\nBy setting the :confval:`log_cli` configuration option to ``true``, pytest will output\nlogging records as they are emitted directly into the console.\n\nYou can specify the logging level for which log records with equal or higher\nlevel are printed to the console by passing :option:`--log-cli-level`. This setting\naccepts the logging level names or numeric values as seen in\n:ref:`logging's documentation <python:levels>`.\n\nAdditionally, you can also specify :option:`--log-cli-format` and\n:option:`--log-cli-date-format` which mirror and default to :option:`--log-format` and\n:option:`--log-date-format` if not provided, but are applied only to the console\nlogging handler.\n\nAll of the CLI log options can also be set in the configuration file. The\noption names are:\n\n* :confval:`log_cli_level`\n* :confval:`log_cli_format`\n* :confval:`log_cli_date_format`\n\nIf you need to record the whole test suite logging calls to a file, you can pass\n:option:`--log-file=/path/to/log/file`. This log file is opened in write mode by default, which\nmeans that it will be overwritten at each test session.\nIf you'd like the file opened in append mode instead, then you can pass :option:`--log-file-mode=a`.\nNote that relative paths for the log-file location, whether passed on the CLI or declared in a\nconfig file, are always resolved relative to the current working directory.\n\nYou can also specify the logging level for the log file by passing\n:option:`--log-file-level`. This setting accepts the logging level names or numeric\nvalues as seen in :ref:`logging's documentation <python:levels>`.\n\nAdditionally, you can also specify :option:`--log-file-format` and\n:option:`--log-file-date-format` which are equal to ``--log-format`` and\n:option:`--log-date-format` but are applied to the log file logging handler.\n\nAll of the log file options can also be set in the configuration file. The\noption names are:\n\n* :confval:`log_file`\n* :confval:`log_file_mode`\n* :confval:`log_file_level`\n* :confval:`log_file_format`\n* :confval:`log_file_date_format`\n\nYou can call ``set_log_path()`` to customize the log_file path dynamically. This functionality\nis considered **experimental**. Note that ``set_log_path()`` respects the :confval:`log_file_mode` option.\n\n.. _log_colors:\n\nCustomizing Colors\n^^^^^^^^^^^^^^^^^^\n\nLog levels are colored if colored terminal output is enabled. Changing\nfrom default colors or putting color on custom log levels is supported\nthrough ``add_color_level()``. Example:\n\n.. code-block:: python\n\n    @pytest.hookimpl(trylast=True)\n    def pytest_configure(config):\n        logging_plugin = config.pluginmanager.get_plugin(\"logging-plugin\")\n\n        # Change color on existing log level\n        logging_plugin.log_cli_handler.formatter.add_color_level(logging.INFO, \"cyan\")\n\n        # Add color to a custom log level (a custom log level `SPAM` is already set up)\n        logging_plugin.log_cli_handler.formatter.add_color_level(logging.SPAM, \"blue\")\n.. warning::\n\n    This feature and its API are considered **experimental** and might change\n    between releases without a deprecation notice.\n.. _log_release_notes:\n\nRelease notes\n^^^^^^^^^^^^^\n\nThis feature was introduced as a drop-in replacement for the\n:pypi:`pytest-catchlog` plugin and they conflict\nwith each other. The backward compatibility API with ``pytest-capturelog``\nhas been dropped when this feature was introduced, so if for that reason you\nstill need ``pytest-catchlog`` you can disable the internal feature by\nadding to your configuration file:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        addopts = [\"-p\", \"no:logging\"]\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        addopts = -p no:logging\n\n\n.. _log_changes_3_4:\n\nIncompatible changes in pytest 3.4\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThis feature was introduced in ``3.3`` and some **incompatible changes** have been\nmade in ``3.4`` after community feedback:\n\n* Log levels are no longer changed unless explicitly requested by the :confval:`log_level` configuration\n  or :option:`--log-level` command-line options. This allows users to configure logger objects themselves.\n  Setting :confval:`log_level` will set the level that is captured globally so if a specific test requires\n  a lower level than this, use the ``caplog.set_level()`` functionality otherwise that test will be prone to\n  failure.\n* :ref:`Live Logs <live_logs>` is now disabled by default and can be enabled setting the\n  :confval:`log_cli` configuration option to ``true``. When enabled, the verbosity is increased so logging for each\n  test is visible.\n* :ref:`Live Logs <live_logs>` are now sent to ``sys.stdout`` and no longer require the :option:`-s` command-line option\n  to work.\n\nIf you want to partially restore the logging behavior of version ``3.3``, you can add these options to your configuration\nfile:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        log_cli = true\n        log_level = \"NOTSET\"\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        log_cli = true\n        log_level = NOTSET\n\nMore details about the discussion that led to these changes can be read in :issue:`3013`.\n"
  },
  {
    "path": "doc/en/how-to/mark.rst",
    "content": ".. _mark:\n\nHow to mark test functions with attributes\n===========================================\n\nBy using the ``pytest.mark`` helper you can easily set\nmetadata on your test functions. You can find the full list of builtin markers\nin the :ref:`API Reference<marks ref>`. Or you can list all the markers, including\nbuiltin and custom, using the CLI - :code:`pytest --markers`.\n\nHere are some of the builtin markers:\n\n* :ref:`usefixtures <usefixtures>` - use fixtures on a test function or class\n* :ref:`filterwarnings <filterwarnings>` - filter certain warnings of a test function\n* :ref:`skip <skip>` - always skip a test function\n* :ref:`skipif <skipif>` - skip a test function if a certain condition is met\n* :ref:`xfail <xfail>` - produce an \"expected failure\" outcome if a certain\n  condition is met\n* :ref:`parametrize <parametrizemark>` - perform multiple calls\n  to the same test function.\n\nIt's easy to create custom markers or to apply markers\nto whole test classes or modules. Those markers can be used by plugins, and also\nare commonly used to :ref:`select tests <mark run>` on the command-line with the :option:`-m` option.\n\nSee :ref:`mark examples` for examples which also serve as documentation.\n\n.. note::\n\n    Marks can only be applied to tests, having no effect on\n    :ref:`fixtures <fixtures>`.\n\n\nRegistering marks\n-----------------\n\nYou can register custom marks in your configuration file like this:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        markers = [\n            \"slow: marks tests as slow (deselect with '-m \\\"not slow\\\"')\",\n            \"serial\",\n        ]\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        markers =\n            slow: marks tests as slow (deselect with '-m \"not slow\"')\n            serial\n\nNote that everything past the ``:`` after the mark name is an optional description.\n\nAlternatively, you can register new markers programmatically in a\n:ref:`pytest_configure <initialization-hooks>` hook:\n\n.. code-block:: python\n\n    def pytest_configure(config):\n        config.addinivalue_line(\n            \"markers\", \"env(name): mark test to run only on named environment\"\n        )\n\n\nRegistered marks appear in pytest's help text and do not emit warnings (see the next section). It\nis recommended that third-party plugins always :ref:`register their markers <registering-markers>`.\n\n.. _unknown-marks:\n\nRaising errors on unknown marks\n-------------------------------\n\nUnregistered marks applied with the ``@pytest.mark.name_of_the_mark`` decorator\nwill always emit a warning in order to avoid silently doing something\nsurprising due to mistyped names. As described in the previous section, you can disable\nthe warning for custom marks by registering them in your configuration file or\nusing a custom ``pytest_configure`` hook.\n\nWhen the :confval:`strict_markers` configuration option is set, any unknown marks applied\nwith the ``@pytest.mark.name_of_the_mark`` decorator will trigger an error. You can\nenforce this validation in your project by setting :confval:`strict_markers` in your configuration:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        addopts = [\"--strict-markers\"]\n        markers = [\n            \"slow: marks tests as slow (deselect with '-m \\\"not slow\\\"')\",\n            \"serial\",\n        ]\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        strict_markers = true\n        markers =\n            slow: marks tests as slow (deselect with '-m \"not slow\"')\n            serial\n"
  },
  {
    "path": "doc/en/how-to/monkeypatch.rst",
    "content": ".. _monkeypatching:\n\nHow to monkeypatch/mock modules and environments\n================================================================\n\n.. currentmodule:: pytest\n\nSometimes tests need to invoke functionality which depends\non global settings or which invokes code which cannot be easily\ntested such as network access.  The ``monkeypatch`` fixture\nhelps you to safely set/delete an attribute, dictionary item or\nenvironment variable, or to modify ``sys.path`` for importing.\n\nThe ``monkeypatch`` fixture provides these helper methods for safely patching and mocking\nfunctionality in tests:\n\n* :meth:`monkeypatch.setattr(obj, name, value, raising=True) <pytest.MonkeyPatch.setattr>`\n* :meth:`monkeypatch.delattr(obj, name, raising=True) <pytest.MonkeyPatch.delattr>`\n* :meth:`monkeypatch.setitem(mapping, name, value) <pytest.MonkeyPatch.setitem>`\n* :meth:`monkeypatch.delitem(obj, name, raising=True) <pytest.MonkeyPatch.delitem>`\n* :meth:`monkeypatch.setenv(name, value, prepend=None) <pytest.MonkeyPatch.setenv>`\n* :meth:`monkeypatch.delenv(name, raising=True) <pytest.MonkeyPatch.delenv>`\n* :meth:`monkeypatch.syspath_prepend(path) <pytest.MonkeyPatch.syspath_prepend>`\n* :meth:`monkeypatch.chdir(path) <pytest.MonkeyPatch.chdir>`\n* :meth:`monkeypatch.context() <pytest.MonkeyPatch.context>`\n\n\nAll modifications will be undone after the requesting\ntest function or fixture has finished. The ``raising``\nparameter determines if a ``KeyError`` or ``AttributeError``\nwill be raised if the target of the set/deletion operation does not exist.\n\nConsider the following scenarios:\n\n1. Modifying the behavior of a function or the property of a class for a test e.g.\nthere is an API call or database connection you will not make for a test but you know\nwhat the expected output should be. Use :py:meth:`monkeypatch.setattr <MonkeyPatch.setattr>` to patch the\nfunction or property with your desired testing behavior. This can include your own functions.\nUse :py:meth:`monkeypatch.delattr <MonkeyPatch.delattr>` to remove the function or property for the test.\n\n2. Modifying the values of dictionaries e.g. you have a global configuration that\nyou want to modify for certain test cases. Use :py:meth:`monkeypatch.setitem <MonkeyPatch.setitem>` to patch the\ndictionary for the test. :py:meth:`monkeypatch.delitem <MonkeyPatch.delitem>` can be used to remove items.\n\n3. Modifying environment variables for a test e.g. to test program behavior if an\nenvironment variable is missing, or to set multiple values to a known variable.\n:py:meth:`monkeypatch.setenv <MonkeyPatch.setenv>` and :py:meth:`monkeypatch.delenv <MonkeyPatch.delenv>` can be used for\nthese patches.\n\n4. Use ``monkeypatch.setenv(\"PATH\", value, prepend=os.pathsep)`` to modify ``$PATH``, and\n:py:meth:`monkeypatch.chdir <MonkeyPatch.chdir>` to change the context of the current working directory\nduring a test.\n\n5. Use :py:meth:`monkeypatch.syspath_prepend <MonkeyPatch.syspath_prepend>` to modify ``sys.path`` which will also\ncall ``pkg_resources.fixup_namespace_packages`` and :py:func:`importlib.invalidate_caches`.\n\n6. Use :py:meth:`monkeypatch.context <MonkeyPatch.context>` to apply patches only in a specific scope, which can help\ncontrol teardown of complex fixtures or patches to the stdlib.\n\nSee the `monkeypatch blog post`_ for some introduction material\nand a discussion of its motivation.\n\n.. _`monkeypatch blog post`: https://tetamap.wordpress.com//2009/03/03/monkeypatching-in-unit-tests-done-right/\n\nMonkeypatching functions\n------------------------\n\nConsider a scenario where you are working with user directories. In the context of\ntesting, you do not want your test to depend on the running user. ``monkeypatch``\ncan be used to patch functions dependent on the user to always return a\nspecific value.\n\nIn this example, :py:meth:`monkeypatch.setattr <MonkeyPatch.setattr>` is used to patch ``Path.home``\nso that the known testing path ``Path(\"/abc\")`` is always used when the test is run.\nThis removes any dependency on the running user for testing purposes.\n:py:meth:`monkeypatch.setattr <MonkeyPatch.setattr>` must be called before the function which will use\nthe patched function is called.\nAfter the test function finishes the ``Path.home`` modification will be undone.\n\n.. code-block:: python\n\n    # contents of test_module.py with source code and the test\n    from pathlib import Path\n\n\n    def getssh():\n        \"\"\"Simple function to return expanded homedir ssh path.\"\"\"\n        return Path.home() / \".ssh\"\n\n\n    def test_getssh(monkeypatch):\n        # mocked return function to replace Path.home\n        # always return '/abc'\n        def mockreturn():\n            return Path(\"/abc\")\n\n        # Application of the monkeypatch to replace Path.home\n        # with the behavior of mockreturn defined above.\n        monkeypatch.setattr(Path, \"home\", mockreturn)\n\n        # Calling getssh() will use mockreturn in place of Path.home\n        # for this test with the monkeypatch.\n        x = getssh()\n        assert x == Path(\"/abc/.ssh\")\n\nMonkeypatching returned objects: building mock classes\n------------------------------------------------------\n\n:py:meth:`monkeypatch.setattr <MonkeyPatch.setattr>` can be used in conjunction with classes to mock returned\nobjects from functions instead of values.\nImagine a simple function to take an API url and return the json response.\n\n.. code-block:: python\n\n    # contents of app.py, a simple API retrieval example\n    import requests\n\n\n    def get_json(url):\n        \"\"\"Takes a URL, and returns the JSON.\"\"\"\n        r = requests.get(url)\n        return r.json()\n\nWe need to mock ``r``, the returned response object for testing purposes.\nThe mock of ``r`` needs a ``.json()`` method which returns a dictionary.\nThis can be done in our test file by defining a class to represent ``r``.\n\n.. code-block:: python\n\n    # contents of test_app.py, a simple test for our API retrieval\n    # import requests for the purposes of monkeypatching\n    import requests\n\n    # our app.py that includes the get_json() function\n    # this is the previous code block example\n    import app\n\n\n    # custom class to be the mock return value\n    # will override the requests.Response returned from requests.get\n    class MockResponse:\n        # mock json() method always returns a specific testing dictionary\n        @staticmethod\n        def json():\n            return {\"mock_key\": \"mock_response\"}\n\n\n    def test_get_json(monkeypatch):\n        # Any arguments may be passed and mock_get() will always return our\n        # mocked object, which only has the .json() method.\n        def mock_get(*args, **kwargs):\n            return MockResponse()\n\n        # apply the monkeypatch for requests.get to mock_get\n        monkeypatch.setattr(requests, \"get\", mock_get)\n\n        # app.get_json, which contains requests.get, uses the monkeypatch\n        result = app.get_json(\"https://fakeurl\")\n        assert result[\"mock_key\"] == \"mock_response\"\n\n\n``monkeypatch`` applies the mock for ``requests.get`` with our ``mock_get`` function.\nThe ``mock_get`` function returns an instance of the ``MockResponse`` class, which\nhas a ``json()`` method defined to return a known testing dictionary and does not\nrequire any outside API connection.\n\nYou can build the ``MockResponse`` class with the appropriate degree of complexity for\nthe scenario you are testing. For instance, it could include an ``ok`` property that\nalways returns ``True``, or return different values from the ``json()`` mocked method\nbased on input strings.\n\nThis mock can be shared across tests using a ``fixture``:\n\n.. code-block:: python\n\n    # contents of test_app.py, a simple test for our API retrieval\n    import pytest\n    import requests\n\n    # app.py that includes the get_json() function\n    import app\n\n\n    # custom class to be the mock return value of requests.get()\n    class MockResponse:\n        @staticmethod\n        def json():\n            return {\"mock_key\": \"mock_response\"}\n\n\n    # monkeypatched requests.get moved to a fixture\n    @pytest.fixture\n    def mock_response(monkeypatch):\n        \"\"\"Requests.get() mocked to return {'mock_key':'mock_response'}.\"\"\"\n\n        def mock_get(*args, **kwargs):\n            return MockResponse()\n\n        monkeypatch.setattr(requests, \"get\", mock_get)\n\n\n    # notice our test uses the custom fixture instead of monkeypatch directly\n    def test_get_json(mock_response):\n        result = app.get_json(\"https://fakeurl\")\n        assert result[\"mock_key\"] == \"mock_response\"\n\n\nFurthermore, if the mock was designed to be applied to all tests, the ``fixture`` could\nbe moved to a ``conftest.py`` file and use the with ``autouse=True`` option.\n\n\nGlobal patch example: preventing \"requests\" from remote operations\n------------------------------------------------------------------\n\nIf you want to prevent the \"requests\" library from performing http\nrequests in all your tests, you can do:\n\n.. code-block:: python\n\n    # contents of conftest.py\n    import pytest\n\n\n    @pytest.fixture(autouse=True)\n    def no_requests(monkeypatch):\n        \"\"\"Remove requests.sessions.Session.request for all tests.\"\"\"\n        monkeypatch.delattr(\"requests.sessions.Session.request\")\n\nThis autouse fixture will be executed for each test function and it\nwill delete the method ``request.session.Session.request``\nso that any attempts within tests to create http requests will fail.\n\n\n.. note::\n\n    Be advised that it is not recommended to patch builtin functions such as ``open``,\n    ``compile``, etc., because it might break pytest's internals. If that's\n    unavoidable, passing :option:`--tb=native`, :option:`--assert=plain` and :option:`--capture=no` might\n    help although there's no guarantee.\n\n.. note::\n\n    Mind that patching ``stdlib`` functions and some third-party libraries used by pytest\n    might break pytest itself, therefore in those cases it is recommended to use\n    :meth:`MonkeyPatch.context` to limit the patching to the block you want tested:\n\n    .. code-block:: python\n\n        import functools\n\n\n        def test_partial(monkeypatch):\n            with monkeypatch.context() as m:\n                m.setattr(functools, \"partial\", 3)\n                assert functools.partial == 3\n\n    See :issue:`3290` for details.\n\n\nMonkeypatching environment variables\n------------------------------------\n\nIf you are working with environment variables you often need to safely change the values\nor delete them from the system for testing purposes. ``monkeypatch`` provides a mechanism\nto do this using the ``setenv`` and ``delenv`` method. Our example code to test:\n\n.. code-block:: python\n\n    # contents of our original code file e.g. code.py\n    import os\n\n\n    def get_os_user_lower():\n        \"\"\"Simple retrieval function.\n        Returns lowercase USER or raises OSError.\"\"\"\n        username = os.getenv(\"USER\")\n\n        if username is None:\n            raise OSError(\"USER environment is not set.\")\n\n        return username.lower()\n\nThere are two potential paths. First, the ``USER`` environment variable is set to a\nvalue. Second, the ``USER`` environment variable does not exist. Using ``monkeypatch``\nboth paths can be safely tested without impacting the running environment:\n\n.. code-block:: python\n\n    # contents of our test file e.g. test_code.py\n    import pytest\n\n\n    def test_upper_to_lower(monkeypatch):\n        \"\"\"Set the USER env var to assert the behavior.\"\"\"\n        monkeypatch.setenv(\"USER\", \"TestingUser\")\n        assert get_os_user_lower() == \"testinguser\"\n\n\n    def test_raise_exception(monkeypatch):\n        \"\"\"Remove the USER env var and assert OSError is raised.\"\"\"\n        monkeypatch.delenv(\"USER\", raising=False)\n\n        with pytest.raises(OSError):\n            _ = get_os_user_lower()\n\nThis behavior can be moved into ``fixture`` structures and shared across tests:\n\n.. code-block:: python\n\n    # contents of our test file e.g. test_code.py\n    import pytest\n\n\n    @pytest.fixture\n    def mock_env_user(monkeypatch):\n        monkeypatch.setenv(\"USER\", \"TestingUser\")\n\n\n    @pytest.fixture\n    def mock_env_missing(monkeypatch):\n        monkeypatch.delenv(\"USER\", raising=False)\n\n\n    # notice the tests reference the fixtures for mocks\n    def test_upper_to_lower(mock_env_user):\n        assert get_os_user_lower() == \"testinguser\"\n\n\n    def test_raise_exception(mock_env_missing):\n        with pytest.raises(OSError):\n            _ = get_os_user_lower()\n\n\nMonkeypatching dictionaries\n---------------------------\n\n:py:meth:`monkeypatch.setitem <MonkeyPatch.setitem>` can be used to safely set the values of dictionaries\nto specific values during tests. Take this simplified connection string example:\n\n.. code-block:: python\n\n    # contents of app.py to generate a simple connection string\n    DEFAULT_CONFIG = {\"user\": \"user1\", \"database\": \"db1\"}\n\n\n    def create_connection_string(config=None):\n        \"\"\"Creates a connection string from input or defaults.\"\"\"\n        config = config or DEFAULT_CONFIG\n        return f\"User Id={config['user']}; Location={config['database']};\"\n\nFor testing purposes we can patch the ``DEFAULT_CONFIG`` dictionary to specific values.\n\n.. code-block:: python\n\n    # contents of test_app.py\n    # app.py with the connection string function (prior code block)\n    import app\n\n\n    def test_connection(monkeypatch):\n        # Patch the values of DEFAULT_CONFIG to specific\n        # testing values only for this test.\n        monkeypatch.setitem(app.DEFAULT_CONFIG, \"user\", \"test_user\")\n        monkeypatch.setitem(app.DEFAULT_CONFIG, \"database\", \"test_db\")\n\n        # expected result based on the mocks\n        expected = \"User Id=test_user; Location=test_db;\"\n\n        # the test uses the monkeypatched dictionary settings\n        result = app.create_connection_string()\n        assert result == expected\n\nYou can use the :py:meth:`monkeypatch.delitem <MonkeyPatch.delitem>` to remove values.\n\n.. code-block:: python\n\n    # contents of test_app.py\n    import pytest\n\n    # app.py with the connection string function\n    import app\n\n\n    def test_missing_user(monkeypatch):\n        # patch the DEFAULT_CONFIG to be missing the 'user' key\n        monkeypatch.delitem(app.DEFAULT_CONFIG, \"user\", raising=False)\n\n        # Key error expected because a config is not passed, and the\n        # default is now missing the 'user' entry.\n        with pytest.raises(KeyError):\n            _ = app.create_connection_string()\n\n\nThe modularity of fixtures gives you the flexibility to define\nseparate fixtures for each potential mock and reference them in the needed tests.\n\n.. code-block:: python\n\n    # contents of test_app.py\n    import pytest\n\n    # app.py with the connection string function\n    import app\n\n\n    # all of the mocks are moved into separated fixtures\n    @pytest.fixture\n    def mock_test_user(monkeypatch):\n        \"\"\"Set the DEFAULT_CONFIG user to test_user.\"\"\"\n        monkeypatch.setitem(app.DEFAULT_CONFIG, \"user\", \"test_user\")\n\n\n    @pytest.fixture\n    def mock_test_database(monkeypatch):\n        \"\"\"Set the DEFAULT_CONFIG database to test_db.\"\"\"\n        monkeypatch.setitem(app.DEFAULT_CONFIG, \"database\", \"test_db\")\n\n\n    @pytest.fixture\n    def mock_missing_default_user(monkeypatch):\n        \"\"\"Remove the user key from DEFAULT_CONFIG\"\"\"\n        monkeypatch.delitem(app.DEFAULT_CONFIG, \"user\", raising=False)\n\n\n    # tests reference only the fixture mocks that are needed\n    def test_connection(mock_test_user, mock_test_database):\n        expected = \"User Id=test_user; Location=test_db;\"\n\n        result = app.create_connection_string()\n        assert result == expected\n\n\n    def test_missing_user(mock_missing_default_user):\n        with pytest.raises(KeyError):\n            _ = app.create_connection_string()\n\n\n.. currentmodule:: pytest\n\nAPI Reference\n-------------\n\nConsult the docs for the :class:`MonkeyPatch` class.\n"
  },
  {
    "path": "doc/en/how-to/output.rst",
    "content": ".. _how-to-manage-output:\n\nManaging pytest's output\n=========================\n\n.. _how-to-modifying-python-tb-printing:\n\nModifying Python traceback printing\n--------------------------------------------------\n\nExamples for modifying traceback printing:\n\n.. code-block:: bash\n\n    pytest --showlocals     # show local variables in tracebacks\n    pytest -l               # show local variables (shortcut)\n    pytest --no-showlocals  # hide local variables (if addopts enables them)\n\n    pytest --capture=fd  # default, capture at the file descriptor level\n    pytest --capture=sys # capture at the sys level\n    pytest --capture=no  # don't capture\n    pytest -s            # don't capture (shortcut)\n    pytest --capture=tee-sys # capture to logs but also output to sys level streams\n\n    pytest --tb=auto    # (default) 'long' tracebacks for the first and last\n                         # entry, but 'short' style for the other entries\n    pytest --tb=long    # exhaustive, informative traceback formatting\n    pytest --tb=short   # shorter traceback format\n    pytest --tb=line    # only one line per failure\n    pytest --tb=native  # Python standard library formatting\n    pytest --tb=no      # no traceback at all\n\nThe :option:`--full-trace` causes very long traces to be printed on error (longer\nthan :option:`--tb=long`). It also ensures that a stack trace is printed on\n**KeyboardInterrupt** (Ctrl+C).\nThis is very useful if the tests are taking too long and you interrupt them\nwith Ctrl+C to find out where the tests are *hanging*. By default no output\nwill be shown (because KeyboardInterrupt is caught by pytest). By using this\noption you make sure a trace is shown.\n\n\nVerbosity\n--------------------------------------------------\n\nExamples for modifying printing verbosity:\n\n.. code-block:: bash\n\n    pytest --quiet          # quiet - less verbose - mode\n    pytest -q               # quiet - less verbose - mode (shortcut)\n    pytest -v               # increase verbosity, display individual test names\n    pytest -vv              # more verbose, display more details from the test output\n    pytest -vvv             # not a standard , but may be used for even more detail in certain setups\n\nThe :option:`-v` flag controls the verbosity of pytest output in various aspects: test session progress, assertion\ndetails when tests fail, fixtures details with :option:`--fixtures`, etc.\n\n.. regendoc:wipe\n\nConsider this simple file:\n\n.. code-block:: python\n\n    # content of test_verbosity_example.py\n    def test_ok():\n        pass\n\n\n    def test_words_fail():\n        fruits1 = [\"banana\", \"apple\", \"grapes\", \"melon\", \"kiwi\"]\n        fruits2 = [\"banana\", \"apple\", \"orange\", \"melon\", \"kiwi\"]\n        assert fruits1 == fruits2\n\n\n    def test_numbers_fail():\n        number_to_text1 = {str(x): x for x in range(5)}\n        number_to_text2 = {str(x * 10): x * 10 for x in range(5)}\n        assert number_to_text1 == number_to_text2\n\n\n    def test_long_text_fail():\n        long_text = \"Lorem ipsum dolor sit amet \" * 10\n        assert \"hello world\" in long_text\n\nExecuting pytest normally gives us this output (we are skipping the header to focus on the rest):\n\n.. code-block:: pytest\n\n    $ pytest --no-header\n    =========================== test session starts ============================\n    collected 4 items\n\n    test_verbosity_example.py .FFF                                       [100%]\n\n    ================================= FAILURES =================================\n    _____________________________ test_words_fail ______________________________\n\n        def test_words_fail():\n            fruits1 = [\"banana\", \"apple\", \"grapes\", \"melon\", \"kiwi\"]\n            fruits2 = [\"banana\", \"apple\", \"orange\", \"melon\", \"kiwi\"]\n    >       assert fruits1 == fruits2\n    E       AssertionError: assert ['banana', 'a...elon', 'kiwi'] == ['banana', 'a...elon', 'kiwi']\n    E\n    E         At index 2 diff: 'grapes' != 'orange'\n    E         Use -v to get more diff\n\n    test_verbosity_example.py:8: AssertionError\n    ____________________________ test_numbers_fail _____________________________\n\n        def test_numbers_fail():\n            number_to_text1 = {str(x): x for x in range(5)}\n            number_to_text2 = {str(x * 10): x * 10 for x in range(5)}\n    >       assert number_to_text1 == number_to_text2\n    E       AssertionError: assert {'0': 0, '1':..., '3': 3, ...} == {'0': 0, '10'...'30': 30, ...}\n    E\n    E         Omitting 1 identical items, use -vv to show\n    E         Left contains 4 more items:\n    E         {'1': 1, '2': 2, '3': 3, '4': 4}\n    E         Right contains 4 more items:\n    E         {'10': 10, '20': 20, '30': 30, '40': 40}\n    E         Use -v to get more diff\n\n    test_verbosity_example.py:14: AssertionError\n    ___________________________ test_long_text_fail ____________________________\n\n        def test_long_text_fail():\n            long_text = \"Lorem ipsum dolor sit amet \" * 10\n    >       assert \"hello world\" in long_text\n    E       AssertionError: assert 'hello world' in 'Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ips... sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet '\n\n    test_verbosity_example.py:19: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_verbosity_example.py::test_words_fail - AssertionError: asser...\n    FAILED test_verbosity_example.py::test_numbers_fail - AssertionError: ass...\n    FAILED test_verbosity_example.py::test_long_text_fail - AssertionError: a...\n    ======================= 3 failed, 1 passed in 0.12s ========================\n\nNotice that:\n\n* Each test inside the file is shown by a single character in the output: ``.`` for passing, ``F`` for failure.\n* ``test_words_fail`` failed, and we are shown a short summary indicating the index 2 of the two lists differ.\n* ``test_numbers_fail`` failed, and we are shown a summary of left/right differences on dictionary items. Identical items are omitted.\n* ``test_long_text_fail`` failed, and the right hand side of the ``in`` statement is truncated using ``...```\n  because it is longer than an internal threshold (240 characters currently).\n\nNow we can increase pytest's verbosity:\n\n.. code-block:: pytest\n\n    $ pytest --no-header -v\n    =========================== test session starts ============================\n    collecting ... collected 4 items\n\n    test_verbosity_example.py::test_ok PASSED                            [ 25%]\n    test_verbosity_example.py::test_words_fail FAILED                    [ 50%]\n    test_verbosity_example.py::test_numbers_fail FAILED                  [ 75%]\n    test_verbosity_example.py::test_long_text_fail FAILED                [100%]\n\n    ================================= FAILURES =================================\n    _____________________________ test_words_fail ______________________________\n\n        def test_words_fail():\n            fruits1 = [\"banana\", \"apple\", \"grapes\", \"melon\", \"kiwi\"]\n            fruits2 = [\"banana\", \"apple\", \"orange\", \"melon\", \"kiwi\"]\n    >       assert fruits1 == fruits2\n    E       AssertionError: assert ['banana', 'a...elon', 'kiwi'] == ['banana', 'a...elon', 'kiwi']\n    E\n    E         At index 2 diff: 'grapes' != 'orange'\n    E\n    E         Full diff:\n    E           [\n    E               'banana',\n    E               'apple',...\n    E\n    E         ...Full output truncated (7 lines hidden), use '-vv' to show\n\n    test_verbosity_example.py:8: AssertionError\n    ____________________________ test_numbers_fail _____________________________\n\n        def test_numbers_fail():\n            number_to_text1 = {str(x): x for x in range(5)}\n            number_to_text2 = {str(x * 10): x * 10 for x in range(5)}\n    >       assert number_to_text1 == number_to_text2\n    E       AssertionError: assert {'0': 0, '1':..., '3': 3, ...} == {'0': 0, '10'...'30': 30, ...}\n    E\n    E         Omitting 1 identical items, use -vv to show\n    E         Left contains 4 more items:\n    E         {'1': 1, '2': 2, '3': 3, '4': 4}\n    E         Right contains 4 more items:\n    E         {'10': 10, '20': 20, '30': 30, '40': 40}\n    E         ...\n    E\n    E         ...Full output truncated (16 lines hidden), use '-vv' to show\n\n    test_verbosity_example.py:14: AssertionError\n    ___________________________ test_long_text_fail ____________________________\n\n        def test_long_text_fail():\n            long_text = \"Lorem ipsum dolor sit amet \" * 10\n    >       assert \"hello world\" in long_text\n    E       AssertionError: assert 'hello world' in 'Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet '\n\n    test_verbosity_example.py:19: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_verbosity_example.py::test_words_fail - AssertionError: asser...\n    FAILED test_verbosity_example.py::test_numbers_fail - AssertionError: ass...\n    FAILED test_verbosity_example.py::test_long_text_fail - AssertionError: a...\n    ======================= 3 failed, 1 passed in 0.12s ========================\n\nNotice now that:\n\n* Each test inside the file gets its own line in the output.\n* ``test_words_fail`` now shows the two failing lists in full, in addition to which index differs.\n* ``test_numbers_fail`` now shows a text diff of the two dictionaries, truncated.\n* ``test_long_text_fail`` no longer truncates the right hand side of the ``in`` statement, because the internal\n  threshold for truncation is larger now (2400 characters currently).\n\nNow if we increase verbosity even more:\n\n.. code-block:: pytest\n\n    $ pytest --no-header -vv\n    =========================== test session starts ============================\n    collecting ... collected 4 items\n\n    test_verbosity_example.py::test_ok PASSED                            [ 25%]\n    test_verbosity_example.py::test_words_fail FAILED                    [ 50%]\n    test_verbosity_example.py::test_numbers_fail FAILED                  [ 75%]\n    test_verbosity_example.py::test_long_text_fail FAILED                [100%]\n\n    ================================= FAILURES =================================\n    _____________________________ test_words_fail ______________________________\n\n        def test_words_fail():\n            fruits1 = [\"banana\", \"apple\", \"grapes\", \"melon\", \"kiwi\"]\n            fruits2 = [\"banana\", \"apple\", \"orange\", \"melon\", \"kiwi\"]\n    >       assert fruits1 == fruits2\n    E       AssertionError: assert ['banana', 'apple', 'grapes', 'melon', 'kiwi'] == ['banana', 'apple', 'orange', 'melon', 'kiwi']\n    E\n    E         At index 2 diff: 'grapes' != 'orange'\n    E\n    E         Full diff:\n    E           [\n    E               'banana',\n    E               'apple',\n    E         -     'orange',\n    E         ?      ^  ^^\n    E         +     'grapes',\n    E         ?      ^  ^ +\n    E               'melon',\n    E               'kiwi',\n    E           ]\n\n    test_verbosity_example.py:8: AssertionError\n    ____________________________ test_numbers_fail _____________________________\n\n        def test_numbers_fail():\n            number_to_text1 = {str(x): x for x in range(5)}\n            number_to_text2 = {str(x * 10): x * 10 for x in range(5)}\n    >       assert number_to_text1 == number_to_text2\n    E       AssertionError: assert {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4} == {'0': 0, '10': 10, '20': 20, '30': 30, '40': 40}\n    E\n    E         Common items:\n    E         {'0': 0}\n    E         Left contains 4 more items:\n    E         {'1': 1, '2': 2, '3': 3, '4': 4}\n    E         Right contains 4 more items:\n    E         {'10': 10, '20': 20, '30': 30, '40': 40}\n    E\n    E         Full diff:\n    E           {\n    E               '0': 0,\n    E         -     '10': 10,\n    E         ?       -    -\n    E         +     '1': 1,\n    E         -     '20': 20,\n    E         ?       -    -\n    E         +     '2': 2,\n    E         -     '30': 30,\n    E         ?       -    -\n    E         +     '3': 3,\n    E         -     '40': 40,\n    E         ?       -    -\n    E         +     '4': 4,\n    E           }\n\n    test_verbosity_example.py:14: AssertionError\n    ___________________________ test_long_text_fail ____________________________\n\n        def test_long_text_fail():\n            long_text = \"Lorem ipsum dolor sit amet \" * 10\n    >       assert \"hello world\" in long_text\n    E       AssertionError: assert 'hello world' in 'Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet '\n\n    test_verbosity_example.py:19: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_verbosity_example.py::test_words_fail - AssertionError: assert ['banana', 'apple', 'grapes', 'melon', 'kiwi'] == ['banana', 'apple', 'orange', 'melon', 'kiwi']\n\n      At index 2 diff: 'grapes' != 'orange'\n\n      Full diff:\n        [\n            'banana',\n            'apple',\n      -     'orange',\n      ?      ^  ^^\n      +     'grapes',\n      ?      ^  ^ +\n            'melon',\n            'kiwi',\n        ]\n    FAILED test_verbosity_example.py::test_numbers_fail - AssertionError: assert {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4} == {'0': 0, '10': 10, '20': 20, '30': 30, '40': 40}\n\n      Common items:\n      {'0': 0}\n      Left contains 4 more items:\n      {'1': 1, '2': 2, '3': 3, '4': 4}\n      Right contains 4 more items:\n      {'10': 10, '20': 20, '30': 30, '40': 40}\n\n      Full diff:\n        {\n            '0': 0,\n      -     '10': 10,\n      ?       -    -\n      +     '1': 1,\n      -     '20': 20,\n      ?       -    -\n      +     '2': 2,\n      -     '30': 30,\n      ?       -    -\n      +     '3': 3,\n      -     '40': 40,\n      ?       -    -\n      +     '4': 4,\n        }\n    FAILED test_verbosity_example.py::test_long_text_fail - AssertionError: assert 'hello world' in 'Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet '\n    ======================= 3 failed, 1 passed in 0.12s ========================\n\nNotice now that:\n\n* Each test inside the file gets its own line in the output.\n* ``test_words_fail`` gives the same output as before in this case.\n* ``test_numbers_fail`` now shows a full text diff of the two dictionaries.\n* ``test_long_text_fail`` also doesn't truncate on the right hand side as before, but now pytest won't truncate any\n  text at all, regardless of its size.\n\nThose were examples of how verbosity affects normal test session output, but verbosity also is used in other\nsituations, for example you are shown even fixtures that start with ``_`` if you use ``pytest --fixtures -v``.\n\nUsing higher verbosity levels (``-vvv``, ``-vvvv``, ...) is supported, but has no effect in pytest itself at the moment,\nhowever some plugins might make use of higher verbosity.\n\n.. _`pytest.fine_grained_verbosity`:\n\nFine-grained verbosity\n~~~~~~~~~~~~~~~~~~~~~~\n\nIn addition to specifying the application wide verbosity level, it is possible to control specific aspects independently.\nThis is done by setting a verbosity level in the configuration file for the specific aspect of the output.\n\n:confval:`verbosity_assertions`: Controls how verbose the assertion output should be when pytest is executed. Running\n``pytest --no-header`` with a value of ``2`` would have the same output as the previous example, but each test inside\nthe file is shown by a single character in the output.\n\n:confval:`verbosity_test_cases`: Controls how verbose the test execution output should be when pytest is executed.\nRunning ``pytest --no-header`` with a value of ``2`` would have the same output as the first verbosity example, but each\ntest inside the file gets its own line in the output.\n\n.. _`pytest.detailed_failed_tests_usage`:\n\nProducing a detailed summary report\n--------------------------------------------------\n\nThe :option:`-r` flag can be used to display a \"short test summary info\" at the end of the test session,\nmaking it easy in large test suites to get a clear picture of all failures, skips, xfails, etc.\n\nIt defaults to ``fE`` to list failures and errors.\n\n.. regendoc:wipe\n\nExample:\n\n.. code-block:: python\n\n    # content of test_example.py\n    import pytest\n\n\n    @pytest.fixture\n    def error_fixture():\n        assert 0\n\n\n    def test_ok():\n        print(\"ok\")\n\n\n    def test_fail():\n        assert 0\n\n\n    def test_error(error_fixture):\n        pass\n\n\n    def test_skip():\n        pytest.skip(\"skipping this test\")\n\n\n    def test_xfail():\n        pytest.xfail(\"xfailing this test\")\n\n\n    @pytest.mark.xfail(reason=\"always xfail\")\n    def test_xpass():\n        pass\n\n\n.. code-block:: pytest\n\n    $ pytest -ra\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 6 items\n\n    test_example.py .FEsxX                                               [100%]\n\n    ================================== ERRORS ==================================\n    _______________________ ERROR at setup of test_error _______________________\n\n        @pytest.fixture\n        def error_fixture():\n    >       assert 0\n    E       assert 0\n\n    test_example.py:6: AssertionError\n    ================================= FAILURES =================================\n    ________________________________ test_fail _________________________________\n\n        def test_fail():\n    >       assert 0\n    E       assert 0\n\n    test_example.py:14: AssertionError\n    ================================= XPASSES ==================================\n    ========================= short test summary info ==========================\n    SKIPPED [1] test_example.py:22: skipping this test\n    XFAIL test_example.py::test_xfail - xfailing this test\n    XPASS test_example.py::test_xpass - always xfail\n    ERROR test_example.py::test_error - assert 0\n    FAILED test_example.py::test_fail - assert 0\n    == 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s ===\n\nThe :option:`-r` options accepts a number of characters after it, with ``a`` used\nabove meaning \"all except passes\".\n\nHere is the full list of available characters that can be used:\n\n - ``f`` - failed\n - ``E`` - error\n - ``s`` - skipped\n - ``x`` - xfailed\n - ``X`` - xpassed\n - ``p`` - passed\n - ``P`` - passed with output\n\nSpecial characters for (de)selection of groups:\n\n - ``a`` - all except ``pP``\n - ``A`` - all\n - ``N`` - none, this can be used to display nothing (since ``fE`` is the default)\n\nMore than one character can be used, so for example to only see failed and skipped tests, you can execute:\n\n.. code-block:: pytest\n\n    $ pytest -rfs\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 6 items\n\n    test_example.py .FEsxX                                               [100%]\n\n    ================================== ERRORS ==================================\n    _______________________ ERROR at setup of test_error _______________________\n\n        @pytest.fixture\n        def error_fixture():\n    >       assert 0\n    E       assert 0\n\n    test_example.py:6: AssertionError\n    ================================= FAILURES =================================\n    ________________________________ test_fail _________________________________\n\n        def test_fail():\n    >       assert 0\n    E       assert 0\n\n    test_example.py:14: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_example.py::test_fail - assert 0\n    SKIPPED [1] test_example.py:22: skipping this test\n    == 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s ===\n\nUsing ``p`` lists the passing tests, whilst ``P`` adds an extra section \"PASSES\" with those tests that passed but had\ncaptured output:\n\n.. code-block:: pytest\n\n    $ pytest -rpP\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 6 items\n\n    test_example.py .FEsxX                                               [100%]\n\n    ================================== ERRORS ==================================\n    _______________________ ERROR at setup of test_error _______________________\n\n        @pytest.fixture\n        def error_fixture():\n    >       assert 0\n    E       assert 0\n\n    test_example.py:6: AssertionError\n    ================================= FAILURES =================================\n    ________________________________ test_fail _________________________________\n\n        def test_fail():\n    >       assert 0\n    E       assert 0\n\n    test_example.py:14: AssertionError\n    ================================== PASSES ==================================\n    _________________________________ test_ok __________________________________\n    --------------------------- Captured stdout call ---------------------------\n    ok\n    ========================= short test summary info ==========================\n    PASSED test_example.py::test_ok\n    == 1 failed, 1 passed, 1 skipped, 1 xfailed, 1 xpassed, 1 error in 0.12s ===\n\n.. note::\n\n    By default, parametrized variants of skipped tests are grouped together if\n    they share the same skip reason. You can use :option:`--no-fold-skipped` to print each skipped test separately.\n\n\n.. _truncation-params:\n\nModifying truncation limits\n--------------------------------------------------\n\n.. versionadded: 8.4\n\nDefault truncation limits are 8 lines or 640 characters, whichever comes first.\nTo set custom truncation limits you can use the following configuration file options:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        truncation_limit_lines = 10\n        truncation_limit_chars = 90\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        truncation_limit_lines = 10\n        truncation_limit_chars = 90\n\nThat will cause pytest to truncate the assertions to 10 lines or 90 characters, whichever comes first.\n\nSetting both :confval:`truncation_limit_lines` and :confval:`truncation_limit_chars` to ``0`` will disable the truncation.\nHowever, setting only one of those values will disable one truncation mode, but will leave the other one intact.\n\n\nCreating JUnitXML format files\n----------------------------------------------------\n\nTo create result files which can be read by Jenkins_ or other Continuous\nintegration servers, use this invocation:\n\n.. code-block:: bash\n\n    pytest --junit-xml=path\n\nto create an XML file at ``path``.\n\n\n\nTo set the name of the root test suite xml item, you can configure the ``junit_suite_name`` option in your config file:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        junit_suite_name = \"my_suite\"\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        junit_suite_name = my_suite\n\n.. versionadded:: 4.0\n\nJUnit XML specification seems to indicate that ``\"time\"`` attribute\nshould report total test execution times, including setup and teardown\n(`1 <http://windyroad.com.au/dl/Open%20Source/JUnit.xsd>`_, `2\n<https://www.ibm.com/support/knowledgecenter/en/SSQ2R2_14.1.0/com.ibm.rsar.analysis.codereview.cobol.doc/topics/cac_useresults_junit.html>`_).\nIt is the default pytest behavior. To report just call durations\ninstead, configure the ``junit_duration_report`` option like this:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        junit_duration_report = \"call\"\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        junit_duration_report = call\n\n.. _record_property example:\n\nrecord_property\n~~~~~~~~~~~~~~~~~\n\nIf you want to log additional information for a test, you can use the\n``record_property`` fixture:\n\n.. code-block:: python\n\n    def test_function(record_property):\n        record_property(\"example_key\", 1)\n        assert True\n\nThis will add an extra property ``example_key=\"1\"`` to the generated\n``testcase`` tag:\n\n.. code-block:: xml\n\n    <testcase classname=\"test_function\" file=\"test_function.py\" line=\"0\" name=\"test_function\" time=\"0.0009\">\n      <properties>\n        <property name=\"example_key\" value=\"1\" />\n      </properties>\n    </testcase>\n\nAlternatively, you can integrate this functionality with custom markers:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n\n    def pytest_collection_modifyitems(session, config, items):\n        for item in items:\n            for marker in item.iter_markers(name=\"test_id\"):\n                test_id = marker.args[0]\n                item.user_properties.append((\"test_id\", test_id))\n\nAnd in your tests:\n\n.. code-block:: python\n\n    # content of test_function.py\n    import pytest\n\n\n    @pytest.mark.test_id(1501)\n    def test_function():\n        assert True\n\nWill result in:\n\n.. code-block:: xml\n\n    <testcase classname=\"test_function\" file=\"test_function.py\" line=\"0\" name=\"test_function\" time=\"0.0009\">\n      <properties>\n        <property name=\"test_id\" value=\"1501\" />\n      </properties>\n    </testcase>\n\n.. warning::\n\n    Please note that using this feature will break schema verifications for the latest JUnitXML schema.\n    This might be a problem when used with some CI servers.\n\n\nrecord_xml_attribute\n~~~~~~~~~~~~~~~~~~~~~~~\n\nTo add an additional xml attribute to a testcase element, you can use\n``record_xml_attribute`` fixture. This can also be used to override existing values:\n\n.. code-block:: python\n\n    def test_function(record_xml_attribute):\n        record_xml_attribute(\"assertions\", \"REQ-1234\")\n        record_xml_attribute(\"classname\", \"custom_classname\")\n        print(\"hello world\")\n        assert True\n\nUnlike ``record_property``, this will not add a new child element.\nInstead, this will add an attribute ``assertions=\"REQ-1234\"`` inside the generated\n``testcase`` tag and override the default ``classname`` with ``\"classname=custom_classname\"``:\n\n.. code-block:: xml\n\n    <testcase classname=\"custom_classname\" file=\"test_function.py\" line=\"0\" name=\"test_function\" time=\"0.003\" assertions=\"REQ-1234\">\n        <system-out>\n            hello world\n        </system-out>\n    </testcase>\n\n.. warning::\n\n    ``record_xml_attribute`` is an experimental feature, and its interface might be replaced\n    by something more powerful and general in future versions. The\n    functionality per-se will be kept, however.\n\n    Using this over ``record_xml_property`` can help when using ci tools to parse the xml report.\n    However, some parsers are quite strict about the elements and attributes that are allowed.\n    Many tools use an xsd schema (like the example below) to validate incoming xml.\n    Make sure you are using attribute names that are allowed by your parser.\n\n    Below is the Scheme used by Jenkins to validate the XML report:\n\n    .. code-block:: xml\n\n        <xs:element name=\"testcase\">\n            <xs:complexType>\n                <xs:sequence>\n                    <xs:element ref=\"skipped\" minOccurs=\"0\" maxOccurs=\"1\"/>\n                    <xs:element ref=\"error\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n                    <xs:element ref=\"failure\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n                    <xs:element ref=\"system-out\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n                    <xs:element ref=\"system-err\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n                </xs:sequence>\n                <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\"/>\n                <xs:attribute name=\"assertions\" type=\"xs:string\" use=\"optional\"/>\n                <xs:attribute name=\"time\" type=\"xs:string\" use=\"optional\"/>\n                <xs:attribute name=\"classname\" type=\"xs:string\" use=\"optional\"/>\n                <xs:attribute name=\"status\" type=\"xs:string\" use=\"optional\"/>\n            </xs:complexType>\n        </xs:element>\n\n.. warning::\n\n    Please note that using this feature will break schema verifications for the latest JUnitXML schema.\n    This might be a problem when used with some CI servers.\n\n.. _record_testsuite_property example:\n\nrecord_testsuite_property\n^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. versionadded:: 4.5\n\nIf you want to add a properties node at the test-suite level, which may contain properties\nthat are relevant to all tests, you can use the ``record_testsuite_property`` session-scoped fixture:\n\nThe ``record_testsuite_property`` session-scoped fixture can be used to add properties relevant\nto all tests.\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.fixture(scope=\"session\", autouse=True)\n    def log_global_env_facts(record_testsuite_property):\n        record_testsuite_property(\"ARCH\", \"PPC\")\n        record_testsuite_property(\"STORAGE_TYPE\", \"CEPH\")\n\n\n    class TestMe:\n        def test_foo(self):\n            assert True\n\nThe fixture is a callable which receives ``name`` and ``value`` of a ``<property>`` tag\nadded at the test-suite level of the generated xml:\n\n.. code-block:: xml\n\n    <testsuite errors=\"0\" failures=\"0\" name=\"pytest\" skipped=\"0\" tests=\"1\" time=\"0.006\">\n      <properties>\n        <property name=\"ARCH\" value=\"PPC\"/>\n        <property name=\"STORAGE_TYPE\" value=\"CEPH\"/>\n      </properties>\n      <testcase classname=\"test_me.TestMe\" file=\"test_me.py\" line=\"16\" name=\"test_foo\" time=\"0.000243663787842\"/>\n    </testsuite>\n\n``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.\n\nThe generated XML is compatible with the latest ``xunit`` standard, contrary to `record_property`_\nand `record_xml_attribute`_.\n\n\nSending test report to an online pastebin service\n--------------------------------------------------\n\n**Creating a URL for each test failure**:\n\n.. code-block:: bash\n\n    pytest --pastebin=failed\n\nThis will submit test run information to a remote Paste service and\nprovide a URL for each failure.  You may select tests as usual or add\nfor example :option:`-x` if you only want to send one particular failure.\n\n**Creating a URL for a whole test session log**:\n\n.. code-block:: bash\n\n    pytest --pastebin=all\n\nCurrently only pasting to the https://bpaste.net/ service is implemented.\n\n.. versionchanged:: 5.2\n\nIf creating the URL fails for any reason, a warning is generated instead of failing the\nentire test suite.\n\n.. _jenkins: https://jenkins-ci.org\n"
  },
  {
    "path": "doc/en/how-to/parametrize.rst",
    "content": "\n.. _`test generators`:\n.. _`parametrizing-tests`:\n.. _`parametrized test functions`:\n.. _`parametrize`:\n\n.. _`parametrize-basics`:\n\nHow to parametrize fixtures and test functions\n==========================================================================\n\npytest enables test parametrization at several levels:\n\n- :py:func:`pytest.fixture` allows one to :ref:`parametrize fixture\n  functions <fixture-parametrize>`.\n\n* `@pytest.mark.parametrize`_ allows one to define multiple sets of\n  arguments and fixtures at the test function or class.\n\n* `pytest_generate_tests`_ allows one to define custom parametrization\n  schemes or extensions.\n\n\n.. note::\n\n    See :ref:`subtests` for an alternative to parametrization.\n\n.. _parametrizemark:\n.. _`@pytest.mark.parametrize`:\n\n\n``@pytest.mark.parametrize``: parametrizing test functions\n---------------------------------------------------------------------\n\n.. regendoc: wipe\n\nThe builtin :ref:`pytest.mark.parametrize ref` decorator enables\nparametrization of arguments for a test function.  Here is a typical example\nof a test function that implements checking that a certain input leads\nto an expected output:\n\n.. code-block:: python\n\n    # content of test_expectation.py\n    import pytest\n\n\n    @pytest.mark.parametrize(\"test_input,expected\", [(\"3+5\", 8), (\"2+4\", 6), (\"6*9\", 42)])\n    def test_eval(test_input, expected):\n        assert eval(test_input) == expected\n\nHere, the ``@parametrize`` decorator defines three different ``(test_input,expected)``\ntuples so that the ``test_eval`` function will run three times using\nthem in turn:\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 3 items\n\n    test_expectation.py ..F                                              [100%]\n\n    ================================= FAILURES =================================\n    ____________________________ test_eval[6*9-42] _____________________________\n\n    test_input = '6*9', expected = 42\n\n        @pytest.mark.parametrize(\"test_input,expected\", [(\"3+5\", 8), (\"2+4\", 6), (\"6*9\", 42)])\n        def test_eval(test_input, expected):\n    >       assert eval(test_input) == expected\n    E       AssertionError: assert 54 == 42\n    E        +  where 54 = eval('6*9')\n\n    test_expectation.py:6: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_expectation.py::test_eval[6*9-42] - AssertionError: assert 54...\n    ======================= 1 failed, 2 passed in 0.12s ========================\n\n.. note::\n\n    Parameter values are passed as-is to tests (no copy whatsoever).\n\n    For example, if you pass a list or a dict as a parameter value, and\n    the test case code mutates it, the mutations will be reflected in subsequent\n    test case calls.\n\n.. note::\n\n    pytest by default escapes any non-ascii characters used in unicode strings\n    for the parametrization because it has several downsides.\n    If however you would like to use unicode strings in parametrization\n    and see them in the terminal as is (non-escaped), use this option\n    in your configuration file:\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true\n\n    Keep in mind however that this might cause unwanted side effects and\n    even bugs depending on the OS used and plugins currently installed,\n    so use it at your own risk.\n\n\nAs designed in this example, only one pair of input/output values fails\nthe simple test function.  And as usual with test function arguments,\nyou can see the ``input`` and ``output`` values in the traceback.\n\nNote that you could also use the parametrize marker on a class or a module\n(see :ref:`mark`) which would invoke several functions with the argument sets,\nfor instance:\n\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.mark.parametrize(\"n,expected\", [(1, 2), (3, 4)])\n    class TestClass:\n        def test_simple_case(self, n, expected):\n            assert n + 1 == expected\n\n        def test_weird_simple_case(self, n, expected):\n            assert (n * 1) + 1 == expected\n\n\nTo parametrize all tests in a module, you can assign to the :globalvar:`pytestmark` global variable:\n\n\n.. code-block:: python\n\n    import pytest\n\n    pytestmark = pytest.mark.parametrize(\"n,expected\", [(1, 2), (3, 4)])\n\n\n    class TestClass:\n        def test_simple_case(self, n, expected):\n            assert n + 1 == expected\n\n        def test_weird_simple_case(self, n, expected):\n            assert (n * 1) + 1 == expected\n\n\nIt is also possible to mark individual test instances within parametrize,\nfor example with the builtin ``mark.xfail``:\n\n.. code-block:: python\n\n    # content of test_expectation.py\n    import pytest\n\n\n    @pytest.mark.parametrize(\n        \"test_input,expected\",\n        [(\"3+5\", 8), (\"2+4\", 6), pytest.param(\"6*9\", 42, marks=pytest.mark.xfail)],\n    )\n    def test_eval(test_input, expected):\n        assert eval(test_input) == expected\n\nLet's run this:\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 3 items\n\n    test_expectation.py ..x                                              [100%]\n\n    ======================= 2 passed, 1 xfailed in 0.12s =======================\n\nThe one parameter set which caused a failure previously now\nshows up as an \"xfailed\" (expected to fail) test.\n\nIn case the values provided to ``parametrize`` result in an empty list - for\nexample, if they're dynamically generated by some function - the behaviour of\npytest is defined by the :confval:`empty_parameter_set_mark` option.\n\nTo get all combinations of multiple parametrized arguments you can stack\n``parametrize`` decorators:\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.mark.parametrize(\"x\", [0, 1])\n    @pytest.mark.parametrize(\"y\", [2, 3])\n    def test_foo(x, y):\n        pass\n\nThis will run the test with the arguments set to ``x=0/y=2``, ``x=1/y=2``,\n``x=0/y=3``, and ``x=1/y=3`` exhausting parameters in the order of the decorators.\n\n\n.. _`pytest_generate_tests`:\n\nBasic ``pytest_generate_tests`` example\n---------------------------------------------\n\nSometimes you may want to implement your own parametrization scheme\nor implement some dynamism for determining the parameters or scope\nof a fixture.   For this, you can use the ``pytest_generate_tests`` hook\nwhich is called when collecting a test function.  Through the passed in\n``metafunc`` object you can inspect the requesting test context and, most\nimportantly, you can call ``metafunc.parametrize()`` to cause\nparametrization.\n\nFor example, let's say we want to run a test taking string inputs which\nwe want to set via a new ``pytest`` command line option.  Let's first write\na simple test accepting a ``stringinput`` fixture function argument:\n\n.. code-block:: python\n\n    # content of test_strings.py\n\n\n    def test_valid_string(stringinput):\n        assert stringinput.isalpha()\n\nNow we add a ``conftest.py`` file containing the addition of a\ncommand line option and the parametrization of our test function:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n\n    def pytest_addoption(parser):\n        parser.addoption(\n            \"--stringinput\",\n            action=\"append\",\n            default=[],\n            help=\"list of stringinputs to pass to test functions\",\n        )\n\n\n    def pytest_generate_tests(metafunc):\n        if \"stringinput\" in metafunc.fixturenames:\n            metafunc.parametrize(\"stringinput\", metafunc.config.getoption(\"stringinput\"))\n\n.. note::\n\n    The :hook:`pytest_generate_tests` hook can also be implemented directly in a test\n    module or inside a test class; unlike other hooks, pytest will discover it there\n    as well. Other hooks must live in a :ref:`conftest.py <localplugin>` or a plugin.\n    See :ref:`writinghooks`.\n\nIf we now pass two stringinput values, our test will run twice:\n\n.. code-block:: pytest\n\n    $ pytest -q --stringinput=\"hello\" --stringinput=\"world\" test_strings.py\n    ..                                                                   [100%]\n    2 passed in 0.12s\n\nLet's also run with a stringinput that will lead to a failing test:\n\n.. code-block:: pytest\n\n    $ pytest -q --stringinput=\"!\" test_strings.py\n    F                                                                    [100%]\n    ================================= FAILURES =================================\n    ___________________________ test_valid_string[!] ___________________________\n\n    stringinput = '!'\n\n        def test_valid_string(stringinput):\n    >       assert stringinput.isalpha()\n    E       AssertionError: assert False\n    E        +  where False = <built-in method isalpha of str object at 0xdeadbeef0001>()\n    E        +    where <built-in method isalpha of str object at 0xdeadbeef0001> = '!'.isalpha\n\n    test_strings.py:4: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_strings.py::test_valid_string[!] - AssertionError: assert False\n    1 failed in 0.12s\n\nAs expected our test function fails.\n\nIf you don't specify a stringinput it will be skipped because\n``metafunc.parametrize()`` will be called with an empty parameter\nlist:\n\n.. code-block:: pytest\n\n    $ pytest -q -rs test_strings.py\n    s                                                                    [100%]\n    ========================= short test summary info ==========================\n    SKIPPED [1] test_strings.py: got empty parameter set for (stringinput)\n    1 skipped in 0.12s\n\nNote that when calling ``metafunc.parametrize`` multiple times with different parameter sets, all parameter names across\nthose sets cannot be duplicated, otherwise an error will be raised.\n\nMore examples\n-------------\n\nFor further examples, you might want to look at :ref:`more\nparametrization examples <paramexamples>`.\n"
  },
  {
    "path": "doc/en/how-to/plugins.rst",
    "content": ".. _`external plugins`:\n.. _`extplugins`:\n.. _`using plugins`:\n\nHow to install and use plugins\n===============================\n\nThis section talks about installing and using third party plugins.\nFor writing your own plugins, please refer to :ref:`writing-plugins`.\n\nInstalling a third party plugin can be easily done with ``pip``:\n\n.. code-block:: bash\n\n    pip install pytest-NAME\n    pip uninstall pytest-NAME\n\nIf a plugin is installed, ``pytest`` automatically finds and integrates it,\nthere is no need to activate it.\n\nHere is a little annotated list for some popular plugins:\n\n* :pypi:`pytest-django`: write tests\n  for `django <https://docs.djangoproject.com/>`_ apps, using pytest integration.\n\n* :pypi:`pytest-twisted`: write tests\n  for `twisted <https://twistedmatrix.com/>`_ apps, starting a reactor and\n  processing deferreds from test functions.\n\n* :pypi:`pytest-cov`:\n  coverage reporting, compatible with distributed testing\n\n* :pypi:`pytest-xdist`:\n  to distribute tests to CPUs and remote hosts, to run in boxed\n  mode which allows to survive segmentation faults, to run in\n  looponfailing mode, automatically re-running failing tests\n  on file changes.\n\n* :pypi:`pytest-instafail`:\n  to report failures while the test run is happening.\n\n* :pypi:`pytest-bdd`:\n  to write tests using behaviour-driven testing.\n\n* :pypi:`pytest-timeout`:\n  to timeout tests based on function marks or global definitions.\n\n* :pypi:`pytest-pep8`:\n  a ``--pep8`` option to enable PEP8 compliance checking.\n\n* :pypi:`pytest-flakes`:\n  check source code with pyflakes.\n\n* :pypi:`allure-pytest`:\n  report test results via `allure-framework <https://github.com/allure-framework/>`_.\n\nTo see a complete list of all plugins with their latest testing\nstatus against different pytest and Python versions, please visit\n:ref:`plugin-list`.\n\nYou may also discover more plugins through a `pytest- pypi.org search`_.\n\n.. _`pytest- pypi.org search`: https://pypi.org/search/?q=pytest-\n\n\n.. _`available installable plugins`:\n\nRequiring/Loading plugins in a test module or conftest file\n-----------------------------------------------------------\n\nYou can require plugins in a test module or a conftest file using :globalvar:`pytest_plugins`:\n\n.. code-block:: python\n\n    pytest_plugins = (\"myapp.testsupport.myplugin\",)\n\nWhen the test module or conftest plugin is loaded the specified plugins\nwill be loaded as well.\n\n.. note::\n\n    Requiring plugins using a ``pytest_plugins`` variable in non-root\n    ``conftest.py`` files is deprecated. See\n    :ref:`full explanation <requiring plugins in non-root conftests>`\n    in the Writing plugins section.\n\n.. note::\n   The name ``pytest_plugins`` is reserved and should not be used as a\n   name for a custom plugin module.\n\n\n.. _`findpluginname`:\n\nFinding out which plugins are active\n------------------------------------\n\nIf you want to find out which plugins are active in your\nenvironment you can type:\n\n.. code-block:: bash\n\n    pytest --trace-config\n\nand will get an extended test header which shows activated plugins\nand their names. It will also print local plugins aka\n:ref:`conftest.py <conftest.py plugins>` files when they are loaded.\n\n.. _`cmdunregister`:\n\nDeactivating / unregistering a plugin by name\n---------------------------------------------\n\nYou can prevent plugins from loading or unregister them:\n\n.. code-block:: bash\n\n    pytest -p no:NAME\n\nThis means that any subsequent try to activate/load the named\nplugin will not work.\n\nIf you want to unconditionally disable a plugin for a project, you can add\nthis option to your configuration file:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        addopts = [\"-p\", \"no:NAME\"]\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        addopts = -p no:NAME\n\nAlternatively to disable it only in certain environments (for example in a\nCI server), you can set ``PYTEST_ADDOPTS`` environment variable to\n``-p no:name``.\n\nSee :ref:`findpluginname` for how to obtain the name of a plugin.\n\n.. _`disable_plugin_autoload`:\n\nDisabling plugins from autoloading\n----------------------------------\n\nIf you want to disable plugins from loading automatically, instead of requiring you to\nmanually specify each plugin with :option:`-p` or :envvar:`PYTEST_PLUGINS`, you can use :option:`--disable-plugin-autoload` or :envvar:`PYTEST_DISABLE_PLUGIN_AUTOLOAD`.\n\n.. code-block:: bash\n\n   export PYTEST_DISABLE_PLUGIN_AUTOLOAD=1\n   export PYTEST_PLUGINS=NAME,NAME2\n   pytest\n\n.. code-block:: bash\n\n   pytest --disable-plugin-autoload -p NAME -p NAME2\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        addopts = [\"--disable-plugin-autoload\", \"-p\", \"NAME\", \"-p\", \"NAME2\"]\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        addopts =\n            --disable-plugin-autoload\n            -p NAME\n            -p NAME2\n\n.. versionadded:: 8.4\n\n   The :option:`--disable-plugin-autoload` command-line flag.\n\n.. note::\n\n   :option:`-p` and :envvar:`PYTEST_PLUGINS` are both ways to explicitly control which\n   plugins are loaded, but they serve slightly different use-cases.\n\n   * :option:`-p` loads (or disables with ``-p no:<name>``) a plugin by name or entry point\n     for a specific pytest invocation, and is processed early during startup.\n   * :envvar:`PYTEST_PLUGINS` is a comma-separated list of Python modules that are imported\n     and registered as plugins during startup. This mechanism is commonly used by test\n     suites, for example when testing a plugin.\n\n   When explicitly controlling plugin loading (especially with\n   :envvar:`PYTEST_DISABLE_PLUGIN_AUTOLOAD` or :option:`--disable-plugin-autoload`),\n   avoid specifying the same plugin via multiple mechanisms. Registering the same plugin\n   more than once can lead to errors during plugin registration.\n\nExamples:\n\n.. code-block:: bash\n\n   # Disable auto-loading and load only specific plugins for this invocation\n   PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 pytest -p xdist\n\n.. code-block:: bash\n\n   # Disable auto-loading and load plugin modules during startup\n   PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 PYTEST_PLUGINS=mymodule.plugin,xdist pytest\n"
  },
  {
    "path": "doc/en/how-to/skipping.rst",
    "content": ".. _`skip and xfail`:\n\n.. _skipping:\n\nHow to use skip and xfail to deal with tests that cannot succeed\n=================================================================\n\nYou can mark test functions that cannot be run on certain platforms\nor that you expect to fail so pytest can deal with them accordingly and\npresent a summary of the test session, while keeping the test suite *green*.\n\nA **skip** means that you expect your test to pass only if some conditions are met,\notherwise pytest should skip running the test altogether. Common examples are skipping\nwindows-only tests on non-windows platforms, or skipping tests that depend on an external\nresource which is not available at the moment (for example a database).\n\nAn **xfail** means that you expect a test to fail for some reason.\nA common example is a test for a feature not yet implemented, or a bug not yet fixed.\nWhen a test passes despite being expected to fail (marked with ``pytest.mark.xfail``),\nit's an **xpass** and will be reported in the test summary.\n\n``pytest`` counts and lists *skip* and *xfail* tests separately. Detailed\ninformation about skipped/xfailed tests is not shown by default to avoid\ncluttering the output.  You can use the :option:`-r` option to see details\ncorresponding to the \"short\" letters shown in the test progress:\n\n.. code-block:: bash\n\n    pytest -rxXs  # show extra info on xfailed, xpassed, and skipped tests\n\nMore details on the :option:`-r` option can be found by running ``pytest -h``.\n\n(See :ref:`how to change command line options defaults`)\n\n.. _skipif:\n.. _skip:\n.. _`condition booleans`:\n\nSkipping test functions\n-----------------------\n\n\n\nThe simplest way to skip a test function is to mark it with the ``skip`` decorator\nwhich may be passed an optional ``reason``:\n\n.. code-block:: python\n\n    @pytest.mark.skip(reason=\"no way of currently testing this\")\n    def test_the_unknown(): ...\n\n\nAlternatively, it is also possible to skip imperatively during test execution or setup\nby calling the ``pytest.skip(reason)`` function:\n\n.. code-block:: python\n\n    def test_function():\n        if not valid_config():\n            pytest.skip(\"unsupported configuration\")\n\nThe imperative method is useful when it is not possible to evaluate the skip condition\nduring import time.\n\nIt is also possible to skip the whole module using\n``pytest.skip(reason, allow_module_level=True)`` at the module level:\n\n.. code-block:: python\n\n    import sys\n\n    import pytest\n\n    if not sys.platform.startswith(\"win\"):\n        pytest.skip(\"skipping windows-only tests\", allow_module_level=True)\n\n\n**Reference**: :ref:`pytest.mark.skip ref`\n\n``skipif``\n~~~~~~~~~~\n\n\n\nIf you wish to skip something conditionally then you can use ``skipif`` instead.\nHere is an example of marking a test function to be skipped\nwhen run on an interpreter earlier than Python3.13:\n\n.. code-block:: python\n\n    import sys\n\n\n    @pytest.mark.skipif(sys.version_info < (3, 13), reason=\"requires python3.13 or higher\")\n    def test_function(): ...\n\nIf the condition evaluates to ``True`` during collection, the test function will be skipped,\nwith the specified reason appearing in the summary when using ``-rs``.\n\nYou can share ``skipif`` markers between modules.  Consider this test module:\n\n.. code-block:: python\n\n    # content of test_mymodule.py\n    import mymodule\n\n    minversion = pytest.mark.skipif(\n        mymodule.__versioninfo__ < (1, 1), reason=\"at least mymodule-1.1 required\"\n    )\n\n\n    @minversion\n    def test_function(): ...\n\nYou can import the marker and reuse it in another test module:\n\n.. code-block:: python\n\n    # test_myothermodule.py\n    from test_mymodule import minversion\n\n\n    @minversion\n    def test_anotherfunction(): ...\n\nFor larger test suites it's usually a good idea to have one file\nwhere you define the markers which you then consistently apply\nthroughout your test suite.\n\nAlternatively, you can use :ref:`condition strings\n<string conditions>` instead of booleans, but they can't be shared between modules easily\nso they are supported mainly for backward compatibility reasons.\n\n**Reference**: :ref:`pytest.mark.skipif ref`\n\n\nSkip all test functions of a class or module\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can use the ``skipif`` marker (as any other marker) on classes:\n\n.. code-block:: python\n\n    @pytest.mark.skipif(sys.platform == \"win32\", reason=\"does not run on windows\")\n    class TestPosixCalls:\n        def test_function(self):\n            \"will not be setup or run under 'win32' platform\"\n\nIf the condition is ``True``, this marker will produce a skip result for\neach of the test methods of that class.\n\nIf you want to skip all test functions of a module, you may use the\n:globalvar:`pytestmark` global:\n\n.. code-block:: python\n\n    # test_module.py\n    pytestmark = pytest.mark.skipif(...)\n\nIf multiple ``skipif`` decorators are applied to a test function, it\nwill be skipped if any of the skip conditions is true.\n\n.. _`whole class- or module level`: mark.html#scoped-marking\n\n\nSkipping files or directories\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSometimes you may need to skip an entire file or directory, for example if the\ntests rely on Python version-specific features or contain code that you do not\nwish pytest to run. In this case, you must exclude the files and directories\nfrom collection. Refer to :ref:`customizing-test-collection` for more\ninformation.\n\n\nSkipping on a missing import dependency\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can skip tests on a missing import by using :ref:`pytest.importorskip ref`\nat module level, within a test, or test setup function.\n\n.. code-block:: python\n\n    docutils = pytest.importorskip(\"docutils\")\n\nIf ``docutils`` cannot be imported here, this will lead to a skip outcome of\nthe test. You can also skip based on the version number of a library:\n\n.. code-block:: python\n\n    docutils = pytest.importorskip(\"docutils\", minversion=\"0.3\")\n\nThe version will be read from the specified\nmodule's ``__version__`` attribute.\n\nSummary\n~~~~~~~\n\nHere's a quick guide on how to skip tests in a module in different situations:\n\n1. Skip all tests in a module unconditionally:\n\n  .. code-block:: python\n\n        pytestmark = pytest.mark.skip(\"all tests still WIP\")\n\n2. Skip all tests in a module based on some condition:\n\n  .. code-block:: python\n\n        pytestmark = pytest.mark.skipif(sys.platform == \"win32\", reason=\"tests for linux only\")\n\n3. Skip all tests in a module if some import is missing:\n\n  .. code-block:: python\n\n        pexpect = pytest.importorskip(\"pexpect\")\n\n\n.. _xfail:\n\nXFail: mark test functions as expected to fail\n----------------------------------------------\n\nYou can use the ``xfail`` marker to indicate that you\nexpect a test to fail:\n\n.. code-block:: python\n\n    @pytest.mark.xfail\n    def test_function(): ...\n\nThis test will run but no traceback will be reported when it fails. Instead, terminal\nreporting will list it in the \"expected to fail\" (``XFAIL``) or \"unexpectedly\npassing\" (``XPASS``) sections.\n\nAlternatively, you can also mark a test as ``XFAIL`` from within the test or its setup function\nimperatively:\n\n.. code-block:: python\n\n    def test_function():\n        if not valid_config():\n            pytest.xfail(\"failing configuration (but should work)\")\n\n.. code-block:: python\n\n    def test_function2():\n        import slow_module\n\n        if slow_module.slow_function():\n            pytest.xfail(\"slow_module taking too long\")\n\nThese two examples illustrate situations where you don't want to check for a condition\nat the module level, which is when a condition would otherwise be evaluated for marks.\n\nThis will make ``test_function`` ``XFAIL``. Note that no other code is executed after\nthe :func:`pytest.xfail` call, differently from the marker. That's because it is implemented\ninternally by raising a known exception.\n\n**Reference**: :ref:`pytest.mark.xfail ref`\n\n\n``condition`` parameter\n~~~~~~~~~~~~~~~~~~~~~~~\n\nIf a test is only expected to fail under a certain condition, you can pass\nthat condition as the first parameter:\n\n.. code-block:: python\n\n    @pytest.mark.xfail(sys.platform == \"win32\", reason=\"bug in a 3rd party library\")\n    def test_function(): ...\n\nNote that you have to pass a reason as well (see the parameter description at\n:ref:`pytest.mark.xfail ref`).\n\n``reason`` parameter\n~~~~~~~~~~~~~~~~~~~~\n\nYou can specify the motive of an expected failure with the ``reason`` parameter:\n\n.. code-block:: python\n\n    @pytest.mark.xfail(reason=\"known parser issue\")\n    def test_function(): ...\n\n\n``raises`` parameter\n~~~~~~~~~~~~~~~~~~~~\n\nIf you want to be more specific as to why the test is failing, you can specify\na single exception, or a tuple of exceptions, in the ``raises`` argument.\n\n.. code-block:: python\n\n    @pytest.mark.xfail(raises=RuntimeError)\n    def test_function(): ...\n\nThen the test will be reported as a regular failure if it fails with an\nexception not mentioned in ``raises``.\n\n``run`` parameter\n~~~~~~~~~~~~~~~~~\n\nIf a test should be marked as xfail and reported as such but should not be\neven executed, use the ``run`` parameter as ``False``:\n\n.. code-block:: python\n\n    @pytest.mark.xfail(run=False)\n    def test_function(): ...\n\nThis is particularly useful for xfailing tests that are crashing the interpreter and should be\ninvestigated later.\n\n.. _`xfail strict tutorial`:\n\n``strict`` parameter\n~~~~~~~~~~~~~~~~~~~~\n\nBoth ``XFAIL`` and ``XPASS`` don't fail the test suite by default.\nYou can change this by setting the ``strict`` keyword-only parameter to ``True``:\n\n.. code-block:: python\n\n    @pytest.mark.xfail(strict=True)\n    def test_function(): ...\n\n\nThis will make ``XPASS`` (\"unexpectedly passing\") results from this test to fail the test suite.\n\nYou can change the default value of the ``strict`` parameter using the\n``strict_xfail`` ini option:\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        [pytest]\n        xfail_strict = true\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        [pytest]\n        strict_xfail = true\n\n\nIgnoring xfail\n~~~~~~~~~~~~~~\n\nBy specifying on the commandline:\n\n.. code-block:: bash\n\n    pytest --runxfail\n\nyou can force the running and reporting of an ``xfail`` marked test\nas if it weren't marked at all. This also causes :func:`pytest.xfail` to produce no effect.\n\nExamples\n~~~~~~~~\n\nHere is a simple test file with the several usages:\n\n.. literalinclude:: /example/xfail_demo.py\n\nRunning it with the report-on-xfail option gives this output:\n\n.. FIXME: Use $ instead of ! again to re-enable regendoc once it's fixed:\n   https://github.com/pytest-dev/pytest/issues/8807\n\n.. code-block:: pytest\n\n    ! pytest -rx xfail_demo.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-6.x.y, py-1.x.y, pluggy-1.x.y\n    cachedir: $PYTHON_PREFIX/.pytest_cache\n    rootdir: $REGENDOC_TMPDIR/example\n    collected 7 items\n\n    xfail_demo.py xxxxxxx                                                [100%]\n\n    ========================= short test summary info ==========================\n    XFAIL xfail_demo.py::test_hello\n    XFAIL xfail_demo.py::test_hello2\n      reason: [NOTRUN]\n    XFAIL xfail_demo.py::test_hello3\n      condition: hasattr(os, 'sep')\n    XFAIL xfail_demo.py::test_hello4\n      bug 110\n    XFAIL xfail_demo.py::test_hello5\n      condition: pytest.__version__[0] != \"17\"\n    XFAIL xfail_demo.py::test_hello6\n      reason: reason\n    XFAIL xfail_demo.py::test_hello7\n    ============================ 7 xfailed in 0.12s ============================\n\n.. _`skip/xfail with parametrize`:\n\nSkip/xfail with parametrize\n---------------------------\n\nIt is possible to apply markers like skip and xfail to individual\ntest instances when using parametrize:\n\n.. code-block:: python\n\n    import sys\n\n    import pytest\n\n\n    @pytest.mark.parametrize(\n        (\"n\", \"expected\"),\n        [\n            (1, 2),\n            pytest.param(1, 0, marks=pytest.mark.xfail),\n            pytest.param(1, 3, marks=pytest.mark.xfail(reason=\"some bug\")),\n            (2, 3),\n            (3, 4),\n            (4, 5),\n            pytest.param(\n                10, 11, marks=pytest.mark.skipif(sys.version_info >= (3, 0), reason=\"py2k\")\n            ),\n        ],\n    )\n    def test_increment(n, expected):\n        assert n + 1 == expected\n"
  },
  {
    "path": "doc/en/how-to/subtests.rst",
    "content": ".. _subtests:\n\nHow to use subtests\n===================\n\n.. versionadded:: 9.0\n\n.. note::\n\n    This feature is experimental. Its behavior, particularly how failures are reported, may evolve in future releases. However, the core functionality and usage are considered stable.\n\npytest allows for grouping assertions within a normal test, known as *subtests*.\n\nSubtests are an alternative to parametrization, particularly useful when the exact parametrization values are not known at collection time.\n\n\n.. code-block:: python\n\n    # content of test_subtest.py\n\n\n    def test(subtests):\n        for i in range(5):\n            with subtests.test(msg=\"custom message\", i=i):\n                assert i % 2 == 0\n\nEach assertion failure or error is caught by the context manager and reported individually:\n\n.. code-block:: pytest\n\n    $ pytest -q test_subtest.py\n    uuuuuF                                                               [100%]\n    ================================= FAILURES =================================\n    _______________________ test [custom message] (i=1) ________________________\n\n    subtests = <_pytest.subtests.Subtests object at 0xdeadbeef0001>\n\n        def test(subtests):\n            for i in range(5):\n                with subtests.test(msg=\"custom message\", i=i):\n    >               assert i % 2 == 0\n    E               assert (1 % 2) == 0\n\n    test_subtest.py:6: AssertionError\n    _______________________ test [custom message] (i=3) ________________________\n\n    subtests = <_pytest.subtests.Subtests object at 0xdeadbeef0001>\n\n        def test(subtests):\n            for i in range(5):\n                with subtests.test(msg=\"custom message\", i=i):\n    >               assert i % 2 == 0\n    E               assert (3 % 2) == 0\n\n    test_subtest.py:6: AssertionError\n    ___________________________________ test ___________________________________\n    contains 2 failed subtests\n    ========================= short test summary info ==========================\n    SUBFAILED[custom message] (i=1) test_subtest.py::test - assert (1 % 2) == 0\n    SUBFAILED[custom message] (i=3) test_subtest.py::test - assert (3 % 2) == 0\n    FAILED test_subtest.py::test - contains 2 failed subtests\n    3 failed, 3 subtests passed in 0.12s\n\nIn the output above:\n\n* Subtest failures are reported as ``SUBFAILED``.\n* Subtests are reported first and the \"top-level\" test is reported at the end on its own.\n\nNote that it is possible to use ``subtests`` multiple times in the same test, or even mix and match with normal assertions\noutside the ``subtests.test`` block:\n\n.. code-block:: python\n\n    def test(subtests):\n        for i in range(5):\n            with subtests.test(\"stage 1\", i=i):\n                assert i % 2 == 0\n\n        assert func() == 10\n\n        for i in range(10, 20):\n            with subtests.test(\"stage 2\", i=i):\n                assert i % 2 == 0\n\n.. note::\n\n    See :ref:`parametrize` for an alternative to subtests.\n\n\nVerbosity\n---------\n\nBy default, only **subtest failures** are shown. Higher verbosity levels (:option:`-v`) will also show progress output for **passed** subtests.\n\nIt is possible to control the verbosity of subtests by setting :confval:`verbosity_subtests`.\n\n\nTyping\n------\n\n:class:`pytest.Subtests` is exported so it can be used in type annotations:\n\n.. code-block:: python\n\n    def test(subtests: pytest.Subtests) -> None: ...\n\n.. _parametrize_vs_subtests:\n\nParametrization vs Subtests\n---------------------------\n\nWhile :ref:`traditional pytest parametrization <parametrize>` and ``subtests`` are similar, they have important differences and use cases.\n\n\nParametrization\n~~~~~~~~~~~~~~~\n\n* Happens at collection time.\n* Generates individual tests.\n* Parametrized tests can be referenced from the command line.\n* Plays well with plugins that handle test execution, such as :option:`--last-failed`.\n* Ideal for decision table testing.\n\nSubtests\n~~~~~~~~\n\n* Happen during test execution.\n* Are not known at collection time.\n* Can be generated dynamically.\n* Cannot be referenced individually from the command line.\n* Plugins that handle test execution cannot target individual subtests.\n* An assertion failure inside a subtest does not interrupt the test, letting users see all failures in the same report.\n\n\n.. note::\n\n    This feature was originally implemented as a separate plugin in `pytest-subtests <https://github.com/pytest-dev/pytest-subtests>`__, but since ``9.0`` has been merged into the core.\n\n    The core implementation should be compatible with the plugin implementation, except it does not contain custom command-line options to control subtest output.\n"
  },
  {
    "path": "doc/en/how-to/tmp_path.rst",
    "content": "\n.. _`tmp_path handling`:\n.. _tmp_path:\n\nHow to use temporary directories and files in tests\n===================================================\n\nThe ``tmp_path`` fixture\n------------------------\n\nYou can use the ``tmp_path`` fixture which will provide a temporary directory\nunique to each test function.\n\n``tmp_path`` is a :class:`pathlib.Path` object. Here is an example test usage:\n\n.. code-block:: python\n\n    # content of test_tmp_path.py\n    CONTENT = \"content\"\n\n\n    def test_create_file(tmp_path):\n        d = tmp_path / \"sub\"\n        d.mkdir()\n        p = d / \"hello.txt\"\n        p.write_text(CONTENT, encoding=\"utf-8\")\n        assert p.read_text(encoding=\"utf-8\") == CONTENT\n        assert len(list(tmp_path.iterdir())) == 1\n        assert 0\n\nRunning this would result in a passed test except for the last\n``assert 0`` line which we use to look at values:\n\n.. code-block:: pytest\n\n    $ pytest test_tmp_path.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_tmp_path.py F                                                   [100%]\n\n    ================================= FAILURES =================================\n    _____________________________ test_create_file _____________________________\n\n    tmp_path = PosixPath('PYTEST_TMPDIR/test_create_file0')\n\n        def test_create_file(tmp_path):\n            d = tmp_path / \"sub\"\n            d.mkdir()\n            p = d / \"hello.txt\"\n            p.write_text(CONTENT, encoding=\"utf-8\")\n            assert p.read_text(encoding=\"utf-8\") == CONTENT\n            assert len(list(tmp_path.iterdir())) == 1\n    >       assert 0\n    E       assert 0\n\n    test_tmp_path.py:11: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_tmp_path.py::test_create_file - assert 0\n    ============================ 1 failed in 0.12s =============================\n\nBy default, ``pytest`` retains the temporary directory for the last 3 ``pytest``\ninvocations. Concurrent invocations of the same test function are supported by\nconfiguring the base temporary directory to be unique for each concurrent\nrun. See `temporary directory location and retention`_ for details.\n\n.. _`tmp_path_factory example`:\n\nThe ``tmp_path_factory`` fixture\n--------------------------------\n\nThe ``tmp_path_factory`` is a session-scoped fixture which can be used\nto create arbitrary temporary directories from any other fixture or test.\n\nFor example, suppose your test suite needs a large image on disk, which is\ngenerated procedurally. Instead of computing the same image for each test\nthat uses it into its own ``tmp_path``, you can generate it once per-session\nto save time:\n\n.. code-block:: python\n\n    # contents of conftest.py\n    import pytest\n\n\n    @pytest.fixture(scope=\"session\")\n    def image_file(tmp_path_factory):\n        img = compute_expensive_image()\n        fn = tmp_path_factory.mktemp(\"data\") / \"img.png\"\n        img.save(fn)\n        return fn\n\n\n    # contents of test_image.py\n    def test_histogram(image_file):\n        img = load_image(image_file)\n        # compute and test histogram\n\nSee :ref:`tmp_path_factory API <tmp_path_factory factory api>` for details.\n\n.. _`tmpdir and tmpdir_factory`:\n.. _tmpdir:\n\nThe ``tmpdir`` and ``tmpdir_factory`` fixtures\n----------------------------------------------\n\nThe ``tmpdir`` and ``tmpdir_factory`` fixtures are similar to ``tmp_path``\nand ``tmp_path_factory``, but use/return legacy `py.path.local`_ objects\nrather than standard :class:`pathlib.Path` objects.\n\n.. note::\n    These days, it is preferred to use ``tmp_path`` and ``tmp_path_factory``.\n\n    In order to help modernize old code bases, one can run pytest with the legacypath\n    plugin disabled:\n\n    .. code-block:: bash\n\n        pytest -p no:legacypath\n\n    This will trigger errors on tests using the legacy paths.\n    It can also be permanently set as part of the :confval:`addopts` parameter in the\n    config file.\n\nSee :fixture:`tmpdir <tmpdir>` :fixture:`tmpdir_factory <tmpdir_factory>`\nAPI for details.\n\n\n.. _`temporary directory location and retention`:\n\nTemporary directory location and retention\n------------------------------------------\n\nThe temporary directories,\nas returned by the :fixture:`tmp_path` and (now deprecated) :fixture:`tmpdir` fixtures,\nare automatically created under a base temporary directory,\nin a structure that depends on the :option:`--basetemp` option:\n\n- By default (when the :option:`--basetemp` option is not set),\n  the temporary directories will follow this template:\n\n  .. code-block:: text\n\n      {temproot}/pytest-of-{user}/pytest-{num}/{testname}/\n\n  where:\n\n  - ``{temproot}`` is the system temporary directory\n    as determined by :py:func:`tempfile.gettempdir`.\n    It can be overridden by the :envvar:`PYTEST_DEBUG_TEMPROOT` environment variable.\n  - ``{user}`` is the user name running the tests,\n  - ``{num}`` is a number that is incremented with each test suite run\n  - ``{testname}`` is a sanitized version of :py:attr:`the name of the current test <_pytest.nodes.Node.name>`.\n\n  The auto-incrementing ``{num}`` placeholder provides a basic retention feature\n  and avoids that existing results of previous test runs are blindly removed.\n  By default, the last 3 temporary directories are kept,\n  but this behavior can be configured with\n  :confval:`tmp_path_retention_count` and :confval:`tmp_path_retention_policy`.\n\n- When the :option:`--basetemp` option is used (e.g. ``pytest --basetemp=mydir``),\n  it will be used directly as base temporary directory:\n\n  .. code-block:: text\n\n      {basetemp}/{testname}/\n\n  Note that there is no retention feature in this case:\n  only the results of the most recent run will be kept.\n\n  .. warning::\n\n      The directory given to :option:`--basetemp` will be cleared blindly before each test run,\n      so make sure to use a directory for that purpose only.\n\nWhen distributing tests on the local machine using ``pytest-xdist``, care is taken to\nautomatically configure a `basetemp` directory for the sub processes such that all temporary\ndata lands below a single per-test run temporary directory.\n\n.. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html\n"
  },
  {
    "path": "doc/en/how-to/unittest.rst",
    "content": "\n.. _`unittest.TestCase`:\n.. _`unittest`:\n\nHow to use ``unittest``-based tests with pytest\n===============================================\n\n``pytest`` supports running Python ``unittest``-based tests out of the box.\nIt's meant for leveraging existing ``unittest``-based test suites\nto use pytest as a test runner and also allow to incrementally adapt\nthe test suite to take full advantage of pytest's features.\n\nTo run an existing ``unittest``-style test suite using ``pytest``, type:\n\n.. code-block:: bash\n\n    pytest tests\n\n\npytest will automatically collect ``unittest.TestCase`` subclasses and\ntheir ``test`` methods in ``test_*.py`` or ``*_test.py`` files.\n\nAlmost all ``unittest`` features are supported:\n\n* :func:`unittest.skip`/:func:`unittest.skipIf` style decorators\n* :meth:`unittest.TestCase.setUp`/:meth:`unittest.TestCase.tearDown`\n* :meth:`unittest.TestCase.setUpClass`/:meth:`unittest.TestCase.tearDownClass`\n* :func:`unittest.setUpModule`/:func:`unittest.tearDownModule`\n* :meth:`unittest.TestCase.subTest` (since version ``9.0``)\n\n.. _`load_tests protocol`: https://docs.python.org/3/library/unittest.html#load-tests-protocol\n\nUp to this point pytest does not have support for the following features:\n\n* `load_tests protocol`_;\n\nBenefits out of the box\n-----------------------\n\nBy running your test suite with pytest you can make use of several features,\nin most cases without having to modify existing code:\n\n* Obtain :ref:`more informative tracebacks <tbreportdemo>`;\n* :ref:`stdout and stderr <captures>` capturing;\n* :ref:`Test selection options <select-tests>` using :option:`-k` and :option:`-m` flags;\n* :ref:`maxfail`;\n* :ref:`--pdb <pdb-option>` command-line option for debugging on test failures\n  (see :ref:`note <pdb-unittest-note>` below);\n* Distribute tests to multiple CPUs using the :pypi:`pytest-xdist` plugin;\n* Use :ref:`plain assert-statements <assert>` instead of ``self.assert*`` functions\n  (:pypi:`unittest2pytest` is immensely helpful in this);\n\n\npytest features in ``unittest.TestCase`` subclasses\n---------------------------------------------------\n\nThe following pytest features work in ``unittest.TestCase`` subclasses:\n\n* :ref:`Marks <mark>`: :ref:`skip <skip>`, :ref:`skipif <skipif>`, :ref:`xfail <xfail>`;\n* :ref:`Auto-use fixtures <mixing-fixtures>`;\n\nThe following pytest features **do not** work, and probably\nnever will due to different design philosophies:\n\n* :ref:`Fixtures <fixture>` (except for ``autouse`` fixtures, see :ref:`below <mixing-fixtures>`);\n* :ref:`Parametrization <parametrize>`;\n* :ref:`Custom hooks <writing-plugins>`;\n\n\nThird party plugins may or may not work well, depending on the plugin and the test suite.\n\n.. _mixing-fixtures:\n\nMixing pytest fixtures into ``unittest.TestCase`` subclasses using marks\n------------------------------------------------------------------------\n\nRunning your unittest with ``pytest`` allows you to use its\n:ref:`fixture mechanism <fixture>` with ``unittest.TestCase`` style\ntests.  Assuming you have at least skimmed the pytest fixture features,\nlet's jump-start into an example that integrates a pytest ``db_class``\nfixture, setting up a class-cached database object, and then reference\nit from a unittest-style test:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n    # we define a fixture function below and it will be \"used\" by\n    # referencing its name from tests\n\n    import pytest\n\n\n    @pytest.fixture(scope=\"class\")\n    def db_class(request):\n        class DummyDB:\n            pass\n\n        # set a class attribute on the invoking test context\n        request.cls.db = DummyDB()\n\nThis defines a fixture function ``db_class`` which - if used - is\ncalled once for each test class and which sets the class-level\n``db`` attribute to a ``DummyDB`` instance.  The fixture function\nachieves this by receiving a special ``request`` object which gives\naccess to :ref:`the requesting test context <request-context>` such\nas the ``cls`` attribute, denoting the class from which the fixture\nis used.  This architecture de-couples fixture writing from actual test\ncode and allows reuse of the fixture by a minimal reference, the fixture\nname.  So let's write an actual ``unittest.TestCase`` class using our\nfixture definition:\n\n.. code-block:: python\n\n    # content of test_unittest_db.py\n\n    import unittest\n\n    import pytest\n\n\n    @pytest.mark.usefixtures(\"db_class\")\n    class MyTest(unittest.TestCase):\n        def test_method1(self):\n            assert hasattr(self, \"db\")\n            assert 0, self.db  # fail for demo purposes\n\n        def test_method2(self):\n            assert 0, self.db  # fail for demo purposes\n\nThe ``@pytest.mark.usefixtures(\"db_class\")`` class-decorator makes sure that\nthe pytest fixture function ``db_class`` is called once per class.\nDue to the deliberately failing assert statements, we can take a look at\nthe ``self.db`` values in the traceback:\n\n.. code-block:: pytest\n\n    $ pytest test_unittest_db.py\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 2 items\n\n    test_unittest_db.py FF                                               [100%]\n\n    ================================= FAILURES =================================\n    ___________________________ MyTest.test_method1 ____________________________\n\n    self = <test_unittest_db.MyTest testMethod=test_method1>\n\n        def test_method1(self):\n            assert hasattr(self, \"db\")\n    >       assert 0, self.db  # fail for demo purposes\n            ^^^^^^^^^^^^^^^^^\n    E       AssertionError: <conftest.db_class.<locals>.DummyDB object at 0xdeadbeef0001>\n    E       assert 0\n\n    test_unittest_db.py:11: AssertionError\n    ___________________________ MyTest.test_method2 ____________________________\n\n    self = <test_unittest_db.MyTest testMethod=test_method2>\n\n        def test_method2(self):\n    >       assert 0, self.db  # fail for demo purposes\n            ^^^^^^^^^^^^^^^^^\n    E       AssertionError: <conftest.db_class.<locals>.DummyDB object at 0xdeadbeef0001>\n    E       assert 0\n\n    test_unittest_db.py:14: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_unittest_db.py::MyTest::test_method1 - AssertionError: <conft...\n    FAILED test_unittest_db.py::MyTest::test_method2 - AssertionError: <conft...\n    ============================ 2 failed in 0.12s =============================\n\nThis default pytest traceback shows that the two test methods\nshare the same ``self.db`` instance which was our intention\nwhen writing the class-scoped fixture function above.\n\n\nUsing autouse fixtures and accessing other fixtures\n---------------------------------------------------\n\nAlthough it's usually better to explicitly declare use of fixtures you need\nfor a given test, you may sometimes want to have fixtures that are\nautomatically used in a given context.  After all, the traditional\nstyle of unittest-setup mandates the use of this implicit fixture writing\nand chances are, you are used to it or like it.\n\nYou can flag fixture functions with ``@pytest.fixture(autouse=True)``\nand define the fixture function in the context where you want it used.\nLet's look at an ``initdir`` fixture which makes all test methods of a\n``TestCase`` class execute in a temporary directory with a\npre-initialized ``samplefile.ini``.  Our ``initdir`` fixture itself uses\nthe pytest builtin :fixture:`tmp_path` fixture to delegate the\ncreation of a per-test temporary directory:\n\n.. code-block:: python\n\n    # content of test_unittest_cleandir.py\n    import unittest\n\n    import pytest\n\n\n    class MyTest(unittest.TestCase):\n        @pytest.fixture(autouse=True)\n        def initdir(self, tmp_path, monkeypatch):\n            monkeypatch.chdir(tmp_path)  # change to pytest-provided temporary directory\n            tmp_path.joinpath(\"samplefile.ini\").write_text(\"# testdata\", encoding=\"utf-8\")\n\n        def test_method(self):\n            with open(\"samplefile.ini\", encoding=\"utf-8\") as f:\n                s = f.read()\n            assert \"testdata\" in s\n\nDue to the ``autouse`` flag the ``initdir`` fixture function will be\nused for all methods of the class where it is defined.  This is a\nshortcut for using a ``@pytest.mark.usefixtures(\"initdir\")`` marker\non the class like in the previous example.\n\nRunning this test module ...:\n\n.. code-block:: pytest\n\n    $ pytest -q test_unittest_cleandir.py\n    .                                                                    [100%]\n    1 passed in 0.12s\n\n... gives us one passed test because the ``initdir`` fixture function\nwas executed ahead of the ``test_method``.\n\n.. note::\n\n   ``unittest.TestCase`` methods cannot directly receive fixture\n   arguments as implementing that is likely to inflict\n   on the ability to run general unittest.TestCase test suites.\n\n   The above ``usefixtures`` and ``autouse`` examples should help to mix in\n   pytest fixtures into unittest suites.\n\n   You can also gradually move away from subclassing from ``unittest.TestCase`` to *plain asserts*\n   and then start to benefit from the full pytest feature set step by step.\n\n.. _pdb-unittest-note:\n\n.. note::\n\n    Due to architectural differences between the two frameworks, setup and\n    teardown for ``unittest``-based tests is performed during the ``call`` phase\n    of testing instead of in ``pytest``'s standard ``setup`` and ``teardown``\n    stages. This can be important to understand in some situations, particularly\n    when reasoning about errors. For example, if a ``unittest``-based suite\n    exhibits errors during setup, ``pytest`` will report no errors during its\n    ``setup`` phase and will instead raise the error during ``call``.\n"
  },
  {
    "path": "doc/en/how-to/usage.rst",
    "content": "\n.. _usage:\n\nHow to invoke pytest\n==========================================\n\n..  seealso:: :ref:`Complete pytest command-line flags reference <command-line-flags>`\n\nIn general, pytest is invoked with the command ``pytest`` (see below for :ref:`other ways to invoke pytest\n<invoke-other>`). This will execute all tests in all files whose names follow the form ``test_*.py`` or ``*_test.py``\nin the current directory and its subdirectories. More generally, pytest follows :ref:`standard test discovery rules\n<test discovery>`.\n\n\n.. _select-tests:\n\nSpecifying which tests to run\n------------------------------\n\nPytest supports several ways to run and select tests from the command-line or from a file\n(see below for :ref:`reading arguments from file <args-from-file>`).\n\n**Run tests in a module**\n\n.. code-block:: bash\n\n    pytest test_mod.py\n\n**Run tests in a directory**\n\n.. code-block:: bash\n\n    pytest testing/\n\n**Run tests by keyword expressions**\n\n.. code-block:: bash\n\n    pytest -k 'MyClass and not method'\n\nThis will run tests which contain names that match the given *string expression* (case-insensitive),\nwhich can include Python operators that use filenames, class names and function names as variables.\nThe example above will run ``TestMyClass.test_something``  but not ``TestMyClass.test_method_simple``.\nUse ``\"\"`` instead of ``''`` in expression when running this on Windows\n\n.. _nodeids:\n\n**Run tests by collection arguments**\n\nPass the module filename relative to the working directory, followed by specifiers like the class name and function name\nseparated by ``::`` characters, and parameters from parameterization enclosed in ``[]``.\n\nTo run a specific test within a module:\n\n.. code-block:: bash\n\n    pytest tests/test_mod.py::test_func\n\nTo run all tests in a class:\n\n.. code-block:: bash\n\n    pytest tests/test_mod.py::TestClass\n\nSpecifying a specific test method:\n\n.. code-block:: bash\n\n    pytest tests/test_mod.py::TestClass::test_method\n\nSpecifying a specific parametrization of a test:\n\n.. code-block:: bash\n\n    pytest tests/test_mod.py::test_func[x1,y2]\n\n**Run tests by marker expressions**\n\nTo run all tests which are decorated with the ``@pytest.mark.slow`` decorator:\n\n.. code-block:: bash\n\n    pytest -m slow\n\n\nTo run all tests which are decorated with the annotated ``@pytest.mark.slow(phase=1)`` decorator,\nwith the ``phase`` keyword argument set to ``1``:\n\n.. code-block:: bash\n\n    pytest -m \"slow(phase=1)\"\n\nFor more information see :ref:`marks <mark>`.\n\n**Run tests from packages**\n\n.. code-block:: bash\n\n    pytest --pyargs pkg.testing\n\nThis will import ``pkg.testing`` and use its filesystem location to find and run tests from.\n\n.. _args-from-file:\n\n**Read arguments from file**\n\n.. versionadded:: 8.2\n\nAll of the above can be read from a file using the ``@`` prefix:\n\n.. code-block:: bash\n\n    pytest @tests_to_run.txt\n\nwhere ``tests_to_run.txt`` contains an entry per line, e.g.:\n\n.. code-block:: text\n\n    tests/test_file.py\n    tests/test_mod.py::test_func[x1,y2]\n    tests/test_mod.py::TestClass\n    -m slow\n\nThis file can also be generated using ``pytest --collect-only -q`` and modified as needed.\n\nGetting help on version, option names, environment variables\n--------------------------------------------------------------\n\n.. code-block:: bash\n\n    pytest --version   # shows where pytest was imported from\n    pytest --fixtures  # show available builtin function arguments\n    pytest -h | --help # show help on command line and config file options\n\n\n.. _durations:\n\nProfiling test execution duration\n-------------------------------------\n\n.. versionchanged:: 6.0\n\nTo get a list of the slowest 10 test durations over 1.0s long:\n\n.. code-block:: bash\n\n    pytest --durations=10 --durations-min=1.0\n\nBy default, pytest will not show test durations that are too small (<0.005s) unless ``-vv`` is passed on the command-line.\n\n\nManaging loading of plugins\n-------------------------------\n\nEarly loading plugins\n~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can early-load plugins (internal and external) explicitly in the command-line with the :option:`-p` option::\n\n    pytest -p mypluginmodule\n\nThe option receives a ``name`` parameter, which can be:\n\n* A full module dotted name, for example ``myproject.plugins``. This dotted name must be importable.\n* The entry-point name of a plugin. This is the name passed to ``importlib`` when the plugin is\n  registered. For example to early-load the :pypi:`pytest-cov` plugin you can use::\n\n    pytest -p pytest_cov\n\n\nDisabling plugins\n~~~~~~~~~~~~~~~~~~\n\nTo disable loading specific plugins at invocation time, use the :option:`-p` option\ntogether with the prefix ``no:``.\n\nExample: to disable loading the plugin ``doctest``, which is responsible for\nexecuting doctest tests from text files, invoke pytest like this:\n\n.. code-block:: bash\n\n    pytest -p no:doctest\n\n\n.. _invoke-other:\n\nOther ways of calling pytest\n-----------------------------------------------------\n\n.. _invoke-python:\n\nCalling pytest through ``python -m pytest``\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can invoke testing through the Python interpreter from the command line:\n\n.. code-block:: text\n\n    python -m pytest [...]\n\nThis is almost equivalent to invoking the command line script ``pytest [...]``\ndirectly, except that calling via ``python`` will also add the current directory to ``sys.path``.\n\n\n.. _`pytest.main-usage`:\n\nCalling pytest from Python code\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can invoke ``pytest`` from Python code directly:\n\n.. code-block:: python\n\n    retcode = pytest.main()\n\nthis acts as if you would call \"pytest\" from the command line.\nIt will not raise :class:`SystemExit` but return the :ref:`exit code <exit-codes>` instead.\nIf you don't pass it any arguments, ``main`` reads the arguments from the command line arguments of the process (:data:`sys.argv`), which may be undesirable.\nYou can pass in options and arguments explicitly:\n\n.. code-block:: python\n\n    retcode = pytest.main([\"-x\", \"mytestdir\"])\n\nYou can specify additional plugins to ``pytest.main``:\n\n.. code-block:: python\n\n    # content of myinvoke.py\n    import sys\n\n    import pytest\n\n\n    class MyPlugin:\n        def pytest_sessionfinish(self):\n            print(\"*** test run reporting finishing\")\n\n\n    if __name__ == \"__main__\":\n        sys.exit(pytest.main([\"-qq\"], plugins=[MyPlugin()]))\n\nRunning it will show that ``MyPlugin`` was added and its\nhook was invoked:\n\n.. code-block:: pytest\n\n    $ python myinvoke.py\n    *** test run reporting finishing\n\n\n.. note::\n\n    Calling ``pytest.main()`` will result in importing your tests and any modules\n    that they import. Due to the caching mechanism of python's import system,\n    making subsequent calls to ``pytest.main()`` from the same process will not\n    reflect changes to those files between the calls. For this reason, making\n    multiple calls to ``pytest.main()`` from the same process (in order to re-run\n    tests, for example) is not recommended.\n"
  },
  {
    "path": "doc/en/how-to/writing_hook_functions.rst",
    "content": ".. _`writinghooks`:\n\nWriting hook functions\n======================\n\n\n.. _validation:\n\nhook function validation and execution\n--------------------------------------\n\npytest calls hook functions from registered plugins for any\ngiven hook specification.  Let's look at a typical hook function\nfor the ``pytest_collection_modifyitems(session, config,\nitems)`` hook which pytest calls after collection of all test items is\ncompleted.\n\nWhen we implement a ``pytest_collection_modifyitems`` function in our plugin\npytest will during registration verify that you use argument\nnames which match the specification and bail out if not.\n\nLet's look at a possible implementation:\n\n.. code-block:: python\n\n    def pytest_collection_modifyitems(config, items):\n        # called after collection is completed\n        # you can modify the ``items`` list\n        ...\n\nHere, ``pytest`` will pass in ``config`` (the pytest config object)\nand ``items`` (the list of collected test items) but will not pass\nin the ``session`` argument because we didn't list it in the function\nsignature.  This dynamic \"pruning\" of arguments allows ``pytest`` to\nbe \"future-compatible\": we can introduce new hook named parameters without\nbreaking the signatures of existing hook implementations.  It is one of\nthe reasons for the general long-lived compatibility of pytest plugins.\n\nNote that hook functions other than ``pytest_runtest_*`` are not\nallowed to raise exceptions.  Doing so will break the pytest run.\n\n\n\n.. _firstresult:\n\nfirstresult: stop at first non-None result\n-------------------------------------------\n\nMost calls to ``pytest`` hooks result in a **list of results** which contains\nall non-None results of the called hook functions.\n\nSome hook specifications use the ``firstresult=True`` option so that the hook\ncall only executes until the first of N registered functions returns a\nnon-None result which is then taken as result of the overall hook call.\nThe remaining hook functions will not be called in this case.\n\n.. _`hookwrapper`:\n\nhook wrappers: executing around other hooks\n-------------------------------------------------\n\npytest plugins can implement hook wrappers which wrap the execution\nof other hook implementations.  A hook wrapper is a generator function\nwhich yields exactly once. When pytest invokes hooks it first executes\nhook wrappers and passes the same arguments as to the regular hooks.\n\nAt the yield point of the hook wrapper pytest will execute the next hook\nimplementations and return their result to the yield point, or will\npropagate an exception if they raised.\n\nHere is an example definition of a hook wrapper:\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.hookimpl(wrapper=True)\n    def pytest_pyfunc_call(pyfuncitem):\n        do_something_before_next_hook_executes()\n\n        # If the outcome is an exception, will raise the exception.\n        res = yield\n\n        new_res = post_process_result(res)\n\n        # Override the return value to the plugin system.\n        return new_res\n\nThe hook wrapper needs to return a result for the hook, or raise an exception.\n\nIn many cases, the wrapper only needs to perform tracing or other side effects\naround the actual hook implementations, in which case it can return the result\nvalue of the ``yield``. The simplest (though useless) hook wrapper is\n``return (yield)``.\n\nIn other cases, the wrapper wants to adjust or adapt the result, in which case\nit can return a new value. If the result of the underlying hook is a mutable\nobject, the wrapper may modify that result, but it's probably better to avoid it.\n\nIf the hook implementation failed with an exception, the wrapper can handle that\nexception using a ``try-catch-finally`` around the ``yield``, by propagating it,\nsuppressing it, or raising a different exception entirely.\n\nFor more information, consult the\n:ref:`pluggy documentation about hook wrappers <pluggy:hookwrappers>`.\n\n.. _plugin-hookorder:\n\nHook function ordering / call example\n-------------------------------------\n\nFor any given hook specification there may be more than one\nimplementation and we thus generally view ``hook`` execution as a\n``1:N`` function call where ``N`` is the number of registered functions.\nThere are ways to influence if a hook implementation comes before or\nafter others, i.e.  the position in the ``N``-sized list of functions:\n\n.. code-block:: python\n\n    # Plugin 1\n    @pytest.hookimpl(tryfirst=True)\n    def pytest_collection_modifyitems(items):\n        # will execute as early as possible\n        ...\n\n\n    # Plugin 2\n    @pytest.hookimpl(trylast=True)\n    def pytest_collection_modifyitems(items):\n        # will execute as late as possible\n        ...\n\n\n    # Plugin 3\n    @pytest.hookimpl(wrapper=True)\n    def pytest_collection_modifyitems(items):\n        # will execute even before the tryfirst one above!\n        try:\n            return (yield)\n        finally:\n            # will execute after all non-wrappers executed\n            ...\n\nHere is the order of execution:\n\n1. Plugin3's pytest_collection_modifyitems called until the yield point\n   because it is a hook wrapper.\n\n2. Plugin1's pytest_collection_modifyitems is called because it is marked\n   with ``tryfirst=True``.\n\n3. Plugin2's pytest_collection_modifyitems is called because it is marked\n   with ``trylast=True`` (but even without this mark it would come after\n   Plugin1).\n\n4. Plugin3's pytest_collection_modifyitems then executing the code after the yield\n   point.  The yield receives the result from calling the non-wrappers, or raises\n   an exception if the non-wrappers raised.\n\nIt's possible to use ``tryfirst`` and ``trylast`` also on hook wrappers\nin which case it will influence the ordering of hook wrappers among each other.\n\n.. _`declaringhooks`:\n\nDeclaring new hooks\n------------------------\n\n.. note::\n\n    This is a quick overview on how to add new hooks and how they work in general, but a more complete\n    overview can be found in `the pluggy documentation <https://pluggy.readthedocs.io/en/latest/>`__.\n\nPlugins and ``conftest.py`` files may declare new hooks that can then be\nimplemented by other plugins in order to alter behaviour or interact with\nthe new plugin:\n\n.. autofunction:: _pytest.hookspec.pytest_addhooks\n    :noindex:\n\nHooks are usually declared as do-nothing functions that contain only\ndocumentation describing when the hook will be called and what return values\nare expected. The names of the functions must start with `pytest_` otherwise pytest won't recognize them.\n\nHere's an example. Let's assume this code is in the ``sample_hook.py`` module.\n\n.. code-block:: python\n\n    def pytest_my_hook(config):\n        \"\"\"\n        Receives the pytest config and does things with it\n        \"\"\"\n\nTo register the hooks with pytest they need to be structured in their own module or class. This\nclass or module can then be passed to the ``pluginmanager`` using the ``pytest_addhooks`` function\n(which itself is a hook exposed by pytest).\n\n.. code-block:: python\n\n    def pytest_addhooks(pluginmanager):\n        \"\"\"This example assumes the hooks are grouped in the 'sample_hook' module.\"\"\"\n        from my_app.tests import sample_hook\n\n        pluginmanager.add_hookspecs(sample_hook)\n\nFor a real world example, see `newhooks.py`_ from `xdist <https://github.com/pytest-dev/pytest-xdist>`_.\n\n.. _`newhooks.py`: https://github.com/pytest-dev/pytest-xdist/blob/974bd566c599dc6a9ea291838c6f226197208b46/xdist/newhooks.py\n\nHooks may be called both from fixtures or from other hooks. In both cases, hooks are called\nthrough the ``hook`` object, available in the ``config`` object. Most hooks receive a\n``config`` object directly, while fixtures may use the ``pytestconfig`` fixture which provides the same object.\n\n.. code-block:: python\n\n    @pytest.fixture()\n    def my_fixture(pytestconfig):\n        # call the hook called \"pytest_my_hook\"\n        # 'result' will be a list of return values from all registered functions.\n        result = pytestconfig.hook.pytest_my_hook(config=pytestconfig)\n\n.. note::\n    Hooks receive parameters using only keyword arguments.\n\nNow your hook is ready to be used. To register a function at the hook, other plugins or users must\nnow simply define the function ``pytest_my_hook`` with the correct signature in their ``conftest.py``.\n\nExample:\n\n.. code-block:: python\n\n    def pytest_my_hook(config):\n        \"\"\"\n        Print all active hooks to the screen.\n        \"\"\"\n        print(config.hook)\n\n.. note::\n\n    Unlike other hooks, the :hook:`pytest_generate_tests` hook is also discovered when\n    defined inside a test module or test class. Other hooks must live in\n    :ref:`conftest.py plugins <localplugin>` or external plugins.\n    See :ref:`parametrize-basics` and the :ref:`hook-reference`.\n\n.. _`addoptionhooks`:\n\n\nUsing hooks in pytest_addoption\n-------------------------------\n\nOccasionally, it is necessary to change the way in which command line options\nare defined by one plugin based on hooks in another plugin. For example,\na plugin may expose a command line option for which another plugin needs\nto define the default value. The pluginmanager can be used to install and\nuse hooks to accomplish this. The plugin would define and add the hooks\nand use pytest_addoption as follows:\n\n.. code-block:: python\n\n   # contents of hooks.py\n\n\n   # Use firstresult=True because we only want one plugin to define this\n   # default value\n   @hookspec(firstresult=True)\n   def pytest_config_file_default_value():\n       \"\"\"Return the default value for the config file command line option.\"\"\"\n\n\n   # contents of myplugin.py\n\n\n   def pytest_addhooks(pluginmanager):\n       \"\"\"This example assumes the hooks are grouped in the 'hooks' module.\"\"\"\n       from . import hooks\n\n       pluginmanager.add_hookspecs(hooks)\n\n\n   def pytest_addoption(parser, pluginmanager):\n       default_value = pluginmanager.hook.pytest_config_file_default_value()\n       parser.addoption(\n           \"--config-file\",\n           help=\"Config file to use, defaults to %(default)s\",\n           default=default_value,\n       )\n\nThe conftest.py that is using myplugin would simply define the hook as follows:\n\n.. code-block:: python\n\n    def pytest_config_file_default_value():\n        return \"config.yaml\"\n\n\nOptionally using hooks from 3rd party plugins\n---------------------------------------------\n\nUsing new hooks from plugins as explained above might be a little tricky\nbecause of the standard :ref:`validation mechanism <validation>`:\nif you depend on a plugin that is not installed, validation will fail and\nthe error message will not make much sense to your users.\n\nOne approach is to defer the hook implementation to a new plugin instead of\ndeclaring the hook functions directly in your plugin module, for example:\n\n.. code-block:: python\n\n    # contents of myplugin.py\n\n\n    class DeferPlugin:\n        \"\"\"Simple plugin to defer pytest-xdist hook functions.\"\"\"\n\n        def pytest_testnodedown(self, node, error):\n            \"\"\"standard xdist hook function.\"\"\"\n\n\n    def pytest_configure(config):\n        if config.pluginmanager.hasplugin(\"xdist\"):\n            config.pluginmanager.register(DeferPlugin())\n\nThis has the added benefit of allowing you to conditionally install hooks\ndepending on which plugins are installed.\n\n.. _plugin-stash:\n\nStoring data on items across hook functions\n-------------------------------------------\n\nPlugins often need to store data on :class:`~pytest.Item`\\s in one hook\nimplementation, and access it in another. One common solution is to just\nassign some private attribute directly on the item, but type-checkers like\nmypy frown upon this, and it may also cause conflicts with other plugins.\nSo pytest offers a better way to do this, :attr:`item.stash <_pytest.nodes.Node.stash>`.\n\nTo use the \"stash\" in your plugins, first create \"stash keys\" somewhere at the\ntop level of your plugin:\n\n.. code-block:: python\n\n    been_there_key = pytest.StashKey[bool]()\n    done_that_key = pytest.StashKey[str]()\n\nthen use the keys to stash your data at some point:\n\n.. code-block:: python\n\n    def pytest_runtest_setup(item: pytest.Item) -> None:\n        item.stash[been_there_key] = True\n        item.stash[done_that_key] = \"no\"\n\nand retrieve them at another point:\n\n.. code-block:: python\n\n    def pytest_runtest_teardown(item: pytest.Item) -> None:\n        if not item.stash[been_there_key]:\n            print(\"Oh?\")\n        item.stash[done_that_key] = \"yes!\"\n\nStashes are available on all node types (like :class:`~pytest.Class`,\n:class:`~pytest.Session`) and also on :class:`~pytest.Config`, if needed.\n"
  },
  {
    "path": "doc/en/how-to/writing_plugins.rst",
    "content": ".. _plugins:\n.. _`writing-plugins`:\n\nWriting plugins\n===============\n\nIt is easy to implement `local conftest plugins`_ for your own project\nor `pip-installable plugins`_ that can be used throughout many projects,\nincluding third party projects.  Please refer to :ref:`using plugins` if you\nonly want to use but not write plugins.\n\nA plugin contains one or multiple hook functions. :ref:`Writing hooks <writinghooks>`\nexplains the basics and details of how you can write a hook function yourself.\n``pytest`` implements all aspects of configuration, collection, running and\nreporting by calling :ref:`well specified hooks <hook-reference>` of the following plugins:\n\n* builtin plugins: loaded from pytest's internal ``_pytest`` directory.\n\n* :ref:`external plugins <extplugins>`: installed third-party modules discovered\n  through :ref:`entry points <pip-installable plugins>` in their packaging metadata\n\n* `conftest.py plugins`_: modules auto-discovered in test directories\n\nIn principle, each hook call is a ``1:N`` Python function call where ``N`` is the\nnumber of registered implementation functions for a given specification.\nAll specifications and implementations follow the ``pytest_`` prefix\nnaming convention, making them easy to distinguish and find.\n\n.. _`pluginorder`:\n\nPlugin discovery order at tool startup\n--------------------------------------\n\n``pytest`` loads plugin modules at tool startup in the following way:\n\n1. by scanning the command line for the ``-p no:name`` option\n   and *blocking* that plugin from being loaded (even builtin plugins can\n   be blocked this way). This happens before normal command-line parsing.\n\n2. by loading all builtin plugins.\n\n3. by scanning the command line for the ``-p name`` option\n   and loading the specified plugin. This happens before normal command-line parsing.\n\n4. by loading all plugins registered through installed third-party package\n   :ref:`entry points <pip-installable plugins>`, unless the\n   :envvar:`PYTEST_DISABLE_PLUGIN_AUTOLOAD` environment variable is set.\n\n5. by loading all plugins specified through the :envvar:`PYTEST_PLUGINS` environment variable.\n\n6. by loading all \"initial\" :file:`conftest.py` files:\n\n   - determine the test paths: specified on the command line, otherwise in\n     :confval:`testpaths` if defined and running from the rootdir, otherwise the\n     current dir\n   - for each test path, load ``conftest.py`` and ``test*/conftest.py`` relative\n     to the directory part of the test path, if exist. Before a ``conftest.py``\n     file is loaded, load ``conftest.py`` files in all of its parent directories.\n     After a ``conftest.py`` file is loaded, recursively load all plugins specified\n     in its :globalvar:`pytest_plugins` variable if present.\n\n\n.. _`conftest.py plugins`:\n.. _`localplugin`:\n.. _`local conftest plugins`:\n\nconftest.py: local per-directory plugins\n----------------------------------------\n\nLocal ``conftest.py`` plugins contain directory-specific hook\nimplementations.  Hook Session and test running activities will\ninvoke all hooks defined in ``conftest.py`` files closer to the\nroot of the filesystem.  Example of implementing the\n``pytest_runtest_setup`` hook so that is called for tests in the ``a``\nsub directory but not for other directories::\n\n    a/conftest.py:\n        def pytest_runtest_setup(item):\n            # called for running each test in 'a' directory\n            print(\"setting up\", item)\n\n    a/test_sub.py:\n        def test_sub():\n            pass\n\n    test_flat.py:\n        def test_flat():\n            pass\n\nHere is how you might run it::\n\n     pytest test_flat.py --capture=no  # will not show \"setting up\"\n     pytest a/test_sub.py --capture=no  # will show \"setting up\"\n\n.. note::\n    If you have ``conftest.py`` files which do not reside in a\n    python package directory (i.e. one containing an ``__init__.py``) then\n    \"import conftest\" can be ambiguous because there might be other\n    ``conftest.py`` files as well on your ``PYTHONPATH`` or ``sys.path``.\n    It is thus good practice for projects to either put ``conftest.py``\n    under a package scope or to never import anything from a\n    ``conftest.py`` file.\n\n    See also: :ref:`pythonpath`.\n\n.. note::\n    Some hooks cannot be implemented in conftest.py files which are not\n    :ref:`initial <pluginorder>` due to how pytest discovers plugins during\n    startup. See the documentation of each hook for details.\n\nWriting your own plugin\n-----------------------\n\nIf you want to write a plugin, there are many real-life examples\nyou can copy from:\n\n* a custom collection example plugin: :ref:`yaml plugin`\n* builtin plugins which provide pytest's own functionality\n* many :ref:`external plugins <plugin-list>` providing additional features\n\nAll of these plugins implement :ref:`hooks <hook-reference>` and/or :ref:`fixtures <fixture>`\nto extend and add functionality.\n\n.. note::\n    Make sure to check out the excellent\n    `cookiecutter-pytest-plugin <https://github.com/pytest-dev/cookiecutter-pytest-plugin>`_\n    project, which is a `cookiecutter template <https://github.com/audreyr/cookiecutter>`_\n    for authoring plugins.\n\n    The template provides an excellent starting point with a working plugin,\n    tests running with tox, a comprehensive README file as well as a\n    pre-configured entry-point.\n\nAlso consider :ref:`contributing your plugin to pytest-dev<submitplugin>`\nonce it has some happy users other than yourself.\n\n\n.. _`setuptools entry points`:\n.. _`pip-installable plugins`:\n\nMaking your plugin installable by others\n----------------------------------------\n\nIf you want to make your plugin externally available, you\nmay define a so-called entry point for your distribution so\nthat ``pytest`` finds your plugin module. Entry points are\na feature that is provided by :std:doc:`packaging tools\n<packaging:specifications/entry-points>`.\n\npytest looks up the ``pytest11`` entrypoint to discover its\nplugins, thus you can make your plugin available by defining\nit in your ``pyproject.toml`` file.\n\n.. sourcecode:: toml\n\n    # sample ./pyproject.toml file\n    [build-system]\n    requires = [\"hatchling\"]\n    build-backend = \"hatchling.build\"\n\n    [project]\n    name = \"myproject\"\n    classifiers = [\n        \"Framework :: Pytest\",\n    ]\n\n    [project.entry-points.pytest11]\n    myproject = \"myproject.pluginmodule\"\n\nIf a package is installed this way, ``pytest`` will load\n``myproject.pluginmodule`` as a plugin which can define\n:ref:`hooks <hook-reference>`. Confirm registration with ``pytest --trace-config``\n\n.. note::\n\n    Make sure to include ``Framework :: Pytest`` in your list of\n    `PyPI classifiers <https://pypi.org/classifiers/>`_\n    to make it easy for users to find your plugin.\n\n\n.. _assertion-rewriting:\n\nAssertion Rewriting\n-------------------\n\nOne of the main features of ``pytest`` is the use of plain assert\nstatements and the detailed introspection of expressions upon\nassertion failures.  This is provided by \"assertion rewriting\" which\nmodifies the parsed AST before it gets compiled to bytecode.  This is\ndone via a :pep:`302` import hook which gets installed early on when\n``pytest`` starts up and will perform this rewriting when modules get\nimported.  However, since we do not want to test different bytecode\nfrom what you will run in production, this hook only rewrites test modules\nthemselves (as defined by the :confval:`python_files` configuration option),\nand any modules which are part of plugins.\nAny other imported module will not be rewritten and normal assertion behaviour\nwill happen.\n\nIf you have assertion helpers in other modules where you would need\nassertion rewriting to be enabled you need to ask ``pytest``\nexplicitly to rewrite this module before it gets imported.\n\n.. autofunction:: pytest.register_assert_rewrite\n    :noindex:\n\nThis is especially important when you write a pytest plugin which is\ncreated using a package.  The import hook only treats ``conftest.py``\nfiles and any modules which are listed in the ``pytest11`` entrypoint\nas plugins.  As an example consider the following package::\n\n   pytest_foo/__init__.py\n   pytest_foo/plugin.py\n   pytest_foo/helper.py\n\nWith the following typical ``setup.py`` extract:\n\n.. code-block:: python\n\n   setup(..., entry_points={\"pytest11\": [\"foo = pytest_foo.plugin\"]}, ...)\n\nIn this case only ``pytest_foo/plugin.py`` will be rewritten.  If the\nhelper module also contains assert statements which need to be\nrewritten it needs to be marked as such, before it gets imported.\nThis is easiest by marking it for rewriting inside the\n``__init__.py`` module, which will always be imported first when a\nmodule inside a package is imported.  This way ``plugin.py`` can still\nimport ``helper.py`` normally.  The contents of\n``pytest_foo/__init__.py`` will then need to look like this:\n\n.. code-block:: python\n\n   import pytest\n\n   pytest.register_assert_rewrite(\"pytest_foo.helper\")\n\n\nRequiring/Loading plugins in a test module or conftest file\n-----------------------------------------------------------\n\nYou can require plugins in a test module or a ``conftest.py`` file using :globalvar:`pytest_plugins`:\n\n.. code-block:: python\n\n    pytest_plugins = [\"name1\", \"name2\"]\n\nWhen the test module or conftest plugin is loaded the specified plugins\nwill be loaded as well. Any module can be blessed as a plugin, including internal\napplication modules:\n\n.. code-block:: python\n\n    pytest_plugins = \"myapp.testsupport.myplugin\"\n\n:globalvar:`pytest_plugins` are processed recursively, so note that in the example above\nif ``myapp.testsupport.myplugin`` also declares :globalvar:`pytest_plugins`, the contents\nof the variable will also be loaded as plugins, and so on.\n\n.. _`requiring plugins in non-root conftests`:\n\n.. note::\n    Requiring plugins using :globalvar:`pytest_plugins` variable in non-root\n    ``conftest.py`` files is deprecated.\n\n    This is important because ``conftest.py`` files implement per-directory\n    hook implementations, but once a plugin is imported, it will affect the\n    entire directory tree. In order to avoid confusion, defining\n    :globalvar:`pytest_plugins` in any ``conftest.py`` file which is not located in the\n    tests root directory is deprecated, and will raise a warning.\n\nThis mechanism makes it easy to share fixtures within applications or even\nexternal applications without the need to create external plugins using the\n:std:doc:`entry point packaging metadata\n<packaging:guides/creating-and-discovering-plugins>` technique.\n\nPlugins imported by :globalvar:`pytest_plugins` will also automatically be marked\nfor assertion rewriting (see :func:`pytest.register_assert_rewrite`).\nHowever for this to have any effect the module must not be\nimported already; if it was already imported at the time the\n:globalvar:`pytest_plugins` statement is processed, a warning will result and\nassertions inside the plugin will not be rewritten.  To fix this you\ncan either call :func:`pytest.register_assert_rewrite` yourself before\nthe module is imported, or you can arrange the code to delay the\nimporting until after the plugin is registered.\n\n\nAccessing another plugin by name\n--------------------------------\n\nIf a plugin wants to collaborate with code from\nanother plugin it can obtain a reference through\nthe plugin manager like this:\n\n.. sourcecode:: python\n\n    plugin = config.pluginmanager.get_plugin(\"name_of_plugin\")\n\nIf you want to look at the names of existing plugins, use\nthe :option:`--trace-config` option.\n\n\n.. _registering-markers:\n\nRegistering custom markers\n--------------------------\n\nIf your plugin uses any markers, you should register them so that they appear in\npytest's help text and do not :ref:`cause spurious warnings <unknown-marks>`.\nFor example, the following plugin would register ``cool_marker`` and\n``mark_with`` for all users:\n\n.. code-block:: python\n\n    def pytest_configure(config):\n        config.addinivalue_line(\"markers\", \"cool_marker: this one is for cool tests.\")\n        config.addinivalue_line(\n            \"markers\", \"mark_with(arg, arg2): this marker takes arguments.\"\n        )\n\n\nTesting plugins\n---------------\n\npytest comes with a plugin named ``pytester`` that helps you write tests for\nyour plugin code. The plugin is disabled by default, so you will have to enable\nit before you can use it.\n\nYou can do so by adding the following line to a ``conftest.py`` file in your\ntesting directory:\n\n.. code-block:: python\n\n    # content of conftest.py\n\n    pytest_plugins = [\"pytester\"]\n\nAlternatively you can invoke pytest with the ``-p pytester`` command line\noption.\n\nThis will allow you to use the :py:class:`pytester <pytest.Pytester>`\nfixture for testing your plugin code.\n\nLet's demonstrate what you can do with the plugin with an example. Imagine we\ndeveloped a plugin that provides a fixture ``hello`` which yields a function\nand we can invoke this function with one optional parameter. It will return a\nstring value of ``Hello World!`` if we do not supply a value or ``Hello\n{value}!`` if we do supply a string value.\n\n.. code-block:: python\n\n    import pytest\n\n\n    def pytest_addoption(parser):\n        group = parser.getgroup(\"helloworld\")\n        group.addoption(\n            \"--name\",\n            action=\"store\",\n            dest=\"name\",\n            default=\"World\",\n            help='Default \"name\" for hello().',\n        )\n\n\n    @pytest.fixture\n    def hello(request):\n        name = request.config.getoption(\"name\")\n\n        def _hello(name=None):\n            if not name:\n                name = request.config.getoption(\"name\")\n            return f\"Hello {name}!\"\n\n        return _hello\n\n\nNow the ``pytester`` fixture provides a convenient API for creating temporary\n``conftest.py`` files and test files. It also allows us to run the tests and\nreturn a result object, with which we can assert the tests' outcomes.\n\n.. code-block:: python\n\n    def test_hello(pytester):\n        \"\"\"Make sure that our plugin works.\"\"\"\n\n        # create a temporary conftest.py file\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[\n                \"Brianna\",\n                \"Andreas\",\n                \"Floris\",\n            ])\n            def name(request):\n                return request.param\n        \"\"\"\n        )\n\n        # create a temporary pytest test file\n        pytester.makepyfile(\n            \"\"\"\n            def test_hello_default(hello):\n                assert hello() == \"Hello World!\"\n\n            def test_hello_name(hello, name):\n                assert hello(name) == \"Hello {0}!\".format(name)\n        \"\"\"\n        )\n\n        # run all tests with pytest\n        result = pytester.runpytest()\n\n        # check that all 4 tests passed\n        result.assert_outcomes(passed=4)\n\n\nAdditionally it is possible to copy examples to the ``pytester``'s isolated environment\nbefore running pytest on it. This way we can abstract the tested logic to separate files,\nwhich is especially useful for longer tests and/or longer ``conftest.py`` files.\n\nNote that for ``pytester.copy_example`` to work we need to set `pytester_example_dir`\nin our configuration file to tell pytest where to look for example files.\n\n.. code-block:: toml\n\n    # content of pytest.toml\n    [pytest]\n    pytester_example_dir = \".\"\n\n\n.. code-block:: python\n\n    # content of test_example.py\n\n\n    def test_plugin(pytester):\n        pytester.copy_example(\"test_example.py\")\n        pytester.runpytest(\"-k\", \"test_example\")\n\n\n    def test_example():\n        pass\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    configfile: pytest.toml\n    collected 2 items\n\n    test_example.py ..                                                   [100%]\n\n    ============================ 2 passed in 0.12s =============================\n\nFor more information about the result object that ``runpytest()`` returns, and\nthe methods that it provides please check out the :py:class:`RunResult\n<_pytest.pytester.RunResult>` documentation.\n"
  },
  {
    "path": "doc/en/how-to/xunit_setup.rst",
    "content": "\n.. _`classic xunit`:\n.. _xunitsetup:\n\nHow to implement xunit-style set-up\n========================================\n\nThis section describes a classic and popular way how you can implement\nfixtures (setup and teardown test state) on a per-module/class/function basis.\n\n\n.. note::\n\n    While these setup/teardown methods are simple and familiar to those\n    coming from a ``unittest`` or ``nose`` background, you may also consider\n    using pytest's more powerful :ref:`fixture mechanism\n    <fixture>` which leverages the concept of dependency injection, allowing\n    for a more modular and more scalable approach for managing test state,\n    especially for larger projects and for functional testing.  You can\n    mix both fixture mechanisms in the same file but\n    test methods of ``unittest.TestCase`` subclasses\n    cannot receive fixture arguments.\n\n\nModule level setup/teardown\n--------------------------------------\n\nIf you have multiple test functions and test classes in a single\nmodule you can optionally implement the following fixture methods\nwhich will usually be called once for all the functions:\n\n.. code-block:: python\n\n    def setup_module(module):\n        \"\"\"setup any state specific to the execution of the given module.\"\"\"\n\n\n    def teardown_module(module):\n        \"\"\"teardown any state that was previously setup with a setup_module\n        method.\n        \"\"\"\n\nAs of pytest-3.0, the ``module`` parameter is optional.\n\nClass level setup/teardown\n----------------------------------\n\nSimilarly, the following methods are called at class level before\nand after all test methods of the class are called:\n\n.. code-block:: python\n\n    @classmethod\n    def setup_class(cls):\n        \"\"\"setup any state specific to the execution of the given class (which\n        usually contains tests).\n        \"\"\"\n\n\n    @classmethod\n    def teardown_class(cls):\n        \"\"\"teardown any state that was previously setup with a call to\n        setup_class.\n        \"\"\"\n\n.. _xunit-method-setup:\n\nMethod and function level setup/teardown\n-----------------------------------------------\n\nSimilarly, the following methods are called around each method invocation:\n\n.. code-block:: python\n\n    def setup_method(self, method):\n        \"\"\"setup any state tied to the execution of the given method in a\n        class.  setup_method is invoked for every test method of a class.\n        \"\"\"\n\n\n    def teardown_method(self, method):\n        \"\"\"teardown any state that was previously setup with a setup_method\n        call.\n        \"\"\"\n\nAs of pytest-3.0, the ``method`` parameter is optional.\n\nIf you would rather define test functions directly at module level\nyou can also use the following functions to implement fixtures:\n\n.. code-block:: python\n\n    def setup_function(function):\n        \"\"\"setup any state tied to the execution of the given function.\n        Invoked for every test function in the module.\n        \"\"\"\n\n\n    def teardown_function(function):\n        \"\"\"teardown any state that was previously setup with a setup_function\n        call.\n        \"\"\"\n\nAs of pytest-3.0, the ``function`` parameter is optional.\n\nRemarks:\n\n* It is possible for setup/teardown pairs to be invoked multiple times\n  per testing process.\n\n* teardown functions are not called if the corresponding setup function existed\n  and failed/was skipped.\n\n* Prior to pytest-4.2, xunit-style functions did not obey the scope rules of fixtures, so\n  it was possible, for example, for a ``setup_method`` to be called before a\n  session-scoped autouse fixture.\n\n  Now the xunit-style functions are integrated with the fixture mechanism and obey the proper\n  scope rules of fixtures involved in the call.\n"
  },
  {
    "path": "doc/en/index.rst",
    "content": ".. _features:\n\n.. sidebar:: **Next Open Trainings and Events**\n\n    - `Professional Testing with Python <https://python-academy.com/courses/python_course_testing.html>`_, via `Python Academy <https://www.python-academy.com/>`_ (3 day in-depth training), **March 9th -- 11th 2027**, Leipzig (DE) / Remote\n\n    Also see :doc:`previous talks and blogposts <talks>`\n\npytest: helps you write better programs\n=======================================\n\n.. toctree::\n    :hidden:\n\n    getting-started\n    how-to/index\n    reference/index\n    explanation/index\n    example/index\n\n.. toctree::\n    :caption: About the project\n    :hidden:\n\n    changelog\n    contributing\n    backwards-compatibility\n    sponsor\n    tidelift\n    license\n    contact\n\n.. toctree::\n    :caption: Useful links\n    :hidden:\n\n    pytest @ PyPI <https://pypi.org/project/pytest/>\n    pytest @ GitHub <https://github.com/pytest-dev/pytest/>\n    Issue Tracker <https://github.com/pytest-dev/pytest/issues>\n    PDF Documentation <https://media.readthedocs.org/pdf/pytest/latest/pytest.pdf>\n\n.. module:: pytest\n\nThe ``pytest`` framework makes it easy to write small, readable tests, and can\nscale to support complex functional testing for applications and libraries.\n\n\n**PyPI package name**: :pypi:`pytest`\n\nA quick example\n---------------\n\n.. code-block:: python\n\n    # content of test_sample.py\n    def inc(x):\n        return x + 1\n\n\n    def test_answer():\n        assert inc(3) == 5\n\n\nTo execute it:\n\n.. code-block:: pytest\n\n    $ pytest\n    =========================== test session starts ============================\n    platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y\n    rootdir: /home/sweet/project\n    collected 1 item\n\n    test_sample.py F                                                     [100%]\n\n    ================================= FAILURES =================================\n    _______________________________ test_answer ________________________________\n\n        def test_answer():\n    >       assert inc(3) == 5\n    E       assert 4 == 5\n    E        +  where 4 = inc(3)\n\n    test_sample.py:6: AssertionError\n    ========================= short test summary info ==========================\n    FAILED test_sample.py::test_answer - assert 4 == 5\n    ============================ 1 failed in 0.12s =============================\n\nDue to ``pytest``'s detailed assertion introspection, only plain ``assert`` statements are used.\nSee :ref:`Get started <getstarted>` for a basic introduction to using pytest.\n\n\nFeatures\n--------\n\n- Detailed info on failing :ref:`assert statements <assert>` (no need to remember ``self.assert*`` names)\n\n- :ref:`Auto-discovery <test discovery>` of test modules and functions\n\n- :ref:`Modular fixtures <fixture>` for managing small or parametrized long-lived test resources\n\n- Can run :ref:`unittest <unittest>` (including trial) test suites out of the box\n\n- Python 3.10+ or PyPy 3\n\n- Rich plugin architecture, with over 1300+ :ref:`external plugins <plugin-list>` and thriving community\n\n\nDocumentation\n-------------\n\n* :ref:`Get started <get-started>` - install pytest and grasp its basics in just twenty minutes\n* :ref:`How-to guides <how-to>` - step-by-step guides, covering a vast range of use-cases and needs\n* :ref:`Reference guides <reference>` - includes the complete pytest API reference, lists of plugins and more\n* :ref:`Explanation <explanation>` - background, discussion of key topics, answers to higher-level questions\n\n\nBugs/Requests\n-------------\n\nPlease use the `GitHub issue tracker <https://github.com/pytest-dev/pytest/issues>`_ to submit bugs or request features.\n\n\nSupport pytest\n--------------\n\n`Open Collective`_ is an online funding platform for open and transparent communities.\nIt provides tools to raise money and share your finances in full transparency.\n\nIt is the platform of choice for individuals and companies that want to make one-time or\nmonthly donations directly to the project.\n\nSee more details in the `pytest collective`_.\n\n.. _Open Collective: https://opencollective.com\n.. _pytest collective: https://opencollective.com/pytest\n\n\npytest for enterprise\n---------------------\n\nAvailable as part of the Tidelift Subscription.\n\nThe maintainers of pytest and thousands of other packages are working with Tidelift to deliver commercial support and\nmaintenance for the open source dependencies you use to build your applications.\nSave time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use.\n\n`Learn more. <https://tidelift.com/subscription/pkg/pypi-pytest?utm_source=pypi-pytest&utm_medium=referral&utm_campaign=enterprise&utm_term=repo>`_\n\nSecurity\n~~~~~~~~\n\npytest has never been associated with a security vulnerability, but in any case, to report a\nsecurity vulnerability please use the `Tidelift security contact <https://tidelift.com/security>`_.\nTidelift will coordinate the fix and disclosure.\n"
  },
  {
    "path": "doc/en/license.rst",
    "content": ".. _license:\n\nLicense\n-------\n\nDistributed under the terms of the `MIT`_ license, pytest is free and open source software.\n\n.. code-block:: text\n\n    The MIT License (MIT)\n\n    Copyright (c) 2004 Holger Krekel and others\n\n    Permission is hereby granted, free of charge, to any person obtaining a copy of\n    this software and associated documentation files (the \"Software\"), to deal in\n    the Software without restriction, including without limitation the rights to\n    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n    of the Software, and to permit persons to whom the Software is furnished to do\n    so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in all\n    copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n    SOFTWARE.\n\n.. _`MIT`: https://github.com/pytest-dev/pytest/blob/main/LICENSE\n"
  },
  {
    "path": "doc/en/naming20.rst",
    "content": "\n.. _naming20:\n\nNew pytest names in 2.0 (flat is better than nested)\n----------------------------------------------------\n\nIf you used older version of the ``py`` distribution (which\nincluded the py.test command line tool and Python name space)\nyou accessed helpers and possibly collection classes through\nthe ``py.test`` Python namespaces.  The new ``pytest``\nPython module flatly provides the same objects, following\nthese renaming rules::\n\n    py.test.XYZ          -> pytest.XYZ\n    py.test.collect.XYZ  -> pytest.XYZ\n    py.test.cmdline.main -> pytest.main\n\nThe old ``py.test.*`` ways to access functionality remain\nvalid but you are encouraged to do global renaming according\nto the above rules in your test code.\n"
  },
  {
    "path": "doc/en/proposals/parametrize_with_fixtures.rst",
    "content": ":orphan:\n\n===================================\nPROPOSAL: Parametrize with fixtures\n===================================\n\n.. warning::\n\n    This document outlines a proposal around using fixtures as input\n    of parametrized tests or fixtures.\n\nProblem\n-------\n\nAs a user I have functional tests that I would like to run against various\nscenarios.\n\nIn this particular example we want to generate a new project based on a\ncookiecutter template. We want to test default values but also data that\nemulates user input.\n\n- use default values\n\n- emulate user input\n\n  - specify 'author'\n\n  - specify 'project_slug'\n\n  - specify 'author' and 'project_slug'\n\nThis is how a functional test could look like:\n\n.. code-block:: python\n\n    import pytest\n\n\n    @pytest.fixture\n    def default_context():\n        return {\"extra_context\": {}}\n\n\n    @pytest.fixture(\n        params=[\n            {\"author\": \"alice\"},\n            {\"project_slug\": \"helloworld\"},\n            {\"author\": \"bob\", \"project_slug\": \"foobar\"},\n        ]\n    )\n    def extra_context(request):\n        return {\"extra_context\": request.param}\n\n\n    @pytest.fixture(params=[\"default\", \"extra\"])\n    def context(request):\n        if request.param == \"default\":\n            return request.getfuncargvalue(\"default_context\")\n        else:\n            return request.getfuncargvalue(\"extra_context\")\n\n\n    def test_generate_project(cookies, context):\n        \"\"\"Call the cookiecutter API to generate a new project from a\n        template.\n        \"\"\"\n        result = cookies.bake(extra_context=context)\n\n        assert result.exit_code == 0\n        assert result.exception is None\n        assert result.project.isdir()\n\n\nIssues\n------\n\n* By using ``request.getfuncargvalue()`` we rely on actual fixture function\n  execution to know what fixtures are involved, due to its dynamic nature\n* More importantly, ``request.getfuncargvalue()`` cannot be combined with\n  parametrized fixtures, such as ``extra_context``\n* This is very inconvenient if you wish to extend an existing test suite by\n  certain parameters for fixtures that are already used by tests\n\npytest version 3.0 reports an error if you try to run above code::\n\n    Failed: The requested fixture has no parameter defined for the current\n    test.\n\n    Requested fixture 'extra_context'\n\n\nProposed solution\n-----------------\n\nA new function that can be used in modules can be used to dynamically define\nfixtures from existing ones.\n\n.. code-block:: python\n\n    pytest.define_combined_fixture(\n        name=\"context\", fixtures=[\"default_context\", \"extra_context\"]\n    )\n\nThe new fixture ``context`` inherits the scope from the used fixtures and yield\nthe following values.\n\n- ``{}``\n\n- ``{'author': 'alice'}``\n\n- ``{'project_slug': 'helloworld'}``\n\n- ``{'author': 'bob', 'project_slug': 'foobar'}``\n\nAlternative approach\n--------------------\n\nA new helper function named ``fixture_request`` would tell pytest to yield\nall parameters marked as a fixture.\n\n.. note::\n\n    The :pypi:`pytest-lazy-fixture` plugin implements a very\n    similar solution to the proposal below, make sure to check it out.\n\n.. code-block:: python\n\n    @pytest.fixture(\n        params=[\n            pytest.fixture_request(\"default_context\"),\n            pytest.fixture_request(\"extra_context\"),\n        ]\n    )\n    def context(request):\n        \"\"\"Returns all values for ``default_context``, one-by-one before it\n        does the same for ``extra_context``.\n\n        request.param:\n            - {}\n            - {'author': 'alice'}\n            - {'project_slug': 'helloworld'}\n            - {'author': 'bob', 'project_slug': 'foobar'}\n        \"\"\"\n        return request.param\n\nThe same helper can be used in combination with ``pytest.mark.parametrize``.\n\n.. code-block:: python\n\n\n    @pytest.mark.parametrize(\n        \"context, expected_response_code\",\n        [\n            (pytest.fixture_request(\"default_context\"), 0),\n            (pytest.fixture_request(\"extra_context\"), 0),\n        ],\n    )\n    def test_generate_project(cookies, context, exit_code):\n        \"\"\"Call the cookiecutter API to generate a new project from a\n        template.\n        \"\"\"\n        result = cookies.bake(extra_context=context)\n\n        assert result.exit_code == exit_code\n"
  },
  {
    "path": "doc/en/pytest.ini",
    "content": "[pytest]\n# just defined to prevent the root level tox.ini from kicking in\n"
  },
  {
    "path": "doc/en/recwarn.rst",
    "content": ":orphan:\n\nThis page has been moved, please see :ref:`assertwarnings`.\n"
  },
  {
    "path": "doc/en/reference/customize.rst",
    "content": "Configuration\n=============\n\nCommand line options and configuration file settings\n-----------------------------------------------------------------\n\nYou can get help on command line and configuration options by using the general help option:\n\n.. code-block:: bash\n\n    pytest -h   # prints options _and_ config file settings\n\nThis will display command line and configuration file settings\nwhich were registered by installed plugins.\n\n.. _`config file formats`:\n\nConfiguration file formats\n--------------------------\n\nMany :ref:`pytest settings <ini options ref>` can be set in a *configuration file*, which\nby convention resides in the root directory of your repository.\n\nA quick example of the configuration files supported by pytest:\n\npytest.toml\n~~~~~~~~~~~\n\n.. versionadded:: 9.0\n\n``pytest.toml`` files take precedence over other files, even when empty.\n\nAlternatively, the hidden version ``.pytest.toml`` can be used.\n\n.. tab:: toml\n\n    .. code-block:: toml\n\n        # pytest.toml or .pytest.toml\n        [pytest]\n        minversion = \"9.0\"\n        addopts = [\"-ra\", \"-q\"]\n        testpaths = [\n            \"tests\",\n            \"integration\",\n        ]\n\npytest.ini\n~~~~~~~~~~\n\n``pytest.ini`` files take precedence over other files (except ``pytest.toml`` and ``.pytest.toml``), even when empty.\n\nAlternatively, the hidden version ``.pytest.ini`` can be used.\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        # pytest.ini or .pytest.ini\n        [pytest]\n        minversion = 6.0\n        addopts = -ra -q\n        testpaths =\n            tests\n            integration\n\n\npyproject.toml\n~~~~~~~~~~~~~~\n\n.. versionadded:: 6.0\n.. versionchanged:: 9.0\n\n``pyproject.toml`` files are supported for configuration.\n\n.. tab:: toml\n\n    Use ``[tool.pytest]`` to leverage native TOML types (supported since pytest 9.0):\n\n    .. code-block:: toml\n\n        # pyproject.toml\n        [tool.pytest]\n        minversion = \"9.0\"\n        addopts = [\"-ra\", \"-q\"]\n        testpaths = [\n            \"tests\",\n            \"integration\",\n        ]\n\n.. tab:: ini\n\n    Use ``[tool.pytest.ini_options]`` for INI-style configuration (supported since pytest 6.0):\n\n    .. code-block:: toml\n\n        # pyproject.toml\n        [tool.pytest.ini_options]\n        minversion = \"6.0\"\n        addopts = \"-ra -q\"\n        testpaths = [\n            \"tests\",\n            \"integration\",\n        ]\n\n    For projects that still run pytest versions older than 6.0, keep\n    ``minversion`` in ``pytest.ini`` or ``setup.cfg`` too. Those versions\n    do not read ``pyproject.toml``.\n\ntox.ini\n~~~~~~~\n\n``tox.ini`` files are the configuration files of the `tox <https://tox.readthedocs.io>`__ project,\nand can also be used to hold pytest configuration if they have a ``[pytest]`` section.\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        # tox.ini\n        [pytest]\n        minversion = 6.0\n        addopts = -ra -q\n        testpaths =\n            tests\n            integration\n\n\nsetup.cfg\n~~~~~~~~~\n\n``setup.cfg`` files are general purpose configuration files, used originally by ``distutils`` (now deprecated) and :std:doc:`setuptools <setuptools:userguide/declarative_config>`, and can also be used to hold pytest configuration\nif they have a ``[tool:pytest]`` section.\n\n.. tab:: ini\n\n    .. code-block:: ini\n\n        # setup.cfg\n        [tool:pytest]\n        minversion = 6.0\n        addopts = -ra -q\n        testpaths =\n            tests\n            integration\n\n.. warning::\n\n    Usage of ``setup.cfg`` is not recommended unless for very simple use cases. ``.cfg``\n    files use a different parser than ``pytest.ini`` and ``tox.ini`` which might cause hard to track\n    down problems.\n    When possible, it is recommended to use the latter files, or ``pyproject.toml``, to hold your\n    pytest configuration.\n\n\n.. _rootdir:\n.. _configfiles:\n\nInitialization: determining rootdir and configfile\n--------------------------------------------------\n\npytest determines a ``rootdir`` for each test run which depends on\nthe command line arguments (specified test files, paths) and on\nthe existence of configuration files.  The determined ``rootdir`` and ``configfile`` are\nprinted as part of the pytest header during startup.\n\nHere's a summary of what ``pytest`` uses ``rootdir`` for:\n\n* Construct *nodeids* during collection; each test is assigned\n  a unique *nodeid* which is rooted at the ``rootdir`` and takes into account\n  the full path, class name, function name and parametrization (if any).\n\n* Is used by plugins as a stable location to store project/test run specific information;\n  for example, the internal :ref:`cache <cache>` plugin creates a ``.pytest_cache`` subdirectory\n  in ``rootdir`` to store its cross-test run state.\n\n``rootdir`` is **NOT** used to modify ``sys.path``/``PYTHONPATH`` or\ninfluence how modules are imported. See :ref:`pythonpath` for more details.\n\nThe :option:`--rootdir=path` command-line option can be used to force a specific directory.\nNote that contrary to other command-line options, ``--rootdir`` cannot be used with\n:confval:`addopts` inside a configuration file because the ``rootdir`` is used to *find* the configuration file\nalready.\n\nFinding the ``rootdir``\n~~~~~~~~~~~~~~~~~~~~~~~\n\nHere is the algorithm which finds the rootdir from ``args``:\n\n- If :option:`-c` is passed in the command-line, use that as configuration file, and its directory as ``rootdir``.\n\n- Determine the common ancestor directory for the specified ``args`` that are\n  recognised as paths that exist in the file system. If no such paths are\n  found, the common ancestor directory is set to the current working directory.\n\n- Look for ``pytest.toml``, ``.pytest.toml``, ``pytest.ini``, ``.pytest.ini``, ``pyproject.toml``, ``tox.ini``, and ``setup.cfg`` files in the ancestor\n  directory and upwards.  If one is matched, it becomes the ``configfile`` and its\n  directory becomes the ``rootdir``.\n\n- If no configuration file was found, look for ``setup.py`` upwards from the common\n  ancestor directory to determine the ``rootdir``.\n\n- If no ``setup.py`` was found, look for ``pytest.toml``, ``.pytest.toml``, ``pytest.ini``, ``.pytest.ini``, ``pyproject.toml``, ``tox.ini``, and\n  ``setup.cfg`` in each of the specified ``args`` and upwards. If one is\n  matched, it becomes the ``configfile`` and its directory becomes the ``rootdir``.\n\n- If no ``configfile`` was found and no configuration argument is passed, use the already determined common ancestor as root\n  directory. This allows the use of pytest in structures that are not part of\n  a package and don't have any particular configuration file.\n\nIf no ``args`` are given, pytest collects tests below the current working\ndirectory and also starts determining the ``rootdir`` from there.\n\nFiles will only be matched for configuration if:\n\n* ``pytest.toml``: will always match and take highest precedence, even if empty.\n* ``pytest.ini``: will always match and take precedence (after ``pytest.toml`` and ``.pytest.toml``), even if empty.\n* ``pyproject.toml``: contains a ``[tool.pytest]`` or ``[tool.pytest.ini_options]`` table.\n* ``tox.ini``: contains a ``[pytest]`` section.\n* ``setup.cfg``: contains a ``[tool:pytest]`` section.\n\nFinally, a ``pyproject.toml`` file will be considered the ``configfile`` if no other match was found, in this case\neven if it does not contain a ``[tool.pytest]`` table (since version ``9.0``) or a ``[tool.pytest.ini_options]``\ntable (since version ``8.1``).\n\nThe files are considered in the order above. Options from multiple ``configfiles`` candidates\nare never merged - the first match wins.\n\nThe configuration file also determines the value of the ``rootpath``.\n\nThe :class:`Config <pytest.Config>` object (accessible via hooks or through the :fixture:`pytestconfig` fixture)\nwill subsequently carry these attributes:\n\n- :attr:`config.rootpath <pytest.Config.rootpath>`: the determined root directory, guaranteed to exist. It is used as\n  a reference directory for constructing test addresses (\"nodeids\") and can be used also by plugins for storing\n  per-testrun information.\n\n- :attr:`config.inipath <pytest.Config.inipath>`: the determined ``configfile``, may be ``None``\n  (it is named ``inipath`` for historical reasons).\n\n.. versionadded:: 6.1\n    The ``config.rootpath`` and ``config.inipath`` properties. They are :class:`pathlib.Path`\n    versions of the older ``config.rootdir`` and ``config.inifile``, which have type\n    ``py.path.local``, and still exist for backward compatibility.\n\n\n\nExample:\n\n.. code-block:: bash\n\n    pytest path/to/testdir path/other/\n\nwill determine the common ancestor as ``path`` and then\ncheck for configuration files as follows:\n\n.. code-block:: text\n\n    # first look for path/pytest.toml\n    path/pytest.toml\n    path/pytest.ini\n    path/pyproject.toml  # must contain a [tool.pytest] table to match\n    path/tox.ini         # must contain [pytest] section to match\n    path/setup.cfg       # must contain [tool:pytest] section to match\n    pytest.toml\n    pytest.ini\n    ... # all the way up to the root\n\n    # now look for setup.py\n    path/setup.py\n    setup.py\n    ... # all the way up to the root\n\n\n.. warning::\n\n    Custom pytest plugin commandline arguments may include a path, as in\n    ``pytest --log-output ../../test.log args``. Then ``args`` is mandatory,\n    otherwise pytest uses the directory of test.log for rootdir determination\n    (see also :issue:`1435`).\n    A dot ``.`` for referencing the current working directory is also\n    possible.\n\n\n.. _`how to change command line options defaults`:\n.. _`adding default options`:\n\n\nBuiltin configuration file options\n----------------------------------------------\n\nFor the full list of options consult the :ref:`reference documentation <ini options ref>`.\n\nSyntax highlighting theme customization\n---------------------------------------\n\nThe syntax highlighting themes used by pytest can be customized using two environment variables:\n\n- :envvar:`PYTEST_THEME` sets a `pygment style <https://pygments.org/docs/styles/>`_ to use.\n- :envvar:`PYTEST_THEME_MODE` sets this style to *light* or *dark*.\n"
  },
  {
    "path": "doc/en/reference/exit-codes.rst",
    "content": ".. _exit-codes:\n\nExit codes\n========================================================\n\nRunning ``pytest`` can result in six different exit codes:\n\n:Exit code 0: All tests were collected and passed successfully\n:Exit code 1: Tests were collected and run but some of the tests failed\n:Exit code 2: Test execution was interrupted by the user\n:Exit code 3: Internal error happened while executing tests\n:Exit code 4: pytest command line usage error\n:Exit code 5: No tests were collected\n\nThey are represented by the :class:`pytest.ExitCode` enum. The exit codes being a part of the public API can be imported and accessed directly using:\n\n.. code-block:: python\n\n    from pytest import ExitCode\n\n.. note::\n\n    If you would like to customize the exit code in some scenarios, specifically when\n    no tests are collected, consider using the\n    `pytest-custom_exit_code <https://github.com/yashtodi94/pytest-custom_exit_code>`__\n    plugin.\n"
  },
  {
    "path": "doc/en/reference/fixtures.rst",
    "content": ".. _reference-fixtures:\n.. _fixture:\n.. _fixtures:\n.. _`@pytest.fixture`:\n.. _`pytest.fixture`:\n\n\nFixtures reference\n========================================================\n\n.. seealso:: :ref:`about-fixtures`\n.. seealso:: :ref:`how-to-fixtures`\n\n.. _`Dependency injection`: https://en.wikipedia.org/wiki/Dependency_injection\n\n\nBuilt-in fixtures\n-----------------\n\n:ref:`Fixtures <fixtures-api>` are defined using the :ref:`@pytest.fixture\n<pytest.fixture-api>` decorator. Pytest has several useful built-in fixtures:\n\n   :fixture:`capfd`\n        Capture, as text, output to file descriptors ``1`` and ``2``.\n\n   :fixture:`capfdbinary`\n        Capture, as bytes, output to file descriptors ``1`` and ``2``.\n\n   :fixture:`caplog`\n        Control logging and access log entries.\n\n   :fixture:`capsys`\n        Capture, as text, output to ``sys.stdout`` and ``sys.stderr``.\n\n   :fixture:`capteesys`\n        Capture in the same manner as :fixture:`capsys`, but also pass text\n        through according to :option:`--capture`.\n\n   :fixture:`capsysbinary`\n        Capture, as bytes, output to ``sys.stdout`` and ``sys.stderr``.\n\n   :fixture:`cache`\n        Store and retrieve values across pytest runs.\n\n   :fixture:`doctest_namespace`\n        Provide a dict injected into the doctests namespace.\n\n   :fixture:`monkeypatch`\n       Temporarily modify classes, functions, dictionaries,\n       ``os.environ``, and other objects.\n\n   :fixture:`pytestconfig`\n        Access to configuration values, pluginmanager and plugin hooks.\n\n   :fixture:`subtests`\n        Enable declaring subtests inside test functions.\n\n   :fixture:`record_property`\n       Add extra properties to the test.\n\n   :fixture:`record_testsuite_property`\n       Add extra properties to the test suite.\n\n   :fixture:`recwarn`\n        Record warnings emitted by test functions.\n\n   :fixture:`request`\n       Provide information on the executing test function.\n\n   :fixture:`testdir`\n        Provide a temporary test directory to aid in running, and\n        testing, pytest plugins.\n\n   :fixture:`tmp_path`\n       Provide a :class:`pathlib.Path` object to a temporary directory\n       which is unique to each test function.\n\n   :fixture:`tmp_path_factory`\n        Make session-scoped temporary directories and return\n        :class:`pathlib.Path` objects.\n\n   :fixture:`tmpdir`\n        Provide a `py.path.local <https://py.readthedocs.io/en/latest/path.html>`_ object to a temporary\n        directory which is unique to each test function;\n        replaced by :fixture:`tmp_path`.\n\n   :fixture:`tmpdir_factory`\n        Make session-scoped temporary directories and return\n        ``py.path.local`` objects;\n        replaced by :fixture:`tmp_path_factory`.\n\n\n.. _`conftest.py`:\n.. _`conftest`:\n\nFixture availability\n---------------------\n\nFixture availability is determined from the perspective of the test. A fixture\nis only available for tests to request if they are in the scope that fixture is\ndefined in. If a fixture is defined inside a class, it can only be requested by\ntests inside that class. But if a fixture is defined inside the global scope of\nthe module, then every test in that module, even if it's defined inside a class,\ncan request it.\n\nSimilarly, a test can also only be affected by an autouse fixture if that test\nis in the same scope that autouse fixture is defined in (see\n:ref:`autouse order`).\n\nA fixture can also request any other fixture, no matter where it's defined, so\nlong as the test requesting them can see all fixtures involved.\n\nFor example, here's a test file with a fixture (``outer``) that requests a\nfixture (``inner``) from a scope it wasn't defined in:\n\n.. literalinclude:: /example/fixtures/test_fixtures_request_different_scope.py\n\nFrom the tests' perspectives, they have no problem seeing each of the fixtures\nthey're dependent on:\n\n.. image:: /example/fixtures/test_fixtures_request_different_scope.*\n    :align: center\n\nSo when they run, ``outer`` will have no problem finding ``inner``, because\npytest searched from the tests' perspectives.\n\n.. note::\n    The scope a fixture is defined in has no bearing on the order it will be\n    instantiated in: the order is mandated by the logic described\n    :ref:`here <fixture order>`.\n\n``conftest.py``: sharing fixtures across multiple files\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe ``conftest.py`` file serves as a means of providing fixtures for an entire\ndirectory. Fixtures defined in a ``conftest.py`` can be used by any test\nin that package without needing to import them (pytest will automatically\ndiscover them).\n\nYou can have multiple nested directories/packages containing your tests, and\neach directory can have its own ``conftest.py`` with its own fixtures, adding on\nto the ones provided by the ``conftest.py`` files in parent directories.\n\nFor example, given a test file structure like this:\n\n::\n\n    tests/\n        __init__.py\n\n        conftest.py\n            # content of tests/conftest.py\n            import pytest\n\n            @pytest.fixture\n            def order():\n                return []\n\n            @pytest.fixture\n            def top(order, innermost):\n                order.append(\"top\")\n\n        test_top.py\n            # content of tests/test_top.py\n            import pytest\n\n            @pytest.fixture\n            def innermost(order):\n                order.append(\"innermost top\")\n\n            def test_order(order, top):\n                assert order == [\"innermost top\", \"top\"]\n\n        subpackage/\n            __init__.py\n\n            conftest.py\n                # content of tests/subpackage/conftest.py\n                import pytest\n\n                @pytest.fixture\n                def mid(order):\n                    order.append(\"mid subpackage\")\n\n            test_subpackage.py\n                # content of tests/subpackage/test_subpackage.py\n                import pytest\n\n                @pytest.fixture\n                def innermost(order, mid):\n                    order.append(\"innermost subpackage\")\n\n                def test_order(order, top):\n                    assert order == [\"mid subpackage\", \"innermost subpackage\", \"top\"]\n\nThe boundaries of the scopes can be visualized like this:\n\n.. image:: /example/fixtures/fixture_availability.*\n    :align: center\n\nThe directories become their own sort of scope where fixtures that are defined\nin a ``conftest.py`` file in that directory become available for that whole\nscope.\n\nTests are allowed to search upward (stepping outside a circle) for fixtures, but\ncan never go down (stepping inside a circle) to continue their search. So\n``tests/subpackage/test_subpackage.py::test_order`` would be able to find the\n``innermost`` fixture defined in ``tests/subpackage/test_subpackage.py``, but\nthe one defined in ``tests/test_top.py`` would be unavailable to it because it\nwould have to step down a level (step inside a circle) to find it.\n\nThe first fixture the test finds is the one that will be used, so\n:ref:`fixtures can be overridden <override fixtures>` if you need to change or\nextend what one does for a particular scope.\n\nYou can also use the ``conftest.py`` file to implement\n:ref:`local per-directory plugins <conftest.py plugins>`.\n\nFixtures from third-party plugins\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFixtures don't have to be defined in this structure to be available for tests,\nthough. They can also be provided by third-party plugins that are installed, and\nthis is how many pytest plugins operate. As long as those plugins are installed,\nthe fixtures they provide can be requested from anywhere in your test suite.\n\nBecause they're provided from outside the structure of your test suite,\nthird-party plugins don't really provide a scope like `conftest.py` files and\nthe directories in your test suite do. As a result, pytest will search for\nfixtures stepping out through scopes as explained previously, only reaching\nfixtures defined in plugins *last*.\n\nFor example, given the following file structure:\n\n::\n\n    tests/\n        __init__.py\n\n        conftest.py\n            # content of tests/conftest.py\n            import pytest\n\n            @pytest.fixture\n            def order():\n                return []\n\n        subpackage/\n            __init__.py\n\n            conftest.py\n                # content of tests/subpackage/conftest.py\n                import pytest\n\n                @pytest.fixture(autouse=True)\n                def mid(order, b_fix):\n                    order.append(\"mid subpackage\")\n\n            test_subpackage.py\n                # content of tests/subpackage/test_subpackage.py\n                import pytest\n\n                @pytest.fixture\n                def inner(order, mid, a_fix):\n                    order.append(\"inner subpackage\")\n\n                def test_order(order, inner):\n                    assert order == [\"b_fix\", \"mid subpackage\", \"a_fix\", \"inner subpackage\"]\n\nIf ``plugin_a`` is installed and provides the fixture ``a_fix``, and\n``plugin_b`` is installed and provides the fixture ``b_fix``, then this is what\nthe test's search for fixtures would look like:\n\n.. image:: /example/fixtures/fixture_availability_plugins.svg\n    :align: center\n\npytest will only search for ``a_fix`` and ``b_fix`` in the plugins after\nsearching for them first in the scopes inside ``tests/``.\n\n.. note::\n\n    pytest can tell you what fixtures are available for a given test if you call\n    ``pytest`` along with the test's name (or the scope it's in), and provide\n    the :option:`--fixtures` flag, e.g. ``pytest --fixtures test_something.py``\n    (fixtures with names that start with ``_`` will only be shown if you also\n    provide the :option:`-v` flag).\n\n\n.. _`fixture order`:\n\nFixture instantiation order\n---------------------------\n\nWhen pytest wants to execute a test, once it knows what fixtures will be\nexecuted, it has to figure out the order they'll be executed in. To do this, it\nconsiders 3 factors:\n\n1. scope\n2. dependencies\n3. autouse\n\nNames of fixtures or tests, where they're defined, the order they're defined in,\nand the order fixtures are requested in have no bearing on execution order\nbeyond coincidence. While pytest will try to make sure coincidences like these\nstay consistent from run to run, it's not something that should be depended on.\nIf you want to control the order, it's safest to rely on these 3 things and make\nsure dependencies are clearly established.\n\nHigher-scoped fixtures are executed first\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nWithin a function request for fixtures, those of higher-scopes (such as\n``session``) are executed before lower-scoped fixtures (such as ``function`` or\n``class``).\n\nHere's an example:\n\n.. literalinclude:: /example/fixtures/test_fixtures_order_scope.py\n\nThe test will pass because the larger scoped fixtures are executing first.\n\nThe order breaks down to this:\n\n.. image:: /example/fixtures/test_fixtures_order_scope.*\n    :align: center\n\nFixtures of the same order execute based on dependencies\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nWhen a fixture requests another fixture, the other fixture is executed first.\nSo if fixture ``a`` requests fixture ``b``, fixture ``b`` will execute first,\nbecause ``a`` depends on ``b`` and can't operate without it. Even if ``a``\ndoesn't need the result of ``b``, it can still request ``b`` if it needs to make\nsure it is executed after ``b``.\n\nFor example:\n\n.. literalinclude:: /example/fixtures/test_fixtures_order_dependencies.py\n\nIf we map out what depends on what, we get something that looks like this:\n\n.. image:: /example/fixtures/test_fixtures_order_dependencies.*\n    :align: center\n\nThe rules provided by each fixture (as to what fixture(s) each one has to come\nafter) are comprehensive enough that it can be flattened to this:\n\n.. image:: /example/fixtures/test_fixtures_order_dependencies_flat.*\n    :align: center\n\nEnough information has to be provided through these requests in order for pytest\nto be able to figure out a clear, linear chain of dependencies, and as a result,\nan order of operations for a given test. If there's any ambiguity, and the order\nof operations can be interpreted more than one way, you should assume pytest\ncould go with any one of those interpretations at any point.\n\nFor example, if ``d`` didn't request ``c``, i.e. the graph would look like this:\n\n.. image:: /example/fixtures/test_fixtures_order_dependencies_unclear.*\n    :align: center\n\nBecause nothing requested ``c`` other than ``g``, and ``g`` also requests ``f``,\nit's now unclear if ``c`` should go before/after ``f``, ``e``, or ``d``. The\nonly rules that were set for ``c`` is that it must execute after ``b`` and\nbefore ``g``.\n\npytest doesn't know where ``c`` should go in the case, so it should be assumed\nthat it could go anywhere between ``g`` and ``b``.\n\nThis isn't necessarily bad, but it's something to keep in mind. If the order\nthey execute in could affect the behavior a test is targeting, or could\notherwise influence the result of a test, then the order should be defined\nexplicitly in a way that allows pytest to linearize/\"flatten\" that order.\n\n.. _`autouse order`:\n\nAutouse fixtures are executed first within their scope\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nAutouse fixtures are assumed to apply to every test that could reference them,\nso they are executed before other fixtures in that scope. Fixtures that are\nrequested by autouse fixtures effectively become autouse fixtures themselves for\nthe tests that the real autouse fixture applies to.\n\nSo if fixture ``a`` is autouse and fixture ``b`` is not, but fixture ``a``\nrequests fixture ``b``, then fixture ``b`` will effectively be an autouse\nfixture as well, but only for the tests that ``a`` applies to.\n\nIn the last example, the graph became unclear if ``d`` didn't request ``c``. But\nif ``c`` was autouse, then ``b`` and ``a`` would effectively also be autouse\nbecause ``c`` depends on them. As a result, they would all be shifted above\nnon-autouse fixtures within that scope.\n\nSo if the test file looked like this:\n\n.. literalinclude:: /example/fixtures/test_fixtures_order_autouse.py\n\nthe graph would look like this:\n\n.. image:: /example/fixtures/test_fixtures_order_autouse.*\n    :align: center\n\nBecause ``c`` can now be put above ``d`` in the graph, pytest can once again\nlinearize the graph to this:\n\n.. image:: /example/fixtures/test_fixtures_order_autouse_flat.*\n    :align: center\n\nIn this example, ``c`` makes ``b`` and ``a`` effectively autouse fixtures as\nwell.\n\nBe careful with autouse, though, as an autouse fixture will automatically\nexecute for every test that can reach it, even if they don't request it. For\nexample, consider this file:\n\n.. literalinclude:: /example/fixtures/test_fixtures_order_autouse_multiple_scopes.py\n\nEven though nothing in ``TestClassWithoutC1Request`` is requesting ``c1``, it still\nis executed for the tests inside it anyway:\n\n.. image:: /example/fixtures/test_fixtures_order_autouse_multiple_scopes.*\n    :align: center\n\nBut just because one autouse fixture requested a non-autouse fixture, that\ndoesn't mean the non-autouse fixture becomes an autouse fixture for all contexts\nthat it can apply to. It only effectively becomes an autouse fixture for the\ncontexts the real autouse fixture (the one that requested the non-autouse\nfixture) can apply to.\n\nFor example, take a look at this test file:\n\n.. literalinclude:: /example/fixtures/test_fixtures_order_autouse_temp_effects.py\n\nIt would break down to something like this:\n\n.. image:: /example/fixtures/test_fixtures_order_autouse_temp_effects.*\n    :align: center\n\nFor ``test_req`` and ``test_no_req`` inside ``TestClassWithAutouse``, ``c3``\neffectively makes ``c2`` an autouse fixture, which is why ``c2`` and ``c3`` are\nexecuted for both tests, despite not being requested, and why ``c2`` and ``c3``\nare executed before ``c1`` for ``test_req``.\n\nIf this made ``c2`` an *actual* autouse fixture, then ``c2`` would also execute\nfor the tests inside ``TestClassWithoutAutouse``, since they can reference\n``c2`` if they wanted to. But it doesn't, because from the perspective of the\n``TestClassWithoutAutouse`` tests, ``c2`` isn't an autouse fixture, since they\ncan't see ``c3``.\n\n\n.. note::\n\n    pytest can tell you what order the fixtures will execute in for a given test\n    if you call ``pytest`` along with the test's name (or the scope it's in),\n    and provide the :option:`--setup-plan` flag, e.g.\n    ``pytest --setup-plan test_something.py`` (fixtures with names that start\n    with ``_`` will only be shown if you also provide the :option:`-v` flag).\n"
  },
  {
    "path": "doc/en/reference/index.rst",
    "content": ":orphan:\n\n.. _reference:\n\nReference guides\n================\n\n.. toctree::\n   :maxdepth: 1\n\n   reference\n   fixtures\n   customize\n   exit-codes\n   plugin_list\n"
  },
  {
    "path": "doc/en/reference/plugin_list.rst",
    "content": "\n.. Note this file is autogenerated by scripts/update-plugin-list.py - usually weekly via github action\n\n.. _plugin-list:\n\nPytest Plugin List\n==================\n\nBelow is an automated compilation of ``pytest`` plugins available on `PyPI <https://pypi.org>`_.\nIt includes PyPI projects whose names begin with ``pytest-`` or ``pytest_`` and a handful of manually selected projects.\nPackages classified as inactive are excluded.\n\nFor detailed insights into how this list is generated,\nplease refer to `the update script <https://github.com/pytest-dev/pytest/blob/main/scripts/update-plugin-list.py>`_.\n\n.. warning::\n\n   Please be aware that this list is not a curated collection of projects\n   and does not undergo a systematic review process.\n   It serves purely as an informational resource to aid in the discovery of ``pytest`` plugins.\n\n   Do not presume any endorsement from the ``pytest`` project or its developers,\n   and always conduct your own quality assessment before incorporating any of these plugins into your own projects.\n\n\n.. The following conditional uses a different format for this list when\n   creating a PDF, because otherwise the table gets far too wide for the\n   page.\n\nThis list contains 1898 plugins.\n\n.. only:: not latex\n\n   =======================================================  ======================================================================================================================================================================================================================================================================================================================================================================================  ==============  =====================  ================================================\n   name                                                     summary                                                                                                                                                                                                                                                                                                                                                                                 last_release    status                 requires\n   =======================================================  ======================================================================================================================================================================================================================================================================================================================================================================================  ==============  =====================  ================================================\n   :pypi:`databricks-labs-pytester`                         Python Testing for Databricks                                                                                                                                                                                                                                                                                                                                                           Oct 17, 2025    4 - Beta               pytest>=8.3\n   :pypi:`logassert`                                        Simple but powerful assertion and verification of logged lines                                                                                                                                                                                                                                                                                                                          Aug 14, 2025    5 - Production/Stable  pytest; extra == \"dev\"\n   :pypi:`logot`                                            Test whether your code is logging correctly 🪵                                                                                                                                                                                                                                                                                                                                          Feb 22, 2026    5 - Production/Stable  pytest<10,>=7; extra == \"pytest\"\n   :pypi:`nuts`                                             Network Unit Testing System                                                                                                                                                                                                                                                                                                                                                             Nov 17, 2025    N/A                    pytest<8,>=7\n   :pypi:`pytest-abort`                                     Pytest plugin + helpers for attributing hard crashes (SIGSEGV/SIGABRT) to the last running test and keeping pytest-html reports mergeable.                                                                                                                                                                                                                                              Feb 11, 2026    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-abq`                                       Pytest integration for the ABQ universal test runner.                                                                                                                                                                                                                                                                                                                                   Apr 07, 2023    N/A                    N/A\n   :pypi:`pytest-abstracts`                                 A contextmanager pytest fixture for handling multiple mock abstracts                                                                                                                                                                                                                                                                                                                    May 25, 2022    N/A                    N/A\n   :pypi:`pytest-accept`                                                                                                                                                                                                                                                                                                                                                                                                                            Mar 01, 2026    N/A                    pytest>=7\n   :pypi:`pytest-adaptavist`                                pytest plugin for generating test execution results within Jira Test Management (tm4j)                                                                                                                                                                                                                                                                                                  Oct 13, 2022    N/A                    pytest (>=5.4.0)\n   :pypi:`pytest-adaptavist-fixed`                          pytest plugin for generating test execution results within Jira Test Management (tm4j)                                                                                                                                                                                                                                                                                                  Jan 17, 2025    N/A                    pytest>=5.4.0\n   :pypi:`pytest-adbc-replay`                               pytest plugin to record and replay ADBC database queries                                                                                                                                                                                                                                                                                                                                Mar 13, 2026    5 - Production/Stable  pytest>=8.0\n   :pypi:`pytest-addons-test`                               用于测试pytest的插件                                                                                                                                                                                                                                                                                                                                                                    Aug 02, 2021    N/A                    pytest (>=6.2.4,<7.0.0)\n   :pypi:`pytest-adf`                                       Pytest plugin for writing Azure Data Factory integration tests                                                                                                                                                                                                                                                                                                                          May 10, 2021    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-adf-azure-identity`                        Pytest plugin for writing Azure Data Factory integration tests                                                                                                                                                                                                                                                                                                                          Mar 06, 2021    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-ads-testplan`                              Azure DevOps Test Case reporting for pytest tests                                                                                                                                                                                                                                                                                                                                       Sep 15, 2022    N/A                    N/A\n   :pypi:`pytest-adversarial`                               Generate adversarial pytest tests using LLM                                                                                                                                                                                                                                                                                                                                             Jan 22, 2026    N/A                    pytest>=7.0.0\n   :pypi:`pytest-affected`                                                                                                                                                                                                                                                                                                                                                                                                                          Nov 06, 2023    N/A                    N/A\n   :pypi:`pytest-agent`                                     Service that exposes a REST API that can be used to interract remotely with Pytest. It is shipped with a dashboard that enables running tests in a more convenient way.                                                                                                                                                                                                                 Nov 25, 2021    N/A                    N/A\n   :pypi:`pytest-agentcontract`                             Deterministic CI tests for LLM agent trajectories — record once, replay offline, assert contracts                                                                                                                                                                                                                                                                                       Feb 18, 2026    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-agent-evals`                               Pytest plugin for evaluating AI Agents                                                                                                                                                                                                                                                                                                                                                  Mar 13, 2026    4 - Beta               pytest>=7.0\n   :pypi:`pytest-agents`                                    Pytest plugin framework with AI agent capabilities for multi-agent testing                                                                                                                                                                                                                                                                                                              Feb 20, 2026    3 - Alpha              pytest>=8.0.0\n   :pypi:`pytest-aggreport`                                 pytest plugin for pytest-repeat that generate aggregate report of the same test cases with additional statistics details.                                                                                                                                                                                                                                                               Mar 07, 2021    4 - Beta               pytest (>=6.2.2)\n   :pypi:`pytest-ai`                                        A Python package to generate regular, edge-case, and security HTTP tests.                                                                                                                                                                                                                                                                                                               Jan 22, 2025    N/A                    N/A\n   :pypi:`pytest-ai1899`                                    pytest plugin for connecting to ai1899 smart system stack                                                                                                                                                                                                                                                                                                                               Mar 13, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-aio`                                       Pytest plugin for testing async python code                                                                                                                                                                                                                                                                                                                                             Feb 12, 2026    5 - Production/Stable  pytest\n   :pypi:`pytest-aioboto3`                                  Aioboto3 Pytest with Moto                                                                                                                                                                                                                                                                                                                                                               Jan 17, 2025    N/A                    N/A\n   :pypi:`pytest-aiofiles`                                  pytest fixtures for writing aiofiles tests with pyfakefs                                                                                                                                                                                                                                                                                                                                May 14, 2017    5 - Production/Stable  N/A\n   :pypi:`pytest-aiogram`                                                                                                                                                                                                                                                                                                                                                                                                                           May 06, 2023    N/A                    N/A\n   :pypi:`pytest-aiohttp`                                   Pytest plugin for aiohttp support                                                                                                                                                                                                                                                                                                                                                       Jan 23, 2025    4 - Beta               pytest>=6.1.0\n   :pypi:`pytest-aiohttp-client`                            Pytest \\`client\\` fixture for the Aiohttp                                                                                                                                                                                                                                                                                                                                               Jan 10, 2023    N/A                    pytest (>=7.2.0,<8.0.0)\n   :pypi:`pytest-aiohttp-mock`                              Send responses to aiohttp.                                                                                                                                                                                                                                                                                                                                                              Sep 13, 2025    3 - Alpha              pytest>=8\n   :pypi:`pytest-aiohutils`                                 Pytest plugin providing fixtures and configuration for aiohutils projects (offline, record, cleanup modes).                                                                                                                                                                                                                                                                             Feb 10, 2026    N/A                    pytest\n   :pypi:`pytest-aiomoto`                                   pytest-aiomoto                                                                                                                                                                                                                                                                                                                                                                          Jun 24, 2023    N/A                    pytest (>=7.0,<8.0)\n   :pypi:`pytest-aioresponses`                              py.test integration for aioresponses                                                                                                                                                                                                                                                                                                                                                    Jan 02, 2025    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-aioworkers`                                A plugin to test aioworkers project with pytest                                                                                                                                                                                                                                                                                                                                         Dec 26, 2024    5 - Production/Stable  pytest>=8.3.4\n   :pypi:`pytest-airflow`                                   pytest support for airflow.                                                                                                                                                                                                                                                                                                                                                             Apr 03, 2019    3 - Alpha              pytest (>=4.4.0)\n   :pypi:`pytest-airflow-utils`                                                                                                                                                                                                                                                                                                                                                                                                                     Nov 15, 2021    N/A                    N/A\n   :pypi:`pytest-aitest`                                    Pytest plugin for testing AI agents with MCP and CLI servers                                                                                                                                                                                                                                                                                                                            Feb 20, 2026    3 - Alpha              pytest>=9.0\n   :pypi:`pytest-alembic`                                   A pytest plugin for verifying alembic migrations.                                                                                                                                                                                                                                                                                                                                       May 27, 2025    N/A                    pytest>=7.0\n   :pypi:`pytest-alerts`                                    A pytest plugin for sending test results to Slack and Telegram                                                                                                                                                                                                                                                                                                                          Feb 21, 2025    4 - Beta               pytest>=7.4.0\n   :pypi:`pytest-allclose`                                  Pytest fixture extending Numpy's allclose function                                                                                                                                                                                                                                                                                                                                      Jul 30, 2019    5 - Production/Stable  pytest\n   :pypi:`pytest-allure-adaptor`                            Plugin for py.test to generate allure xml reports                                                                                                                                                                                                                                                                                                                                       Jan 10, 2018    N/A                    pytest (>=2.7.3)\n   :pypi:`pytest-allure-adaptor2`                           Plugin for py.test to generate allure xml reports                                                                                                                                                                                                                                                                                                                                       Oct 14, 2020    N/A                    pytest (>=2.7.3)\n   :pypi:`pytest-allure-collection`                         pytest plugin to collect allure markers without running any tests                                                                                                                                                                                                                                                                                                                       Apr 13, 2023    N/A                    pytest\n   :pypi:`pytest-allure-dsl`                                pytest plugin to test case doc string dls instructions                                                                                                                                                                                                                                                                                                                                  Oct 25, 2020    4 - Beta               pytest\n   :pypi:`pytest-allure-host`                               Publish Allure static reports to private S3 behind CloudFront with history preservation                                                                                                                                                                                                                                                                                                 Nov 03, 2025    3 - Alpha              N/A\n   :pypi:`pytest-allure-id2history`                         Overwrite allure history id with testcase full name and testcase id if testcase has id, exclude parameters.                                                                                                                                                                                                                                                                             May 14, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-allure-intersection`                                                                                                                                                                                                                                                                                                                                                                                                               Oct 27, 2022    N/A                    pytest (<5)\n   :pypi:`pytest-allure-spec-coverage`                      The pytest plugin aimed to display test coverage of the specs(requirements) in Allure                                                                                                                                                                                                                                                                                                   Oct 26, 2021    N/A                    pytest\n   :pypi:`pytest-allure-step`                               Enhanced logging integration with Allure reports for pytest                                                                                                                                                                                                                                                                                                                             Jul 13, 2025    3 - Alpha              pytest>=6.0.0\n   :pypi:`pytest-alphamoon`                                 Static code checks used at Alphamoon                                                                                                                                                                                                                                                                                                                                                    Dec 30, 2021    5 - Production/Stable  pytest (>=3.5.0)\n   :pypi:`pytest-amaranth-sim`                              Fixture to automate running Amaranth simulations                                                                                                                                                                                                                                                                                                                                        Feb 18, 2026    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-ampel-core`                                A plugin to provide AmpelContext fixtures in pytest                                                                                                                                                                                                                                                                                                                                     Dec 17, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-analyzer`                                  this plugin allows to analyze tests in pytest project, collect test metadata and sync it with testomat.io TCM system                                                                                                                                                                                                                                                                    Feb 21, 2024    N/A                    pytest <8.0.0,>=7.3.1\n   :pypi:`pytest-android`                                   This fixture provides a configured \"driver\" for Android Automated Testing, using uiautomator2.                                                                                                                                                                                                                                                                                          Feb 21, 2019    3 - Alpha              pytest\n   :pypi:`pytest-anki`                                      A pytest plugin for testing Anki add-ons                                                                                                                                                                                                                                                                                                                                                Jul 31, 2022    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-annotate`                                  pytest-annotate: Generate PyAnnotate annotations from your pytest tests.                                                                                                                                                                                                                                                                                                                Jun 07, 2022    3 - Alpha              pytest (<8.0.0,>=3.2.0)\n   :pypi:`pytest-annotated`                                 Pytest plugin to allow use of Annotated in tests to resolve fixtures                                                                                                                                                                                                                                                                                                                    Sep 30, 2024    N/A                    pytest>=8.3.3\n   :pypi:`pytest-ansible`                                   Plugin for pytest to simplify calling ansible modules from tests or fixtures                                                                                                                                                                                                                                                                                                            Feb 24, 2026    5 - Production/Stable  pytest>=6\n   :pypi:`pytest-ansible-playbook`                          Pytest fixture which runs given ansible playbook file.                                                                                                                                                                                                                                                                                                                                  Mar 08, 2019    4 - Beta               N/A\n   :pypi:`pytest-ansible-playbook-runner`                   Pytest fixture which runs given ansible playbook file.                                                                                                                                                                                                                                                                                                                                  Dec 02, 2020    4 - Beta               pytest (>=3.1.0)\n   :pypi:`pytest-ansible-units`                             A pytest plugin for running unit tests within an ansible collection                                                                                                                                                                                                                                                                                                                     Apr 14, 2022    N/A                    N/A\n   :pypi:`pytest-antilru`                                   Bust functools.lru_cache when running pytest to avoid test pollution                                                                                                                                                                                                                                                                                                                    Jul 28, 2024    5 - Production/Stable  pytest>=7; python_version >= \"3.10\"\n   :pypi:`pytest-anyio`                                     The pytest anyio plugin is built into anyio. You don't need this package.                                                                                                                                                                                                                                                                                                               Jun 29, 2021    N/A                    pytest\n   :pypi:`pytest-anything`                                  Pytest fixtures to assert anything and something                                                                                                                                                                                                                                                                                                                                        Jan 18, 2024    N/A                    pytest\n   :pypi:`pytest-aoc`                                       Downloads puzzle inputs for Advent of Code and synthesizes PyTest fixtures                                                                                                                                                                                                                                                                                                              Dec 02, 2023    5 - Production/Stable  pytest ; extra == 'test'\n   :pypi:`pytest-aoreporter`                                pytest report                                                                                                                                                                                                                                                                                                                                                                           Jun 27, 2022    N/A                    N/A\n   :pypi:`pytest-api`                                       An ASGI middleware to populate OpenAPI Specification examples from pytest functions                                                                                                                                                                                                                                                                                                     May 12, 2022    N/A                    pytest (>=7.1.1,<8.0.0)\n   :pypi:`pytest-apibean`                                   Pytest plugin providing apibean-based API testing fixtures integrated with apibean-client, designed for testing apibean REST services and datacore backends.                                                                                                                                                                                                                            Dec 30, 2025    N/A                    pytest\n   :pypi:`pytest-api-cov`                                   Pytest Plugin to provide API Coverage statistics for Python Web Frameworks                                                                                                                                                                                                                                                                                                              Feb 05, 2026    N/A                    pytest>=6.0.0\n   :pypi:`pytest-api-framework`                             pytest framework                                                                                                                                                                                                                                                                                                                                                                        Jun 22, 2025    N/A                    pytest==7.2.2\n   :pypi:`pytest-api-framework-alpha`                                                                                                                                                                                                                                                                                                                                                                                                               Mar 03, 2026    N/A                    pytest==7.2.2\n   :pypi:`pytest-api-soup`                                  Validate multiple endpoints with unit testing using a single source of truth.                                                                                                                                                                                                                                                                                                           Aug 27, 2022    N/A                    N/A\n   :pypi:`pytest-apistellar`                                apistellar plugin for pytest.                                                                                                                                                                                                                                                                                                                                                           Jun 18, 2019    N/A                    N/A\n   :pypi:`pytest-apiver`                                                                                                                                                                                                                                                                                                                                                                                                                            Jun 21, 2024    N/A                    pytest\n   :pypi:`pytest-appengine`                                 AppEngine integration that works well with pytest-django                                                                                                                                                                                                                                                                                                                                Feb 27, 2017    N/A                    N/A\n   :pypi:`pytest-appium`                                    Pytest plugin for appium                                                                                                                                                                                                                                                                                                                                                                Dec 05, 2019    N/A                    N/A\n   :pypi:`pytest-approval`                                  A simple approval test library utilizing external diff programs such as PyCharm and Visual Studio Code to compare approved and received output.                                                                                                                                                                                                                                         Jan 27, 2026    N/A                    pytest>=8.3.5\n   :pypi:`pytest-approvaltests`                             A plugin to use approvaltests with pytest                                                                                                                                                                                                                                                                                                                                               May 08, 2022    4 - Beta               pytest (>=7.0.1)\n   :pypi:`pytest-approvaltests-geo`                         Extension for ApprovalTests.Python specific to geo data verification                                                                                                                                                                                                                                                                                                                    Jul 14, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-archon`                                    Rule your architecture like a real developer                                                                                                                                                                                                                                                                                                                                            Sep 19, 2025    5 - Production/Stable  pytest>=7.2\n   :pypi:`pytest-argus`                                     pyest results colection plugin                                                                                                                                                                                                                                                                                                                                                          Jun 24, 2021    5 - Production/Stable  pytest (>=6.2.4)\n   :pypi:`pytest-argus-reporter`                            A simple plugin to report results of test into argus                                                                                                                                                                                                                                                                                                                                    Mar 03, 2026    4 - Beta               pytest~=9.0.0; extra == \"dev\"\n   :pypi:`pytest-argus-server`                              A plugin that provides a running Argus API server for tests                                                                                                                                                                                                                                                                                                                             Mar 05, 2026    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-arrakis`                                   Pytest plugin providing Arrakis fixtures for testing                                                                                                                                                                                                                                                                                                                                    Mar 05, 2026    3 - Alpha              pytest\n   :pypi:`pytest-arraydiff`                                 pytest plugin to help with comparing array output from tests                                                                                                                                                                                                                                                                                                                            Nov 27, 2023    4 - Beta               pytest >=4.6\n   :pypi:`pytest-artifact`                                  Pytest plugin for managing test artifacts                                                                                                                                                                                                                                                                                                                                               Feb 09, 2026    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-asdf-plugin`                               Pytest plugin for testing ASDF schemas                                                                                                                                                                                                                                                                                                                                                  Aug 18, 2025    5 - Production/Stable  pytest>=7\n   :pypi:`pytest-asgi-server`                               Convenient ASGI client/server fixtures for Pytest                                                                                                                                                                                                                                                                                                                                       Dec 12, 2020    N/A                    pytest (>=5.4.1)\n   :pypi:`pytest-aspec`                                     A rspec format reporter for pytest                                                                                                                                                                                                                                                                                                                                                      Dec 20, 2023    4 - Beta               N/A\n   :pypi:`pytest-asptest`                                   test Answer Set Programming programs                                                                                                                                                                                                                                                                                                                                                    Apr 28, 2018    4 - Beta               N/A\n   :pypi:`pytest-assay`                                     Evaluation framework for Pydantic AI agents                                                                                                                                                                                                                                                                                                                                             Mar 04, 2026    4 - Beta               N/A\n   :pypi:`pytest-assertcount`                               Plugin to count actual number of asserts in pytest                                                                                                                                                                                                                                                                                                                                      Oct 23, 2022    N/A                    pytest (>=5.0.0)\n   :pypi:`pytest-assertions`                                Pytest Assertions                                                                                                                                                                                                                                                                                                                                                                       Apr 27, 2022    N/A                    N/A\n   :pypi:`pytest-assert-type`                               Use typing.assert_type() to test runtime behavior                                                                                                                                                                                                                                                                                                                                       Oct 26, 2025    3 - Alpha              pytest>=6.2.0\n   :pypi:`pytest-assertutil`                                pytest-assertutil                                                                                                                                                                                                                                                                                                                                                                       May 10, 2019    N/A                    N/A\n   :pypi:`pytest-assert-utils`                              Useful assertion utilities for use with pytest                                                                                                                                                                                                                                                                                                                                          Apr 14, 2022    3 - Alpha              N/A\n   :pypi:`pytest-assist`                                    pytest plugin library                                                                                                                                                                                                                                                                                                                                                                   Oct 29, 2025    4 - Beta               pytest\n   :pypi:`pytest-assume`                                    A pytest plugin that allows multiple failures per test                                                                                                                                                                                                                                                                                                                                  Jun 24, 2021    N/A                    pytest (>=2.7)\n   :pypi:`pytest-assurka`                                   A pytest plugin for Assurka Studio                                                                                                                                                                                                                                                                                                                                                      Aug 04, 2022    N/A                    N/A\n   :pypi:`pytest-ast-back-to-python`                        A plugin for pytest devs to view how assertion rewriting recodes the AST                                                                                                                                                                                                                                                                                                                Sep 29, 2019    4 - Beta               N/A\n   :pypi:`pytest-asteroid`                                  PyTest plugin for docker-based testing on database images                                                                                                                                                                                                                                                                                                                               Aug 15, 2022    N/A                    pytest (>=6.2.5,<8.0.0)\n   :pypi:`pytest-astropy`                                   Meta-package containing dependencies for testing                                                                                                                                                                                                                                                                                                                                        Sep 26, 2023    5 - Production/Stable  pytest >=4.6\n   :pypi:`pytest-astropy-header`                            pytest plugin to add diagnostic information to the header of the test output                                                                                                                                                                                                                                                                                                            Sep 06, 2022    3 - Alpha              pytest (>=4.6)\n   :pypi:`pytest-ast-transformer`                                                                                                                                                                                                                                                                                                                                                                                                                   May 04, 2019    3 - Alpha              pytest\n   :pypi:`pytest_async`                                     pytest-async - Run your coroutine in event loop without decorator                                                                                                                                                                                                                                                                                                                       Feb 26, 2020    N/A                    N/A\n   :pypi:`pytest-async-benchmark`                           pytest-async-benchmark: Modern pytest benchmarking for async code. 🚀                                                                                                                                                                                                                                                                                                                   May 28, 2025    N/A                    pytest>=8.3.5\n   :pypi:`pytest-async-generators`                          Pytest fixtures for async generators                                                                                                                                                                                                                                                                                                                                                    Jul 05, 2023    N/A                    N/A\n   :pypi:`pytest-asyncio`                                   Pytest support for asyncio                                                                                                                                                                                                                                                                                                                                                              Nov 10, 2025    5 - Production/Stable  pytest<10,>=8.2\n   :pypi:`pytest-asyncio-concurrent`                        Pytest plugin to execute python async tests concurrently.                                                                                                                                                                                                                                                                                                                               May 17, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-asyncio-cooperative`                       Run all your asynchronous tests cooperatively.                                                                                                                                                                                                                                                                                                                                          Jun 24, 2025    N/A                    N/A\n   :pypi:`pytest-asyncio-network-simulator`                 pytest-asyncio-network-simulator: Plugin for pytest for simulator the network in tests                                                                                                                                                                                                                                                                                                  Jul 31, 2018    3 - Alpha              pytest (<3.7.0,>=3.3.2)\n   :pypi:`pytest-async-mongodb`                             pytest plugin for async MongoDB                                                                                                                                                                                                                                                                                                                                                         Oct 18, 2017    5 - Production/Stable  pytest (>=2.5.2)\n   :pypi:`pytest-async-sqlalchemy`                          Database testing fixtures using the SQLAlchemy asyncio API                                                                                                                                                                                                                                                                                                                              Oct 07, 2021    4 - Beta               pytest (>=6.0.0)\n   :pypi:`pytest-atf-allure`                                基于allure-pytest进行自定义                                                                                                                                                                                                                                                                                                                                                             Nov 29, 2023    N/A                    pytest (>=7.4.2,<8.0.0)\n   :pypi:`pytest-atomic`                                    Skip rest of tests if previous test failed.                                                                                                                                                                                                                                                                                                                                             Nov 24, 2018    4 - Beta               N/A\n   :pypi:`pytest-atstack`                                   A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Jan 02, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-attempt-summary`                           Enhanced Allure Attempt Summary for Playwright + Pytest                                                                                                                                                                                                                                                                                                                                 Jan 04, 2026    N/A                    pytest>=7.0\n   :pypi:`pytest-attrib`                                    pytest plugin to select tests based on attributes similar to the nose-attrib plugin                                                                                                                                                                                                                                                                                                     May 24, 2016    4 - Beta               N/A\n   :pypi:`pytest-attributes`                                A plugin that allows users to add attributes to their tests. These attributes can then be referenced by fixtures or the test itself.                                                                                                                                                                                                                                                    Jun 24, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-audioeval`                                 Pytest plugin for STT/TTS integration testing with httpx, metrics, and embedded audio samples.                                                                                                                                                                                                                                                                                          Mar 13, 2026    4 - Beta               pytest>=8.0\n   :pypi:`pytest-austin`                                    Austin plugin for pytest                                                                                                                                                                                                                                                                                                                                                                Oct 11, 2020    4 - Beta               N/A\n   :pypi:`pytest-autocap`                                   automatically capture test & fixture stdout/stderr to files                                                                                                                                                                                                                                                                                                                             May 15, 2022    N/A                    pytest (<7.2,>=7.1.2)\n   :pypi:`pytest-autochecklog`                              automatically check condition and log all the checks                                                                                                                                                                                                                                                                                                                                    Apr 25, 2015    4 - Beta               N/A\n   :pypi:`pytest-autofixture`                               simplify pytest fixtures                                                                                                                                                                                                                                                                                                                                                                Aug 01, 2024    N/A                    pytest>=8\n   :pypi:`pytest-autofocus`                                 Auto-focus plugin: run only @pytest.mark.focus tests when --auto-focus is set                                                                                                                                                                                                                                                                                                           Dec 02, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-automation`                                pytest plugin for building a test suite, using YAML files to extend pytest parameterize functionality.                                                                                                                                                                                                                                                                                  Apr 24, 2024    N/A                    pytest>=7.0.0\n   :pypi:`pytest-automock`                                  Pytest plugin for automatical mocks creation                                                                                                                                                                                                                                                                                                                                            May 16, 2023    N/A                    pytest ; extra == 'dev'\n   :pypi:`pytest-auto-parametrize`                          pytest plugin: avoid repeating arguments in parametrize                                                                                                                                                                                                                                                                                                                                 Oct 02, 2016    3 - Alpha              N/A\n   :pypi:`pytest-autoprofile`                               \\`line_profiler.autoprofile\\`-ing your \\`pytest\\` test suite                                                                                                                                                                                                                                                                                                                            Mar 13, 2026    4 - Beta               pytest>=7.0\n   :pypi:`pytest-autotest`                                  This fixture provides a configured \"driver\" for Android Automated Testing, using uiautomator2.                                                                                                                                                                                                                                                                                          Aug 25, 2021    N/A                    pytest\n   :pypi:`pytest-aviator`                                   Aviator's Flakybot pytest plugin that automatically reruns flaky tests.                                                                                                                                                                                                                                                                                                                 Nov 04, 2022    4 - Beta               pytest\n   :pypi:`pytest-avoidance`                                 Makes pytest skip tests that don not need rerunning                                                                                                                                                                                                                                                                                                                                     May 23, 2019    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-awaiting-fix`                              A simple plugin to use with pytest for traceability across Jira and disabled automated tests                                                                                                                                                                                                                                                                                            Aug 09, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-aws`                                       pytest plugin for testing AWS resource configurations                                                                                                                                                                                                                                                                                                                                   Oct 04, 2017    4 - Beta               N/A\n   :pypi:`pytest-aws-apigateway`                            pytest plugin for AWS ApiGateway                                                                                                                                                                                                                                                                                                                                                        May 24, 2024    4 - Beta               pytest\n   :pypi:`pytest-aws-config`                                Protect your AWS credentials in unit tests                                                                                                                                                                                                                                                                                                                                              May 28, 2021    N/A                    N/A\n   :pypi:`pytest-aws-fixtures`                              A series of fixtures to use in integration tests involving actual AWS services.                                                                                                                                                                                                                                                                                                         Nov 11, 2025    N/A                    pytest<10.0.0,>=8.0.0\n   :pypi:`pytest-aws-fixtures-293984`                       AWS configuration utilities for Python applications                                                                                                                                                                                                                                                                                                                                     Dec 04, 2025    3 - Alpha              N/A\n   :pypi:`pytest-axe`                                       pytest plugin for axe-selenium-python                                                                                                                                                                                                                                                                                                                                                   Nov 12, 2018    N/A                    pytest (>=3.0.0)\n   :pypi:`pytest-axe-playwright-snapshot`                   A pytest plugin that runs Axe-core on Playwright pages and takes snapshots of the results.                                                                                                                                                                                                                                                                                              Jul 25, 2023    N/A                    pytest\n   :pypi:`pytest-azure`                                     Pytest utilities and mocks for Azure                                                                                                                                                                                                                                                                                                                                                    Jan 18, 2023    3 - Alpha              pytest\n   :pypi:`pytest-azure-devops`                              Simplifies using azure devops parallel strategy (https://docs.microsoft.com/en-us/azure/devops/pipelines/test/parallel-testing-any-test-runner) with pytest.                                                                                                                                                                                                                            Jul 16, 2025    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-azurepipelines`                            Formatting PyTest output for Azure Pipelines UI                                                                                                                                                                                                                                                                                                                                         Oct 06, 2023    5 - Production/Stable  pytest (>=5.0.0)\n   :pypi:`pytest-bandit`                                    A bandit plugin for pytest                                                                                                                                                                                                                                                                                                                                                              Feb 23, 2021    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-bandit-xayon`                              A bandit plugin for pytest                                                                                                                                                                                                                                                                                                                                                              Oct 17, 2022    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-base-url`                                  pytest plugin for URL based testing                                                                                                                                                                                                                                                                                                                                                     Jan 31, 2024    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-bashdoctest`                               A pytest plugin for testing bash command examples in markdown documentation                                                                                                                                                                                                                                                                                                             Oct 03, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-batch-regression`                          A pytest plugin to repeat the entire test suite in batches.                                                                                                                                                                                                                                                                                                                             May 08, 2024    N/A                    pytest>=6.0.0\n   :pypi:`pytest-bazel`                                     A pytest runner with bazel support                                                                                                                                                                                                                                                                                                                                                      Oct 31, 2025    4 - Beta               pytest\n   :pypi:`pytest-bdd`                                       BDD for pytest                                                                                                                                                                                                                                                                                                                                                                          Dec 05, 2024    6 - Mature             pytest>=7.0.0\n   :pypi:`pytest-bdd-html`                                  pytest plugin to display BDD info in HTML test report                                                                                                                                                                                                                                                                                                                                   Nov 22, 2022    3 - Alpha              pytest (!=6.0.0,>=5.0)\n   :pypi:`pytest-bdd-md-report`                             Markdown test report formatter for pytest-bdd with pytest-playwright screenshot support                                                                                                                                                                                                                                                                                                 Feb 07, 2026    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-bdd-ng`                                    BDD for pytest                                                                                                                                                                                                                                                                                                                                                                          Nov 26, 2024    4 - Beta               pytest>=5.2\n   :pypi:`pytest-bdd-property`                              Property-based testing plugin for pytest-bdd — express universal invariants in standard Gherkin, executed by Hypothesis                                                                                                                                                                                                                                                                 Mar 12, 2026    3 - Alpha              pytest>=8.0\n   :pypi:`pytest-bdd-report`                                A pytest-bdd plugin for generating useful and informative BDD test reports                                                                                                                                                                                                                                                                                                              Dec 29, 2025    N/A                    pytest>=7.1.3\n   :pypi:`pytest-bdd-reporter`                              Enterprise-grade BDD test reporting with interactive dashboards, suite management, and comprehensive email integration                                                                                                                                                                                                                                                                  Oct 14, 2025    5 - Production/Stable  pytest>=6.0.0\n   :pypi:`pytest-bdd-splinter`                              Common steps for pytest bdd and splinter integration                                                                                                                                                                                                                                                                                                                                    Aug 12, 2019    5 - Production/Stable  pytest (>=4.0.0)\n   :pypi:`pytest-bdd-web`                                   A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Jan 02, 2020    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-bdd-wrappers`                                                                                                                                                                                                                                                                                                                                                                                                                      Feb 11, 2020    2 - Pre-Alpha          N/A\n   :pypi:`pytest-beakerlib`                                 A pytest plugin that reports test results to the BeakerLib framework                                                                                                                                                                                                                                                                                                                    Mar 17, 2017    5 - Production/Stable  pytest\n   :pypi:`pytest-beartype`                                  Pytest plugin to run your tests with beartype checking enabled.                                                                                                                                                                                                                                                                                                                         Oct 31, 2024    N/A                    pytest\n   :pypi:`pytest-bec-e2e`                                   BEC pytest plugin for end-to-end tests                                                                                                                                                                                                                                                                                                                                                  Mar 13, 2026    3 - Alpha              pytest\n   :pypi:`pytest-beds`                                      Fixtures for testing Google Appengine (GAE) apps                                                                                                                                                                                                                                                                                                                                        Jun 07, 2016    4 - Beta               N/A\n   :pypi:`pytest-beeprint`                                  use icdiff for better error messages in pytest assertions                                                                                                                                                                                                                                                                                                                               Jul 04, 2023    4 - Beta               N/A\n   :pypi:`pytest-bench`                                     Benchmark utility that plugs into pytest.                                                                                                                                                                                                                                                                                                                                               Jul 21, 2014    3 - Alpha              N/A\n   :pypi:`pytest-benchmark`                                 A \\`\\`pytest\\`\\` fixture for benchmarking code. It will group the tests into rounds that are calibrated to the chosen timer.                                                                                                                                                                                                                                                            Nov 09, 2025    5 - Production/Stable  pytest>=8.1\n   :pypi:`pytest-better-datadir`                            A small example package                                                                                                                                                                                                                                                                                                                                                                 Mar 13, 2023    N/A                    N/A\n   :pypi:`pytest-better-parametrize`                        Better description of parametrized test cases                                                                                                                                                                                                                                                                                                                                           Mar 05, 2024    4 - Beta               pytest >=6.2.0\n   :pypi:`pytest-bg-process`                                Pytest plugin to initialize background process                                                                                                                                                                                                                                                                                                                                          Jan 24, 2022    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-bigchaindb`                                A BigchainDB plugin for pytest.                                                                                                                                                                                                                                                                                                                                                         Jan 24, 2022    4 - Beta               N/A\n   :pypi:`pytest-bigquery-mock`                             Provides a mock fixture for python bigquery client                                                                                                                                                                                                                                                                                                                                      Dec 28, 2022    N/A                    pytest (>=5.0)\n   :pypi:`pytest-bisect-tests`                              Find tests leaking state and affecting other                                                                                                                                                                                                                                                                                                                                            Jun 09, 2024    N/A                    N/A\n   :pypi:`pytest-black`                                     A pytest plugin to enable format checking with black                                                                                                                                                                                                                                                                                                                                    Dec 15, 2024    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-black-multipy`                             Allow '--black' on older Pythons                                                                                                                                                                                                                                                                                                                                                        Jan 14, 2021    5 - Production/Stable  pytest (!=3.7.3,>=3.5) ; extra == 'testing'\n   :pypi:`pytest-black-ng`                                  A pytest plugin to enable format checking with black                                                                                                                                                                                                                                                                                                                                    Oct 20, 2022    4 - Beta               pytest (>=7.0.0)\n   :pypi:`pytest-blame`                                     A pytest plugin helps developers to debug by providing useful commits history.                                                                                                                                                                                                                                                                                                          May 04, 2019    N/A                    pytest (>=4.4.0)\n   :pypi:`pytest-blender`                                   Blender Pytest plugin.                                                                                                                                                                                                                                                                                                                                                                  Jun 25, 2025    N/A                    pytest\n   :pypi:`pytest-blink1`                                    Pytest plugin to emit notifications via the Blink(1) RGB LED                                                                                                                                                                                                                                                                                                                            Jan 07, 2018    4 - Beta               N/A\n   :pypi:`pytest-blockage`                                  Disable network requests during a test run.                                                                                                                                                                                                                                                                                                                                             Dec 21, 2021    N/A                    pytest\n   :pypi:`pytest-blocker`                                   pytest plugin to mark a test as blocker and skip all other tests                                                                                                                                                                                                                                                                                                                        Sep 07, 2015    4 - Beta               N/A\n   :pypi:`pytest-b-logger`                                  BLogger is a Pytest plugin for enhanced test logging and generating convenient and lightweight reports.                                                                                                                                                                                                                                                                                 Dec 16, 2025    N/A                    pytest\n   :pypi:`pytest-blue`                                      A pytest plugin that adds a \\`blue\\` fixture for printing stuff in blue.                                                                                                                                                                                                                                                                                                                Sep 05, 2022    N/A                    N/A\n   :pypi:`pytest-board`                                     Local continuous test runner with pytest and watchdog.                                                                                                                                                                                                                                                                                                                                  Jan 20, 2019    N/A                    N/A\n   :pypi:`pytest-boardfarm3`                                Integrate boardfarm as a pytest plugin.                                                                                                                                                                                                                                                                                                                                                 Sep 15, 2025    N/A                    pytest\n   :pypi:`pytest-boilerplate`                               The pytest plugin for your Django Boilerplate.                                                                                                                                                                                                                                                                                                                                          Sep 12, 2024    5 - Production/Stable  pytest>=4.0.0\n   :pypi:`pytest-bonsai`                                                                                                                                                                                                                                                                                                                                                                                                                            Apr 08, 2025    N/A                    pytest>=6\n   :pypi:`pytest-boost-xml`                                 Plugin for pytest to generate boost xml reports                                                                                                                                                                                                                                                                                                                                         Nov 30, 2022    4 - Beta               N/A\n   :pypi:`pytest-bootstrap`                                                                                                                                                                                                                                                                                                                                                                                                                         Mar 04, 2022    N/A                    N/A\n   :pypi:`pytest-boto-mock`                                 Thin-wrapper around the mock package for easier use with pytest                                                                                                                                                                                                                                                                                                                         Jan 20, 2026    5 - Production/Stable  pytest>=8.2.0\n   :pypi:`pytest-bpdb`                                      A py.test plug-in to enable drop to bpdb debugger on test failure.                                                                                                                                                                                                                                                                                                                      Jan 19, 2015    2 - Pre-Alpha          N/A\n   :pypi:`pytest-bq`                                        BigQuery fixtures and fixture factories for Pytest.                                                                                                                                                                                                                                                                                                                                     May 08, 2024    5 - Production/Stable  pytest>=6.2\n   :pypi:`pytest-bravado`                                   Pytest-bravado automatically generates from OpenAPI specification client fixtures.                                                                                                                                                                                                                                                                                                      Feb 15, 2022    N/A                    N/A\n   :pypi:`pytest-breadcrumb`                                Self-healing test framework for Playwright. Your tests survive app changes.                                                                                                                                                                                                                                                                                                             Mar 09, 2026    2 - Pre-Alpha          pytest>=8.0; extra == \"dev\"\n   :pypi:`pytest-breakword`                                 Use breakword with pytest                                                                                                                                                                                                                                                                                                                                                               Aug 04, 2021    N/A                    pytest (>=6.2.4,<7.0.0)\n   :pypi:`pytest-breed-adapter`                             A simple plugin to connect with breed-server                                                                                                                                                                                                                                                                                                                                            Nov 07, 2018    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-briefcase`                                 A pytest plugin for running tests on a Briefcase project.                                                                                                                                                                                                                                                                                                                               Jun 14, 2020    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-brightest`                                 Bright ideas for improving your pytest experience                                                                                                                                                                                                                                                                                                                                       Jul 15, 2025    3 - Alpha              pytest>=8.4.1\n   :pypi:`pytest-broadcaster`                               Pytest plugin to broadcast pytest output to various destinations                                                                                                                                                                                                                                                                                                                        Mar 02, 2025    3 - Alpha              pytest\n   :pypi:`pytest-browser`                                   A pytest plugin for console based browser test selection just after the collection phase                                                                                                                                                                                                                                                                                                Dec 10, 2016    3 - Alpha              N/A\n   :pypi:`pytest-browsermob-proxy`                          BrowserMob proxy plugin for py.test.                                                                                                                                                                                                                                                                                                                                                    Jun 11, 2013    4 - Beta               N/A\n   :pypi:`pytest_browserstack`                              Py.test plugin for BrowserStack                                                                                                                                                                                                                                                                                                                                                         Jan 27, 2016    4 - Beta               N/A\n   :pypi:`pytest-browserstack-local`                        \\`\\`py.test\\`\\` plugin to run \\`\\`BrowserStackLocal\\`\\` in background.                                                                                                                                                                                                                                                                                                                  Feb 09, 2018    N/A                    N/A\n   :pypi:`pytest-budosystems`                               Budo Systems is a martial arts school management system. This module is the Budo Systems Pytest Plugin.                                                                                                                                                                                                                                                                                 May 07, 2023    3 - Alpha              pytest\n   :pypi:`pytest-bug`                                       Pytest plugin for marking tests as a bug                                                                                                                                                                                                                                                                                                                                                Dec 30, 2025    5 - Production/Stable  pytest>=9.0.0\n   :pypi:`pytest-bugtong-tag`                               pytest-bugtong-tag is a plugin for pytest                                                                                                                                                                                                                                                                                                                                               Jan 16, 2022    N/A                    N/A\n   :pypi:`pytest-bugzilla`                                  py.test bugzilla integration plugin                                                                                                                                                                                                                                                                                                                                                     May 05, 2010    4 - Beta               N/A\n   :pypi:`pytest-bugzilla-notifier`                         A plugin that allows you to execute create, update, and read information from BugZilla bugs                                                                                                                                                                                                                                                                                             Jun 15, 2018    4 - Beta               pytest (>=2.9.2)\n   :pypi:`pytest-buildkite`                                 Plugin for pytest that automatically publishes coverage and pytest report annotations to Buildkite.                                                                                                                                                                                                                                                                                     Jul 13, 2019    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-builtin-types`                                                                                                                                                                                                                                                                                                                                                                                                                     Nov 17, 2021    N/A                    pytest\n   :pypi:`pytest-bwrap`                                     Run your tests in Bubblewrap sandboxes                                                                                                                                                                                                                                                                                                                                                  Feb 25, 2024    3 - Alpha              N/A\n   :pypi:`pytest-cache`                                     pytest plugin with mechanisms for caching across test runs                                                                                                                                                                                                                                                                                                                              Jun 04, 2013    3 - Alpha              N/A\n   :pypi:`pytest-cache-assert`                              Cache assertion data to simplify regression testing of complex serializable data                                                                                                                                                                                                                                                                                                        Aug 14, 2023    5 - Production/Stable  pytest (>=6.0.0)\n   :pypi:`pytest-cagoule`                                   Pytest plugin to only run tests affected by changes                                                                                                                                                                                                                                                                                                                                     Jan 01, 2020    3 - Alpha              N/A\n   :pypi:`pytest-cairo`                                     Pytest support for cairo-lang and starknet                                                                                                                                                                                                                                                                                                                                              Apr 17, 2022    N/A                    pytest\n   :pypi:`pytest-call-checker`                              Small pytest utility to easily create test doubles                                                                                                                                                                                                                                                                                                                                      Oct 16, 2022    4 - Beta               pytest (>=7.1.3,<8.0.0)\n   :pypi:`pytest-camel-collect`                             Enable CamelCase-aware pytest class collection                                                                                                                                                                                                                                                                                                                                          Aug 02, 2020    N/A                    pytest (>=2.9)\n   :pypi:`pytest-canonical-data`                            A plugin which allows to compare results with canonical results, based on previous runs                                                                                                                                                                                                                                                                                                 May 08, 2020    2 - Pre-Alpha          pytest (>=3.5.0)\n   :pypi:`pytest-canvas`                                    A minimal pytest plugin that streamlines testing for projects using the Canvas SDK.                                                                                                                                                                                                                                                                                                     Jul 22, 2025    N/A                    pytest<9,>=8.4\n   :pypi:`pytest-caprng`                                    A plugin that replays pRNG state on failure.                                                                                                                                                                                                                                                                                                                                            May 02, 2018    4 - Beta               N/A\n   :pypi:`pytest-capsqlalchemy`                             Pytest plugin to allow capturing SQLAlchemy queries.                                                                                                                                                                                                                                                                                                                                    Mar 19, 2025    4 - Beta               N/A\n   :pypi:`pytest-capture-deprecatedwarnings`                pytest plugin to capture all deprecatedwarnings and put them in one file                                                                                                                                                                                                                                                                                                                Apr 30, 2019    N/A                    N/A\n   :pypi:`pytest-capture-warnings`                          pytest plugin to capture all warnings and put them in one file of your choice                                                                                                                                                                                                                                                                                                           May 03, 2022    N/A                    pytest\n   :pypi:`pytest-case`                                      A clean, modern, wrapper for pytest.mark.parametrize                                                                                                                                                                                                                                                                                                                                    Nov 25, 2024    N/A                    pytest<9.0.0,>=8.3.3\n   :pypi:`pytest-case-provider`                             Advanced pytest parametrization plugin that generates test case instances from sync or async factories.                                                                                                                                                                                                                                                                                 Dec 15, 2025    3 - Alpha              pytest>=8\n   :pypi:`pytest-cases`                                     Separate test code from test cases in pytest.                                                                                                                                                                                                                                                                                                                                           Mar 02, 2026    5 - Production/Stable  pytest\n   :pypi:`pytest-case-start-from`                           A pytest plugin to start test execution from a specific test case                                                                                                                                                                                                                                                                                                                       Oct 28, 2025    4 - Beta               pytest>=6.0.0\n   :pypi:`pytest-casewise-package-install`                  A pytest plugin for test case-level dynamic dependency management                                                                                                                                                                                                                                                                                                                       Oct 31, 2025    3 - Alpha              pytest>=6.0.0\n   :pypi:`pytest-cassandra`                                 Cassandra CCM Test Fixtures for pytest                                                                                                                                                                                                                                                                                                                                                  Nov 04, 2017    1 - Planning           N/A\n   :pypi:`pytest-catchlog`                                  py.test plugin to catch log messages. This is a fork of pytest-capturelog.                                                                                                                                                                                                                                                                                                              Jan 24, 2016    4 - Beta               pytest (>=2.6)\n   :pypi:`pytest-catch-server`                              Pytest plugin with server for catching HTTP requests.                                                                                                                                                                                                                                                                                                                                   Dec 12, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-cdist`                                     A pytest plugin to split your test suite into multiple parts                                                                                                                                                                                                                                                                                                                            Jan 08, 2026    N/A                    pytest>=8\n   :pypi:`pytest-celery`                                    Pytest plugin for Celery                                                                                                                                                                                                                                                                                                                                                                Mar 02, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-celery-py37`                               Pytest plugin for Celery (compatible with python 3.7)                                                                                                                                                                                                                                                                                                                                   May 23, 2025    5 - Production/Stable  N/A\n   :pypi:`pytest-celery-utils`                              Pytest plugin for inspecting Celery task queues in Redis during tests                                                                                                                                                                                                                                                                                                                   Jan 28, 2026    N/A                    pytest>=9.0.1\n   :pypi:`pytest-cfg-fetcher`                               Pass config options to your unit tests.                                                                                                                                                                                                                                                                                                                                                 Feb 26, 2024    N/A                    N/A\n   :pypi:`pytest-chainmaker`                                pytest plugin for chainmaker                                                                                                                                                                                                                                                                                                                                                            Oct 15, 2021    N/A                    N/A\n   :pypi:`pytest-chalice`                                   A set of py.test fixtures for AWS Chalice                                                                                                                                                                                                                                                                                                                                               Jul 01, 2020    4 - Beta               N/A\n   :pypi:`pytest-change-assert`                             修改报错中文为英文                                                                                                                                                                                                                                                                                                                                                                      Oct 19, 2022    N/A                    N/A\n   :pypi:`pytest-change-demo`                               turn . into √，turn F into x                                                                                                                                                                                                                                                                                                                                                            Mar 02, 2022    N/A                    pytest\n   :pypi:`pytest-change-report`                             turn . into √，turn F into x                                                                                                                                                                                                                                                                                                                                                            Sep 14, 2020    N/A                    pytest\n   :pypi:`pytest-change-xds`                                turn . into √，turn F into x                                                                                                                                                                                                                                                                                                                                                            Apr 16, 2022    N/A                    pytest\n   :pypi:`pytest-chdir`                                     A pytest fixture for changing current working directory                                                                                                                                                                                                                                                                                                                                 Jan 28, 2020    N/A                    pytest (>=5.0.0,<6.0.0)\n   :pypi:`pytest-check`                                     A pytest plugin that allows multiple failures per test.                                                                                                                                                                                                                                                                                                                                 Mar 05, 2026    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-checkdocs`                                 check the README when running tests                                                                                                                                                                                                                                                                                                                                                     Dec 26, 2025    5 - Production/Stable  pytest!=8.1.*,>=6; extra == \"test\"\n   :pypi:`pytest-checkers`                                  Pytest Plugin for dry-run checks LSPs, Type Checkers, Linters, and Formatters during testing                                                                                                                                                                                                                                                                                            Dec 27, 2025    N/A                    pytest>=9.0.2\n   :pypi:`pytest-checkipdb`                                 plugin to check if there are ipdb debugs left                                                                                                                                                                                                                                                                                                                                           Dec 04, 2023    5 - Production/Stable  pytest >=2.9.2\n   :pypi:`pytest-check-library`                             check your missing library                                                                                                                                                                                                                                                                                                                                                              Jul 17, 2022    N/A                    N/A\n   :pypi:`pytest-check-libs`                                check your missing library                                                                                                                                                                                                                                                                                                                                                              Jul 17, 2022    N/A                    N/A\n   :pypi:`pytest-check-links`                               Check links in files                                                                                                                                                                                                                                                                                                                                                                    Jul 29, 2020    N/A                    pytest<9,>=7.0\n   :pypi:`pytest-checklist`                                 Pytest plugin to track and report unit/function coverage.                                                                                                                                                                                                                                                                                                                               May 23, 2025    N/A                    N/A\n   :pypi:`pytest-check-mk`                                  pytest plugin to test Check_MK checks                                                                                                                                                                                                                                                                                                                                                   Nov 19, 2015    4 - Beta               pytest\n   :pypi:`pytest-checkpoint`                                Restore a checkpoint in pytest                                                                                                                                                                                                                                                                                                                                                          Oct 04, 2025    N/A                    pytest>=8.0.0\n   :pypi:`pytest-ch-framework`                              My pytest framework                                                                                                                                                                                                                                                                                                                                                                     Apr 17, 2024    N/A                    pytest==8.0.1\n   :pypi:`pytest-chic-report`                               Simple pytest plugin for generating and sending report to messengers.                                                                                                                                                                                                                                                                                                                   Nov 01, 2024    N/A                    pytest>=6.0\n   :pypi:`pytest-chinesereport`                                                                                                                                                                                                                                                                                                                                                                                                                     Apr 16, 2025    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-choose`                                    Provide the pytest with the ability to collect use cases based on rules in text files                                                                                                                                                                                                                                                                                                   Feb 04, 2024    N/A                    pytest >=7.0.0\n   :pypi:`pytest-chronicle`                                 Reusable pytest results ingestion tooling with database export and CLI helpers.                                                                                                                                                                                                                                                                                                         Dec 15, 2025    N/A                    pytest>=8.0; extra == \"dev\"\n   :pypi:`pytest-chunks`                                    Run only a chunk of your test suite                                                                                                                                                                                                                                                                                                                                                     Jul 05, 2022    N/A                    pytest (>=6.0.0)\n   :pypi:`pytest_cid`                                       Compare data structures containing matching CIDs of different versions and encoding                                                                                                                                                                                                                                                                                                     Sep 01, 2023    4 - Beta               pytest >= 5.0, < 7.0\n   :pypi:`pytest-circleci`                                  py.test plugin for CircleCI                                                                                                                                                                                                                                                                                                                                                             May 03, 2019    N/A                    N/A\n   :pypi:`pytest-circleci-parallelized`                     Parallelize pytest across CircleCI workers.                                                                                                                                                                                                                                                                                                                                             Oct 20, 2022    N/A                    N/A\n   :pypi:`pytest-circleci-parallelized-rjp`                 Parallelize pytest across CircleCI workers.                                                                                                                                                                                                                                                                                                                                             Jun 21, 2022    N/A                    pytest\n   :pypi:`pytest-ckan`                                      Backport of CKAN 2.9 pytest plugin and fixtures to CAKN 2.8                                                                                                                                                                                                                                                                                                                             Apr 28, 2020    4 - Beta               pytest\n   :pypi:`pytest-clab`                                      A pytest plugin for managing containerlab topologies in tests.                                                                                                                                                                                                                                                                                                                          Mar 02, 2026    N/A                    pytest>=9.0.2\n   :pypi:`pytest-clarity`                                   A plugin providing an alternative, colourful diff output for failing assertions.                                                                                                                                                                                                                                                                                                        Jun 11, 2021    N/A                    N/A\n   :pypi:`pytest-class-fixtures`                            Class as PyTest fixtures (and BDD steps)                                                                                                                                                                                                                                                                                                                                                Nov 15, 2024    N/A                    pytest<9.0.0,>=8.3.3\n   :pypi:`pytest-claude-agent-sdk`                          Use Claude Code in your pytests, or pytest your own Claude Code agents — or both                                                                                                                                                                                                                                                                                                        Jan 19, 2026    3 - Alpha              pytest>=6.0\n   :pypi:`pytest-cldf`                                      Easy quality control for CLDF datasets using pytest                                                                                                                                                                                                                                                                                                                                     Nov 07, 2022    N/A                    pytest (>=3.6)\n   :pypi:`pytest-clean-database`                            A pytest plugin that cleans your database up after every test.                                                                                                                                                                                                                                                                                                                          Mar 14, 2025    3 - Alpha              pytest<9,>=7.0\n   :pypi:`pytest-cleanslate`                                Collects and executes pytest tests separately                                                                                                                                                                                                                                                                                                                                           Apr 10, 2025    N/A                    pytest\n   :pypi:`pytest_cleanup`                                   Automated, comprehensive and well-organised pytest test cases.                                                                                                                                                                                                                                                                                                                          Jan 28, 2020    N/A                    N/A\n   :pypi:`pytest-cleanuptotal`                              A cleanup plugin for pytest                                                                                                                                                                                                                                                                                                                                                             Jul 22, 2025    5 - Production/Stable  N/A\n   :pypi:`pytest-clerk`                                     A set of pytest fixtures to help with integration testing with Clerk.                                                                                                                                                                                                                                                                                                                   Feb 04, 2026    N/A                    pytest<10.0.0,>=8.0.0\n   :pypi:`pytest-clerk-mock`                                A pytest plugin for mocking Clerk authentication                                                                                                                                                                                                                                                                                                                                        Mar 14, 2026    N/A                    N/A\n   :pypi:`pytest-cli2-ansible`                                                                                                                                                                                                                                                                                                                                                                                                                      Mar 05, 2025    N/A                    N/A\n   :pypi:`pytest-click`                                     Pytest plugin for Click                                                                                                                                                                                                                                                                                                                                                                 Feb 11, 2022    5 - Production/Stable  pytest (>=5.0)\n   :pypi:`pytest-cli-fixtures`                              Automatically register fixtures for custom CLI arguments                                                                                                                                                                                                                                                                                                                                Jul 28, 2022    N/A                    pytest (~=7.0)\n   :pypi:`pytest-clld`                                                                                                                                                                                                                                                                                                                                                                                                                              Oct 23, 2024    N/A                    pytest>=3.9\n   :pypi:`pytest-cloud`                                     Distributed tests planner plugin for pytest testing framework.                                                                                                                                                                                                                                                                                                                          Oct 05, 2020    6 - Mature             N/A\n   :pypi:`pytest-cloudflare-worker`                         pytest plugin for testing cloudflare workers                                                                                                                                                                                                                                                                                                                                            Mar 30, 2021    4 - Beta               pytest (>=6.0.0)\n   :pypi:`pytest-cloudist`                                  Distribute tests to cloud machines without fuss                                                                                                                                                                                                                                                                                                                                         Sep 02, 2022    4 - Beta               pytest (>=7.1.2,<8.0.0)\n   :pypi:`pytest-cmake`                                     Provide CMake module for Pytest                                                                                                                                                                                                                                                                                                                                                         Jan 03, 2026    N/A                    pytest<10,>=4\n   :pypi:`pytest-cmake-presets`                             Execute CMake Presets via pytest                                                                                                                                                                                                                                                                                                                                                        Dec 26, 2022    N/A                    pytest (>=7.2.0,<8.0.0)\n   :pypi:`pytest-cmdline-add-args`                          Pytest plugin for custom argument handling and Allure reporting. This plugin allows you to add arguments before running a test.                                                                                                                                                                                                                                                         Sep 01, 2024    N/A                    N/A\n   :pypi:`pytest-cobra`                                     PyTest plugin for testing Smart Contracts for Ethereum blockchain.                                                                                                                                                                                                                                                                                                                      Jun 29, 2019    3 - Alpha              pytest (<4.0.0,>=3.7.1)\n   :pypi:`pytest-cocotb`                                    Pytest plugin that enables using pytest as the regression manager for running cocotb tests.                                                                                                                                                                                                                                                                                             Nov 09, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-cocotb-cov`                                Pytest plugin for measuring HDL coverage.                                                                                                                                                                                                                                                                                                                                               Nov 09, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-cocotb-fusesoc`                            Pytest plugin to integrate FuseSoC with Cocotb.                                                                                                                                                                                                                                                                                                                                         Jan 07, 2026    5 - Production/Stable  pytest\n   :pypi:`pytest-cocotb-pyuvm`                              Pytest plugin that enables using pytest as the regression manager for running pyuvm tests.                                                                                                                                                                                                                                                                                              Nov 09, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-codeblock`                                 Pytest plugin to collect and test code blocks in reStructuredText and Markdown files.                                                                                                                                                                                                                                                                                                   Mar 07, 2026    4 - Beta               pytest\n   :pypi:`pytest_codeblocks`                                Test code blocks in your READMEs                                                                                                                                                                                                                                                                                                                                                        Sep 17, 2023    5 - Production/Stable  pytest >= 7.0.0\n   :pypi:`pytest-codecarbon`                                Pytest plugin for measuring carbon emissions                                                                                                                                                                                                                                                                                                                                            Jun 15, 2022    N/A                    pytest\n   :pypi:`pytest-codecheckers`                              pytest plugin to add source code sanity checks (pep8 and friends)                                                                                                                                                                                                                                                                                                                       Feb 13, 2010    N/A                    N/A\n   :pypi:`pytest-codecov`                                   Pytest plugin for uploading pytest-cov results to codecov.io                                                                                                                                                                                                                                                                                                                            Mar 25, 2025    4 - Beta               pytest>=4.6.0\n   :pypi:`pytest-codegen`                                   Automatically create pytest test signatures                                                                                                                                                                                                                                                                                                                                             Aug 23, 2020    2 - Pre-Alpha          N/A\n   :pypi:`pytest-codeowners`                                Pytest plugin for selecting tests by GitHub CODEOWNERS.                                                                                                                                                                                                                                                                                                                                 Mar 30, 2022    4 - Beta               pytest (>=6.0.0)\n   :pypi:`pytest-codestyle`                                 pytest plugin to run pycodestyle                                                                                                                                                                                                                                                                                                                                                        Mar 23, 2020    3 - Alpha              N/A\n   :pypi:`pytest-codingagents`                              Pytest plugin for testing real coding agents via their SDK                                                                                                                                                                                                                                                                                                                              Feb 20, 2026    3 - Alpha              pytest>=9.0\n   :pypi:`pytest-codspeed`                                  Pytest plugin to create CodSpeed benchmarks                                                                                                                                                                                                                                                                                                                                             Feb 09, 2026    5 - Production/Stable  pytest>=3.8\n   :pypi:`pytest-collect-appoint-info`                      set your encoding                                                                                                                                                                                                                                                                                                                                                                       Aug 03, 2023    N/A                    pytest\n   :pypi:`pytest-collect-formatter`                         Formatter for pytest collect output                                                                                                                                                                                                                                                                                                                                                     Mar 29, 2021    5 - Production/Stable  N/A\n   :pypi:`pytest-collect-formatter2`                        Formatter for pytest collect output                                                                                                                                                                                                                                                                                                                                                     May 31, 2021    5 - Production/Stable  N/A\n   :pypi:`pytest-collect-interface-info-plugin`             Get executed interface information in pytest interface automation framework                                                                                                                                                                                                                                                                                                             Sep 25, 2023    4 - Beta               N/A\n   :pypi:`pytest-collect-markers`                           A pytest plugin to collect and output test markers to JSON                                                                                                                                                                                                                                                                                                                              Jan 24, 2026    N/A                    pytest>=7.0.0\n   :pypi:`pytest-collector`                                 Python package for collecting pytest.                                                                                                                                                                                                                                                                                                                                                   Aug 02, 2022    N/A                    pytest (>=7.0,<8.0)\n   :pypi:`pytest-collect-pytest-interinfo`                  A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Sep 26, 2023    4 - Beta               N/A\n   :pypi:`pytest-collect-requirements`                      A pytest plugin to collect test requirements from requirements marker.                                                                                                                                                                                                                                                                                                                  Feb 07, 2026    5 - Production/Stable  pytest>=9.0.1\n   :pypi:`pytest-colordots`                                 Colorizes the progress indicators                                                                                                                                                                                                                                                                                                                                                       Oct 06, 2017    5 - Production/Stable  N/A\n   :pypi:`pytest-comfyui`                                   Integration testing framework for ComfyUI nodes and workflows.                                                                                                                                                                                                                                                                                                                          Jan 09, 2026    N/A                    N/A\n   :pypi:`pytest-commander`                                 An interactive GUI test runner for PyTest                                                                                                                                                                                                                                                                                                                                               Aug 17, 2021    N/A                    pytest (<7.0.0,>=6.2.4)\n   :pypi:`pytest-common-subject`                            pytest framework for testing different aspects of a common method                                                                                                                                                                                                                                                                                                                       Oct 22, 2025    N/A                    pytest<9,>=3.6\n   :pypi:`pytest-compare`                                   pytest plugin for comparing call arguments.                                                                                                                                                                                                                                                                                                                                             Jun 22, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-concurrent`                                Concurrently execute test cases with multithread, multiprocess and gevent                                                                                                                                                                                                                                                                                                               Jan 12, 2019    4 - Beta               pytest (>=3.1.1)\n   :pypi:`pytest-conductor`                                 Pytest plugin for coordinating the order in which marked tests run.                                                                                                                                                                                                                                                                                                                     Jul 30, 2025    N/A                    pytest<8.4; python_version == \"3.8\"\n   :pypi:`pytest-config`                                    Base configurations and utilities for developing    your Python project test suite with pytest.                                                                                                                                                                                                                                                                                         Nov 07, 2014    5 - Production/Stable  N/A\n   :pypi:`pytest-confluence-report`                         Package stands for pytest plugin to upload results into Confluence page.                                                                                                                                                                                                                                                                                                                Apr 17, 2022    N/A                    N/A\n   :pypi:`pytest-console-scripts`                           Pytest plugin for testing console scripts                                                                                                                                                                                                                                                                                                                                               May 31, 2023    4 - Beta               pytest (>=4.0.0)\n   :pypi:`pytest-consul`                                    pytest plugin with fixtures for testing consul aware apps                                                                                                                                                                                                                                                                                                                               Nov 24, 2018    3 - Alpha              pytest\n   :pypi:`pytest-container`                                 Pytest fixtures for writing container based tests                                                                                                                                                                                                                                                                                                                                       Jun 30, 2025    4 - Beta               pytest>=3.10\n   :pypi:`pytest-contextfixture`                            Define pytest fixtures as context managers.                                                                                                                                                                                                                                                                                                                                             Mar 12, 2013    4 - Beta               N/A\n   :pypi:`pytest-contexts`                                  A plugin to run tests written with the Contexts framework using pytest                                                                                                                                                                                                                                                                                                                  May 19, 2021    4 - Beta               N/A\n   :pypi:`pytest-continuous`                                A pytest plugin to run tests continuously until failure or interruption.                                                                                                                                                                                                                                                                                                                Apr 23, 2024    N/A                    N/A\n   :pypi:`pytest-cookies`                                   The pytest plugin for your Cookiecutter templates. 🍪                                                                                                                                                                                                                                                                                                                                   Mar 22, 2023    5 - Production/Stable  pytest (>=3.9.0)\n   :pypi:`pytest-copie`                                     The pytest plugin for your copier templates 📒                                                                                                                                                                                                                                                                                                                                          Sep 29, 2025    3 - Alpha              pytest\n   :pypi:`pytest-copier`                                    A pytest plugin to help testing Copier templates                                                                                                                                                                                                                                                                                                                                        Dec 11, 2023    4 - Beta               pytest>=7.3.2\n   :pypi:`pytest-couchdbkit`                                py.test extension for per-test couchdb databases using couchdbkit                                                                                                                                                                                                                                                                                                                       Apr 17, 2012    N/A                    N/A\n   :pypi:`pytest-count`                                     count erros and send email                                                                                                                                                                                                                                                                                                                                                              Jan 12, 2018    4 - Beta               N/A\n   :pypi:`pytest-cov`                                       Pytest plugin for measuring coverage.                                                                                                                                                                                                                                                                                                                                                   Sep 09, 2025    5 - Production/Stable  pytest>=7\n   :pypi:`pytest-cover`                                     Pytest plugin for measuring coverage. Forked from \\`pytest-cov\\`.                                                                                                                                                                                                                                                                                                                       Aug 01, 2015    5 - Production/Stable  N/A\n   :pypi:`pytest-coverage`                                                                                                                                                                                                                                                                                                                                                                                                                          Jun 17, 2015    N/A                    N/A\n   :pypi:`pytest-coverage-context`                          Coverage dynamic context support for PyTest, including sub-processes                                                                                                                                                                                                                                                                                                                    Jun 28, 2023    4 - Beta               N/A\n   :pypi:`pytest-coverage-impact`                           Sensoria: High-fidelity coverage impact analysis for Python.                                                                                                                                                                                                                                                                                                                            Jan 16, 2026    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-coveragemarkers`                           Using pytest markers to track functional coverage and filtering of tests                                                                                                                                                                                                                                                                                                                May 15, 2025    N/A                    pytest<8.0.0,>=7.1.2\n   :pypi:`pytest-cov-exclude`                               Pytest plugin for excluding tests based on coverage data                                                                                                                                                                                                                                                                                                                                Apr 29, 2016    4 - Beta               pytest (>=2.8.0,<2.9.0); extra == 'dev'\n   :pypi:`pytest_covid`                                     Too many faillure, less tests.                                                                                                                                                                                                                                                                                                                                                          Jun 24, 2020    N/A                    N/A\n   :pypi:`pytest-cpp`                                       Use pytest's runner to discover and execute C++ tests                                                                                                                                                                                                                                                                                                                                   Sep 18, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-cqase`                                     Custom qase pytest plugin                                                                                                                                                                                                                                                                                                                                                               Aug 22, 2022    N/A                    pytest (>=7.1.2,<8.0.0)\n   :pypi:`pytest-cram`                                      Run cram tests with pytest.                                                                                                                                                                                                                                                                                                                                                             Aug 08, 2020    N/A                    N/A\n   :pypi:`pytest-crap`                                      pytest plugin that calculates CRAP scores to guide test writing                                                                                                                                                                                                                                                                                                                         Dec 02, 2025    4 - Beta               pytest>=7.0\n   :pypi:`pytest-crate`                                     Manages CrateDB instances during your integration tests                                                                                                                                                                                                                                                                                                                                 May 28, 2019    3 - Alpha              pytest (>=4.0)\n   :pypi:`pytest-cratedb`                                   Manage CrateDB instances for integration tests                                                                                                                                                                                                                                                                                                                                          Jan 05, 2026    4 - Beta               pytest<10\n   :pypi:`pytest-cratedb-reporter`                          A pytest plugin for reporting test results to CrateDB                                                                                                                                                                                                                                                                                                                                   Mar 11, 2025    N/A                    pytest>=6.0.0\n   :pypi:`pytest-crayons`                                   A pytest plugin for colorful print statements                                                                                                                                                                                                                                                                                                                                           Oct 14, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-cream`                                     The cream of test execution - smooth pytest workflows with intelligent orchestration                                                                                                                                                                                                                                                                                                    Oct 26, 2025    N/A                    pytest\n   :pypi:`pytest-create`                                    pytest-create                                                                                                                                                                                                                                                                                                                                                                           Feb 15, 2023    1 - Planning           N/A\n   :pypi:`pytest-cricri`                                    A Cricri plugin for pytest.                                                                                                                                                                                                                                                                                                                                                             Jan 27, 2018    N/A                    pytest\n   :pypi:`pytest-crontab`                                   add crontab task in crontab                                                                                                                                                                                                                                                                                                                                                             Dec 09, 2019    N/A                    N/A\n   :pypi:`pytest-csv`                                       CSV output for pytest.                                                                                                                                                                                                                                                                                                                                                                  Apr 22, 2021    N/A                    pytest (>=6.0)\n   :pypi:`pytest-csv-params`                                Pytest plugin for Test Case Parametrization with CSV files                                                                                                                                                                                                                                                                                                                              May 29, 2025    5 - Production/Stable  pytest<9,>=8.3\n   :pypi:`pytest-culprit`                                   Find the last Git commit where a pytest test started failing                                                                                                                                                                                                                                                                                                                            May 15, 2025    N/A                    N/A\n   :pypi:`pytest-curio`                                     Pytest support for curio.                                                                                                                                                                                                                                                                                                                                                               Oct 06, 2024    N/A                    pytest\n   :pypi:`pytest-curl-report`                               pytest plugin to generate curl command line report                                                                                                                                                                                                                                                                                                                                      Dec 11, 2016    4 - Beta               N/A\n   :pypi:`pytest-custom-concurrency`                        Custom grouping concurrence for pytest                                                                                                                                                                                                                                                                                                                                                  Feb 08, 2021    N/A                    N/A\n   :pypi:`pytest-custom-exit-code`                          Exit pytest test session with custom exit code in different scenarios                                                                                                                                                                                                                                                                                                                   Aug 07, 2019    4 - Beta               pytest (>=4.0.2)\n   :pypi:`pytest-custom-nodeid`                             Custom grouping for pytest-xdist, rename test cases name and test cases nodeid, support allure report                                                                                                                                                                                                                                                                                   Mar 07, 2021    N/A                    N/A\n   :pypi:`pytest-custom-outputs`                            A plugin that allows users to create and use custom outputs instead of the standard Pass and Fail. Also allows users to retrieve test results in fixtures.                                                                                                                                                                                                                              Jul 10, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-custom-report`                             Configure the symbols displayed for test outcomes                                                                                                                                                                                                                                                                                                                                       Jan 30, 2019    N/A                    pytest\n   :pypi:`pytest-custom-scheduling`                         Custom grouping for pytest-xdist, rename test cases name and test cases nodeid, support allure report                                                                                                                                                                                                                                                                                   Mar 01, 2021    N/A                    N/A\n   :pypi:`pytest-custom-timeout`                            Use custom logic when a test times out. Based on pytest-timeout.                                                                                                                                                                                                                                                                                                                        Jan 08, 2025    4 - Beta               pytest>=8.0.0\n   :pypi:`pytest-cython`                                    A plugin for testing Cython extension modules.                                                                                                                                                                                                                                                                                                                                          Mar 11, 2026    5 - Production/Stable  pytest>=8\n   :pypi:`pytest-cython-collect`                                                                                                                                                                                                                                                                                                                                                                                                                    Jun 17, 2022    N/A                    pytest\n   :pypi:`pytest-darker`                                    A pytest plugin for checking of modified code using Darker                                                                                                                                                                                                                                                                                                                              Feb 25, 2024    N/A                    pytest <7,>=6.0.1\n   :pypi:`pytest-dash`                                      pytest fixtures to run dash applications.                                                                                                                                                                                                                                                                                                                                               Mar 18, 2019    N/A                    N/A\n   :pypi:`pytest-dashboard`                                                                                                                                                                                                                                                                                                                                                                                                                         Jun 02, 2025    N/A                    pytest<8.0.0,>=7.4.3\n   :pypi:`pytest-data`                                      Useful functions for managing data for pytest fixtures                                                                                                                                                                                                                                                                                                                                  Nov 01, 2016    5 - Production/Stable  N/A\n   :pypi:`pytest-databases`                                 Reusable database fixtures for any and all databases.                                                                                                                                                                                                                                                                                                                                   Mar 10, 2026    4 - Beta               pytest\n   :pypi:`pytest-databricks`                                Pytest plugin for remote Databricks notebooks testing                                                                                                                                                                                                                                                                                                                                   Jul 29, 2020    N/A                    pytest\n   :pypi:`pytest-datadir`                                   pytest plugin for test data directories and files                                                                                                                                                                                                                                                                                                                                       Jul 30, 2025    5 - Production/Stable  pytest>=7.0\n   :pypi:`pytest-datadir-mgr`                               Manager for test data: downloads, artifact caching, and a tmpdir context.                                                                                                                                                                                                                                                                                                               Apr 06, 2023    5 - Production/Stable  pytest (>=7.1)\n   :pypi:`pytest-datadir-ng`                                Fixtures for pytest allowing test functions/methods to easily retrieve test resources from the local filesystem.                                                                                                                                                                                                                                                                        Dec 25, 2019    5 - Production/Stable  pytest\n   :pypi:`pytest-datadir-nng`                               Fixtures for pytest allowing test functions/methods to easily retrieve test resources from the local filesystem.                                                                                                                                                                                                                                                                        Nov 09, 2022    5 - Production/Stable  pytest (>=7.0.0,<8.0.0)\n   :pypi:`pytest-data-extractor`                            A pytest plugin to extract relevant metadata about tests into an external file (currently only json support)                                                                                                                                                                                                                                                                            Jul 19, 2022    N/A                    pytest (>=7.0.1)\n   :pypi:`pytest-data-file`                                 Fixture \"data\" and \"case_data\" for test from yaml file                                                                                                                                                                                                                                                                                                                                  Dec 04, 2019    N/A                    N/A\n   :pypi:`pytest-datafiles`                                 py.test plugin to create a 'tmp_path' containing predefined files/directories.                                                                                                                                                                                                                                                                                                          Jan 04, 2026    5 - Production/Stable  pytest>=6.2.0\n   :pypi:`pytest-datafixtures`                              Data fixtures for pytest made simple.                                                                                                                                                                                                                                                                                                                                                   May 15, 2025    5 - Production/Stable  N/A\n   :pypi:`pytest-data-from-files`                           pytest plugin to provide data from files loaded automatically                                                                                                                                                                                                                                                                                                                           Oct 13, 2021    4 - Beta               pytest\n   :pypi:`pytest-dataguard`                                 Data validation and integrity testing for your datasets using pytest.                                                                                                                                                                                                                                                                                                                   Oct 08, 2025    N/A                    pytest>=8.4.2\n   :pypi:`pytest-data-loader`                               Pytest plugin for loading test data for data-driven testing (DDT)                                                                                                                                                                                                                                                                                                                       Feb 21, 2026    4 - Beta               pytest<10,>=7.0.0\n   :pypi:`pytest-dataplugin`                                A pytest plugin for managing an archive of test data.                                                                                                                                                                                                                                                                                                                                   Sep 16, 2017    1 - Planning           N/A\n   :pypi:`pytest-datarecorder`                              A py.test plugin recording and comparing test output.                                                                                                                                                                                                                                                                                                                                   Jul 31, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-dataset`                                   Plugin for loading different datasets for pytest by prefix from json or yaml files                                                                                                                                                                                                                                                                                                      Sep 01, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-data-suites`                               Class-based pytest parametrization                                                                                                                                                                                                                                                                                                                                                      Apr 06, 2024    N/A                    pytest<9.0,>=6.0\n   :pypi:`pytest-datatest`                                  A pytest plugin for test driven data-wrangling (this is the development version of datatest's pytest integration).                                                                                                                                                                                                                                                                      Oct 15, 2020    4 - Beta               pytest (>=3.3)\n   :pypi:`pytest-db`                                        Session scope fixture \"db\" for mysql query or change                                                                                                                                                                                                                                                                                                                                    Nov 11, 2025    N/A                    pytest\n   :pypi:`pytest-dbfixtures`                                Databases fixtures plugin for py.test.                                                                                                                                                                                                                                                                                                                                                  Dec 07, 2016    4 - Beta               N/A\n   :pypi:`pytest-db-plugin`                                                                                                                                                                                                                                                                                                                                                                                                                         Nov 27, 2021    N/A                    pytest (>=5.0)\n   :pypi:`pytest-dbt`                                       Unit test dbt models with standard python tooling                                                                                                                                                                                                                                                                                                                                       Jun 08, 2023    2 - Pre-Alpha          pytest (>=7.0.0,<8.0.0)\n   :pypi:`pytest-dbt-adapter`                               A pytest plugin for testing dbt adapter plugins                                                                                                                                                                                                                                                                                                                                         Nov 24, 2021    N/A                    pytest (<7,>=6)\n   :pypi:`pytest-dbt-conventions`                           A pytest plugin for linting a dbt project's conventions                                                                                                                                                                                                                                                                                                                                 Mar 02, 2022    N/A                    pytest (>=6.2.5,<7.0.0)\n   :pypi:`pytest-dbt-core`                                  Pytest extension for dbt.                                                                                                                                                                                                                                                                                                                                                               Jun 04, 2024    N/A                    pytest>=6.2.5; extra == \"test\"\n   :pypi:`pytest-dbt-duckdb`                                Fearless testing for dbt models, powered by DuckDB.                                                                                                                                                                                                                                                                                                                                     Mar 06, 2026    4 - Beta               pytest>=8.3.4\n   :pypi:`pytest-dbt-postgres`                              Pytest tooling to unittest DBT & Postgres models                                                                                                                                                                                                                                                                                                                                        Sep 03, 2024    N/A                    pytest<9.0.0,>=8.3.2\n   :pypi:`pytest-dbus-notification`                         D-BUS notifications for pytest results.                                                                                                                                                                                                                                                                                                                                                 Mar 05, 2014    5 - Production/Stable  N/A\n   :pypi:`pytest-dbx`                                       Pytest plugin to run unit tests for dbx (Databricks CLI extensions) related code                                                                                                                                                                                                                                                                                                        Nov 29, 2022    N/A                    pytest (>=7.1.3,<8.0.0)\n   :pypi:`pytest-dc`                                        Manages Docker containers during your integration tests                                                                                                                                                                                                                                                                                                                                 Aug 16, 2023    5 - Production/Stable  pytest >=3.3\n   :pypi:`pytest-deadfixtures`                              A simple plugin to list unused fixtures in pytest                                                                                                                                                                                                                                                                                                                                       Jan 15, 2026    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-deduplicate`                               Identifies duplicate unit tests                                                                                                                                                                                                                                                                                                                                                         Aug 12, 2023    4 - Beta               pytest\n   :pypi:`pytest-deepassert`                                A pytest plugin for enhanced assertion reporting with detailed diffs                                                                                                                                                                                                                                                                                                                    Nov 04, 2025    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-deepcov`                                   deepcov                                                                                                                                                                                                                                                                                                                                                                                 Mar 30, 2021    N/A                    N/A\n   :pypi:`pytest_defer`                                     A 'defer' fixture for pytest                                                                                                                                                                                                                                                                                                                                                            Nov 13, 2024    N/A                    pytest>=8.3\n   :pypi:`pytest-delta`                                     Run only tests impacted by your code changes (delta-based selection) for pytest.                                                                                                                                                                                                                                                                                                        Feb 12, 2026    4 - Beta               pytest<10.0.0,>=9.0.2\n   :pypi:`pytest-demo-plugin`                               pytest示例插件                                                                                                                                                                                                                                                                                                                                                                          May 15, 2021    N/A                    N/A\n   :pypi:`pytest-dependency`                                Manage dependencies of tests                                                                                                                                                                                                                                                                                                                                                            Feb 15, 2026    4 - Beta               N/A\n   :pypi:`pytest-depends`                                   Tests that depend on other tests                                                                                                                                                                                                                                                                                                                                                        Apr 05, 2020    5 - Production/Stable  pytest (>=3)\n   :pypi:`pytest-depends-on`                                A Python package for managing test dependencies in pytest.                                                                                                                                                                                                                                                                                                                              Feb 07, 2026    5 - Production/Stable  pytest>=9.0.1\n   :pypi:`pytest-depper`                                    Smart test selection based on AST-level code dependency analysis                                                                                                                                                                                                                                                                                                                        Oct 23, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-deprecate`                                 Mark tests as testing a deprecated feature with a warning note.                                                                                                                                                                                                                                                                                                                         Jul 01, 2019    N/A                    N/A\n   :pypi:`pytest-deprecator`                                A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Dec 02, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-describe`                                  Describe-style plugin for pytest                                                                                                                                                                                                                                                                                                                                                        Dec 12, 2025    5 - Production/Stable  pytest<10,>=6\n   :pypi:`pytest-describe-beautifully`                      Beautiful terminal and HTML output for pytest-describe.                                                                                                                                                                                                                                                                                                                                 Jan 28, 2026    4 - Beta               pytest>=7.0\n   :pypi:`pytest-describe-it`                               plugin for rich text descriptions                                                                                                                                                                                                                                                                                                                                                       Jul 19, 2019    4 - Beta               pytest\n   :pypi:`pytest-deselect-if`                               A plugin to deselect pytests tests rather than using skipif                                                                                                                                                                                                                                                                                                                             Dec 26, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-devpi-server`                              DevPI server fixture for py.test                                                                                                                                                                                                                                                                                                                                                        Oct 17, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-devtools`                                  Pytest plugin providing debug fixtures, ANSI-stripped capsys, whitespace-visible assertions, and terminal column management.                                                                                                                                                                                                                                                            Feb 10, 2026    N/A                    pytest>=9.0.2\n   :pypi:`pytest-dfm`                                       pytest-dfm provides a pytest integration for DV Flow Manager, a build system for silicon design                                                                                                                                                                                                                                                                                         Nov 23, 2025    N/A                    pytest\n   :pypi:`pytest-dhos`                                      Common fixtures for pytest in DHOS services and libraries                                                                                                                                                                                                                                                                                                                               Sep 07, 2022    N/A                    N/A\n   :pypi:`pytest-diamond`                                   pytest plugin for diamond                                                                                                                                                                                                                                                                                                                                                               Aug 31, 2015    4 - Beta               N/A\n   :pypi:`pytest-dicom`                                     pytest plugin to provide DICOM fixtures                                                                                                                                                                                                                                                                                                                                                 Dec 19, 2018    3 - Alpha              pytest\n   :pypi:`pytest-dictsdiff`                                                                                                                                                                                                                                                                                                                                                                                                                         Jul 26, 2019    N/A                    N/A\n   :pypi:`pytest-diff`                                      A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Mar 30, 2019    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-diff-selector`                             Get tests affected by code changes (using git)                                                                                                                                                                                                                                                                                                                                          Feb 24, 2022    4 - Beta               pytest (>=6.2.2) ; extra == 'all'\n   :pypi:`pytest-difftest`                                  Blazingly fast test selection for pytest - only run tests affected by your changes (Rust-powered)                                                                                                                                                                                                                                                                                       Feb 23, 2026    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-difido`                                    PyTest plugin for generating Difido reports                                                                                                                                                                                                                                                                                                                                             Oct 23, 2022    4 - Beta               pytest (>=4.0.0)\n   :pypi:`pytest-directives`                                Control your tests flow                                                                                                                                                                                                                                                                                                                                                                 Aug 11, 2025    3 - Alpha              pytest\n   :pypi:`pytest-dir-equal`                                 pytest-dir-equals is a pytest plugin providing helpers to assert directories equality allowing golden testing                                                                                                                                                                                                                                                                           Dec 11, 2023    4 - Beta               pytest>=7.3.2\n   :pypi:`pytest-dirty`                                     Static import analysis for thrifty testing.                                                                                                                                                                                                                                                                                                                                             Jun 08, 2025    3 - Alpha              pytest>=8.2; extra == \"dev\"\n   :pypi:`pytest-disable`                                   pytest plugin to disable a test and skip it from testrun                                                                                                                                                                                                                                                                                                                                Sep 10, 2015    4 - Beta               N/A\n   :pypi:`pytest-disable-plugin`                            Disable plugins per test                                                                                                                                                                                                                                                                                                                                                                Feb 28, 2019    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-discord`                                   A pytest plugin to notify test results to a Discord channel.                                                                                                                                                                                                                                                                                                                            May 11, 2024    4 - Beta               pytest!=6.0.0,<9,>=3.3.2\n   :pypi:`pytest-discover`                                  Pytest plugin to record discovered tests in a file                                                                                                                                                                                                                                                                                                                                      Mar 26, 2024    N/A                    pytest\n   :pypi:`pytest-ditto`                                     Snapshot testing pytest plugin with minimal ceremony and flexible persistence formats.                                                                                                                                                                                                                                                                                                  Jun 09, 2024    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-ditto-pandas`                              pytest-ditto plugin for pandas snapshots.                                                                                                                                                                                                                                                                                                                                               May 29, 2024    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-ditto-pyarrow`                             pytest-ditto plugin for pyarrow tables.                                                                                                                                                                                                                                                                                                                                                 Jun 09, 2024    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-django`                                    A Django plugin for pytest.                                                                                                                                                                                                                                                                                                                                                             Feb 14, 2026    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-django-ahead`                              A Django plugin for pytest.                                                                                                                                                                                                                                                                                                                                                             Oct 27, 2016    5 - Production/Stable  pytest (>=2.9)\n   :pypi:`pytest-djangoapp`                                 Nice pytest plugin to help you with Django pluggable application testing.                                                                                                                                                                                                                                                                                                               Dec 13, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-django-cache-xdist`                        A djangocachexdist plugin for pytest                                                                                                                                                                                                                                                                                                                                                    May 12, 2020    4 - Beta               N/A\n   :pypi:`pytest-django-casperjs`                           Integrate CasperJS with your django tests as a pytest fixture.                                                                                                                                                                                                                                                                                                                          Mar 15, 2015    2 - Pre-Alpha          N/A\n   :pypi:`pytest-django-class`                              A pytest plugin for running django in class-scoped fixtures                                                                                                                                                                                                                                                                                                                             Aug 08, 2023    4 - Beta               N/A\n   :pypi:`pytest-django-docker-pg`                                                                                                                                                                                                                                                                                                                                                                                                                  Jun 13, 2024    5 - Production/Stable  pytest<9.0.0,>=7.0.0\n   :pypi:`pytest-django-dotenv`                             Pytest plugin used to setup environment variables with django-dotenv                                                                                                                                                                                                                                                                                                                    Nov 26, 2019    4 - Beta               pytest (>=2.6.0)\n   :pypi:`pytest-django-factories`                          Factories for your Django models that can be used as Pytest fixtures.                                                                                                                                                                                                                                                                                                                   Nov 12, 2020    4 - Beta               N/A\n   :pypi:`pytest-django-filefield`                          Replaces FileField.storage with something you can patch globally.                                                                                                                                                                                                                                                                                                                       May 09, 2022    5 - Production/Stable  pytest >= 5.2\n   :pypi:`pytest-django-gcir`                               A Django plugin for pytest.                                                                                                                                                                                                                                                                                                                                                             Mar 06, 2018    5 - Production/Stable  N/A\n   :pypi:`pytest-django-haystack`                           Cleanup your Haystack indexes between tests                                                                                                                                                                                                                                                                                                                                             Sep 03, 2017    5 - Production/Stable  pytest (>=2.3.4)\n   :pypi:`pytest-django-ifactory`                           A model instance factory for pytest-django                                                                                                                                                                                                                                                                                                                                              Apr 30, 2025    5 - Production/Stable  N/A\n   :pypi:`pytest-django-lite`                               The bare minimum to integrate py.test with Django.                                                                                                                                                                                                                                                                                                                                      Jan 30, 2014    N/A                    N/A\n   :pypi:`pytest-django-liveserver-ssl`                                                                                                                                                                                                                                                                                                                                                                                                             Jan 09, 2025    3 - Alpha              N/A\n   :pypi:`pytest-django-model`                              A Simple Way to Test your Django Models                                                                                                                                                                                                                                                                                                                                                 Feb 14, 2019    4 - Beta               N/A\n   :pypi:`pytest-django-ordering`                           A pytest plugin for preserving the order in which Django runs tests.                                                                                                                                                                                                                                                                                                                    Jul 25, 2019    5 - Production/Stable  pytest (>=2.3.0)\n   :pypi:`pytest-django-queries`                            Generate performance reports from your django database performance tests.                                                                                                                                                                                                                                                                                                               Mar 01, 2026    5 - Production/Stable  pytest>=7.2.0\n   :pypi:`pytest-djangorestframework`                       A djangorestframework plugin for pytest                                                                                                                                                                                                                                                                                                                                                 Aug 11, 2019    4 - Beta               N/A\n   :pypi:`pytest-django-rq`                                 A pytest plugin to help writing unit test for django-rq                                                                                                                                                                                                                                                                                                                                 Apr 13, 2020    4 - Beta               N/A\n   :pypi:`pytest-django-sqlcounts`                          py.test plugin for reporting the number of SQLs executed per django testcase.                                                                                                                                                                                                                                                                                                           Jun 16, 2015    4 - Beta               N/A\n   :pypi:`pytest-django-testing-postgresql`                 Use a temporary PostgreSQL database with pytest-django                                                                                                                                                                                                                                                                                                                                  Jan 31, 2022    4 - Beta               N/A\n   :pypi:`pytest-doc`                                       A documentation plugin for py.test.                                                                                                                                                                                                                                                                                                                                                     Jun 28, 2015    5 - Production/Stable  N/A\n   :pypi:`pytest-docfiles`                                  pytest plugin to test codeblocks in your documentation.                                                                                                                                                                                                                                                                                                                                 Dec 22, 2021    4 - Beta               pytest (>=3.7.0)\n   :pypi:`pytest-docgen`                                    An RST Documentation Generator for pytest-based test suites                                                                                                                                                                                                                                                                                                                             Apr 17, 2020    N/A                    N/A\n   :pypi:`pytest-docker`                                    Simple pytest fixtures for Docker and Docker Compose based tests                                                                                                                                                                                                                                                                                                                        Nov 12, 2025    N/A                    pytest<10.0,>=4.0\n   :pypi:`pytest-docker-apache-fixtures`                    Pytest fixtures for testing with apache2 (httpd).                                                                                                                                                                                                                                                                                                                                       Aug 12, 2024    4 - Beta               pytest\n   :pypi:`pytest-docker-butla`                                                                                                                                                                                                                                                                                                                                                                                                                      Jun 16, 2019    3 - Alpha              N/A\n   :pypi:`pytest-dockerc`                                   Run, manage and stop Docker Compose project from Docker API                                                                                                                                                                                                                                                                                                                             Oct 09, 2020    5 - Production/Stable  pytest (>=3.0)\n   :pypi:`pytest-docker-compose`                            Manages Docker containers during your integration tests                                                                                                                                                                                                                                                                                                                                 Jan 26, 2021    5 - Production/Stable  pytest (>=3.3)\n   :pypi:`pytest-docker-compose-v2`                         Manages Docker containers during your integration tests                                                                                                                                                                                                                                                                                                                                 Dec 17, 2025    4 - Beta               pytest<10,>=7.2.2\n   :pypi:`pytest-docker-db`                                 A plugin to use docker databases for pytests                                                                                                                                                                                                                                                                                                                                            Mar 20, 2021    5 - Production/Stable  pytest (>=3.1.1)\n   :pypi:`pytest-docker-fixtures`                           pytest docker fixtures                                                                                                                                                                                                                                                                                                                                                                  Dec 01, 2025    3 - Alpha              pytest\n   :pypi:`pytest-docker-git-fixtures`                       Pytest fixtures for testing with git scm.                                                                                                                                                                                                                                                                                                                                               Aug 12, 2024    4 - Beta               pytest\n   :pypi:`pytest-docker-haproxy-fixtures`                   Pytest fixtures for testing with haproxy.                                                                                                                                                                                                                                                                                                                                               Aug 12, 2024    4 - Beta               pytest\n   :pypi:`pytest-docker-pexpect`                            pytest plugin for writing functional tests with pexpect and docker                                                                                                                                                                                                                                                                                                                      Jan 14, 2019    N/A                    pytest\n   :pypi:`pytest-docker-postgresql`                         A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Sep 24, 2019    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-docker-py`                                 Easy to use, simple to extend, pytest plugin that minimally leverages docker-py.                                                                                                                                                                                                                                                                                                        Nov 27, 2018    N/A                    pytest (==4.0.0)\n   :pypi:`pytest-docker-registry-fixtures`                  Pytest fixtures for testing with docker registries.                                                                                                                                                                                                                                                                                                                                     Aug 12, 2024    4 - Beta               pytest\n   :pypi:`pytest-docker-service`                            pytest plugin to start docker container                                                                                                                                                                                                                                                                                                                                                 Jan 03, 2024    3 - Alpha              pytest (>=7.1.3)\n   :pypi:`pytest-docker-squid-fixtures`                     Pytest fixtures for testing with squid.                                                                                                                                                                                                                                                                                                                                                 Aug 12, 2024    4 - Beta               pytest\n   :pypi:`pytest-docker-tools`                              Docker integration tests for pytest                                                                                                                                                                                                                                                                                                                                                     Mar 16, 2025    4 - Beta               pytest>=6.0.1\n   :pypi:`pytest-docs`                                      Documentation tool for pytest                                                                                                                                                                                                                                                                                                                                                           Nov 11, 2018    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-docstyle`                                  pytest plugin to run pydocstyle                                                                                                                                                                                                                                                                                                                                                         Mar 23, 2020    3 - Alpha              N/A\n   :pypi:`pytest-doctest-custom`                            A py.test plugin for customizing string representations of doctest results.                                                                                                                                                                                                                                                                                                             Jul 25, 2016    4 - Beta               N/A\n   :pypi:`pytest-doctest-ellipsis-markers`                  Setup additional values for ELLIPSIS_MARKER for doctests                                                                                                                                                                                                                                                                                                                                Jan 12, 2018    4 - Beta               N/A\n   :pypi:`pytest-doctest-import`                            A simple pytest plugin to import names and add them to the doctest namespace.                                                                                                                                                                                                                                                                                                           Nov 13, 2018    4 - Beta               pytest (>=3.3.0)\n   :pypi:`pytest-doctest-mkdocstrings`                      Run pytest --doctest-modules with markdown docstrings in code blocks (\\`\\`\\`)                                                                                                                                                                                                                                                                                                           Mar 02, 2024    N/A                    pytest\n   :pypi:`pytest-doctest-only`                              A plugin to run only doctest                                                                                                                                                                                                                                                                                                                                                            Jul 30, 2025    4 - Beta               pytest>=8.3.0\n   :pypi:`pytest-doctestplus`                               Pytest plugin with advanced doctest features.                                                                                                                                                                                                                                                                                                                                           Jan 26, 2026    5 - Production/Stable  pytest>=7.0\n   :pypi:`pytest-documentary`                               A simple pytest plugin to generate test documentation                                                                                                                                                                                                                                                                                                                                   Jul 11, 2024    N/A                    pytest\n   :pypi:`pytest-dogu-report`                               pytest plugin for dogu report                                                                                                                                                                                                                                                                                                                                                           Jul 07, 2023    N/A                    N/A\n   :pypi:`pytest-dogu-sdk`                                  pytest plugin for the Dogu                                                                                                                                                                                                                                                                                                                                                              Dec 14, 2023    N/A                    N/A\n   :pypi:`pytest-dolphin`                                   Some extra stuff that we use ininternally                                                                                                                                                                                                                                                                                                                                               Nov 30, 2016    4 - Beta               pytest (==3.0.4)\n   :pypi:`pytest-donde`                                     record pytest session characteristics per test item (coverage and duration) into a persistent file and use them in your own plugin or script.                                                                                                                                                                                                                                           Oct 01, 2023    4 - Beta               pytest >=7.3.1\n   :pypi:`pytest-doorstop`                                  A pytest plugin for adding test results into doorstop items.                                                                                                                                                                                                                                                                                                                            Jun 09, 2020    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-dotenv`                                    A py.test plugin that parses environment files before running tests                                                                                                                                                                                                                                                                                                                     Jun 16, 2020    4 - Beta               pytest (>=5.0.0)\n   :pypi:`pytest-dotenv-modern`                             A modern pytest plugin that loads environment variables from dotenv files                                                                                                                                                                                                                                                                                                               Sep 27, 2025    4 - Beta               pytest>=6.0.0\n   :pypi:`pytest-dot-only-pkcopley`                         A Pytest marker for only running a single test                                                                                                                                                                                                                                                                                                                                          Oct 27, 2023    N/A                    N/A\n   :pypi:`pytest-dparam`                                    A more readable alternative to @pytest.mark.parametrize.                                                                                                                                                                                                                                                                                                                                Aug 27, 2024    6 - Mature             pytest\n   :pypi:`pytest-dpg`                                       pytest-dpg is a pytest plugin for testing Dear PyGui (DPG) applications                                                                                                                                                                                                                                                                                                                 Aug 13, 2024    N/A                    N/A\n   :pypi:`pytest-draw`                                      Pytest plugin for randomly selecting a specific number of tests                                                                                                                                                                                                                                                                                                                         Mar 21, 2023    3 - Alpha              pytest\n   :pypi:`pytest-drf`                                       A Django REST framework plugin for pytest.                                                                                                                                                                                                                                                                                                                                              Jul 12, 2022    5 - Production/Stable  pytest (>=3.7)\n   :pypi:`pytest-drill-sergeant`                            A pytest plugin that enforces test quality standards through automatic marker detection and AAA structure validation                                                                                                                                                                                                                                                                    Feb 20, 2026    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-drivings`                                  Tool to allow webdriver automation to be ran locally or remotely                                                                                                                                                                                                                                                                                                                        Jan 13, 2021    N/A                    N/A\n   :pypi:`pytest-drop-dup-tests`                            A Pytest plugin to drop duplicated tests during collection                                                                                                                                                                                                                                                                                                                              Mar 04, 2024    5 - Production/Stable  pytest >=7\n   :pypi:`pytest-dryci`                                     Test caching plugin for pytest                                                                                                                                                                                                                                                                                                                                                          Sep 27, 2024    4 - Beta               N/A\n   :pypi:`pytest-dryrun`                                    A Pytest plugin to ignore tests during collection without reporting them in the test summary.                                                                                                                                                                                                                                                                                           Jan 19, 2025    5 - Production/Stable  pytest<9,>=7.40\n   :pypi:`pytest-dsl`                                       A DSL testing framework based on pytest                                                                                                                                                                                                                                                                                                                                                 Mar 02, 2026    N/A                    pytest>=7.0.0\n   :pypi:`pytest-dsl-ssh`                                   SSH/SFTP关键字插件，为pytest-dsl提供SSH和SFTP操作能力                                                                                                                                                                                                                                                                                                                                   Jul 25, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-dsl-ui`                                    Playwright-based UI automation keywords for pytest-dsl framework                                                                                                                                                                                                                                                                                                                        Aug 21, 2025    N/A                    pytest>=7.0.0; extra == \"dev\"\n   :pypi:`pytest-dummynet`                                  A py.test plugin providing access to a dummynet.                                                                                                                                                                                                                                                                                                                                        Dec 15, 2021    5 - Production/Stable  pytest\n   :pypi:`pytest-dump2json`                                 A pytest plugin for dumping test results to json.                                                                                                                                                                                                                                                                                                                                       Jun 29, 2015    N/A                    N/A\n   :pypi:`pytest-duration-insights`                                                                                                                                                                                                                                                                                                                                                                                                                 Jul 15, 2024    N/A                    N/A\n   :pypi:`pytest-durations`                                 Pytest plugin reporting fixtures and test functions execution time.                                                                                                                                                                                                                                                                                                                     Mar 13, 2026    5 - Production/Stable  pytest>=4.6\n   :pypi:`pytest-dynamic-parameterize`                      A pytest plugin to dynamically parameterize tests based on external data sources.                                                                                                                                                                                                                                                                                                       Feb 07, 2026    5 - Production/Stable  pytest>=9.0.1\n   :pypi:`pytest-dynamic-params`                            Dynamic parameters plugin for pytest                                                                                                                                                                                                                                                                                                                                                    Mar 12, 2026    N/A                    pytest\n   :pypi:`pytest-dynamicrerun`                              A pytest plugin to rerun tests dynamically based off of test outcome and output.                                                                                                                                                                                                                                                                                                        Aug 15, 2020    4 - Beta               N/A\n   :pypi:`pytest-dynamodb`                                  DynamoDB fixtures for pytest                                                                                                                                                                                                                                                                                                                                                            Mar 13, 2026    5 - Production/Stable  pytest>=8.4.0\n   :pypi:`pytest-easy-addoption`                            pytest-easy-addoption: Easy way to work with pytest addoption                                                                                                                                                                                                                                                                                                                           Jan 22, 2020    N/A                    N/A\n   :pypi:`pytest-easyMPI`                                   Package that supports mpi tests in pytest                                                                                                                                                                                                                                                                                                                                               Oct 21, 2020    N/A                    N/A\n   :pypi:`pytest-easyread`                                  pytest plugin that makes terminal printouts of the reports easier to read                                                                                                                                                                                                                                                                                                               Nov 17, 2017    N/A                    N/A\n   :pypi:`pytest-easy-server`                               Pytest plugin for easy testing against servers                                                                                                                                                                                                                                                                                                                                          May 01, 2021    4 - Beta               pytest (<5.0.0,>=4.3.1) ; python_version < \"3.5\"\n   :pypi:`pytest-ebics-sandbox`                             A pytest plugin for testing against an EBICS sandbox server. Requires docker.                                                                                                                                                                                                                                                                                                           Aug 15, 2022    N/A                    N/A\n   :pypi:`pytest-ec2`                                       Pytest execution on EC2 instance                                                                                                                                                                                                                                                                                                                                                        Oct 22, 2019    3 - Alpha              N/A\n   :pypi:`pytest-echo`                                      pytest plugin that allows to dump environment variables, package version and generic attributes                                                                                                                                                                                                                                                                                         Apr 27, 2025    5 - Production/Stable  pytest>=8.3.3\n   :pypi:`pytest-edit`                                      Edit the source code of a failed test with \\`pytest --edit\\`.                                                                                                                                                                                                                                                                                                                           Nov 17, 2024    N/A                    pytest\n   :pypi:`pytest-ekstazi`                                   Pytest plugin to select test using Ekstazi algorithm                                                                                                                                                                                                                                                                                                                                    Sep 10, 2022    N/A                    pytest\n   :pypi:`pytest-elastic-reporter`                                                                                                                                                                                                                                                                                                                                                                                                                  Mar 13, 2026    N/A                    pytest>=7.0\n   :pypi:`pytest-elasticsearch`                             Elasticsearch fixtures and fixture factories for Pytest.                                                                                                                                                                                                                                                                                                                                Feb 16, 2026    5 - Production/Stable  pytest>=8.4.0\n   :pypi:`pytest-elasticsearch-test`                        Elasticsearch fixtures and fixture factories for Pytest.                                                                                                                                                                                                                                                                                                                                Apr 20, 2025    5 - Production/Stable  pytest>=7.0\n   :pypi:`pytest-elegant`                                   A pytest plugin that provides elegant, beautiful test output                                                                                                                                                                                                                                                                                                                            Mar 08, 2026    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-elements`                                  Tool to help automate user interfaces                                                                                                                                                                                                                                                                                                                                                   Jan 13, 2021    N/A                    pytest (>=5.4,<6.0)\n   :pypi:`pytest-eliot`                                     An eliot plugin for pytest.                                                                                                                                                                                                                                                                                                                                                             Aug 31, 2022    1 - Planning           pytest (>=5.4.0)\n   :pypi:`pytest-elk-reporter`                              A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Jul 25, 2024    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-email`                                     Send execution result email                                                                                                                                                                                                                                                                                                                                                             Jul 08, 2020    N/A                    pytest\n   :pypi:`pytest-embedded`                                  A pytest plugin that designed for embedded testing.                                                                                                                                                                                                                                                                                                                                     Mar 02, 2026    5 - Production/Stable  pytest>=7.0\n   :pypi:`pytest-embedded-arduino`                          Make pytest-embedded plugin work with Arduino.                                                                                                                                                                                                                                                                                                                                          Mar 02, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-embedded-idf`                              Make pytest-embedded plugin work with ESP-IDF.                                                                                                                                                                                                                                                                                                                                          Mar 02, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-embedded-jtag`                             Make pytest-embedded plugin work with JTAG.                                                                                                                                                                                                                                                                                                                                             Mar 02, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-embedded-nuttx`                            Make pytest-embedded plugin work with NuttX.                                                                                                                                                                                                                                                                                                                                            Mar 02, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-embedded-qemu`                             Make pytest-embedded plugin work with QEMU.                                                                                                                                                                                                                                                                                                                                             Mar 02, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-embedded-serial`                           Make pytest-embedded plugin work with Serial.                                                                                                                                                                                                                                                                                                                                           Mar 02, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-embedded-serial-esp`                       Make pytest-embedded plugin work with Espressif target boards.                                                                                                                                                                                                                                                                                                                          Mar 02, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-embedded-wokwi`                            Make pytest-embedded plugin work with the Wokwi CLI.                                                                                                                                                                                                                                                                                                                                    Mar 02, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-embrace`                                   💝  Dataclasses-as-tests. Describe the runtime once and multiply coverage with no boilerplate.                                                                                                                                                                                                                                                                                          Mar 25, 2023    N/A                    pytest (>=7.0,<8.0)\n   :pypi:`pytest-emoji`                                     A pytest plugin that adds emojis to your test result report                                                                                                                                                                                                                                                                                                                             Feb 19, 2019    4 - Beta               pytest (>=4.2.1)\n   :pypi:`pytest-emoji-output`                              Pytest plugin to represent test output with emoji support                                                                                                                                                                                                                                                                                                                               Apr 09, 2023    4 - Beta               pytest (==7.0.1)\n   :pypi:`pytest-enabler`                                   Enable installed pytest plugins                                                                                                                                                                                                                                                                                                                                                         May 16, 2025    5 - Production/Stable  pytest!=8.1.*,>=6; extra == \"test\"\n   :pypi:`pytest-encode`                                    set your encoding and logger                                                                                                                                                                                                                                                                                                                                                            Nov 06, 2021    N/A                    N/A\n   :pypi:`pytest-encode-kane`                               set your encoding and logger                                                                                                                                                                                                                                                                                                                                                            Nov 16, 2021    N/A                    pytest\n   :pypi:`pytest-encoding`                                  set your encoding and logger                                                                                                                                                                                                                                                                                                                                                            Aug 11, 2023    N/A                    pytest\n   :pypi:`pytest_energy_reporter`                           An energy estimation reporter for pytest                                                                                                                                                                                                                                                                                                                                                Mar 28, 2024    3 - Alpha              pytest<9.0.0,>=8.1.1\n   :pypi:`pytest-enhanced-reports`                          Enhanced test reports for pytest                                                                                                                                                                                                                                                                                                                                                        Dec 15, 2022    N/A                    N/A\n   :pypi:`pytest-enhancements`                              Improvements for pytest (rejected upstream)                                                                                                                                                                                                                                                                                                                                             Oct 30, 2019    4 - Beta               N/A\n   :pypi:`pytest-env`                                       pytest plugin that allows you to add environment variables.                                                                                                                                                                                                                                                                                                                             Mar 12, 2026    5 - Production/Stable  pytest>=9.0.2\n   :pypi:`pytest-envfiles`                                  A py.test plugin that parses environment files before running tests                                                                                                                                                                                                                                                                                                                     Oct 08, 2015    3 - Alpha              N/A\n   :pypi:`pytest-env-info`                                  Push information about the running pytest into envvars                                                                                                                                                                                                                                                                                                                                  Nov 25, 2017    4 - Beta               pytest (>=3.1.1)\n   :pypi:`pytest-environment`                               Pytest Environment                                                                                                                                                                                                                                                                                                                                                                      Mar 17, 2024    1 - Planning           N/A\n   :pypi:`pytest-envraw`                                    py.test plugin that allows you to add environment variables.                                                                                                                                                                                                                                                                                                                            Aug 27, 2020    4 - Beta               pytest (>=2.6.0)\n   :pypi:`pytest-envvars`                                   Pytest plugin to validate use of envvars on your tests                                                                                                                                                                                                                                                                                                                                  Jun 13, 2020    5 - Production/Stable  pytest (>=3.0.0)\n   :pypi:`pytest-envx`                                      Pytest plugin for managing environment variables with interpolation and .env file support.                                                                                                                                                                                                                                                                                              Jun 28, 2025    4 - Beta               pytest>=8.4.1\n   :pypi:`pytest-env-yaml`                                                                                                                                                                                                                                                                                                                                                                                                                          Apr 02, 2019    N/A                    N/A\n   :pypi:`pytest-ephemeral-container`                       Spawn epehemeral containers in pytest                                                                                                                                                                                                                                                                                                                                                   Dec 05, 2025    N/A                    pytest\n   :pypi:`pytest-eradicate`                                 pytest plugin to check for commented out code                                                                                                                                                                                                                                                                                                                                           Sep 08, 2020    N/A                    pytest (>=2.4.2)\n   :pypi:`pytest_erp`                                       py.test plugin to send test info to report portal dynamically                                                                                                                                                                                                                                                                                                                           Jan 13, 2015    N/A                    N/A\n   :pypi:`pytest-error`                                     A decorator for testing exceptions with pytest                                                                                                                                                                                                                                                                                                                                          Dec 06, 2025    4 - Beta               pytest>=8.4\n   :pypi:`pytest-error-for-skips`                           Pytest plugin to treat skipped tests a test failure                                                                                                                                                                                                                                                                                                                                     Dec 19, 2019    4 - Beta               pytest (>=4.6)\n   :pypi:`pytest-errxfail`                                  pytest plugin to mark a test as xfailed if it fails with the specified error message in the captured output                                                                                                                                                                                                                                                                             Jan 06, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-essentials`                                A Pytest plugin providing essential utilities like soft assertions.                                                                                                                                                                                                                                                                                                                     May 19, 2025    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-eth`                                       PyTest plugin for testing Smart Contracts for Ethereum Virtual Machine (EVM).                                                                                                                                                                                                                                                                                                           Aug 14, 2020    1 - Planning           N/A\n   :pypi:`pytest-ethereum`                                  pytest-ethereum: Pytest library for ethereum projects.                                                                                                                                                                                                                                                                                                                                  Jun 24, 2019    3 - Alpha              pytest (==3.3.2); extra == 'dev'\n   :pypi:`pytest-eucalyptus`                                Pytest Plugin for BDD                                                                                                                                                                                                                                                                                                                                                                   Jun 28, 2022    N/A                    pytest (>=4.2.0)\n   :pypi:`pytest-eval`                                      LLM testing for humans.                                                                                                                                                                                                                                                                                                                                                                 Feb 11, 2026    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-evals`                                     A pytest plugin for running and analyzing LLM evaluation tests                                                                                                                                                                                                                                                                                                                          Feb 02, 2025    N/A                    pytest>=7.0.0\n   :pypi:`pytest-eventlet`                                  Applies eventlet monkey-patch as a pytest plugin.                                                                                                                                                                                                                                                                                                                                       Oct 04, 2021    N/A                    pytest ; extra == 'dev'\n   :pypi:`pytest-everyfunc`                                 A pytest plugin to detect completely untested functions using coverage                                                                                                                                                                                                                                                                                                                  Apr 30, 2025    4 - Beta               pytest\n   :pypi:`pytest_evm`                                       The testing package containing tools to test Web3-based projects                                                                                                                                                                                                                                                                                                                        Sep 23, 2024    4 - Beta               pytest<9.0.0,>=8.1.1\n   :pypi:`pytest_exact_fixtures`                            Parse queries in Lucene and Elasticsearch syntaxes                                                                                                                                                                                                                                                                                                                                      Feb 04, 2019    N/A                    N/A\n   :pypi:`pytest-examples`                                  Pytest plugin for testing examples in docstrings and markdown files.                                                                                                                                                                                                                                                                                                                    May 06, 2025    N/A                    pytest>=7\n   :pypi:`pytest-exasol-backend`                                                                                                                                                                                                                                                                                                                                                                                                                    Mar 03, 2026    N/A                    pytest<9,>=7\n   :pypi:`pytest-exasol-extension`                                                                                                                                                                                                                                                                                                                                                                                                                  Feb 06, 2026    N/A                    pytest<9,>=7\n   :pypi:`pytest-exasol-itde`                                                                                                                                                                                                                                                                                                                                                                                                                       Nov 22, 2024    N/A                    pytest<9,>=7\n   :pypi:`pytest-exasol-saas`                                                                                                                                                                                                                                                                                                                                                                                                                       Nov 22, 2024    N/A                    pytest<9,>=7\n   :pypi:`pytest-exasol-slc`                                                                                                                                                                                                                                                                                                                                                                                                                        Feb 12, 2026    N/A                    pytest<9,>=7\n   :pypi:`pytest-excel`                                     pytest plugin for generating excel reports                                                                                                                                                                                                                                                                                                                                              Jul 22, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-exceptional`                               Better exceptions                                                                                                                                                                                                                                                                                                                                                                       Mar 16, 2017    4 - Beta               N/A\n   :pypi:`pytest-exception-script`                          Walk your code through exception script to check it's resiliency to failures.                                                                                                                                                                                                                                                                                                           Aug 04, 2020    3 - Alpha              pytest\n   :pypi:`pytest-executable`                                pytest plugin for testing executables                                                                                                                                                                                                                                                                                                                                                   Oct 07, 2023    N/A                    pytest <8,>=5\n   :pypi:`pytest-execution-timer`                           A timer for the phases of Pytest's execution.                                                                                                                                                                                                                                                                                                                                           Dec 24, 2021    4 - Beta               N/A\n   :pypi:`pytest-exit-code`                                 A pytest plugin that overrides the built-in exit codes to retain more information about the test results.                                                                                                                                                                                                                                                                               May 06, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-exit-status`                               Enhance.                                                                                                                                                                                                                                                                                                                                                                                Jan 25, 2025    N/A                    pytest>=8.0.0\n   :pypi:`pytest-expect`                                    py.test plugin to store test expectations and mark tests based on them                                                                                                                                                                                                                                                                                                                  Apr 21, 2016    4 - Beta               N/A\n   :pypi:`pytest-expectdir`                                 A pytest plugin to provide initial/expected directories, and check a test transforms the initial directory to the expected one                                                                                                                                                                                                                                                          Mar 19, 2023    5 - Production/Stable  pytest (>=5.0)\n   :pypi:`pytest-expected`                                  Record and play back your expectations                                                                                                                                                                                                                                                                                                                                                  Feb 26, 2025    N/A                    pytest\n   :pypi:`pytest-expecter`                                  Better testing with expecter and pytest.                                                                                                                                                                                                                                                                                                                                                Sep 18, 2022    5 - Production/Stable  N/A\n   :pypi:`pytest-expectr`                                   This plugin is used to expect multiple assert using pytest framework.                                                                                                                                                                                                                                                                                                                   Oct 05, 2018    N/A                    pytest (>=2.4.2)\n   :pypi:`pytest-expect-test`                               A fixture to support expect tests in pytest                                                                                                                                                                                                                                                                                                                                             Apr 10, 2023    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-experiments`                               A pytest plugin to help developers of research-oriented software projects keep track of the results of their numerical experiments.                                                                                                                                                                                                                                                     Dec 13, 2021    4 - Beta               pytest (>=6.2.5,<7.0.0)\n   :pypi:`pytest-explicit`                                  A Pytest plugin to ignore certain marked tests by default                                                                                                                                                                                                                                                                                                                               Jun 15, 2021    5 - Production/Stable  pytest\n   :pypi:`pytest-exploratory`                               Interactive console for pytest.                                                                                                                                                                                                                                                                                                                                                         Sep 18, 2024    N/A                    pytest>=6.2\n   :pypi:`pytest-explorer`                                  terminal ui for exploring and running tests                                                                                                                                                                                                                                                                                                                                             Aug 01, 2023    N/A                    N/A\n   :pypi:`pytest-ext`                                       pytest plugin for automation test                                                                                                                                                                                                                                                                                                                                                       Mar 31, 2024    N/A                    pytest>=5.3\n   :pypi:`pytest-extended-mock`                             a pytest extension for easy mock setup                                                                                                                                                                                                                                                                                                                                                  Mar 12, 2025    N/A                    pytest<9.0.0,>=8.3.5\n   :pypi:`pytest-extensions`                                A collection of helpers for pytest to ease testing                                                                                                                                                                                                                                                                                                                                      Aug 17, 2022    4 - Beta               pytest ; extra == 'testing'\n   :pypi:`pytest-external-blockers`                         a special outcome for tests that are blocked for external reasons                                                                                                                                                                                                                                                                                                                       Oct 05, 2021    N/A                    pytest\n   :pypi:`pytest_extra`                                     Some helpers for writing tests with pytest.                                                                                                                                                                                                                                                                                                                                             Aug 14, 2014    N/A                    N/A\n   :pypi:`pytest-extra-durations`                           A pytest plugin to get durations on a per-function basis and per module basis.                                                                                                                                                                                                                                                                                                          Apr 21, 2020    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-extra-markers`                             Additional pytest markers to dynamically enable/disable tests viia CLI flags                                                                                                                                                                                                                                                                                                            Mar 05, 2023    4 - Beta               pytest\n   :pypi:`pytest-f3ts`                                      Pytest Plugin for communicating test results and information to a FixturFab Test Runner GUI                                                                                                                                                                                                                                                                                             Mar 09, 2026    N/A                    pytest<8.0.0,>=7.2.1\n   :pypi:`pytest-fabric`                                    Provides test utilities to run fabric task tests by using docker containers                                                                                                                                                                                                                                                                                                             Sep 12, 2018    5 - Production/Stable  N/A\n   :pypi:`pytest-factory`                                   Use factories for test setup with py.test                                                                                                                                                                                                                                                                                                                                               Sep 06, 2020    3 - Alpha              pytest (>4.3)\n   :pypi:`pytest-factoryboy`                                Factory Boy support for pytest.                                                                                                                                                                                                                                                                                                                                                         Jul 01, 2025    6 - Mature             pytest>=7.0\n   :pypi:`pytest-factoryboy-fixtures`                       Generates pytest fixtures that allow the use of type hinting                                                                                                                                                                                                                                                                                                                            Jun 25, 2020    N/A                    N/A\n   :pypi:`pytest-factoryboy-state`                          Simple factoryboy random state management                                                                                                                                                                                                                                                                                                                                               Mar 22, 2022    5 - Production/Stable  pytest (>=5.0)\n   :pypi:`pytest-failed-screen-record`                      Create a video of the screen when pytest fails                                                                                                                                                                                                                                                                                                                                          Jan 05, 2023    4 - Beta               pytest (>=7.1.2d,<8.0.0)\n   :pypi:`pytest-failed-screenshot`                         Test case fails,take a screenshot,save it,attach it to the allure                                                                                                                                                                                                                                                                                                                       Apr 21, 2021    N/A                    N/A\n   :pypi:`pytest-failed-to-verify`                          A pytest plugin that helps better distinguishing real test failures from setup flakiness.                                                                                                                                                                                                                                                                                               Aug 08, 2019    5 - Production/Stable  pytest (>=4.1.0)\n   :pypi:`pytest-fail-slow`                                 Fail tests that take too long to run                                                                                                                                                                                                                                                                                                                                                    Jun 01, 2024    N/A                    pytest>=7.0\n   :pypi:`pytest-failure-tracker`                           A pytest plugin for tracking test failures over multiple runs                                                                                                                                                                                                                                                                                                                           Jul 17, 2024    N/A                    pytest>=6.0.0\n   :pypi:`pytest-faker`                                     Faker integration with the pytest framework.                                                                                                                                                                                                                                                                                                                                            Dec 19, 2016    6 - Mature             N/A\n   :pypi:`pytest-falcon`                                    Pytest helpers for Falcon.                                                                                                                                                                                                                                                                                                                                                              Sep 07, 2016    4 - Beta               N/A\n   :pypi:`pytest-fantasy`                                   Pytest plugin for Flask Fantasy Framework                                                                                                                                                                                                                                                                                                                                               Mar 14, 2019    N/A                    N/A\n   :pypi:`pytest-fastapi`                                                                                                                                                                                                                                                                                                                                                                                                                           Dec 27, 2020    N/A                    N/A\n   :pypi:`pytest-fastapi-deps`                              A fixture which allows easy replacement of fastapi dependencies for testing                                                                                                                                                                                                                                                                                                             Jul 20, 2022    5 - Production/Stable  pytest\n   :pypi:`pytest-fastcollect`                               A high-performance pytest plugin that replaces test collection with a Rust-based implementation                                                                                                                                                                                                                                                                                         Nov 19, 2025    N/A                    pytest>=7.0.0\n   :pypi:`pytest-fastest`                                   Use SCM and coverage to run only needed tests                                                                                                                                                                                                                                                                                                                                           Oct 04, 2023    4 - Beta               pytest (>=4.4)\n   :pypi:`pytest-fast-first`                                Pytest plugin that runs fast tests first                                                                                                                                                                                                                                                                                                                                                Jan 19, 2023    3 - Alpha              pytest\n   :pypi:`pytest-faulthandler`                              py.test plugin that activates the fault handler module for tests (dummy package)                                                                                                                                                                                                                                                                                                        Jul 04, 2019    6 - Mature             pytest (>=5.0)\n   :pypi:`pytest-fauna`                                     A collection of helpful test fixtures for Fauna DB.                                                                                                                                                                                                                                                                                                                                     Jan 03, 2025    N/A                    N/A\n   :pypi:`pytest-fauxfactory`                               Integration of fauxfactory into pytest.                                                                                                                                                                                                                                                                                                                                                 Dec 06, 2017    5 - Production/Stable  pytest (>=3.2)\n   :pypi:`pytest-figleaf`                                   py.test figleaf coverage plugin                                                                                                                                                                                                                                                                                                                                                         Jan 18, 2010    5 - Production/Stable  N/A\n   :pypi:`pytest-file`                                      Pytest File                                                                                                                                                                                                                                                                                                                                                                             Mar 18, 2024    1 - Planning           N/A\n   :pypi:`pytest-filecov`                                   A pytest plugin to detect unused files                                                                                                                                                                                                                                                                                                                                                  Jun 27, 2021    4 - Beta               pytest\n   :pypi:`pytest-filedata`                                  easily load test data from files                                                                                                                                                                                                                                                                                                                                                        Apr 29, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-filemarker`                                A pytest plugin that runs marked tests when files change.                                                                                                                                                                                                                                                                                                                               Dec 01, 2020    N/A                    pytest\n   :pypi:`pytest-file-watcher`                              Pytest-File-Watcher is a CLI tool that watches for changes in your code and runs pytest on the changed files.                                                                                                                                                                                                                                                                           Mar 23, 2023    N/A                    pytest\n   :pypi:`pytest-filter-case`                               run test cases filter by mark                                                                                                                                                                                                                                                                                                                                                           Nov 05, 2020    N/A                    N/A\n   :pypi:`pytest-filterfixtures`                            pytest plugin to execute or ignore tests based on fixtures                                                                                                                                                                                                                                                                                                                              Jan 09, 2026    N/A                    pytest>=9.0.2\n   :pypi:`pytest-filter-subpackage`                         Pytest plugin for filtering based on sub-packages                                                                                                                                                                                                                                                                                                                                       Mar 04, 2024    5 - Production/Stable  pytest >=4.6\n   :pypi:`pytest-find-dependencies`                         A pytest plugin to find dependencies between tests                                                                                                                                                                                                                                                                                                                                      Jul 16, 2025    5 - Production/Stable  pytest>=6.2.4\n   :pypi:`pytest-finer-verdicts`                            A pytest plugin to treat non-assertion failures as test errors.                                                                                                                                                                                                                                                                                                                         Jun 18, 2020    N/A                    pytest (>=5.4.3)\n   :pypi:`pytest-firefox`                                                                                                                                                                                                                                                                                                                                                                                                                           Feb 28, 2025    N/A                    N/A\n   :pypi:`pytest-firestore`                                 A Pytest fixture for managing Google Cloud Firestore emulator                                                                                                                                                                                                                                                                                                                           Mar 10, 2026    N/A                    pytest>=7.0\n   :pypi:`pytest-fixedpoint`                                Pytest plugin for recording and replaying deterministic function calls                                                                                                                                                                                                                                                                                                                  Mar 12, 2026    N/A                    pytest>=7.0\n   :pypi:`pytest-fixture-cache`                             Smart fixture caching for pytest with SQLite storage                                                                                                                                                                                                                                                                                                                                    Jan 25, 2026    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-fixturecheck`                              A pytest plugin to check fixture validity before test execution                                                                                                                                                                                                                                                                                                                         Jun 02, 2025    3 - Alpha              pytest>=6.0.0\n   :pypi:`pytest-fixture-classes`                           Fixtures as classes that work well with dependency injection, autocompletetion, type checkers, and language servers                                                                                                                                                                                                                                                                     Oct 12, 2025    5 - Production/Stable  N/A\n   :pypi:`pytest-fixture-collect`                           A utility to collect pytest fixture file paths.                                                                                                                                                                                                                                                                                                                                         Jul 25, 2025    N/A                    pytest; extra == \"test\"\n   :pypi:`pytest-fixturecollection`                         A pytest plugin to collect tests based on fixtures being used by tests                                                                                                                                                                                                                                                                                                                  Feb 22, 2024    4 - Beta               pytest >=3.5.0\n   :pypi:`pytest-fixture-config`                            Fixture configuration utils for py.test                                                                                                                                                                                                                                                                                                                                                 Oct 17, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-fixture-forms`                             A pytest plugin for creating fixtures that holds different forms between tests.                                                                                                                                                                                                                                                                                                         Dec 06, 2024    N/A                    pytest<9.0.0,>=7.0.0\n   :pypi:`pytest-fixture-maker`                             Pytest plugin to load fixtures from YAML files                                                                                                                                                                                                                                                                                                                                          Sep 21, 2021    N/A                    N/A\n   :pypi:`pytest-fixture-marker`                            A pytest plugin to add markers based on fixtures used.                                                                                                                                                                                                                                                                                                                                  Oct 11, 2020    5 - Production/Stable  N/A\n   :pypi:`pytest-fixture-order`                             pytest plugin to control fixture evaluation order                                                                                                                                                                                                                                                                                                                                       Oct 22, 2025    5 - Production/Stable  pytest>=3.0\n   :pypi:`pytest-fixture-ref`                               Lets users reference fixtures without name matching magic.                                                                                                                                                                                                                                                                                                                              Nov 17, 2022    4 - Beta               N/A\n   :pypi:`pytest-fixture-remover`                           A LibCST codemod to remove pytest fixtures applied via the usefixtures decorator, as well as its parametrizations.                                                                                                                                                                                                                                                                      Feb 14, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-fixture-rtttg`                             Warn or fail on fixture name clash                                                                                                                                                                                                                                                                                                                                                      Feb 23, 2022    N/A                    pytest (>=7.0.1,<8.0.0)\n   :pypi:`pytest-fixtures`                                  Common fixtures for pytest                                                                                                                                                                                                                                                                                                                                                              May 01, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-fixtures-fixtures`                         Handy fixtues to access your fixtures from your _pytest tests.                                                                                                                                                                                                                                                                                                                          Nov 06, 2025    4 - Beta               pytest>=8.4.1\n   :pypi:`pytest-fixture-timing`                            Tiny plugin to report total duration per fixture                                                                                                                                                                                                                                                                                                                                        Dec 11, 2025    N/A                    pytest>=7.0\n   :pypi:`pytest-fixture-tools`                             Plugin for pytest which provides tools for fixtures                                                                                                                                                                                                                                                                                                                                     Apr 30, 2025    6 - Mature             pytest\n   :pypi:`pytest-fixture-typecheck`                         A pytest plugin to assert type annotations at runtime.                                                                                                                                                                                                                                                                                                                                  Aug 24, 2021    N/A                    pytest\n   :pypi:`pytest-fkit`                                      A pytest plugin that prevents crashes from killing your test suite                                                                                                                                                                                                                                                                                                                      Feb 19, 2026    N/A                    pytest>=6.0.0\n   :pypi:`pytest-flake8`                                    pytest plugin to check FLAKE8 requirements                                                                                                                                                                                                                                                                                                                                              Nov 09, 2024    5 - Production/Stable  pytest>=7.0\n   :pypi:`pytest-flake8-path`                               A pytest fixture for testing flake8 plugins.                                                                                                                                                                                                                                                                                                                                            Sep 09, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-flake8-v2`                                 pytest plugin to check FLAKE8 requirements                                                                                                                                                                                                                                                                                                                                              Mar 01, 2022    5 - Production/Stable  pytest (>=7.0)\n   :pypi:`pytest-flake-detection`                           Continuously runs your tests to detect flaky tests                                                                                                                                                                                                                                                                                                                                      Nov 29, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-flakefighters`                             Pytest plugin implementing flaky test failure detection and classification.                                                                                                                                                                                                                                                                                                             Mar 05, 2026    N/A                    pytest>=6.2.0\n   :pypi:`pytest-flakefinder`                               Runs tests multiple times to expose flakiness.                                                                                                                                                                                                                                                                                                                                          Oct 26, 2022    4 - Beta               pytest (>=2.7.1)\n   :pypi:`pytest-flakes`                                    pytest plugin to check source code with pyflakes                                                                                                                                                                                                                                                                                                                                        Dec 02, 2021    5 - Production/Stable  pytest (>=5)\n   :pypi:`pytest-flakiness`                                 Pytest reporter for Flakiness.io                                                                                                                                                                                                                                                                                                                                                        Feb 28, 2026    N/A                    pytest>=9.0.2\n   :pypi:`pytest-flaptastic`                                Flaptastic py.test plugin                                                                                                                                                                                                                                                                                                                                                               Mar 17, 2019    N/A                    N/A\n   :pypi:`pytest-flask`                                     A set of py.test fixtures to test Flask applications.                                                                                                                                                                                                                                                                                                                                   Oct 23, 2023    5 - Production/Stable  pytest >=5.2\n   :pypi:`pytest-flask-ligand`                              Pytest fixtures and helper functions to use for testing flask-ligand microservices.                                                                                                                                                                                                                                                                                                     Apr 25, 2023    4 - Beta               pytest (~=7.3)\n   :pypi:`pytest-flask-sqlalchemy`                          A pytest plugin for preserving test isolation in Flask-SQlAlchemy using database transactions.                                                                                                                                                                                                                                                                                          Apr 30, 2022    4 - Beta               pytest (>=3.2.1)\n   :pypi:`pytest-flask-sqlalchemy-transactions`             Run tests in transactions using pytest, Flask, and SQLalchemy.                                                                                                                                                                                                                                                                                                                          Aug 02, 2018    4 - Beta               pytest (>=3.2.1)\n   :pypi:`pytest-flexreport`                                                                                                                                                                                                                                                                                                                                                                                                                        Apr 15, 2023    4 - Beta               pytest\n   :pypi:`pytest-fluent`                                    A pytest plugin in order to provide logs via fluentd                                                                                                                                                                                                                                                                                                                                    Aug 14, 2024    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-fluentbit`                                 A pytest plugin in order to provide logs via fluentbit                                                                                                                                                                                                                                                                                                                                  Jun 16, 2023    4 - Beta               pytest (>=7.0.0)\n   :pypi:`pytest-fly`                                       pytest runner and observer                                                                                                                                                                                                                                                                                                                                                              Feb 23, 2026    3 - Alpha              pytest\n   :pypi:`pytest-flyte`                                     Pytest fixtures for simplifying Flyte integration testing                                                                                                                                                                                                                                                                                                                               May 03, 2021    N/A                    pytest\n   :pypi:`pytest-fmu-filter`                                A pytest plugin to filter fmus                                                                                                                                                                                                                                                                                                                                                          Jun 23, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-focus`                                     A pytest plugin that alerts user of failed test cases with screen notifications                                                                                                                                                                                                                                                                                                         May 04, 2019    4 - Beta               pytest\n   :pypi:`pytest-forbid`                                                                                                                                                                                                                                                                                                                                                                                                                            Mar 07, 2023    N/A                    pytest (>=7.2.2,<8.0.0)\n   :pypi:`pytest-forcefail`                                 py.test plugin to make the test failing regardless of pytest.mark.xfail                                                                                                                                                                                                                                                                                                                 May 15, 2018    4 - Beta               N/A\n   :pypi:`pytest-forger`                                    Automatic test scaffolding and mock generation for Python                                                                                                                                                                                                                                                                                                                               Mar 09, 2026    N/A                    pytest>=7.4.0\n   :pypi:`pytest-forward-compatability`                     A name to avoid typosquating pytest-foward-compatibility                                                                                                                                                                                                                                                                                                                                Sep 06, 2020    N/A                    N/A\n   :pypi:`pytest-forward-compatibility`                     A pytest plugin to shim pytest commandline options for fowards compatibility                                                                                                                                                                                                                                                                                                            Sep 29, 2020    N/A                    N/A\n   :pypi:`pytest-frappe`                                    Pytest Frappe Plugin - A set of pytest fixtures to test Frappe applications                                                                                                                                                                                                                                                                                                             Jul 30, 2024    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-freethreaded`                              pytest plugin for running parallel tests                                                                                                                                                                                                                                                                                                                                                Oct 03, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-freeze`                                    Pytest plugin to simplify writing freeze tests.                                                                                                                                                                                                                                                                                                                                         Jan 27, 2026    N/A                    N/A\n   :pypi:`pytest-freezeblaster`                             Wrap tests with fixtures in freeze_time                                                                                                                                                                                                                                                                                                                                                 Oct 13, 2025    N/A                    pytest>=6.2.5\n   :pypi:`pytest-freezegun`                                 Wrap tests with fixtures in freeze_time                                                                                                                                                                                                                                                                                                                                                 Jul 19, 2020    4 - Beta               pytest (>=3.0.0)\n   :pypi:`pytest-freezer`                                   Pytest plugin providing a fixture interface for spulec/freezegun                                                                                                                                                                                                                                                                                                                        Dec 12, 2024    N/A                    pytest>=3.6\n   :pypi:`pytest-freeze-reqs`                               Check if requirement files are frozen                                                                                                                                                                                                                                                                                                                                                   Apr 29, 2021    N/A                    N/A\n   :pypi:`pytest-frozen-uuids`                              Deterministically frozen UUID's for your tests                                                                                                                                                                                                                                                                                                                                          Apr 17, 2022    N/A                    pytest (>=3.0)\n   :pypi:`pytest_ftpserver`                                 A PyTest plugin which provides an FTP fixture for your tests                                                                                                                                                                                                                                                                                                                            Feb 10, 2026    5 - Production/Stable  pytest\n   :pypi:`pytest-func-cov`                                  Pytest plugin for measuring function coverage                                                                                                                                                                                                                                                                                                                                           Apr 15, 2021    3 - Alpha              pytest (>=5)\n   :pypi:`pytest-funcnodes`                                 Testing plugin for funcnodes                                                                                                                                                                                                                                                                                                                                                            Dec 21, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-funparam`                                  An alternative way to parametrize test cases.                                                                                                                                                                                                                                                                                                                                           Dec 02, 2021    4 - Beta               pytest >=4.6.0\n   :pypi:`pytest-fv`                                        pytest extensions to support running functional-verification jobs                                                                                                                                                                                                                                                                                                                       Jun 06, 2025    N/A                    pytest\n   :pypi:`pytest-fxa`                                       pytest plugin for Firefox Accounts                                                                                                                                                                                                                                                                                                                                                      Aug 28, 2018    5 - Production/Stable  N/A\n   :pypi:`pytest-fxa-mte`                                   pytest plugin for Firefox Accounts                                                                                                                                                                                                                                                                                                                                                      Oct 02, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-fxtest`                                                                                                                                                                                                                                                                                                                                                                                                                            Oct 27, 2020    N/A                    N/A\n   :pypi:`pytest-fzf`                                       fzf-based test selector for pytest                                                                                                                                                                                                                                                                                                                                                      Jan 06, 2025    4 - Beta               pytest>=6.0.0\n   :pypi:`pytest_gae`                                       pytest plugin for apps written with Google's AppEngine                                                                                                                                                                                                                                                                                                                                  Aug 03, 2016    3 - Alpha              N/A\n   :pypi:`pytest-gak`                                       A Pytest plugin and command line tool for interactive testing with Pytest                                                                                                                                                                                                                                                                                                               Apr 10, 2025    N/A                    N/A\n   :pypi:`pytest-gather-fixtures`                           set up asynchronous pytest fixtures concurrently                                                                                                                                                                                                                                                                                                                                        Aug 18, 2024    N/A                    pytest>=7.0.0\n   :pypi:`pytest-gc`                                        The garbage collector plugin for py.test                                                                                                                                                                                                                                                                                                                                                Feb 01, 2018    N/A                    N/A\n   :pypi:`pytest-gcov`                                      Uses gcov to measure test coverage of a C library                                                                                                                                                                                                                                                                                                                                       Feb 01, 2018    3 - Alpha              N/A\n   :pypi:`pytest-gcppubsub`                                 A Pytest fixture for managing Google Cloud Platform PubSub emulator                                                                                                                                                                                                                                                                                                                     Mar 10, 2026    N/A                    pytest>=7.0\n   :pypi:`pytest-gcpsecretmanager`                          A PyTest plugin for mocking GCP's Secret Manager                                                                                                                                                                                                                                                                                                                                        Feb 18, 2026    N/A                    pytest>=7.0\n   :pypi:`pytest-gcs`                                       GCS fixtures and fixture factories for Pytest.                                                                                                                                                                                                                                                                                                                                          Jan 24, 2025    5 - Production/Stable  pytest>=6.2\n   :pypi:`pytest-gee`                                       The Python plugin for your GEE based packages.                                                                                                                                                                                                                                                                                                                                          Oct 16, 2025    3 - Alpha              pytest\n   :pypi:`pytest-gevent`                                    Ensure that gevent is properly patched when invoking pytest                                                                                                                                                                                                                                                                                                                             Feb 25, 2020    N/A                    pytest\n   :pypi:`pytest-gherkin`                                   A flexible framework for executing BDD gherkin tests                                                                                                                                                                                                                                                                                                                                    Jul 27, 2019    3 - Alpha              pytest (>=5.0.0)\n   :pypi:`pytest-gh-log-group`                              pytest plugin for gh actions                                                                                                                                                                                                                                                                                                                                                            Jan 11, 2022    3 - Alpha              pytest\n   :pypi:`pytest-ghostinspector`                            For finding/executing Ghost Inspector tests                                                                                                                                                                                                                                                                                                                                             May 17, 2016    3 - Alpha              N/A\n   :pypi:`pytest-girder`                                    A set of pytest fixtures for testing Girder applications.                                                                                                                                                                                                                                                                                                                               Mar 04, 2026    N/A                    pytest>=3.6\n   :pypi:`pytest-git`                                       Git repository fixture for py.test                                                                                                                                                                                                                                                                                                                                                      Oct 17, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-gitconfig`                                 Provide a Git config sandbox for testing                                                                                                                                                                                                                                                                                                                                                Dec 28, 2025    4 - Beta               pytest>=7.1.2\n   :pypi:`pytest-gitcov`                                    Pytest plugin for reporting on coverage of the last git commit.                                                                                                                                                                                                                                                                                                                         Jan 11, 2020    2 - Pre-Alpha          N/A\n   :pypi:`pytest-git-diff`                                  Pytest plugin that allows the user to select the tests affected by a range of git commits                                                                                                                                                                                                                                                                                               Apr 02, 2024    N/A                    N/A\n   :pypi:`pytest-git-fixtures`                              Pytest fixtures for testing with git.                                                                                                                                                                                                                                                                                                                                                   Mar 11, 2021    4 - Beta               pytest\n   :pypi:`pytest-github`                                    Plugin for py.test that associates tests with github issues using a marker.                                                                                                                                                                                                                                                                                                             Mar 07, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-github-actions-annotate-failures`          pytest plugin to annotate failed tests with a workflow command for GitHub Actions                                                                                                                                                                                                                                                                                                       Mar 02, 2026    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-github-report`                             Generate a GitHub report using pytest in GitHub Workflows                                                                                                                                                                                                                                                                                                                               Jun 03, 2022    4 - Beta               N/A\n   :pypi:`pytest-gitignore`                                 py.test plugin to ignore the same files as git                                                                                                                                                                                                                                                                                                                                          Jul 17, 2015    4 - Beta               N/A\n   :pypi:`pytest-gitlab`                                    Pytest Plugin for Gitlab                                                                                                                                                                                                                                                                                                                                                                Oct 16, 2024    N/A                    N/A\n   :pypi:`pytest-gitlabci-parallelized`                     Parallelize pytest across GitLab CI workers.                                                                                                                                                                                                                                                                                                                                            Mar 08, 2023    N/A                    N/A\n   :pypi:`pytest-gitlab-code-quality`                       Collects warnings while testing and generates a GitLab Code Quality Report.                                                                                                                                                                                                                                                                                                             Nov 23, 2025    N/A                    pytest>=8.1.1\n   :pypi:`pytest-gitlab-fold`                               Folds output sections in GitLab CI build log                                                                                                                                                                                                                                                                                                                                            Dec 31, 2023    4 - Beta               pytest >=2.6.0\n   :pypi:`pytest-gitscope`                                  A pragmatic pytest plugin that runs only the tests that matter, and ship faster                                                                                                                                                                                                                                                                                                         Sep 24, 2025    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-git-selector`                              Utility to select tests that have had its dependencies modified (as identified by git diff)                                                                                                                                                                                                                                                                                             Nov 17, 2022    N/A                    N/A\n   :pypi:`pytest-glamor-allure`                             Extends allure-pytest functionality                                                                                                                                                                                                                                                                                                                                                     Jan 30, 2026    5 - Production/Stable  pytest<=9.0.2\n   :pypi:`pytest-glow-report`                               Beautiful, glowing HTML test reports for PyTest and unittest.                                                                                                                                                                                                                                                                                                                           Dec 08, 2025    4 - Beta               pytest>=6.0; extra == \"dev\"\n   :pypi:`pytest-gnupg-fixtures`                            Pytest fixtures for testing with gnupg.                                                                                                                                                                                                                                                                                                                                                 Mar 04, 2021    4 - Beta               pytest\n   :pypi:`pytest-golden`                                    Plugin for pytest that offloads expected outputs to data files                                                                                                                                                                                                                                                                                                                          Jan 06, 2026    5 - Production/Stable  pytest>=6.1.2\n   :pypi:`pytest-goldie`                                    A plugin to support golden tests with pytest.                                                                                                                                                                                                                                                                                                                                           May 23, 2023    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-google-chat`                               Notify google chat channel for test results                                                                                                                                                                                                                                                                                                                                             Mar 27, 2022    4 - Beta               pytest\n   :pypi:`pytest-google-cloud-storage`                      Pytest custom features, e.g. fixtures and various tests. Aimed to emulate Google Cloud Storage service                                                                                                                                                                                                                                                                                  Sep 11, 2025    N/A                    pytest>=8.0.0\n   :pypi:`pytest-grader`                                    Pytest extension for scoring programming assignments.                                                                                                                                                                                                                                                                                                                                   Aug 25, 2025    N/A                    pytest>=8\n   :pypi:`pytest-gradescope`                                A pytest plugin for Gradescope integration                                                                                                                                                                                                                                                                                                                                              Apr 29, 2025    N/A                    N/A\n   :pypi:`pytest-graphql-schema`                            Get graphql schema as fixture for pytest                                                                                                                                                                                                                                                                                                                                                Oct 18, 2019    N/A                    N/A\n   :pypi:`pytest-greendots`                                 Green progress dots                                                                                                                                                                                                                                                                                                                                                                     Feb 08, 2014    3 - Alpha              N/A\n   :pypi:`pytest-greener`                                   Pytest plugin for Greener                                                                                                                                                                                                                                                                                                                                                               Dec 24, 2025    N/A                    pytest<9.0.0,>=8.3.3\n   :pypi:`pytest-green-light`                               Pytest plugin that gives SQLAlchemy async engines the green light - automatically fixes MissingGreenlet errors                                                                                                                                                                                                                                                                          Nov 03, 2025    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-greet`                                                                                                                                                                                                                                                                                                                                                                                                                             Oct 21, 2025    N/A                    N/A\n   :pypi:`pytest-gremlins`                                  Fast-first mutation testing for pytest. Let the gremlins loose, see which ones survive.                                                                                                                                                                                                                                                                                                 Mar 14, 2026    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-group-by-class`                            A Pytest plugin for running a subset of your tests by splitting them in to groups of classes.                                                                                                                                                                                                                                                                                           Jun 27, 2023    5 - Production/Stable  pytest (>=2.5)\n   :pypi:`pytest-growl`                                     Growl notifications for pytest results.                                                                                                                                                                                                                                                                                                                                                 Jan 13, 2014    5 - Production/Stable  N/A\n   :pypi:`pytest-grpc`                                      pytest plugin for grpc                                                                                                                                                                                                                                                                                                                                                                  May 01, 2020    N/A                    pytest (>=3.6.0)\n   :pypi:`pytest-grpc-aio`                                  pytest plugin for grpc.aio                                                                                                                                                                                                                                                                                                                                                              Oct 28, 2025    N/A                    pytest>=3.6.0\n   :pypi:`pytest-grunnur`                                   Py.Test plugin for Grunnur-based packages.                                                                                                                                                                                                                                                                                                                                              Jul 26, 2024    N/A                    pytest>=6\n   :pypi:`pytest_gui_status`                                Show pytest status in gui                                                                                                                                                                                                                                                                                                                                                               Jan 23, 2016    N/A                    pytest\n   :pypi:`pytest-hammertime`                                Display \"🔨 \" instead of \".\" for passed pytest tests.                                                                                                                                                                                                                                                                                                                                   Jul 28, 2018    N/A                    pytest\n   :pypi:`pytest-hardware-test-report`                      A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Apr 01, 2024    4 - Beta               pytest<9.0.0,>=8.0.0\n   :pypi:`pytest-harmony`                                   Chain tests and data with pytest                                                                                                                                                                                                                                                                                                                                                        Jan 17, 2023    N/A                    pytest (>=7.2.1,<8.0.0)\n   :pypi:`pytest-harvest`                                   Store data created during your pytest tests execution, and retrieve it at the end of the session, e.g. for applicative benchmarking purposes.                                                                                                                                                                                                                                           Mar 16, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-helm`                                      Simple, ergonomic Helm manifest fixtures for pytest.                                                                                                                                                                                                                                                                                                                                    Feb 21, 2026    3 - Alpha              pytest>=8.0.0\n   :pypi:`pytest-helm-charts`                               A plugin to provide different types and configs of Kubernetes clusters that can be used for testing.                                                                                                                                                                                                                                                                                    Dec 23, 2025    4 - Beta               pytest<9,>=8.0.0\n   :pypi:`pytest-helm-templates`                            Pytest fixtures for unit testing the output of helm templates                                                                                                                                                                                                                                                                                                                           Aug 07, 2024    N/A                    pytest~=7.4.0; extra == \"dev\"\n   :pypi:`pytest-helper`                                    Functions to help in using the pytest testing framework                                                                                                                                                                                                                                                                                                                                 May 31, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-helpers`                                   pytest helpers                                                                                                                                                                                                                                                                                                                                                                          May 17, 2020    N/A                    pytest\n   :pypi:`pytest-helpers-namespace`                         Pytest Helpers Namespace Plugin                                                                                                                                                                                                                                                                                                                                                         Dec 29, 2021    5 - Production/Stable  pytest (>=6.0.0)\n   :pypi:`pytest-henry`                                                                                                                                                                                                                                                                                                                                                                                                                             Aug 29, 2023    N/A                    N/A\n   :pypi:`pytest-hidecaptured`                              Hide captured output                                                                                                                                                                                                                                                                                                                                                                    May 04, 2018    4 - Beta               pytest (>=2.8.5)\n   :pypi:`pytest-himark`                                    This plugin aims to create markers automatically based on a json configuration.                                                                                                                                                                                                                                                                                                         Jun 05, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-historic`                                  Custom report to display pytest historical execution records                                                                                                                                                                                                                                                                                                                            Apr 08, 2020    N/A                    pytest\n   :pypi:`pytest-historic-hook`                             Custom listener to store execution results into MYSQL DB, which is used for pytest-historic report                                                                                                                                                                                                                                                                                      Apr 08, 2020    N/A                    pytest\n   :pypi:`pytest-history`                                   Pytest plugin to keep a history of your pytest runs                                                                                                                                                                                                                                                                                                                                     Jan 14, 2024    N/A                    pytest (>=7.4.3,<8.0.0)\n   :pypi:`pytest-home`                                      Home directory fixtures                                                                                                                                                                                                                                                                                                                                                                 Jul 28, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-homeassistant`                             A pytest plugin for use with homeassistant custom components.                                                                                                                                                                                                                                                                                                                           Aug 12, 2020    4 - Beta               N/A\n   :pypi:`pytest-homeassistant-custom-component`            Experimental package to automatically extract test plugins for Home Assistant custom components                                                                                                                                                                                                                                                                                         Mar 07, 2026    3 - Alpha              pytest==9.0.0\n   :pypi:`pytest-homeassistant-custom-component-framework`  Experimental package to automatically extract test plugins for Home Assistant custom components                                                                                                                                                                                                                                                                                         Mar 07, 2026    3 - Alpha              pytest==9.0.0\n   :pypi:`pytest-honey`                                     A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Jan 07, 2022    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-honors`                                    Report on tests that honor constraints, and guard against regressions                                                                                                                                                                                                                                                                                                                   Mar 06, 2020    4 - Beta               N/A\n   :pypi:`pytest-hot-reloading`                                                                                                                                                                                                                                                                                                                                                                                                                     Sep 23, 2024    N/A                    N/A\n   :pypi:`pytest-hot-test`                                  A plugin that tracks test changes                                                                                                                                                                                                                                                                                                                                                       Dec 10, 2022    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-houdini`                                   pytest plugin for testing code in Houdini.                                                                                                                                                                                                                                                                                                                                              Jul 15, 2024    N/A                    pytest\n   :pypi:`pytest-hoverfly`                                  Simplify working with Hoverfly from pytest                                                                                                                                                                                                                                                                                                                                              Jan 30, 2023    N/A                    pytest (>=5.0)\n   :pypi:`pytest-hoverfly-wrapper`                          Integrates the Hoverfly HTTP proxy into Pytest                                                                                                                                                                                                                                                                                                                                          Feb 27, 2023    5 - Production/Stable  pytest (>=3.7.0)\n   :pypi:`pytest-hpfeeds`                                   Helpers for testing hpfeeds in your python project                                                                                                                                                                                                                                                                                                                                      Feb 28, 2023    4 - Beta               pytest (>=6.2.4,<7.0.0)\n   :pypi:`pytest-html`                                      pytest plugin for generating HTML reports                                                                                                                                                                                                                                                                                                                                               Jan 19, 2026    5 - Production/Stable  pytest>=7\n   :pypi:`pytest-html5`                                     the best report for pytest                                                                                                                                                                                                                                                                                                                                                              Dec 18, 2025    N/A                    N/A\n   :pypi:`pytest-html-cn`                                   pytest plugin for generating HTML reports                                                                                                                                                                                                                                                                                                                                               Aug 19, 2024    5 - Production/Stable  pytest!=6.0.0,>=5.0\n   :pypi:`pytest-html-dashboard`                            Beautiful dashboard-style HTML reports for pytest with charts, error analysis, and visual insights                                                                                                                                                                                                                                                                                      Nov 24, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-html-lee`                                  optimized pytest plugin for generating HTML reports                                                                                                                                                                                                                                                                                                                                     Jun 30, 2020    5 - Production/Stable  pytest (>=5.0)\n   :pypi:`pytest-html-merger`                               Pytest HTML reports merging utility                                                                                                                                                                                                                                                                                                                                                     Jul 12, 2024    N/A                    N/A\n   :pypi:`pytest-html-nova-act`                             A Pytest Plugin for Amazon Nova Act Python SDK.                                                                                                                                                                                                                                                                                                                                         Nov 05, 2025    N/A                    N/A\n   :pypi:`pytest-html-object-storage`                       Pytest report plugin for send HTML report on object-storage                                                                                                                                                                                                                                                                                                                             Jan 17, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-html-plus`                                 Generate Actionable, automatic screenshots, unified Mobile friendly Pytest HTML report in less than 3 seconds — no hooks, merge plugins, no config, xdist-ready.                                                                                                                                                                                                                        Feb 06, 2026    N/A                    N/A\n   :pypi:`pytest-html-profiling`                            Pytest plugin for generating HTML reports with per-test profiling and optionally call graph visualizations. Based on pytest-html by Dave Hunt.                                                                                                                                                                                                                                          Feb 11, 2020    5 - Production/Stable  pytest (>=3.0)\n   :pypi:`pytest-html-report`                               Enhanced HTML reporting for pytest with categories, specifications, and detailed logging                                                                                                                                                                                                                                                                                                Jun 24, 2025    4 - Beta               pytest>=6.0\n   :pypi:`pytest-html-reporter`                             Generates a static html report based on pytest framework                                                                                                                                                                                                                                                                                                                                Feb 13, 2022    N/A                    N/A\n   :pypi:`pytest-html-report-merger`                                                                                                                                                                                                                                                                                                                                                                                                                May 22, 2024    N/A                    N/A\n   :pypi:`pytest-html-thread`                               pytest plugin for generating HTML reports                                                                                                                                                                                                                                                                                                                                               Dec 29, 2020    5 - Production/Stable  N/A\n   :pypi:`pytest-htmlx`                                     Custom HTML report plugin for Pytest with charts and tables                                                                                                                                                                                                                                                                                                                             Sep 09, 2025    4 - Beta               pytest\n   :pypi:`pytest-http`                                      Fixture \"http\" for http requests                                                                                                                                                                                                                                                                                                                                                        Aug 22, 2024    N/A                    pytest\n   :pypi:`pytest-httpbin`                                   Easily test your HTTP library against a local copy of httpbin                                                                                                                                                                                                                                                                                                                           Sep 18, 2024    5 - Production/Stable  pytest; extra == \"test\"\n   :pypi:`pytest-httpchain`                                 pytest plugin for HTTP testing using JSON files                                                                                                                                                                                                                                                                                                                                         Jan 09, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-httpchain-jsonref`                         JSON reference ($ref) support for pytest-httpchain                                                                                                                                                                                                                                                                                                                                      Jan 09, 2026    N/A                    N/A\n   :pypi:`pytest-httpchain-mcp`                             MCP server for pytest-httpchain                                                                                                                                                                                                                                                                                                                                                         Jan 09, 2026    N/A                    N/A\n   :pypi:`pytest-httpchain-models`                          Pydantic models for pytest-httpchain                                                                                                                                                                                                                                                                                                                                                    Jan 09, 2026    N/A                    N/A\n   :pypi:`pytest-httpchain-templates`                       Templating support for pytest-httpchain                                                                                                                                                                                                                                                                                                                                                 Jan 09, 2026    N/A                    N/A\n   :pypi:`pytest-httpchain-userfunc`                        User functions support for pytest-httpchain                                                                                                                                                                                                                                                                                                                                             Jan 09, 2026    N/A                    N/A\n   :pypi:`pytest-httpdbg`                                   A pytest plugin to record HTTP(S) requests with stack trace.                                                                                                                                                                                                                                                                                                                            Oct 26, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-http-mocker`                               Pytest plugin for http mocking (via https://github.com/vilus/mocker)                                                                                                                                                                                                                                                                                                                    Oct 20, 2019    N/A                    N/A\n   :pypi:`pytest-httpretty`                                 A thin wrapper of HTTPretty for pytest                                                                                                                                                                                                                                                                                                                                                  Feb 16, 2014    3 - Alpha              N/A\n   :pypi:`pytest_httpserver`                                pytest-httpserver is a httpserver for pytest                                                                                                                                                                                                                                                                                                                                            Feb 14, 2026    3 - Alpha              N/A\n   :pypi:`pytest-httptesting`                               http_testing framework on top of pytest                                                                                                                                                                                                                                                                                                                                                 Dec 19, 2024    N/A                    pytest>=8.2.0\n   :pypi:`pytest-httpx`                                     Send responses to httpx.                                                                                                                                                                                                                                                                                                                                                                Dec 02, 2025    5 - Production/Stable  pytest==9.*\n   :pypi:`pytest-httpx-blockage`                            Disable httpx requests during a test run                                                                                                                                                                                                                                                                                                                                                Feb 16, 2023    N/A                    pytest (>=7.2.1)\n   :pypi:`pytest-httpx-recorder`                            Recorder feature based on pytest_httpx, like recorder feature in responses.                                                                                                                                                                                                                                                                                                             Jan 04, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-hue`                                       Visualise PyTest status via your Phillips Hue lights                                                                                                                                                                                                                                                                                                                                    May 09, 2019    N/A                    N/A\n   :pypi:`pytest-human`                                     A beautiful nested pytest HTML test report                                                                                                                                                                                                                                                                                                                                              Jan 25, 2026    4 - Beta               pytest>=8\n   :pypi:`pytest-hy`                                        Pytest plugin for discovering and running Hy test files                                                                                                                                                                                                                                                                                                                                 Feb 11, 2026    N/A                    pytest>=7.0\n   :pypi:`pytest-hylang`                                    Pytest plugin to allow running tests written in hylang                                                                                                                                                                                                                                                                                                                                  Mar 28, 2021    N/A                    pytest\n   :pypi:`pytest-hypo-25`                                   help hypo module for pytest                                                                                                                                                                                                                                                                                                                                                             Jan 12, 2020    3 - Alpha              N/A\n   :pypi:`pytest-hypothesis`                                                                                                                                                                                                                                                                                                                                                                                                                        Feb 09, 2026    N/A                    N/A\n   :pypi:`pytest-iam`                                       A fully functional OAUTH2 / OpenID Connect (OIDC) / SCIM server to be used in your testsuite                                                                                                                                                                                                                                                                                            Nov 02, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-ibutsu`                                    A plugin to sent pytest results to an Ibutsu server                                                                                                                                                                                                                                                                                                                                     Feb 23, 2026    4 - Beta               pytest\n   :pypi:`pytest-icdiff`                                    use icdiff for better error messages in pytest assertions                                                                                                                                                                                                                                                                                                                               Dec 05, 2023    4 - Beta               pytest\n   :pypi:`pytest-idapro`                                    A pytest plugin for idapython. Allows a pytest setup to run tests outside and inside IDA in an automated manner by runnig pytest inside IDA and by mocking idapython api                                                                                                                                                                                                                Nov 03, 2018    N/A                    N/A\n   :pypi:`pytest-idem`                                      A pytest plugin to help with testing idem projects                                                                                                                                                                                                                                                                                                                                      Dec 13, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-idempotent`                                Pytest plugin for testing function idempotence.                                                                                                                                                                                                                                                                                                                                         Jul 25, 2022    N/A                    N/A\n   :pypi:`pytest-ignore-flaky`                              ignore failures from flaky tests (pytest plugin)                                                                                                                                                                                                                                                                                                                                        Apr 20, 2024    5 - Production/Stable  pytest>=6.0\n   :pypi:`pytest-ignore-test-results`                       A pytest plugin to ignore test results.                                                                                                                                                                                                                                                                                                                                                 Feb 03, 2025    5 - Production/Stable  pytest>=7.0\n   :pypi:`pytest-image-diff`                                                                                                                                                                                                                                                                                                                                                                                                                        Dec 31, 2024    3 - Alpha              pytest\n   :pypi:`pytest-image-snapshot`                            A pytest plugin for image snapshot management and comparison.                                                                                                                                                                                                                                                                                                                           Jul 16, 2025    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-impacted`                                  A pytest plugin that selectively runs tests impacted by code changes via git introspection, AST parsing, and dependency graph analysis.                                                                                                                                                                                                                                                 Feb 12, 2026    4 - Beta               pytest>=8.0.0\n   :pypi:`pytest-import-check`                              pytest plugin to check whether Python modules can be imported                                                                                                                                                                                                                                                                                                                           Jul 19, 2024    3 - Alpha              pytest>=8.1\n   :pypi:`pytest-incremental`                               an incremental test runner (pytest plugin)                                                                                                                                                                                                                                                                                                                                              Apr 24, 2021    5 - Production/Stable  N/A\n   :pypi:`pytest-in-docker`                                 Seamlessly run pytest tests inside docker containers                                                                                                                                                                                                                                                                                                                                    Feb 09, 2026    3 - Alpha              pytest>=9.0.2\n   :pypi:`pytest-infinity`                                                                                                                                                                                                                                                                                                                                                                                                                          Jun 09, 2024    N/A                    pytest<9.0.0,>=8.0.0\n   :pypi:`pytest-influx`                                    Pytest plugin for managing your influx instance between test runs                                                                                                                                                                                                                                                                                                                       Oct 16, 2024    N/A                    pytest<9.0.0,>=8.3.3\n   :pypi:`pytest-influxdb`                                  Plugin for influxdb and pytest integration.                                                                                                                                                                                                                                                                                                                                             Apr 20, 2021    N/A                    N/A\n   :pypi:`pytest-info-collector`                            pytest plugin to collect information from tests                                                                                                                                                                                                                                                                                                                                         May 26, 2019    3 - Alpha              N/A\n   :pypi:`pytest-info-plugin`                               Get executed interface information in pytest interface automation framework                                                                                                                                                                                                                                                                                                             Sep 14, 2023    N/A                    N/A\n   :pypi:`pytest-informative-node`                          display more node ininformation.                                                                                                                                                                                                                                                                                                                                                        Apr 25, 2019    4 - Beta               N/A\n   :pypi:`pytest-infrahouse`                                A set of fixtures to use with pytest                                                                                                                                                                                                                                                                                                                                                    Jan 29, 2026    4 - Beta               pytest~=9.0\n   :pypi:`pytest-infrastructure`                            pytest stack validation prior to testing executing                                                                                                                                                                                                                                                                                                                                      Apr 12, 2020    4 - Beta               N/A\n   :pypi:`pytest-ini`                                       Reuse pytest.ini to store env variables                                                                                                                                                                                                                                                                                                                                                 Apr 26, 2022    N/A                    N/A\n   :pypi:`pytest-initry`                                    Plugin for sending automation test data from Pytest to the initry                                                                                                                                                                                                                                                                                                                       Apr 30, 2024    N/A                    pytest<9.0.0,>=8.1.1\n   :pypi:`pytest-inject`                                    A pytest plugin that allows you to inject arguments into fixtures and parametrized tests using pytest command-line options.                                                                                                                                                                                                                                                             Nov 25, 2025    N/A                    pytest>=6.0.0\n   :pypi:`pytest-inline`                                    A pytest plugin for writing inline tests                                                                                                                                                                                                                                                                                                                                                Oct 24, 2024    4 - Beta               pytest<9.0,>=7.0\n   :pypi:`pytest-inline-snapshot`                           inline-snapshot is the package you are looking for                                                                                                                                                                                                                                                                                                                                      Nov 09, 2025    N/A                    N/A\n   :pypi:`pytest-inline-tdd`                                A pytest plugin for writing inline tests                                                                                                                                                                                                                                                                                                                                                Mar 09, 2026    4 - Beta               pytest<9.0,>=7.0\n   :pypi:`pytest-inmanta`                                   A py.test plugin providing fixtures to simplify inmanta modules testing.                                                                                                                                                                                                                                                                                                                Nov 18, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-inmanta-extensions`                        Inmanta tests package                                                                                                                                                                                                                                                                                                                                                                   Mar 03, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-inmanta-lsm`                               Common fixtures used in inmanta LSM related modules                                                                                                                                                                                                                                                                                                                                     Feb 12, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-inmanta-srlinux`                           Pytest library to facilitate end to end testing of inmanta projects                                                                                                                                                                                                                                                                                                                     Apr 22, 2025    3 - Alpha              N/A\n   :pypi:`pytest-inmanta-yang`                              Common fixtures used in inmanta yang related modules                                                                                                                                                                                                                                                                                                                                    Oct 28, 2025    4 - Beta               pytest\n   :pypi:`pytest-Inomaly`                                   A simple image diff plugin for pytest                                                                                                                                                                                                                                                                                                                                                   Feb 13, 2018    4 - Beta               N/A\n   :pypi:`pytest-in-robotframework`                         The extension enables easy execution of pytest tests within the Robot Framework environment.                                                                                                                                                                                                                                                                                            Nov 23, 2024    N/A                    pytest\n   :pypi:`pytest-insper`                                    Pytest plugin for courses at Insper                                                                                                                                                                                                                                                                                                                                                     Mar 21, 2024    N/A                    pytest\n   :pypi:`pytest-insta`                                     A practical snapshot testing plugin for pytest                                                                                                                                                                                                                                                                                                                                          Nov 22, 2025    N/A                    pytest>=9.0.0\n   :pypi:`pytest-instafail`                                 pytest plugin to show failures instantly                                                                                                                                                                                                                                                                                                                                                Mar 31, 2023    4 - Beta               pytest (>=5)\n   :pypi:`pytest-instrument`                                pytest plugin to instrument tests                                                                                                                                                                                                                                                                                                                                                       Apr 05, 2020    5 - Production/Stable  pytest (>=5.1.0)\n   :pypi:`pytest-insubprocess`                              A pytest plugin to execute test cases in a subprocess                                                                                                                                                                                                                                                                                                                                   Dec 08, 2025    4 - Beta               pytest>=7.4\n   :pypi:`pytest-integration`                               Organizing pytests by integration or not                                                                                                                                                                                                                                                                                                                                                Nov 17, 2022    N/A                    N/A\n   :pypi:`pytest-integration-mark`                          Automatic integration test marking and excluding plugin for pytest                                                                                                                                                                                                                                                                                                                      May 22, 2023    N/A                    pytest (>=5.2)\n   :pypi:`pytest-intent`                                    A pytest plugin for tracking requirement coverage.                                                                                                                                                                                                                                                                                                                                      Dec 17, 2025    N/A                    pytest<10.0.0,>=9.0.0\n   :pypi:`pytest-interactive`                               A pytest plugin for console based interactive test selection just after the collection phase                                                                                                                                                                                                                                                                                            Nov 30, 2017    3 - Alpha              N/A\n   :pypi:`pytest-intercept-remote`                          Pytest plugin for intercepting outgoing connection requests during pytest run.                                                                                                                                                                                                                                                                                                          May 24, 2021    4 - Beta               pytest (>=4.6)\n   :pypi:`pytest-interface-tester`                          Pytest plugin for checking charm relation interface protocol compliance.                                                                                                                                                                                                                                                                                                                Feb 11, 2026    4 - Beta               pytest\n   :pypi:`pytest-invenio`                                   Pytest fixtures for Invenio.                                                                                                                                                                                                                                                                                                                                                            Jan 27, 2026    5 - Production/Stable  pytest<9.0.0,>=6\n   :pypi:`pytest-involve`                                   Run tests covering a specific file or changeset                                                                                                                                                                                                                                                                                                                                         Feb 02, 2020    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-iovis`                                     A Pytest plugin to enable Jupyter Notebook testing with Papermill                                                                                                                                                                                                                                                                                                                       Nov 06, 2024    4 - Beta               pytest>=7.1.0\n   :pypi:`pytest-ipdb`                                      A py.test plug-in to enable drop to ipdb debugger on test failure.                                                                                                                                                                                                                                                                                                                      Mar 20, 2013    2 - Pre-Alpha          N/A\n   :pypi:`pytest-ipynb`                                     THIS PROJECT IS ABANDONED                                                                                                                                                                                                                                                                                                                                                               Jan 29, 2019    3 - Alpha              N/A\n   :pypi:`pytest-ipynb2`                                    Pytest plugin to run tests in Jupyter Notebooks                                                                                                                                                                                                                                                                                                                                         Mar 09, 2025    N/A                    pytest\n   :pypi:`pytest-ipywidgets`                                                                                                                                                                                                                                                                                                                                                                                                                        Feb 24, 2026    N/A                    pytest\n   :pypi:`pytest-isolate`                                   Run pytest tests in isolated subprocesses                                                                                                                                                                                                                                                                                                                                               Sep 08, 2025    4 - Beta               pytest\n   :pypi:`pytest-isolated`                                  Run marked pytest tests in grouped subprocesses (cross-platform).                                                                                                                                                                                                                                                                                                                       Mar 04, 2026    4 - Beta               pytest>=7.0\n   :pypi:`pytest-isolate-mpi`                               pytest-isolate-mpi allows for MPI-parallel tests being executed in a segfault and MPI_Abort safe manner                                                                                                                                                                                                                                                                                 Feb 24, 2025    4 - Beta               pytest>=5\n   :pypi:`pytest-isort`                                     py.test plugin to check import ordering using isort                                                                                                                                                                                                                                                                                                                                     Mar 05, 2024    5 - Production/Stable  pytest (>=5.0)\n   :pypi:`pytest-it`                                        Pytest plugin to display test reports as a plaintext spec, inspired by Rspec: https://github.com/mattduck/pytest-it.                                                                                                                                                                                                                                                                    Jan 29, 2024    4 - Beta               N/A\n   :pypi:`pytest-item-dict`                                 Get a hierarchical dict of session.items                                                                                                                                                                                                                                                                                                                                                Nov 14, 2024    4 - Beta               pytest>=8.3.0\n   :pypi:`pytest-iterassert`                                Nicer list and iterable assertion messages for pytest                                                                                                                                                                                                                                                                                                                                   May 11, 2020    3 - Alpha              N/A\n   :pypi:`pytest-iteration`                                 Add iteration mark for tests                                                                                                                                                                                                                                                                                                                                                            Aug 22, 2024    N/A                    pytest\n   :pypi:`pytest-iters`                                     A contextmanager pytest fixture for handling multiple mock iters                                                                                                                                                                                                                                                                                                                        May 24, 2022    N/A                    N/A\n   :pypi:`pytest_jar_yuan`                                  A allure and pytest used package                                                                                                                                                                                                                                                                                                                                                        Dec 12, 2022    N/A                    N/A\n   :pypi:`pytest-jasmine`                                   Run jasmine tests from your pytest test suite                                                                                                                                                                                                                                                                                                                                           Nov 04, 2017    1 - Planning           N/A\n   :pypi:`pytest-jelastic`                                  Pytest plugin defining the necessary command-line options to pass to pytests testing a Jelastic environment.                                                                                                                                                                                                                                                                            Nov 16, 2022    N/A                    pytest (>=7.2.0,<8.0.0)\n   :pypi:`pytest-jest`                                      A custom jest-pytest oriented Pytest reporter                                                                                                                                                                                                                                                                                                                                           May 22, 2018    4 - Beta               pytest (>=3.3.2)\n   :pypi:`pytest-jinja`                                     A plugin to generate customizable jinja-based HTML reports in pytest                                                                                                                                                                                                                                                                                                                    Oct 04, 2022    3 - Alpha              pytest (>=6.2.5,<7.0.0)\n   :pypi:`pytest-jinja-check`                               Pytest plugin to lint Jinja2 templates in FastAPI applications                                                                                                                                                                                                                                                                                                                          Mar 14, 2026    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-jira`                                      py.test JIRA integration plugin, using markers                                                                                                                                                                                                                                                                                                                                          Apr 15, 2025    3 - Alpha              N/A\n   :pypi:`pytest-jira-xfail`                                Plugin skips (xfail) tests if unresolved Jira issue(s) linked                                                                                                                                                                                                                                                                                                                           Jul 09, 2024    N/A                    pytest>=7.2.0\n   :pypi:`pytest-jira-xray`                                 pytest plugin to integrate tests with JIRA XRAY                                                                                                                                                                                                                                                                                                                                         Oct 11, 2025    4 - Beta               pytest>=6.2.4\n   :pypi:`pytest-job-selection`                             A pytest plugin for load balancing test suites                                                                                                                                                                                                                                                                                                                                          Jan 30, 2023    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-jobserver`                                 Limit parallel tests with posix jobserver.                                                                                                                                                                                                                                                                                                                                              Feb 02, 2026    5 - Production/Stable  pytest\n   :pypi:`pytest-joke`                                      Test failures are better served with humor.                                                                                                                                                                                                                                                                                                                                             Oct 08, 2019    4 - Beta               pytest (>=4.2.1)\n   :pypi:`pytest-json`                                      Generate JSON test reports                                                                                                                                                                                                                                                                                                                                                              Jan 18, 2016    4 - Beta               N/A\n   :pypi:`pytest-json-ctrf`                                 Pytest plugin to generate json report in CTRF (Common Test Report Format)                                                                                                                                                                                                                                                                                                               Dec 28, 2025    N/A                    pytest>6.0.0\n   :pypi:`pytest-json-fixtures`                             JSON output for the --fixtures flag                                                                                                                                                                                                                                                                                                                                                     Mar 14, 2023    4 - Beta               N/A\n   :pypi:`pytest-jsonlint`                                  UNKNOWN                                                                                                                                                                                                                                                                                                                                                                                 Aug 04, 2016    N/A                    N/A\n   :pypi:`pytest-json-report`                               A pytest plugin to report test results as JSON files                                                                                                                                                                                                                                                                                                                                    Mar 15, 2022    4 - Beta               pytest (>=3.8.0)\n   :pypi:`pytest-json-report-wip`                           A pytest plugin to report test results as JSON files                                                                                                                                                                                                                                                                                                                                    Jul 23, 2025    4 - Beta               pytest >=3.8.0\n   :pypi:`pytest-jsonschema`                                A pytest plugin to perform JSONSchema validations                                                                                                                                                                                                                                                                                                                                       Nov 07, 2025    5 - Production/Stable  pytest>=6.2.0\n   :pypi:`pytest-jsonschema-snapshot`                       Pytest plugin for automatic JSON Schema generation and validation from examples                                                                                                                                                                                                                                                                                                         Mar 08, 2026    N/A                    pytest\n   :pypi:`pytest-jtr`                                       pytest plugin supporting json test report output                                                                                                                                                                                                                                                                                                                                        Jul 21, 2024    N/A                    pytest<8.0.0,>=7.1.2\n   :pypi:`pytest-jubilant`                                  Add your description here                                                                                                                                                                                                                                                                                                                                                               Mar 13, 2026    N/A                    pytest>=8.3.5\n   :pypi:`pytest-junit-logging`                             A pytest plugin for embedding log output into JUnit XML reports                                                                                                                                                                                                                                                                                                                         Nov 27, 2025    4 - Beta               pytest>=6.0\n   :pypi:`pytest-junit-xray-xml`                            Export test results in an augmented JUnit format for usage with Xray ()                                                                                                                                                                                                                                                                                                                 Jan 01, 2025    4 - Beta               pytest\n   :pypi:`pytest-jupyter`                                   A pytest plugin for testing Jupyter libraries and extensions.                                                                                                                                                                                                                                                                                                                           Oct 16, 2025    4 - Beta               pytest>=7.0\n   :pypi:`pytest-jupyterhub`                                A reusable JupyterHub pytest plugin                                                                                                                                                                                                                                                                                                                                                     Apr 25, 2023    5 - Production/Stable  pytest\n   :pypi:`pytest-jux`                                       A pytest plugin for signing and publishing JUnit XML test reports to the Jux REST API                                                                                                                                                                                                                                                                                                   Jan 08, 2026    3 - Alpha              pytest>=7.4\n   :pypi:`pytest-k8s`                                       Kubernetes-based testing for pytest                                                                                                                                                                                                                                                                                                                                                     Jul 07, 2025    N/A                    pytest>=8.4.1\n   :pypi:`pytest-kafka`                                     Zookeeper, Kafka server, and Kafka consumer fixtures for Pytest                                                                                                                                                                                                                                                                                                                         Aug 14, 2024    N/A                    pytest\n   :pypi:`pytest-kafka-broker`                              Pytest plugin to run a single-broker Kafka cluster                                                                                                                                                                                                                                                                                                                                      Feb 15, 2026    N/A                    N/A\n   :pypi:`pytest-kafkavents`                                A plugin to send pytest events to Kafka                                                                                                                                                                                                                                                                                                                                                 Sep 08, 2021    4 - Beta               pytest\n   :pypi:`pytest-kairos`                                    Pytest plugin with random number generation, reproducibility, and test repetition                                                                                                                                                                                                                                                                                                       Aug 08, 2024    5 - Production/Stable  pytest>=5.0.0\n   :pypi:`pytest-kasima`                                    Display horizontal lines above and below the captured standard output for easy viewing.                                                                                                                                                                                                                                                                                                 Jan 26, 2023    5 - Production/Stable  pytest (>=7.2.1,<8.0.0)\n   :pypi:`pytest-kedge`                                     Agent-friendly structured test data collector for pytest                                                                                                                                                                                                                                                                                                                                Jan 10, 2026    N/A                    pytest>=7.0.0\n   :pypi:`pytest-keep-together`                             Pytest plugin to customize test ordering by running all 'related' tests together                                                                                                                                                                                                                                                                                                        Dec 07, 2022    5 - Production/Stable  pytest\n   :pypi:`pytest-kexi`                                                                                                                                                                                                                                                                                                                                                                                                                              Apr 29, 2022    N/A                    pytest (>=7.1.2,<8.0.0)\n   :pypi:`pytest-keyring`                                   A Pytest plugin to access the system's keyring to provide credentials for tests                                                                                                                                                                                                                                                                                                         Dec 08, 2024    N/A                    pytest>=8.0.2\n   :pypi:`pytest-kind`                                      Kubernetes test support with KIND for pytest                                                                                                                                                                                                                                                                                                                                            Nov 30, 2022    5 - Production/Stable  N/A\n   :pypi:`pytest-kivy`                                      Kivy GUI tests fixtures using pytest                                                                                                                                                                                                                                                                                                                                                    Jul 06, 2021    4 - Beta               pytest (>=3.6)\n   :pypi:`pytest-knows`                                     A pytest plugin that can automaticly skip test case based on dependence info calculated by trace                                                                                                                                                                                                                                                                                        Aug 22, 2014    N/A                    N/A\n   :pypi:`pytest-konira`                                    Run Konira DSL tests with py.test                                                                                                                                                                                                                                                                                                                                                       Oct 09, 2011    N/A                    N/A\n   :pypi:`pytest-kookit`                                    Your simple but kooky integration testing with pytest                                                                                                                                                                                                                                                                                                                                   Sep 10, 2024    N/A                    N/A\n   :pypi:`pytest-koopmans`                                  A plugin for testing the koopmans package                                                                                                                                                                                                                                                                                                                                               Nov 21, 2022    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-krtech-common`                             pytest krtech common library                                                                                                                                                                                                                                                                                                                                                            Nov 28, 2016    4 - Beta               N/A\n   :pypi:`pytest-kubernetes`                                                                                                                                                                                                                                                                                                                                                                                                                        Oct 23, 2025    N/A                    pytest<9.0.0,>=8.3.0\n   :pypi:`pytest_kustomize`                                 Parse and validate kustomize output                                                                                                                                                                                                                                                                                                                                                     Dec 08, 2025    N/A                    N/A\n   :pypi:`pytest-kuunda`                                    pytest plugin to help with test data setup for PySpark tests                                                                                                                                                                                                                                                                                                                            Feb 25, 2024    4 - Beta               pytest >=6.2.0\n   :pypi:`pytest-kwparametrize`                             Alternate syntax for @pytest.mark.parametrize with test cases as dictionaries and default value fallbacks                                                                                                                                                                                                                                                                               Jan 22, 2021    N/A                    pytest (>=6)\n   :pypi:`pytest-lambda`                                    Define pytest fixtures with lambda functions.                                                                                                                                                                                                                                                                                                                                           May 27, 2024    5 - Production/Stable  pytest<9,>=3.6\n   :pypi:`pytest-lamp`                                                                                                                                                                                                                                                                                                                                                                                                                              Jan 06, 2017    3 - Alpha              N/A\n   :pypi:`pytest-langchain`                                 Pytest-style test runner for langchain agents                                                                                                                                                                                                                                                                                                                                           Feb 26, 2023    N/A                    pytest\n   :pypi:`pytest-language-server`                           A blazingly fast Language Server Protocol implementation for pytest                                                                                                                                                                                                                                                                                                                     Mar 04, 2026    4 - Beta               N/A\n   :pypi:`pytest-lark`                                      Create fancy and clear HTML test reports.                                                                                                                                                                                                                                                                                                                                               Nov 05, 2023    N/A                    N/A\n   :pypi:`pytest-latin-hypercube`                           Implementation of Latin Hypercube Sampling for pytest.                                                                                                                                                                                                                                                                                                                                  Jun 26, 2025    N/A                    pytest\n   :pypi:`pytest-launchable`                                Launchable Pytest Plugin                                                                                                                                                                                                                                                                                                                                                                Apr 05, 2023    N/A                    pytest (>=4.2.0)\n   :pypi:`pytest-layab`                                     Pytest fixtures for layab.                                                                                                                                                                                                                                                                                                                                                              Oct 05, 2020    5 - Production/Stable  N/A\n   :pypi:`pytest-lazy-fixture`                              It helps to use fixtures in pytest.mark.parametrize                                                                                                                                                                                                                                                                                                                                     Feb 01, 2020    4 - Beta               pytest (>=3.2.5)\n   :pypi:`pytest-lazy-fixtures`                             Allows you to use fixtures in @pytest.mark.parametrize.                                                                                                                                                                                                                                                                                                                                 Sep 16, 2025    N/A                    pytest>=7\n   :pypi:`pytest-ldap`                                      python-ldap fixtures for pytest                                                                                                                                                                                                                                                                                                                                                         Aug 18, 2020    N/A                    pytest\n   :pypi:`pytest-leak-finder`                               Find the test that's leaking before the one that fails                                                                                                                                                                                                                                                                                                                                  Dec 19, 2025    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-leaks`                                     A pytest plugin to trace resource leaks.                                                                                                                                                                                                                                                                                                                                                Nov 27, 2019    1 - Planning           N/A\n   :pypi:`pytest-leaping`                                   A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Mar 27, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-leela`                                     Type-aware mutation testing for Python — fast, opinionated, pytest-native                                                                                                                                                                                                                                                                                                               Feb 19, 2026    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-leo-interface`                             Pytest extension tool for leo projects.                                                                                                                                                                                                                                                                                                                                                 Mar 19, 2025    N/A                    N/A\n   :pypi:`pytest-level`                                     Select tests of a given level or lower                                                                                                                                                                                                                                                                                                                                                  Oct 21, 2019    N/A                    pytest\n   :pypi:`pytest-lf-skip`                                   A pytest plugin which makes \\`--last-failed\\` skip instead of deselect tests.                                                                                                                                                                                                                                                                                                           Feb 27, 2026    4 - Beta               pytest>=8.3.5\n   :pypi:`pytest-libfaketime`                               A python-libfaketime plugin for pytest                                                                                                                                                                                                                                                                                                                                                  Apr 12, 2024    4 - Beta               pytest>=3.0.0\n   :pypi:`pytest-libiio`                                    A pytest plugin for testing libiio based devices                                                                                                                                                                                                                                                                                                                                        Aug 15, 2025    N/A                    pytest>=3.5.0\n   :pypi:`pytest-libnotify`                                 Pytest plugin that shows notifications about the test run                                                                                                                                                                                                                                                                                                                               Apr 02, 2021    3 - Alpha              pytest\n   :pypi:`pytest-ligo`                                                                                                                                                                                                                                                                                                                                                                                                                              Jan 16, 2020    4 - Beta               N/A\n   :pypi:`pytest-lineno`                                    A pytest plugin to show the line numbers of test functions                                                                                                                                                                                                                                                                                                                              Dec 04, 2020    N/A                    pytest\n   :pypi:`pytest-line-profiler`                             Profile code executed by pytest                                                                                                                                                                                                                                                                                                                                                         Aug 10, 2023    4 - Beta               pytest >=3.5.0\n   :pypi:`pytest-line-profiler-apn`                         Profile code executed by pytest                                                                                                                                                                                                                                                                                                                                                         Dec 05, 2022    N/A                    pytest (>=3.5.0)\n   :pypi:`pytest-line-runner`                               Run pytest tests by line number instead of exact test name                                                                                                                                                                                                                                                                                                                              Feb 08, 2026    N/A                    N/A\n   :pypi:`pytest-lisa`                                      Pytest plugin for organizing tests.                                                                                                                                                                                                                                                                                                                                                     Jan 21, 2021    3 - Alpha              pytest (>=6.1.2,<7.0.0)\n   :pypi:`pytest-listener`                                  A simple network listener                                                                                                                                                                                                                                                                                                                                                               Nov 29, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-litf`                                      A pytest plugin that stream output in LITF format                                                                                                                                                                                                                                                                                                                                       Jan 18, 2021    4 - Beta               pytest (>=3.1.1)\n   :pypi:`pytest-litter`                                    Pytest plugin which verifies that tests do not modify file trees.                                                                                                                                                                                                                                                                                                                       Nov 23, 2023    4 - Beta               pytest >=6.1\n   :pypi:`pytest-live`                                      Live results for pytest                                                                                                                                                                                                                                                                                                                                                                 Mar 08, 2020    N/A                    pytest\n   :pypi:`pytest-liveview`                                  Pytest plugin that shows a real-time test dashboard in a local web server                                                                                                                                                                                                                                                                                                               Mar 09, 2026    N/A                    pytest>=7.0\n   :pypi:`pytest-llm`                                       pytest-llm: A pytest plugin for testing LLM outputs with success rate thresholds.                                                                                                                                                                                                                                                                                                       Oct 03, 2025    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-llm-agent`                                 LLM Agent for working with pytest                                                                                                                                                                                                                                                                                                                                                       Dec 16, 2025    N/A                    pytest>=9.0.2\n   :pypi:`pytest-llm-assert`                                Simple LLM-powered assertions for any pytest test                                                                                                                                                                                                                                                                                                                                       Feb 03, 2026    3 - Alpha              pytest>=9.0\n   :pypi:`pytest-llmeval`                                   A pytest plugin to evaluate/benchmark LLM prompts                                                                                                                                                                                                                                                                                                                                       Mar 19, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-llm-report`                                Human-friendly pytest test reports with optional LLM annotations                                                                                                                                                                                                                                                                                                                        Jan 21, 2026    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-llmtest`                                   The pytest for LLMs — fast, Pydantic-based assertions for AI applications                                                                                                                                                                                                                                                                                                               Mar 08, 2026    3 - Alpha              pytest>=7.0; extra == \"dev\"\n   :pypi:`pytest-lobster`                                   Pytest to generate lobster tracing files                                                                                                                                                                                                                                                                                                                                                Jul 26, 2025    N/A                    pytest>=7.0\n   :pypi:`pytest-local-badge`                               Generate local badges (shields) reporting your test suite status.                                                                                                                                                                                                                                                                                                                       Jan 15, 2023    N/A                    pytest (>=6.1.0)\n   :pypi:`pytest-localftpserver`                            A PyTest plugin which provides an FTP fixture for your tests                                                                                                                                                                                                                                                                                                                            Nov 16, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-localserver`                               pytest plugin to test server connections locally.                                                                                                                                                                                                                                                                                                                                       Nov 24, 2025    4 - Beta               N/A\n   :pypi:`pytest-localstack`                                Pytest plugin for AWS integration tests                                                                                                                                                                                                                                                                                                                                                 Jun 07, 2023    4 - Beta               pytest (>=6.0.0,<7.0.0)\n   :pypi:`pytest-lock`                                      pytest-lock is a pytest plugin that allows you to \"lock\" the results of unit tests, storing them in a local cache. This is particularly useful for tests that are resource-intensive or don't need to be run every time. When the tests are run subsequently, pytest-lock will compare the current results with the locked results and issue a warning if there are any discrepancies.  Feb 03, 2024    N/A                    pytest (>=7.4.3,<8.0.0)\n   :pypi:`pytest-lockable`                                  lockable resource plugin for pytest                                                                                                                                                                                                                                                                                                                                                     Sep 08, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-locker`                                    Used to lock object during testing. Essentially changing assertions from being hard coded to asserting that nothing changed                                                                                                                                                                                                                                                             Dec 20, 2024    N/A                    pytest>=5.4\n   :pypi:`pytest-loco`                                      Another one YAML-based DSL for testing                                                                                                                                                                                                                                                                                                                                                  Mar 08, 2026    3 - Alpha              pytest<10.0.0,>=9.0.2\n   :pypi:`pytest-loco-allure`                               Allure support for pytest-loco                                                                                                                                                                                                                                                                                                                                                          Mar 08, 2026    3 - Alpha              N/A\n   :pypi:`pytest-loco-http`                                 HTTP support for pytest-loco                                                                                                                                                                                                                                                                                                                                                            Feb 25, 2026    3 - Alpha              N/A\n   :pypi:`pytest-loco-json`                                 JSON support for pytest-loco                                                                                                                                                                                                                                                                                                                                                            Feb 25, 2026    3 - Alpha              N/A\n   :pypi:`pytest-log`                                       print log                                                                                                                                                                                                                                                                                                                                                                               Aug 15, 2021    N/A                    pytest (>=3.8)\n   :pypi:`pytest-logbook`                                   py.test plugin to capture logbook log messages                                                                                                                                                                                                                                                                                                                                          Nov 23, 2015    5 - Production/Stable  pytest (>=2.8)\n   :pypi:`pytest-logdog`                                    Pytest plugin to test logging                                                                                                                                                                                                                                                                                                                                                           Jun 15, 2021    1 - Planning           pytest (>=6.2.0)\n   :pypi:`pytest-logfest`                                   Pytest plugin providing three logger fixtures with basic or full writing to log files                                                                                                                                                                                                                                                                                                   Jul 21, 2019    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-log-filter`                                Ignore some loggers' log for pytest                                                                                                                                                                                                                                                                                                                                                     Nov 13, 2025    N/A                    pytest\n   :pypi:`pytest-logger`                                    Plugin configuring handlers for loggers from Python logging module.                                                                                                                                                                                                                                                                                                                     Mar 10, 2024    5 - Production/Stable  pytest (>=3.2)\n   :pypi:`pytest-logger-db`                                 Add your description here                                                                                                                                                                                                                                                                                                                                                               Sep 14, 2025    N/A                    N/A\n   :pypi:`pytest-logging`                                   Configures logging and allows tweaking the log level with a py.test flag                                                                                                                                                                                                                                                                                                                Nov 04, 2015    4 - Beta               N/A\n   :pypi:`pytest-logging-end-to-end-test-tool`                                                                                                                                                                                                                                                                                                                                                                                                      Sep 23, 2022    N/A                    pytest (>=7.1.2,<8.0.0)\n   :pypi:`pytest-logging-strict`                            pytest fixture logging configured from packaged YAML                                                                                                                                                                                                                                                                                                                                    May 20, 2025    3 - Alpha              pytest\n   :pypi:`pytest-logikal`                                   Common testing environment                                                                                                                                                                                                                                                                                                                                                              Mar 13, 2026    5 - Production/Stable  pytest==9.0.2\n   :pypi:`pytest-log-report`                                Package for creating a pytest test run reprot                                                                                                                                                                                                                                                                                                                                           Dec 26, 2019    N/A                    N/A\n   :pypi:`pytest-logscanner`                                Pytest plugin for logscanner (A logger for python logging outputting to easily viewable (and filterable) html files. Good for people not grep savey, and color higlighting and quickly changing filters might even bye useful for commandline wizards.)                                                                                                                                 Sep 30, 2024    4 - Beta               pytest>=8.2.2\n   :pypi:`pytest-loguru`                                    Pytest Loguru                                                                                                                                                                                                                                                                                                                                                                           Mar 20, 2024    5 - Production/Stable  pytest; extra == \"test\"\n   :pypi:`pytest-loop`                                      pytest plugin for looping tests                                                                                                                                                                                                                                                                                                                                                         Oct 17, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-lsp`                                       A pytest plugin for end-to-end testing of language servers                                                                                                                                                                                                                                                                                                                              Oct 25, 2025    5 - Production/Stable  pytest>=8.0\n   :pypi:`pytest-lw-realtime-result`                        Pytest plugin to generate realtime test results to a file                                                                                                                                                                                                                                                                                                                               Mar 13, 2025    N/A                    pytest>=3.5.0\n   :pypi:`pytest-manifest`                                  PyTest plugin for recording and asserting against a manifest file                                                                                                                                                                                                                                                                                                                       Apr 07, 2025    N/A                    pytest\n   :pypi:`pytest-manual-marker`                             pytest marker for marking manual tests                                                                                                                                                                                                                                                                                                                                                  Aug 04, 2022    3 - Alpha              pytest>=7\n   :pypi:`pytest-mark-ac`                                   Provides a marker to reference acceptance criteria from PyTest tests through annotations                                                                                                                                                                                                                                                                                                Mar 02, 2026    5 - Production/Stable  pytest<10,>=8.4\n   :pypi:`pytest-mark-count`                                Get a count of the number of tests marked, unmarked, and unique tests if tests have multiple markers                                                                                                                                                                                                                                                                                    Nov 13, 2024    4 - Beta               pytest>=8.0.0\n   :pypi:`pytest-markdir`                                                                                                                                                                                                                                                                                                                                                                                                                           Feb 01, 2026    N/A                    pytest<10,>=8.0\n   :pypi:`pytest-markdoctest`                               A pytest plugin to doctest your markdown files                                                                                                                                                                                                                                                                                                                                          Jul 22, 2022    4 - Beta               pytest (>=6)\n   :pypi:`pytest-markdown`                                  Test your markdown docs with pytest                                                                                                                                                                                                                                                                                                                                                     Jan 15, 2021    4 - Beta               pytest (>=6.0.1,<7.0.0)\n   :pypi:`pytest-markdown-docs`                             Run markdown code fences through pytest                                                                                                                                                                                                                                                                                                                                                 Jan 28, 2026    N/A                    pytest>=7.0.0\n   :pypi:`pytest-markdown-report`                           Token-efficient markdown test reports for LLM-based TDD agents                                                                                                                                                                                                                                                                                                                          Jan 10, 2026    N/A                    pytest>=7.0\n   :pypi:`pytest-marker-bugzilla`                           py.test bugzilla integration plugin, using markers                                                                                                                                                                                                                                                                                                                                      Apr 02, 2025    5 - Production/Stable  pytest>=2.2.4\n   :pypi:`pytest-markers-presence`                          A simple plugin to detect missed pytest tags and markers\"                                                                                                                                                                                                                                                                                                                               Oct 30, 2024    4 - Beta               pytest>=6.0\n   :pypi:`pytest-mark-filter`                               Filter pytest marks by name using match kw                                                                                                                                                                                                                                                                                                                                              May 11, 2025    N/A                    pytest>=8.3.0\n   :pypi:`pytest-markfiltration`                            UNKNOWN                                                                                                                                                                                                                                                                                                                                                                                 Nov 08, 2011    3 - Alpha              N/A\n   :pypi:`pytest-mark-integration`                          Pytest plugin for automatic integration test marking and management                                                                                                                                                                                                                                                                                                                     Jan 13, 2026    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-mark-manage`                               用例标签化管理                                                                                                                                                                                                                                                                                                                                                                          Aug 15, 2024    N/A                    pytest\n   :pypi:`pytest-mark-no-py3`                               pytest plugin and bowler codemod to help migrate tests to Python 3                                                                                                                                                                                                                                                                                                                      May 17, 2019    N/A                    pytest\n   :pypi:`pytest-marks`                                     UNKNOWN                                                                                                                                                                                                                                                                                                                                                                                 Nov 23, 2012    3 - Alpha              N/A\n   :pypi:`pytest-mask-secrets`                              Pytest plugin to hide sensitive data in test reports                                                                                                                                                                                                                                                                                                                                    Dec 17, 2025    N/A                    N/A\n   :pypi:`pytest-matcher`                                   Easy way to match captured \\`pytest\\` output against expectations stored in files                                                                                                                                                                                                                                                                                                       Aug 07, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-matchers`                                  Matchers for pytest                                                                                                                                                                                                                                                                                                                                                                     Dec 19, 2025    N/A                    pytest<10.0,>=7.0\n   :pypi:`pytest-match-skip`                                Skip matching marks. Matches partial marks using wildcards.                                                                                                                                                                                                                                                                                                                             May 15, 2019    4 - Beta               pytest (>=4.4.1)\n   :pypi:`pytest-mat-report`                                this is report                                                                                                                                                                                                                                                                                                                                                                          Jan 20, 2021    N/A                    N/A\n   :pypi:`pytest-matrix`                                    Provide tools for generating tests from combinations of fixtures.                                                                                                                                                                                                                                                                                                                       Jun 24, 2020    5 - Production/Stable  pytest (>=5.4.3,<6.0.0)\n   :pypi:`pytest-maxcov`                                    Compute the maximum coverage available through pytest with the minimum execution time cost                                                                                                                                                                                                                                                                                              Sep 24, 2023    N/A                    pytest (>=7.4.0,<8.0.0)\n   :pypi:`pytest-max-warnings`                              A Pytest plugin to exit non-zero exit code when the configured maximum warnings has been exceeded.                                                                                                                                                                                                                                                                                      Oct 23, 2024    4 - Beta               pytest>=8.3.3\n   :pypi:`pytest-maybe-context`                             Simplify tests with warning and exception cases.                                                                                                                                                                                                                                                                                                                                        Apr 16, 2023    N/A                    pytest (>=7,<8)\n   :pypi:`pytest-maybe-raises`                              Pytest fixture for optional exception testing.                                                                                                                                                                                                                                                                                                                                          May 27, 2022    N/A                    pytest ; extra == 'dev'\n   :pypi:`pytest-mccabe`                                    pytest plugin to run the mccabe code complexity checker.                                                                                                                                                                                                                                                                                                                                Jul 22, 2020    3 - Alpha              pytest (>=5.4.0)\n   :pypi:`pytest-mcp`                                       Pytest-style framework for evaluating Model Context Protocol (MCP) servers.                                                                                                                                                                                                                                                                                                             Jul 07, 2025    N/A                    pytest>=8.4.0\n   :pypi:`pytest-mcp-tools`                                                                                                                                                                                                                                                                                                                                                                                                                         Mar 12, 2026    N/A                    pytest>=7.0.0; extra == \"test\"\n   :pypi:`pytest-md`                                        Plugin for generating Markdown reports for pytest results                                                                                                                                                                                                                                                                                                                               Jul 11, 2019    3 - Alpha              pytest (>=4.2.1)\n   :pypi:`pytest-md-report`                                 A pytest plugin to generate test outcomes reports with markdown table format.                                                                                                                                                                                                                                                                                                           May 02, 2025    4 - Beta               pytest!=6.0.0,<9,>=3.3.2\n   :pypi:`pytest-meilisearch`                               Pytest helpers for testing projects using Meilisearch                                                                                                                                                                                                                                                                                                                                   Oct 08, 2024    N/A                    pytest>=7.4.3\n   :pypi:`pytest-memlog`                                    Log memory usage during tests                                                                                                                                                                                                                                                                                                                                                           May 03, 2023    N/A                    pytest (>=7.3.0,<8.0.0)\n   :pypi:`pytest-memprof`                                   Estimates memory consumption of test functions                                                                                                                                                                                                                                                                                                                                          Mar 29, 2019    4 - Beta               N/A\n   :pypi:`pytest-memray`                                    A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Aug 18, 2025    N/A                    pytest>=7.2\n   :pypi:`pytest-menu`                                      A pytest plugin for console based interactive test selection just after the collection phase                                                                                                                                                                                                                                                                                            Oct 04, 2017    3 - Alpha              pytest (>=2.4.2)\n   :pypi:`pytest-mercurial`                                 pytest plugin to write integration tests for projects using Mercurial Python internals                                                                                                                                                                                                                                                                                                  Nov 21, 2020    1 - Planning           N/A\n   :pypi:`pytest-mergify`                                   Pytest plugin for Mergify                                                                                                                                                                                                                                                                                                                                                               Jan 26, 2026    N/A                    pytest>=6.0.0\n   :pypi:`pytest-mesh`                                      pytest_mesh插件                                                                                                                                                                                                                                                                                                                                                                         Aug 05, 2022    N/A                    pytest (==7.1.2)\n   :pypi:`pytest-message`                                   Pytest plugin for sending report message of marked tests execution                                                                                                                                                                                                                                                                                                                      Aug 04, 2022    N/A                    pytest (>=6.2.5)\n   :pypi:`pytest-messenger`                                 Pytest to Slack reporting plugin                                                                                                                                                                                                                                                                                                                                                        Nov 24, 2022    5 - Production/Stable  N/A\n   :pypi:`pytest-metadata`                                  pytest plugin for test session metadata                                                                                                                                                                                                                                                                                                                                                 Feb 12, 2024    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-metaexport`                                Pytest plugin for exporting custom test metadata to JSON.                                                                                                                                                                                                                                                                                                                               Jun 24, 2025    N/A                    pytest>=7.1.0\n   :pypi:`pytest-metrics`                                   Custom metrics report for pytest                                                                                                                                                                                                                                                                                                                                                        Apr 04, 2020    N/A                    pytest\n   :pypi:`pytest-mfd-config`                                Pytest Plugin that handles test and topology configs and all their belongings like helper fixtures.                                                                                                                                                                                                                                                                                     Jul 11, 2025    N/A                    pytest<9,>=7.2.1\n   :pypi:`pytest-mfd-logging`                               Module for handling PyTest logging.                                                                                                                                                                                                                                                                                                                                                     Nov 14, 2025    N/A                    pytest<9,>=7.2.1\n   :pypi:`pytest-mh`                                        Pytest multihost plugin                                                                                                                                                                                                                                                                                                                                                                 Oct 16, 2025    N/A                    pytest\n   :pypi:`pytest-mimesis`                                   Mimesis integration with the pytest test runner                                                                                                                                                                                                                                                                                                                                         Mar 21, 2020    5 - Production/Stable  pytest (>=4.2)\n   :pypi:`pytest-mimic`                                     Easily record function calls while testing                                                                                                                                                                                                                                                                                                                                              Apr 24, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-minecraft`                                 A pytest plugin for running tests against Minecraft releases                                                                                                                                                                                                                                                                                                                            Apr 06, 2022    N/A                    pytest (>=6.0.1)\n   :pypi:`pytest-mini`                                      A plugin to test mp                                                                                                                                                                                                                                                                                                                                                                     Feb 06, 2023    N/A                    pytest (>=7.2.0,<8.0.0)\n   :pypi:`pytest-minio-mock`                                A pytest plugin for mocking Minio S3 interactions                                                                                                                                                                                                                                                                                                                                       Aug 06, 2025    N/A                    pytest>=5.0.0\n   :pypi:`pytest-mirror`                                    A pluggy-based pytest plugin and CLI tool for ensuring your test suite mirrors your source code structure                                                                                                                                                                                                                                                                               Jul 30, 2025    4 - Beta               N/A\n   :pypi:`pytest-missing-fixtures`                          Pytest plugin that creates missing fixtures                                                                                                                                                                                                                                                                                                                                             Oct 14, 2020    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-missing-modules`                           Pytest plugin to easily fake missing modules                                                                                                                                                                                                                                                                                                                                            Nov 17, 2025    N/A                    pytest>=8.3.2\n   :pypi:`pytest-mitmproxy`                                 pytest plugin for mitmproxy tests                                                                                                                                                                                                                                                                                                                                                       Nov 13, 2024    N/A                    pytest>=7.0\n   :pypi:`pytest-mitmproxy-plugin`                          Use MITM Proxy in autotests with full control from code                                                                                                                                                                                                                                                                                                                                 Apr 10, 2025    4 - Beta               pytest>=7.2.0\n   :pypi:`pytest-ml`                                        Test your machine learning!                                                                                                                                                                                                                                                                                                                                                             May 04, 2019    4 - Beta               N/A\n   :pypi:`pytest-mocha`                                     pytest plugin to display test execution output like a mochajs                                                                                                                                                                                                                                                                                                                           Apr 02, 2020    4 - Beta               pytest (>=5.4.0)\n   :pypi:`pytest-mock`                                      Thin-wrapper around the mock package for easier use with pytest                                                                                                                                                                                                                                                                                                                         Sep 16, 2025    5 - Production/Stable  pytest>=6.2.5\n   :pypi:`pytest-mock-api`                                  A mock API server with configurable routes and responses available as a fixture.                                                                                                                                                                                                                                                                                                        Feb 13, 2019    1 - Planning           pytest (>=4.0.0)\n   :pypi:`pytest-mock-generator`                            A pytest fixture wrapper for https://pypi.org/project/mock-generator                                                                                                                                                                                                                                                                                                                    May 16, 2022    5 - Production/Stable  N/A\n   :pypi:`pytest-mock-helper`                               Help you mock HTTP call and generate mock code                                                                                                                                                                                                                                                                                                                                          Jan 24, 2018    N/A                    pytest\n   :pypi:`pytest-mockito`                                   Base fixtures for mockito                                                                                                                                                                                                                                                                                                                                                               Feb 10, 2026    5 - Production/Stable  pytest>=6\n   :pypi:`pytest-mockllm`                                   🚀 Zero-config pytest plugin for mocking LLM APIs - OpenAI, Anthropic, Gemini, LangChain & more                                                                                                                                                                                                                                                                                         Dec 22, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-mockredis`                                 An in-memory mock of a Redis server that runs in a separate thread. This is to be used for unit-tests that require a Redis database.                                                                                                                                                                                                                                                    Jan 02, 2018    2 - Pre-Alpha          N/A\n   :pypi:`pytest-mock-resources`                            A pytest plugin for easily instantiating reproducible mock resources.                                                                                                                                                                                                                                                                                                                   Sep 17, 2025    N/A                    pytest>=1.0\n   :pypi:`pytest-mock-server`                               Mock server plugin for pytest                                                                                                                                                                                                                                                                                                                                                           Jan 09, 2022    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-mockservers`                               A set of fixtures to test your requests to HTTP/UDP servers                                                                                                                                                                                                                                                                                                                             Mar 31, 2020    N/A                    pytest (>=4.3.0)\n   :pypi:`pytest-mocktcp`                                   A pytest plugin for testing TCP clients                                                                                                                                                                                                                                                                                                                                                 Oct 11, 2022    N/A                    pytest\n   :pypi:`pytest-mock-unity-catalog`                        Unity Catalog pyspark fixtures                                                                                                                                                                                                                                                                                                                                                          Mar 12, 2026    N/A                    pytest\n   :pypi:`pytest-modalt`                                    Massively distributed pytest runs using modal.com                                                                                                                                                                                                                                                                                                                                       Feb 27, 2024    4 - Beta               pytest >=6.2.0\n   :pypi:`pytest-model-lib`                                 pytest plugin for model-lib                                                                                                                                                                                                                                                                                                                                                             Feb 22, 2026    N/A                    N/A\n   :pypi:`pytest-modern`                                    A more modern pytest                                                                                                                                                                                                                                                                                                                                                                    Aug 19, 2025    4 - Beta               pytest>=8\n   :pypi:`pytest-modified-env`                              Pytest plugin to fail a test if it leaves modified \\`os.environ\\` afterwards.                                                                                                                                                                                                                                                                                                           Jan 29, 2022    4 - Beta               N/A\n   :pypi:`pytest-modifyjunit`                               Utility for adding additional properties to junit xml for IDM QE                                                                                                                                                                                                                                                                                                                        Jan 10, 2019    N/A                    N/A\n   :pypi:`pytest-molecule`                                  PyTest Molecule Plugin :: discover and run molecule tests                                                                                                                                                                                                                                                                                                                               Mar 29, 2022    5 - Production/Stable  pytest (>=7.0.0)\n   :pypi:`pytest-molecule-JC`                               PyTest Molecule Plugin :: discover and run molecule tests                                                                                                                                                                                                                                                                                                                               Jul 18, 2023    5 - Production/Stable  pytest (>=7.0.0)\n   :pypi:`pytest-mongo`                                     MongoDB process and client fixtures plugin for Pytest.                                                                                                                                                                                                                                                                                                                                  Feb 04, 2026    5 - Production/Stable  pytest>=8.4\n   :pypi:`pytest-mongodb`                                   pytest plugin for MongoDB fixtures                                                                                                                                                                                                                                                                                                                                                      May 16, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-mongodb-nono`                              pytest plugin for MongoDB                                                                                                                                                                                                                                                                                                                                                               Jan 07, 2025    N/A                    N/A\n   :pypi:`pytest-mongodb-ry`                                pytest plugin for MongoDB                                                                                                                                                                                                                                                                                                                                                               Sep 25, 2025    N/A                    N/A\n   :pypi:`pytest-mongo-docker`                              A tiny plugin for pytest which runs MongoDB in Docker                                                                                                                                                                                                                                                                                                                                   Mar 05, 2026    5 - Production/Stable  pytest>=7.4\n   :pypi:`pytest-monitor`                                   Pytest plugin for analyzing resource usage.                                                                                                                                                                                                                                                                                                                                             Jun 25, 2023    5 - Production/Stable  pytest\n   :pypi:`pytest-monkeyplus`                                pytest's monkeypatch subclass with extra functionalities                                                                                                                                                                                                                                                                                                                                Sep 18, 2012    5 - Production/Stable  N/A\n   :pypi:`pytest-monkeytype`                                pytest-monkeytype: Generate Monkeytype annotations from your pytest tests.                                                                                                                                                                                                                                                                                                              Jul 29, 2020    4 - Beta               N/A\n   :pypi:`pytest-moto`                                      Fixtures for integration tests of AWS services,uses moto mocking library.                                                                                                                                                                                                                                                                                                               Aug 28, 2015    1 - Planning           N/A\n   :pypi:`pytest-moto-fixtures`                             Fixtures for testing code that interacts with AWS                                                                                                                                                                                                                                                                                                                                       Nov 17, 2025    1 - Planning           pytest<9.1,>=8.3; extra == \"pytest\"\n   :pypi:`pytest-motor`                                     A pytest plugin for motor, the non-blocking MongoDB driver.                                                                                                                                                                                                                                                                                                                             Jul 21, 2021    3 - Alpha              pytest\n   :pypi:`pytest-mp`                                        A test batcher for multiprocessed Pytest runs                                                                                                                                                                                                                                                                                                                                           May 23, 2018    4 - Beta               pytest\n   :pypi:`pytest-mpi`                                       pytest plugin to collect information from tests                                                                                                                                                                                                                                                                                                                                         Jan 08, 2022    3 - Alpha              pytest\n   :pypi:`pytest-mpiexec`                                   pytest plugin for running individual tests with mpiexec                                                                                                                                                                                                                                                                                                                                 Jul 29, 2024    3 - Alpha              pytest\n   :pypi:`pytest-mpi-tmweigand`                             forked pytest plugin to collect information from tests                                                                                                                                                                                                                                                                                                                                  Dec 27, 2025    3 - Alpha              pytest\n   :pypi:`pytest-mpl`                                       pytest plugin to help with testing figures output from Matplotlib                                                                                                                                                                                                                                                                                                                       Nov 15, 2025    5 - Production/Stable  pytest>=5.4.0\n   :pypi:`pytest-mpl-oggm`                                  pytest plugin to help with testing figures output from Matplotlib - OGGM fork                                                                                                                                                                                                                                                                                                           Mar 09, 2026    5 - Production/Stable  pytest>=6.2.5\n   :pypi:`pytest-mproc`                                     low-startup-overhead, scalable, distributed-testing pytest plugin                                                                                                                                                                                                                                                                                                                       Nov 15, 2022    4 - Beta               pytest (>=6)\n   :pypi:`pytest-mqtt`                                      pytest-mqtt supports testing systems based on MQTT                                                                                                                                                                                                                                                                                                                                      Jan 28, 2026    5 - Production/Stable  pytest<10; extra == \"test\"\n   :pypi:`pytest-multihost`                                 Utility for writing multi-host tests for pytest                                                                                                                                                                                                                                                                                                                                         Apr 07, 2020    4 - Beta               N/A\n   :pypi:`pytest-multilog`                                  Multi-process logs handling and other helpers for pytest                                                                                                                                                                                                                                                                                                                                Dec 28, 2025    N/A                    pytest\n   :pypi:`pytest-multithreading`                            a pytest plugin for th and concurrent testing                                                                                                                                                                                                                                                                                                                                           Aug 05, 2024    N/A                    N/A\n   :pypi:`pytest-multithreading-allure`                     pytest_multithreading_allure                                                                                                                                                                                                                                                                                                                                                            Nov 25, 2022    N/A                    N/A\n   :pypi:`pytest-mutagen`                                   Add the mutation testing feature to pytest                                                                                                                                                                                                                                                                                                                                              Jul 24, 2020    N/A                    pytest (>=5.4)\n   :pypi:`pytest-my-cool-lib`                                                                                                                                                                                                                                                                                                                                                                                                                       Nov 02, 2023    N/A                    pytest (>=7.1.3,<8.0.0)\n   :pypi:`pytest-my-plugin`                                 A pytest plugin that does awesome things                                                                                                                                                                                                                                                                                                                                                Jan 27, 2025    N/A                    pytest>=6.0\n   :pypi:`pytest-mypy`                                      A Pytest Plugin for Mypy                                                                                                                                                                                                                                                                                                                                                                Apr 02, 2025    5 - Production/Stable  pytest>=7.0\n   :pypi:`pytest-mypyd`                                     Mypy static type checker plugin for Pytest                                                                                                                                                                                                                                                                                                                                              Aug 20, 2019    4 - Beta               pytest (<4.7,>=2.8) ; python_version < \"3.5\"\n   :pypi:`pytest-mypy-plugins`                              pytest plugin for writing tests for mypy plugins                                                                                                                                                                                                                                                                                                                                        Mar 12, 2026    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-mypy-plugins-shim`                         Substitute for \"pytest-mypy-plugins\" for Python implementations which aren't supported by mypy.                                                                                                                                                                                                                                                                                         Feb 14, 2025    N/A                    pytest>=6.0.0\n   :pypi:`pytest-mypy-runner`                               Run the mypy static type checker as a pytest test case                                                                                                                                                                                                                                                                                                                                  Apr 23, 2024    N/A                    pytest>=8.0\n   :pypi:`pytest-mypy-testing`                              Pytest plugin to check mypy output                                                                                                                                                                                                                                                                                                                                                      Jan 26, 2026    N/A                    pytest>=8\n   :pypi:`pytest-mysql`                                     MySQL process and client fixtures for pytest                                                                                                                                                                                                                                                                                                                                            Dec 10, 2024    5 - Production/Stable  pytest>=6.2\n   :pypi:`pytest-nb`                                        Seedable Jupyter Notebook testing tool                                                                                                                                                                                                                                                                                                                                                  Jul 26, 2025    N/A                    pytest==8.4.1\n   :pypi:`pytest-nb-as-test`                                Use notebooks as pytests. Keep your notebooks working.                                                                                                                                                                                                                                                                                                                                  Feb 25, 2026    4 - Beta               pytest<9.1.0,>=7.0.0; python_version < \"3.14\"\n   :pypi:`pytest-nbgrader`                                  Pytest plugin for using with nbgrader and generating test cases.                                                                                                                                                                                                                                                                                                                        Nov 05, 2025    2 - Pre-Alpha          pytest>=8.3.2; extra == \"dev\"\n   :pypi:`pytest-ndb`                                       pytest notebook debugger                                                                                                                                                                                                                                                                                                                                                                Apr 28, 2024    N/A                    pytest\n   :pypi:`pytest-needle`                                    pytest plugin for visual testing websites using selenium                                                                                                                                                                                                                                                                                                                                Dec 10, 2018    4 - Beta               pytest (<5.0.0,>=3.0.0)\n   :pypi:`pytest-neo`                                       pytest-neo is a plugin for pytest that shows tests like screen of Matrix.                                                                                                                                                                                                                                                                                                               Jan 08, 2022    3 - Alpha              pytest (>=6.2.0)\n   :pypi:`pytest-neon`                                      Pytest plugin for Neon database branch isolation in tests                                                                                                                                                                                                                                                                                                                               Feb 05, 2026    4 - Beta               pytest>=7.0\n   :pypi:`pytest-neos`                                      Pytest plugin for neos                                                                                                                                                                                                                                                                                                                                                                  Sep 10, 2024    5 - Production/Stable  pytest<8.0,>=7.2; extra == \"dev\"\n   :pypi:`pytest-netconf`                                   A pytest plugin that provides a mock NETCONF (RFC6241/RFC6242) server for local testing.                                                                                                                                                                                                                                                                                                Nov 03, 2025    N/A                    N/A\n   :pypi:`pytest-netdut`                                    \"Automated software testing for switches using pytest\"                                                                                                                                                                                                                                                                                                                                  Oct 09, 2025    N/A                    pytest>=3.5.0\n   :pypi:`pytest-network`                                   A simple plugin to disable network on socket level.                                                                                                                                                                                                                                                                                                                                     May 07, 2020    N/A                    N/A\n   :pypi:`pytest-network-endpoints`                         Network endpoints plugin for pytest                                                                                                                                                                                                                                                                                                                                                     Mar 06, 2022    N/A                    pytest\n   :pypi:`pytest-never-sleep`                               pytest plugin helps to avoid adding tests without mock \\`time.sleep\\`                                                                                                                                                                                                                                                                                                                   May 05, 2021    3 - Alpha              pytest (>=3.5.1)\n   :pypi:`pytest-nginx`                                     nginx fixture for pytest                                                                                                                                                                                                                                                                                                                                                                May 03, 2025    5 - Production/Stable  pytest>=3.0.0\n   :pypi:`pytest-nginx-iplweb`                              nginx fixture for pytest - iplweb temporary fork                                                                                                                                                                                                                                                                                                                                        Mar 01, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-ngrok`                                                                                                                                                                                                                                                                                                                                                                                                                             Jan 20, 2022    3 - Alpha              pytest\n   :pypi:`pytest-ngsfixtures`                               pytest ngs fixtures                                                                                                                                                                                                                                                                                                                                                                     Sep 06, 2019    2 - Pre-Alpha          pytest (>=5.0.0)\n   :pypi:`pytest-nhsd-apim`                                 Pytest plugin accessing NHSDigital's APIM proxies                                                                                                                                                                                                                                                                                                                                       Feb 13, 2026    N/A                    pytest<9.0.0,>=8.2.0\n   :pypi:`pytest-nice`                                      A pytest plugin that alerts user of failed test cases with screen notifications                                                                                                                                                                                                                                                                                                         May 04, 2019    4 - Beta               pytest\n   :pypi:`pytest-nice-parametrize`                          A small snippet for nicer PyTest's Parametrize                                                                                                                                                                                                                                                                                                                                          Apr 17, 2021    5 - Production/Stable  N/A\n   :pypi:`pytest_nlcov`                                     Pytest plugin to get the coverage of the new lines (based on git diff) only                                                                                                                                                                                                                                                                                                             Aug 05, 2024    N/A                    N/A\n   :pypi:`pytest-nocustom`                                  Run all tests without custom markers                                                                                                                                                                                                                                                                                                                                                    Aug 05, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-node-dependency`                           pytest plugin for controlling execution flow                                                                                                                                                                                                                                                                                                                                            Apr 10, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-nodev`                                     Test-driven source code search for Python.                                                                                                                                                                                                                                                                                                                                              Jul 21, 2016    4 - Beta               pytest (>=2.8.1)\n   :pypi:`pytest-nogarbage`                                 Ensure a test produces no garbage                                                                                                                                                                                                                                                                                                                                                       Feb 24, 2025    5 - Production/Stable  pytest>=4.6.0\n   :pypi:`pytest-no-problem`                                Pytest plugin to tell you when there's no problem                                                                                                                                                                                                                                                                                                                                       Jan 11, 2026    N/A                    pytest>=7.0\n   :pypi:`pytest-nose-attrib`                               pytest plugin to use nose @attrib marks decorators and pick tests based on attributes and partially uses nose-attrib plugin approach                                                                                                                                                                                                                                                    Aug 13, 2023    N/A                    N/A\n   :pypi:`pytest_notebook`                                  A pytest plugin for testing Jupyter Notebooks.                                                                                                                                                                                                                                                                                                                                          Nov 28, 2023    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-notice`                                    Send pytest execution result email                                                                                                                                                                                                                                                                                                                                                      Nov 05, 2020    N/A                    N/A\n   :pypi:`pytest-notification`                              A pytest plugin for sending a desktop notification and playing a sound upon completion of tests                                                                                                                                                                                                                                                                                         Jun 19, 2020    N/A                    pytest (>=4)\n   :pypi:`pytest-notifier`                                  A pytest plugin to notify test result                                                                                                                                                                                                                                                                                                                                                   Jun 12, 2020    3 - Alpha              pytest\n   :pypi:`pytest-notifier-plugin`                           Pytest plugin для отправки нотификаций в различные каналы связи о статуе прохождения тестов.                                                                                                                                                                                                                                                                                            Dec 22, 2025    N/A                    pytest>=7.0\n   :pypi:`pytest_notify`                                    Get notifications when your tests ends                                                                                                                                                                                                                                                                                                                                                  Jul 05, 2017    N/A                    pytest>=3.0.0\n   :pypi:`pytest-notimplemented`                            Pytest markers for not implemented features and tests.                                                                                                                                                                                                                                                                                                                                  Aug 27, 2019    N/A                    pytest (>=5.1,<6.0)\n   :pypi:`pytest-notion`                                    A PyTest Reporter to send test runs to Notion.so                                                                                                                                                                                                                                                                                                                                        Aug 07, 2019    N/A                    N/A\n   :pypi:`pytest-nunit`                                     A pytest plugin for generating NUnit3 test result XML output                                                                                                                                                                                                                                                                                                                            Feb 26, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-oar`                                       PyTest plugin for the OAR testing framework                                                                                                                                                                                                                                                                                                                                             May 12, 2025    N/A                    pytest>=6.0.1\n   :pypi:`pytest-oarepo`                                                                                                                                                                                                                                                                                                                                                                                                                            Feb 17, 2026    N/A                    pytest>=7.1.2; extra == \"dev\"\n   :pypi:`pytest-object-getter`                             Import any object from a 3rd party module while mocking its namespace on demand.                                                                                                                                                                                                                                                                                                        Jul 31, 2022    5 - Production/Stable  pytest\n   :pypi:`pytest-ochrus`                                    pytest results data-base and HTML reporter                                                                                                                                                                                                                                                                                                                                              Feb 21, 2018    4 - Beta               N/A\n   :pypi:`pytest-odc`                                       A pytest plugin for simplifying ODC database tests                                                                                                                                                                                                                                                                                                                                      Aug 04, 2023    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-odoo`                                      py.test plugin to run Odoo tests                                                                                                                                                                                                                                                                                                                                                        May 20, 2025    5 - Production/Stable  pytest>=8\n   :pypi:`pytest-odoo-fixtures`                             Project description                                                                                                                                                                                                                                                                                                                                                                     Jun 25, 2019    N/A                    N/A\n   :pypi:`pytest-oduit`                                     py.test plugin to run Odoo tests                                                                                                                                                                                                                                                                                                                                                        Feb 11, 2026    5 - Production/Stable  pytest>=8\n   :pypi:`pytest-oerp`                                      pytest plugin to test OpenERP modules                                                                                                                                                                                                                                                                                                                                                   Feb 28, 2012    3 - Alpha              N/A\n   :pypi:`pytest-offline`                                                                                                                                                                                                                                                                                                                                                                                                                           Mar 09, 2023    1 - Planning           pytest (>=7.0.0,<8.0.0)\n   :pypi:`pytest-ogsm-plugin`                               针对特定项目定制化插件，优化了pytest报告展示方式,并添加了项目所需特定参数                                                                                                                                                                                                                                                                                                               May 16, 2023    N/A                    N/A\n   :pypi:`pytest-ok`                                        The ultimate pytest output plugin                                                                                                                                                                                                                                                                                                                                                       Apr 01, 2019    4 - Beta               N/A\n   :pypi:`pytest-once`                                      xdist-safe 'run once' fixture decorator for pytest (setup/teardown across workers)                                                                                                                                                                                                                                                                                                      Oct 10, 2025    3 - Alpha              pytest>=8.4.0\n   :pypi:`pytest-only`                                      Use @pytest.mark.only to run a single test                                                                                                                                                                                                                                                                                                                                              May 27, 2024    5 - Production/Stable  pytest<9,>=3.6.0\n   :pypi:`pytest-oof`                                       A Pytest plugin providing structured, programmatic access to a test run's results                                                                                                                                                                                                                                                                                                       Dec 11, 2023    4 - Beta               N/A\n   :pypi:`pytest-oot`                                       Run object-oriented tests in a simple format                                                                                                                                                                                                                                                                                                                                            Sep 18, 2016    4 - Beta               N/A\n   :pypi:`pytest-openapi`                                   \\`pytest --openapi\\` - an opinionated, lightweight black-box contract tester against a live API using its OpenAPI specification as the source of truth                                                                                                                                                                                                                                  Mar 04, 2026    N/A                    pytest>=7.0.0\n   :pypi:`pytest-openfiles`                                 Pytest plugin for detecting inadvertent open file handles                                                                                                                                                                                                                                                                                                                               Jun 05, 2024    3 - Alpha              pytest>=4.6\n   :pypi:`pytest-open-html`                                 Auto-open HTML reports after pytest runs                                                                                                                                                                                                                                                                                                                                                Mar 31, 2025    N/A                    pytest>=6.0\n   :pypi:`pytest-opentelemetry`                             A pytest plugin for instrumenting test runs via OpenTelemetry                                                                                                                                                                                                                                                                                                                           Apr 25, 2025    N/A                    pytest\n   :pypi:`pytest-opentmi`                                   pytest plugin for publish results to opentmi                                                                                                                                                                                                                                                                                                                                            Feb 09, 2026    5 - Production/Stable  pytest>=5.0\n   :pypi:`pytest-operator`                                  Fixtures for Charmed Operators                                                                                                                                                                                                                                                                                                                                                          Sep 28, 2022    N/A                    pytest\n   :pypi:`pytest-optional`                                  include/exclude values of fixtures in pytest                                                                                                                                                                                                                                                                                                                                            Oct 07, 2015    N/A                    N/A\n   :pypi:`pytest-optional-tests`                            Easy declaration of optional tests (i.e., that are not run by default)                                                                                                                                                                                                                                                                                                                  Jul 21, 2025    4 - Beta               pytest; extra == \"dev\"\n   :pypi:`pytest-orchestration`                             A pytest plugin for orchestrating tests                                                                                                                                                                                                                                                                                                                                                 Jul 18, 2019    N/A                    N/A\n   :pypi:`pytest-order`                                     pytest plugin to run your tests in a specific order                                                                                                                                                                                                                                                                                                                                     Aug 22, 2024    5 - Production/Stable  pytest>=5.0; python_version < \"3.10\"\n   :pypi:`pytest-ordered`                                   Declare the order in which tests should run in your pytest.ini                                                                                                                                                                                                                                                                                                                          Nov 09, 2025    N/A                    pytest>=6.2.0\n   :pypi:`pytest-ordering`                                  pytest plugin to run your tests in a specific order                                                                                                                                                                                                                                                                                                                                     Nov 14, 2018    4 - Beta               pytest\n   :pypi:`pytest-order-modify`                              新增run_marker 来自定义用例的执行顺序                                                                                                                                                                                                                                                                                                                                                   Nov 04, 2022    N/A                    N/A\n   :pypi:`pytest-osxnotify`                                 OS X notifications for py.test results.                                                                                                                                                                                                                                                                                                                                                 May 15, 2015    N/A                    N/A\n   :pypi:`pytest-ot`                                        A pytest plugin for instrumenting test runs via OpenTelemetry                                                                                                                                                                                                                                                                                                                           Mar 21, 2024    N/A                    pytest; extra == \"dev\"\n   :pypi:`pytest-otel`                                      OpenTelemetry plugin for Pytest                                                                                                                                                                                                                                                                                                                                                         Mar 12, 2026    N/A                    pytest==9.0.2\n   :pypi:`pytest-otelmark`                                  Pytest plugin for otelmark.                                                                                                                                                                                                                                                                                                                                                             Sep 14, 2025    3 - Alpha              pytest>=8.3.5\n   :pypi:`pytest-override-env-var`                          Pytest mark to override a value of an environment variable.                                                                                                                                                                                                                                                                                                                             Feb 25, 2023    N/A                    N/A\n   :pypi:`pytest-owner`                                     Add owner mark for tests                                                                                                                                                                                                                                                                                                                                                                Aug 19, 2024    N/A                    pytest\n   :pypi:`pytest-pact`                                      A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Jan 07, 2019    4 - Beta               N/A\n   :pypi:`pytest-pagerduty`                                 Pytest plugin for PagerDuty integration via automation testing.                                                                                                                                                                                                                                                                                                                         Mar 22, 2025    N/A                    pytest<9.0.0,>=7.4.0\n   :pypi:`pytest-pahrametahrize`                            Parametrize your tests with a Boston accent.                                                                                                                                                                                                                                                                                                                                            Nov 24, 2021    4 - Beta               pytest (>=6.0,<7.0)\n   :pypi:`pytest-paia-blockly`                              pytest plugin for PAIA Blockly: verify get_solution() against test cases                                                                                                                                                                                                                                                                                                                Mar 02, 2026    N/A                    pytest>=8.0\n   :pypi:`pytest-paraflow`                                  Deterministic pytest test sharding across CI machines                                                                                                                                                                                                                                                                                                                                   Feb 26, 2026    3 - Alpha              pytest>=9.0.0\n   :pypi:`pytest-parallel`                                  a pytest plugin for parallel and concurrent testing                                                                                                                                                                                                                                                                                                                                     Oct 10, 2021    3 - Alpha              pytest (>=3.0.0)\n   :pypi:`pytest-parallel-39`                               a pytest plugin for parallel and concurrent testing                                                                                                                                                                                                                                                                                                                                     Jul 12, 2021    3 - Alpha              pytest (>=3.0.0)\n   :pypi:`pytest-parallelize-tests`                         pytest plugin that parallelizes test execution across multiple hosts                                                                                                                                                                                                                                                                                                                    Jan 27, 2023    4 - Beta               N/A\n   :pypi:`pytest-param`                                     pytest plugin to test all, first, last or random params                                                                                                                                                                                                                                                                                                                                 Sep 11, 2016    4 - Beta               pytest (>=2.6.0)\n   :pypi:`pytest-parametrization`                           Simpler PyTest parametrization                                                                                                                                                                                                                                                                                                                                                          May 22, 2022    5 - Production/Stable  N/A\n   :pypi:`pytest-parametrization-annotation`                A pytest library for parametrizing tests using type hints.                                                                                                                                                                                                                                                                                                                              Dec 10, 2024    5 - Production/Stable  pytest>=7\n   :pypi:`pytest-parametrize`                               pytest decorator for parametrizing test cases in a dict-way                                                                                                                                                                                                                                                                                                                             Sep 25, 2025    5 - Production/Stable  pytest<9.0.0,>=8.3.0\n   :pypi:`pytest-parametrize-cases`                         A more user-friendly way to write parametrized tests.                                                                                                                                                                                                                                                                                                                                   Mar 13, 2022    N/A                    pytest (>=6.1.2)\n   :pypi:`pytest-parametrized`                              Pytest decorator for parametrizing tests with default iterables.                                                                                                                                                                                                                                                                                                                        Dec 21, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-parametrize-suite`                         A simple pytest extension for creating a named test suite.                                                                                                                                                                                                                                                                                                                              Jan 19, 2023    5 - Production/Stable  pytest\n   :pypi:`pytest_param_files`                               Create pytest parametrize decorators from external files.                                                                                                                                                                                                                                                                                                                               Jul 29, 2023    N/A                    pytest\n   :pypi:`pytest-params`                                    Simplified pytest test case parameters.                                                                                                                                                                                                                                                                                                                                                 Mar 14, 2026    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-param-scope`                               pytest parametrize scope fixture workaround                                                                                                                                                                                                                                                                                                                                             Oct 18, 2023    N/A                    pytest\n   :pypi:`pytest-parawtf`                                   Finally spell paramete?ri[sz]e correctly                                                                                                                                                                                                                                                                                                                                                Dec 03, 2018    4 - Beta               pytest (>=3.6.0)\n   :pypi:`pytest-park`                                      Organise and analyse your pytest benchmarks                                                                                                                                                                                                                                                                                                                                             Mar 14, 2026    N/A                    N/A\n   :pypi:`pytest-pass`                                      Check out https://github.com/elilutsky/pytest-pass                                                                                                                                                                                                                                                                                                                                      Dec 04, 2019    N/A                    N/A\n   :pypi:`pytest-passrunner`                                Pytest plugin providing the 'run_on_pass' marker                                                                                                                                                                                                                                                                                                                                        Feb 10, 2021    5 - Production/Stable  pytest (>=4.6.0)\n   :pypi:`pytest-paste-config`                              Allow setting the path to a paste config file                                                                                                                                                                                                                                                                                                                                           Sep 18, 2013    3 - Alpha              N/A\n   :pypi:`pytest-patch`                                     An automagic \\`patch\\` fixture that can patch objects directly or by name.                                                                                                                                                                                                                                                                                                              Apr 29, 2023    3 - Alpha              pytest (>=7.0.0)\n   :pypi:`pytest-patches`                                   A contextmanager pytest fixture for handling multiple mock patches                                                                                                                                                                                                                                                                                                                      Aug 30, 2021    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-patterns`                                  pytest plugin to make testing complicated long string output easy to write and easy to debug                                                                                                                                                                                                                                                                                            Oct 22, 2024    4 - Beta               pytest>=6\n   :pypi:`pytest-pdb`                                       pytest plugin which adds pdb helper commands related to pytest.                                                                                                                                                                                                                                                                                                                         Jul 31, 2018    N/A                    N/A\n   :pypi:`pytest-peach`                                     pytest plugin for fuzzing with Peach API Security                                                                                                                                                                                                                                                                                                                                       Apr 12, 2019    4 - Beta               pytest (>=2.8.7)\n   :pypi:`pytest-pep257`                                    py.test plugin for pep257                                                                                                                                                                                                                                                                                                                                                               Jul 09, 2016    N/A                    N/A\n   :pypi:`pytest-pep8`                                      pytest plugin to check PEP8 requirements                                                                                                                                                                                                                                                                                                                                                Apr 27, 2014    N/A                    N/A\n   :pypi:`pytest-percent`                                   Change the exit code of pytest test sessions when a required percent of tests pass.                                                                                                                                                                                                                                                                                                     May 21, 2020    N/A                    pytest (>=5.2.0)\n   :pypi:`pytest-percents`                                                                                                                                                                                                                                                                                                                                                                                                                          Mar 16, 2024    N/A                    N/A\n   :pypi:`pytest-perf`                                      Run performance tests against the mainline code.                                                                                                                                                                                                                                                                                                                                        May 20, 2024    5 - Production/Stable  pytest!=8.1.*,>=6; extra == \"testing\"\n   :pypi:`pytest-performance`                               A simple plugin to ensure the execution of critical sections of code has not been impacted                                                                                                                                                                                                                                                                                              Sep 11, 2020    5 - Production/Stable  pytest (>=3.7.0)\n   :pypi:`pytest-performancetotal`                          A performance plugin for pytest                                                                                                                                                                                                                                                                                                                                                         Aug 05, 2025    5 - Production/Stable  N/A\n   :pypi:`pytest-persistence`                               Pytest tool for persistent objects                                                                                                                                                                                                                                                                                                                                                      Aug 21, 2024    N/A                    N/A\n   :pypi:`pytest-pexpect`                                   Pytest pexpect plugin.                                                                                                                                                                                                                                                                                                                                                                  Sep 10, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-pg`                                        A tiny plugin for pytest which runs PostgreSQL in Docker                                                                                                                                                                                                                                                                                                                                May 18, 2025    5 - Production/Stable  pytest>=7.4\n   :pypi:`pytest-pgsql`                                     Pytest plugins and helpers for tests using a Postgres database.                                                                                                                                                                                                                                                                                                                         May 13, 2020    5 - Production/Stable  pytest (>=3.0.0)\n   :pypi:`pytest-phmdoctest`                                pytest plugin to test Python examples in Markdown using phmdoctest.                                                                                                                                                                                                                                                                                                                     Apr 15, 2022    4 - Beta               pytest (>=5.4.3)\n   :pypi:`pytest-phoenix-interface`                         Pytest extension tool for phoenix projects.                                                                                                                                                                                                                                                                                                                                             Mar 19, 2025    N/A                    N/A\n   :pypi:`pytest-picked`                                    Run the tests related to the changed files                                                                                                                                                                                                                                                                                                                                              Nov 06, 2024    N/A                    pytest>=3.7.0\n   :pypi:`pytest-pickle-cache`                              A pytest plugin for caching test results using pickle.                                                                                                                                                                                                                                                                                                                                  Feb 06, 2026    4 - Beta               pytest>=9\n   :pypi:`pytest-pigeonhole`                                                                                                                                                                                                                                                                                                                                                                                                                        Jun 25, 2018    5 - Production/Stable  pytest (>=3.4)\n   :pypi:`pytest-pikachu`                                   Show surprise when tests are passing                                                                                                                                                                                                                                                                                                                                                    Aug 05, 2021    5 - Production/Stable  pytest\n   :pypi:`pytest-pilot`                                     Slice in your test base thanks to powerful markers.                                                                                                                                                                                                                                                                                                                                     Dec 17, 2025    5 - Production/Stable  N/A\n   :pypi:`pytest-pingguo-pytest-plugin`                     pingguo test                                                                                                                                                                                                                                                                                                                                                                            Oct 26, 2022    4 - Beta               N/A\n   :pypi:`pytest-pings`                                     🦊 The pytest plugin for Firefox Telemetry 📊                                                                                                                                                                                                                                                                                                                                           Jun 29, 2019    3 - Alpha              pytest (>=5.0.0)\n   :pypi:`pytest-pinned`                                    A simple pytest plugin for pinning tests                                                                                                                                                                                                                                                                                                                                                Sep 17, 2021    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-pinpoint`                                  A pytest plugin which runs SBFL algorithms to detect faults.                                                                                                                                                                                                                                                                                                                            Sep 25, 2020    N/A                    pytest (>=4.4.0)\n   :pypi:`pytest-pipeline`                                  Pytest plugin for functional testing of data analysispipelines                                                                                                                                                                                                                                                                                                                          Jan 24, 2017    3 - Alpha              N/A\n   :pypi:`pytest-pitch`                                     runs tests in an order such that coverage increases as fast as possible                                                                                                                                                                                                                                                                                                                 Nov 02, 2023    4 - Beta               pytest >=7.3.1\n   :pypi:`pytest-platform-adapter`                          Pytest集成自动化平台插件                                                                                                                                                                                                                                                                                                                                                                Mar 12, 2026    5 - Production/Stable  pytest>=6.2.5\n   :pypi:`pytest-platform-markers`                          Markers for pytest to skip tests on specific platforms                                                                                                                                                                                                                                                                                                                                  Sep 09, 2019    4 - Beta               pytest (>=3.6.0)\n   :pypi:`pytest-play`                                      pytest plugin that let you automate actions and assertions with test metrics reporting executing plain YAML files                                                                                                                                                                                                                                                                       Jun 12, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-playbook`                                  Pytest plugin for reading playbooks.                                                                                                                                                                                                                                                                                                                                                    Jan 21, 2021    3 - Alpha              pytest (>=6.1.2,<7.0.0)\n   :pypi:`pytest-playwright`                                A pytest wrapper with fixtures for Playwright to automate web browsers                                                                                                                                                                                                                                                                                                                  Nov 24, 2025    N/A                    pytest<10.0.0,>=6.2.4\n   :pypi:`pytest-playwright-artifacts`                      Capture screenshots, HTML, and console logs on Playwright test failures                                                                                                                                                                                                                                                                                                                 Feb 19, 2026    N/A                    N/A\n   :pypi:`pytest_playwright_async`                          ASYNC Pytest plugin for Playwright                                                                                                                                                                                                                                                                                                                                                      Sep 28, 2024    N/A                    N/A\n   :pypi:`pytest-playwright-asyncio`                        A pytest wrapper with async fixtures for Playwright to automate web browsers                                                                                                                                                                                                                                                                                                            Nov 24, 2025    N/A                    pytest<10.0.0,>=6.2.4\n   :pypi:`pytest-playwright-axe`                            An axe-core integration for accessibility testing using Playwright Python.                                                                                                                                                                                                                                                                                                              Jan 12, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-playwright-enhanced`                       A pytest plugin for playwright python                                                                                                                                                                                                                                                                                                                                                   Mar 24, 2024    N/A                    pytest<9.0.0,>=8.0.0\n   :pypi:`pytest-playwright-json`                           Generate Playwright-compatible JSON reports from pytest-playwright test runs                                                                                                                                                                                                                                                                                                            Jan 06, 2026    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-playwrights`                               A pytest wrapper with fixtures for Playwright to automate web browsers                                                                                                                                                                                                                                                                                                                  Dec 02, 2021    N/A                    N/A\n   :pypi:`pytest-playwright-snapshot`                       A pytest wrapper for snapshot testing with playwright                                                                                                                                                                                                                                                                                                                                   Aug 19, 2021    N/A                    N/A\n   :pypi:`pytest-playwright-visual`                         A pytest fixture for visual testing with Playwright                                                                                                                                                                                                                                                                                                                                     Apr 28, 2022    N/A                    N/A\n   :pypi:`pytest-playwright-visual-snapshot`                Easy pytest visual regression testing using playwright                                                                                                                                                                                                                                                                                                                                  Feb 05, 2026    N/A                    N/A\n   :pypi:`pytest-pl-grader`                                 A pytest plugin for autograding Python code. Designed for use with the PrairieLearn platform.                                                                                                                                                                                                                                                                                           Nov 12, 2025    3 - Alpha              pytest\n   :pypi:`pytest-plone`                                     Pytest plugin to test Plone addons                                                                                                                                                                                                                                                                                                                                                      Jun 11, 2025    3 - Alpha              pytest<8.0.0\n   :pypi:`pytest-plt`                                       Fixtures for quickly making Matplotlib plots in tests                                                                                                                                                                                                                                                                                                                                   Jan 17, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-plugin-helpers`                            A plugin to help developing and testing other plugins                                                                                                                                                                                                                                                                                                                                   Nov 23, 2019    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-plugins`                                   A Python package for managing pytest plugins.                                                                                                                                                                                                                                                                                                                                           Feb 07, 2026    5 - Production/Stable  pytest>=9.0.1\n   :pypi:`pytest-plugin-utils`                              Reusable configuration and artifact utilities for building pytest plugins                                                                                                                                                                                                                                                                                                               Feb 10, 2026    N/A                    N/A\n   :pypi:`pytest-plus`                                      PyTest Plus Plugin :: extends pytest functionality                                                                                                                                                                                                                                                                                                                                      Feb 02, 2025    5 - Production/Stable  pytest>=7.4.2\n   :pypi:`pytest-pmisc`                                                                                                                                                                                                                                                                                                                                                                                                                             Mar 21, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-podman`                                    Pytest plugin for Podman integration                                                                                                                                                                                                                                                                                                                                                    Feb 03, 2026    N/A                    N/A\n   :pypi:`pytest-pogo`                                      Pytest plugin for pogo-migrate                                                                                                                                                                                                                                                                                                                                                          Jan 20, 2026    4 - Beta               pytest>=7\n   :pypi:`pytest-pointers`                                  Pytest plugin to define functions you test with special marks for better navigation and reports                                                                                                                                                                                                                                                                                         Dec 26, 2022    N/A                    N/A\n   :pypi:`pytest-pokie`                                     Pokie plugin for pytest                                                                                                                                                                                                                                                                                                                                                                 Oct 19, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-polarion-cfme`                             pytest plugin for collecting test cases and recording test results                                                                                                                                                                                                                                                                                                                      Nov 13, 2017    3 - Alpha              N/A\n   :pypi:`pytest-polarion-collect`                          pytest plugin for collecting polarion test cases data                                                                                                                                                                                                                                                                                                                                   Jun 18, 2020    3 - Alpha              pytest\n   :pypi:`pytest-polecat`                                   Provides Polecat pytest fixtures                                                                                                                                                                                                                                                                                                                                                        Aug 12, 2019    4 - Beta               N/A\n   :pypi:`pytest-polymeric-report`                          A polymeric test report plugin for pytest                                                                                                                                                                                                                                                                                                                                               Feb 24, 2026    N/A                    N/A\n   :pypi:`pytest-ponyorm`                                   PonyORM in Pytest                                                                                                                                                                                                                                                                                                                                                                       Oct 31, 2018    N/A                    pytest (>=3.1.1)\n   :pypi:`pytest-poo`                                       Visualize your crappy tests                                                                                                                                                                                                                                                                                                                                                             Mar 25, 2021    5 - Production/Stable  pytest (>=2.3.4)\n   :pypi:`pytest-poo-fail`                                  Visualize your failed tests with poo                                                                                                                                                                                                                                                                                                                                                    Feb 12, 2015    5 - Production/Stable  N/A\n   :pypi:`pytest-pook`                                      Pytest plugin for pook                                                                                                                                                                                                                                                                                                                                                                  Feb 15, 2024    4 - Beta               pytest\n   :pypi:`pytest-pop`                                       A pytest plugin to help with testing pop projects                                                                                                                                                                                                                                                                                                                                       May 09, 2023    5 - Production/Stable  pytest\n   :pypi:`pytest-porcochu`                                  Show surprise when tests are passing                                                                                                                                                                                                                                                                                                                                                    Nov 28, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-portion`                                   Select a portion of the collected tests                                                                                                                                                                                                                                                                                                                                                 Mar 04, 2026    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-postgres`                                  Run PostgreSQL in Docker container in Pytest.                                                                                                                                                                                                                                                                                                                                           Mar 22, 2020    N/A                    pytest\n   :pypi:`pytest-postgresql`                                Postgresql fixtures and fixture factories for Pytest.                                                                                                                                                                                                                                                                                                                                   Jan 23, 2026    5 - Production/Stable  pytest>=8.2\n   :pypi:`pytest-power`                                     pytest plugin with powerful fixtures                                                                                                                                                                                                                                                                                                                                                    Dec 31, 2020    N/A                    pytest (>=5.4)\n   :pypi:`pytest-powerpack`                                 A plugin containing extra batteries for pytest                                                                                                                                                                                                                                                                                                                                          Jan 04, 2025    N/A                    pytest<9.0.0,>=8.1.1\n   :pypi:`pytest-prairielearn-grader`                       A pytest plugin for autograding Python code. Designed for use with the PrairieLearn platform.                                                                                                                                                                                                                                                                                           Jan 27, 2026    3 - Alpha              pytest\n   :pypi:`pytest-prefer-nested-dup-tests`                   A Pytest plugin to drop duplicated tests during collection, but will prefer keeping nested packages.                                                                                                                                                                                                                                                                                    Apr 27, 2022    4 - Beta               pytest (>=7.1.1,<8.0.0)\n   :pypi:`pytest-pretty`                                    pytest plugin for printing summary data as I want it                                                                                                                                                                                                                                                                                                                                    Jun 04, 2025    5 - Production/Stable  pytest>=7\n   :pypi:`pytest-pretty-terminal`                           pytest plugin for generating prettier terminal output                                                                                                                                                                                                                                                                                                                                   Jan 31, 2022    N/A                    pytest (>=3.4.1)\n   :pypi:`pytest-pride`                                     Minitest-style test colors                                                                                                                                                                                                                                                                                                                                                              Apr 02, 2016    3 - Alpha              N/A\n   :pypi:`pytest-print`                                     pytest-print adds the printer fixture you can use to print messages to the user (directly to the pytest runner, not stdout)                                                                                                                                                                                                                                                             Feb 11, 2026    5 - Production/Stable  pytest>=9.0.2\n   :pypi:`pytest-priority`                                  pytest plugin for add priority for tests                                                                                                                                                                                                                                                                                                                                                Aug 19, 2024    N/A                    pytest\n   :pypi:`pytest-proceed`                                                                                                                                                                                                                                                                                                                                                                                                                           Oct 01, 2024    N/A                    pytest\n   :pypi:`pytest-profiles`                                  pytest plugin for configuration profiles                                                                                                                                                                                                                                                                                                                                                Dec 09, 2021    4 - Beta               pytest (>=3.7.0)\n   :pypi:`pytest-profiling`                                 Profiling plugin for py.test                                                                                                                                                                                                                                                                                                                                                            Nov 29, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-progress`                                  pytest plugin for instant test progress status                                                                                                                                                                                                                                                                                                                                          Nov 11, 2025    5 - Production/Stable  pytest>=6.0\n   :pypi:`pytest-prometheus`                                Report test pass / failures to a Prometheus PushGateway                                                                                                                                                                                                                                                                                                                                 Oct 03, 2017    N/A                    N/A\n   :pypi:`pytest-prometheus-pushgateway`                    Pytest report plugin for Zulip                                                                                                                                                                                                                                                                                                                                                          Sep 27, 2022    5 - Production/Stable  pytest\n   :pypi:`pytest-prometheus-pushgw`                         Pytest plugin to export test metrics to Prometheus Pushgateway                                                                                                                                                                                                                                                                                                                          May 19, 2025    N/A                    pytest>=6.0.0\n   :pypi:`pytest-proofy`                                    Pytest plugin for Proofy test reporting                                                                                                                                                                                                                                                                                                                                                 Nov 13, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-prosper`                                   Test helpers for Prosper projects                                                                                                                                                                                                                                                                                                                                                       Sep 24, 2018    N/A                    N/A\n   :pypi:`pytest-prysk`                                     Pytest plugin for prysk                                                                                                                                                                                                                                                                                                                                                                 Dec 10, 2024    4 - Beta               pytest>=7.3.2\n   :pypi:`pytest-pspec`                                     A rspec format reporter for Python ptest                                                                                                                                                                                                                                                                                                                                                Jun 02, 2020    4 - Beta               pytest (>=3.0.0)\n   :pypi:`pytest-psqlgraph`                                 pytest plugin for testing applications that use psqlgraph                                                                                                                                                                                                                                                                                                                               Oct 19, 2021    4 - Beta               pytest (>=6.0)\n   :pypi:`pytest-pt`                                        pytest plugin to use \\*.pt files as tests                                                                                                                                                                                                                                                                                                                                               Nov 21, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-ptera`                                     Use ptera probes in tests                                                                                                                                                                                                                                                                                                                                                               Mar 01, 2022    N/A                    pytest (>=6.2.4,<7.0.0)\n   :pypi:`pytest-publish`                                                                                                                                                                                                                                                                                                                                                                                                                           Jun 04, 2024    N/A                    pytest<9.0.0,>=8.0.0\n   :pypi:`pytest-pudb`                                      Pytest PuDB debugger integration                                                                                                                                                                                                                                                                                                                                                        Oct 25, 2018    3 - Alpha              pytest (>=2.0)\n   :pypi:`pytest-pudb-resurrected`                          Pytest PuDB debugger integration                                                                                                                                                                                                                                                                                                                                                        Mar 12, 2026    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-pumpkin-spice`                             A pytest plugin that makes your test reporting pumpkin-spiced                                                                                                                                                                                                                                                                                                                           Sep 18, 2022    4 - Beta               N/A\n   :pypi:`pytest-purkinje`                                  py.test plugin for purkinje test runner                                                                                                                                                                                                                                                                                                                                                 Oct 28, 2017    2 - Pre-Alpha          N/A\n   :pypi:`pytest-pusher`                                    pytest plugin for push report to minio                                                                                                                                                                                                                                                                                                                                                  Jan 06, 2023    5 - Production/Stable  pytest (>=3.6)\n   :pypi:`pytest-pvcr`                                      PyTest Process VCR                                                                                                                                                                                                                                                                                                                                                                      Feb 25, 2026    3 - Alpha              pytest>=3.5.0\n   :pypi:`pytest-pve-cloud`                                                                                                                                                                                                                                                                                                                                                                                                                         Feb 27, 2026    N/A                    pytest==8.4.2\n   :pypi:`pytest-pw-config-gen`                             Generate pytest-playwright configuration files (pytest.ini, pyproject.toml, conftest.py) via CLI                                                                                                                                                                                                                                                                                        Mar 14, 2026    N/A                    pytest>=7.4; extra == \"dev\"\n   :pypi:`pytest-py125`                                                                                                                                                                                                                                                                                                                                                                                                                             Dec 03, 2022    N/A                    N/A\n   :pypi:`pytest-pycharm`                                   Plugin for py.test to enter PyCharm debugger on uncaught exceptions                                                                                                                                                                                                                                                                                                                     Aug 13, 2020    5 - Production/Stable  pytest (>=2.3)\n   :pypi:`pytest-pycodestyle`                               pytest plugin to run pycodestyle                                                                                                                                                                                                                                                                                                                                                        Jul 20, 2025    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-pydantic-schema-sync`                      Pytest plugin to synchronise Pydantic model schemas with JSONSchema files                                                                                                                                                                                                                                                                                                               Aug 29, 2024    N/A                    pytest>=6\n   :pypi:`pytest-pydev`                                     py.test plugin to connect to a remote debug server with PyDev or PyCharm.                                                                                                                                                                                                                                                                                                               Nov 15, 2017    3 - Alpha              N/A\n   :pypi:`pytest-pydocstyle`                                pytest plugin to run pydocstyle                                                                                                                                                                                                                                                                                                                                                         Oct 09, 2024    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-pyeval`                                    pytest plugin integrating pydantic-evals                                                                                                                                                                                                                                                                                                                                                Mar 14, 2026    N/A                    pytest>=8.0\n   :pypi:`pytest-pylembic`                                  This package provides pytest plugin for validating Alembic migrations using the pylembic package.                                                                                                                                                                                                                                                                                       Jul 22, 2025    3 - Alpha              N/A\n   :pypi:`pytest-pylint`                                    pytest plugin to check source code with pylint                                                                                                                                                                                                                                                                                                                                          Oct 06, 2023    5 - Production/Stable  pytest >=7.0\n   :pypi:`pytest-pylyzer`                                   A pytest plugin for pylyzer                                                                                                                                                                                                                                                                                                                                                             Feb 15, 2025    4 - Beta               N/A\n   :pypi:`pytest-pymysql-autorecord`                        Record PyMySQL queries and mock with the stored data.                                                                                                                                                                                                                                                                                                                                   Sep 02, 2022    N/A                    N/A\n   :pypi:`pytest-pyodide`                                   Pytest plugin for testing applications that use Pyodide                                                                                                                                                                                                                                                                                                                                 Feb 27, 2026    N/A                    pytest\n   :pypi:`pytest-pypi`                                      Easily test your HTTP library against a local copy of pypi                                                                                                                                                                                                                                                                                                                              Mar 04, 2018    3 - Alpha              N/A\n   :pypi:`pytest-pypom-navigation`                          Core engine for cookiecutter-qa and pytest-play packages                                                                                                                                                                                                                                                                                                                                Feb 18, 2019    4 - Beta               pytest (>=3.0.7)\n   :pypi:`pytest-pyppeteer`                                 A plugin to run pyppeteer in pytest                                                                                                                                                                                                                                                                                                                                                     Apr 28, 2022    N/A                    pytest (>=6.2.5,<7.0.0)\n   :pypi:`pytest-pyq`                                       Pytest fixture \"q\" for pyq                                                                                                                                                                                                                                                                                                                                                              Mar 10, 2020    5 - Production/Stable  N/A\n   :pypi:`pytest-pyramid`                                   pytest_pyramid - provides fixtures for testing pyramid applications with pytest test suite                                                                                                                                                                                                                                                                                              Sep 30, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-pyramid-server`                            Pyramid server fixture for py.test                                                                                                                                                                                                                                                                                                                                                      Oct 17, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-pyreport`                                  PyReport is a lightweight reporting plugin for Pytest that provides concise HTML report                                                                                                                                                                                                                                                                                                 May 05, 2024    N/A                    pytest\n   :pypi:`pytest-pyright`                                   Pytest plugin for type checking code with Pyright                                                                                                                                                                                                                                                                                                                                       Jan 26, 2024    4 - Beta               pytest >=7.0.0\n   :pypi:`pytest-pyspark-plugin`                            Pytest pyspark plugin (p3)                                                                                                                                                                                                                                                                                                                                                              Nov 23, 2025    4 - Beta               pytest>=8.0.0\n   :pypi:`pytest-pyspec`                                    The pytest-pyspec plugin transforms pytest output into a beautiful, readable format similar to RSpec. It provides semantic meaning to your tests by organizing them into descriptive hierarchies, using the prefixes \\`Describe\\`/\\`Test\\`, \\`With\\`/\\`Without\\`/\\`When\\`, and \\`test\\`/\\`it\\`, while allowing docstrings and decorators to override the descriptions.                  Nov 18, 2025    5 - Production/Stable  pytest<10,>=9\n   :pypi:`pytest-pystack`                                   Plugin to run pystack after a timeout for a test suite.                                                                                                                                                                                                                                                                                                                                 Nov 16, 2024    N/A                    pytest>=3.5.0\n   :pypi:`pytest-pytestdb`                                  Add your description here                                                                                                                                                                                                                                                                                                                                                               Sep 14, 2025    N/A                    N/A\n   :pypi:`pytest-pytestrail`                                Pytest plugin for interaction with TestRail                                                                                                                                                                                                                                                                                                                                             Aug 27, 2020    4 - Beta               pytest (>=3.8.0)\n   :pypi:`pytest-pytestrail-internal`                       Pytest plugin for interaction with TestRail, Pytest plugin for TestRail (internal fork from: https://github.com/tolstislon/pytest-pytestrail with PR #25 fix)                                                                                                                                                                                                                           Jun 12, 2025    4 - Beta               pytest>=3.8.0\n   :pypi:`pytest-pythonhashseed`                            Pytest plugin to set PYTHONHASHSEED env var.                                                                                                                                                                                                                                                                                                                                            Nov 16, 2025    4 - Beta               pytest>=3.0.0\n   :pypi:`pytest-pythonpath`                                pytest plugin for adding to the PYTHONPATH from command line or configs.                                                                                                                                                                                                                                                                                                                Feb 10, 2022    5 - Production/Stable  pytest (<7,>=2.5.2)\n   :pypi:`pytest-python-test-engineer-sort`                 Sort plugin for Pytest                                                                                                                                                                                                                                                                                                                                                                  May 13, 2024    N/A                    pytest>=6.2.0\n   :pypi:`pytest-pytorch`                                   pytest plugin for a better developer experience when working with the PyTorch test suite                                                                                                                                                                                                                                                                                                May 25, 2021    4 - Beta               pytest\n   :pypi:`pytest-pyvenv`                                    A package for create venv in tests                                                                                                                                                                                                                                                                                                                                                      Feb 27, 2024    N/A                    pytest ; extra == 'test'\n   :pypi:`pytest-pyvista`                                   Pytest-pyvista package.                                                                                                                                                                                                                                                                                                                                                                 Dec 02, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-qanova`                                    A pytest plugin to collect test information                                                                                                                                                                                                                                                                                                                                             Sep 05, 2024    3 - Alpha              pytest\n   :pypi:`pytest-qaseio`                                    Pytest plugin for Qase.io integration                                                                                                                                                                                                                                                                                                                                                   Dec 10, 2025    5 - Production/Stable  pytest>=7.2.2\n   :pypi:`pytest-qasync`                                    Pytest support for qasync.                                                                                                                                                                                                                                                                                                                                                              Jul 12, 2021    4 - Beta               pytest (>=5.4.0)\n   :pypi:`pytest-qatouch`                                   Pytest plugin for uploading test results to your QA Touch Testrun.                                                                                                                                                                                                                                                                                                                      Feb 14, 2023    4 - Beta               pytest (>=6.2.0)\n   :pypi:`pytest-qgis`                                      A pytest plugin for testing QGIS python plugins                                                                                                                                                                                                                                                                                                                                         Jun 14, 2024    5 - Production/Stable  pytest>=6.0\n   :pypi:`pytest-qml`                                       Run QML Tests with pytest                                                                                                                                                                                                                                                                                                                                                               Dec 02, 2020    4 - Beta               pytest (>=6.0.0)\n   :pypi:`pytest-qr`                                        pytest plugin to generate test result QR codes                                                                                                                                                                                                                                                                                                                                          Nov 25, 2021    4 - Beta               N/A\n   :pypi:`pytest-qt`                                        pytest support for PyQt and PySide applications                                                                                                                                                                                                                                                                                                                                         Jul 01, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-qt-app`                                    QT app fixture for py.test                                                                                                                                                                                                                                                                                                                                                              Oct 17, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-quarantine`                                A plugin for pytest to manage expected test failures                                                                                                                                                                                                                                                                                                                                    Nov 24, 2019    5 - Production/Stable  pytest (>=4.6)\n   :pypi:`pytest-quickcheck`                                pytest plugin to generate random data inspired by QuickCheck                                                                                                                                                                                                                                                                                                                            Nov 05, 2022    4 - Beta               pytest (>=4.0)\n   :pypi:`pytest_quickify`                                  Run test suites with pytest-quickify.                                                                                                                                                                                                                                                                                                                                                   Jun 14, 2019    N/A                    pytest\n   :pypi:`pytest-rabbitmq`                                  RabbitMQ process and client fixtures for pytest                                                                                                                                                                                                                                                                                                                                         Oct 15, 2024    5 - Production/Stable  pytest>=6.2\n   :pypi:`pytest-race`                                      Race conditions tester for pytest                                                                                                                                                                                                                                                                                                                                                       Jun 07, 2022    4 - Beta               N/A\n   :pypi:`pytest-rage`                                      pytest plugin to implement PEP712                                                                                                                                                                                                                                                                                                                                                       Oct 21, 2011    3 - Alpha              N/A\n   :pypi:`pytest-rail`                                      pytest plugin for creating TestRail runs and adding results                                                                                                                                                                                                                                                                                                                             May 02, 2022    N/A                    pytest (>=3.6)\n   :pypi:`pytest-railflow-testrail-reporter`                Generate json reports along with specified metadata defined in test markers.                                                                                                                                                                                                                                                                                                            Jun 29, 2022    5 - Production/Stable  pytest\n   :pypi:`pytest-raises`                                    An implementation of pytest.raises as a pytest.mark fixture                                                                                                                                                                                                                                                                                                                             Apr 23, 2020    N/A                    pytest (>=3.2.2)\n   :pypi:`pytest-raisesregexp`                              Simple pytest plugin to look for regex in Exceptions                                                                                                                                                                                                                                                                                                                                    Dec 18, 2015    N/A                    N/A\n   :pypi:`pytest-raisin`                                    Plugin enabling the use of exception instances with pytest.raises                                                                                                                                                                                                                                                                                                                       Feb 06, 2022    N/A                    pytest\n   :pypi:`pytest-random`                                    py.test plugin to randomize tests                                                                                                                                                                                                                                                                                                                                                       Apr 28, 2013    3 - Alpha              N/A\n   :pypi:`pytest-randomly`                                  Pytest plugin to randomly order tests and control random.seed.                                                                                                                                                                                                                                                                                                                          Sep 12, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-randomness`                                Pytest plugin about random seed management                                                                                                                                                                                                                                                                                                                                              May 30, 2019    3 - Alpha              N/A\n   :pypi:`pytest-random-num`                                Randomise the order in which pytest tests are run with some control over the randomness                                                                                                                                                                                                                                                                                                 Oct 19, 2020    5 - Production/Stable  N/A\n   :pypi:`pytest-random-order`                              Randomise the order in which pytest tests are run with some control over the randomness                                                                                                                                                                                                                                                                                                 Jun 22, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-ranking`                                   A Pytest plugin for faster fault detection via regression test prioritization                                                                                                                                                                                                                                                                                                           Apr 08, 2025    4 - Beta               pytest>=7.4.3\n   :pypi:`pytest-rca-report`                                Interactive RCA report generator for pytest runs, with AI-based analysis and visual dashboard                                                                                                                                                                                                                                                                                           Aug 04, 2025    N/A                    N/A\n   :pypi:`pytest-readable`                                  Pytest plugin that renders readable test specifications and exports documentation                                                                                                                                                                                                                                                                                                       Mar 12, 2026    3 - Alpha              pytest<10.0,>=9.0\n   :pypi:`pytest-readme`                                    Test your README.md file                                                                                                                                                                                                                                                                                                                                                                Aug 01, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-reana`                                     Pytest fixtures for REANA.                                                                                                                                                                                                                                                                                                                                                              Mar 03, 2026    3 - Alpha              N/A\n   :pypi:`pytest-recap`                                     Capture your test sessions. Recap the results.                                                                                                                                                                                                                                                                                                                                          Jun 16, 2025    N/A                    pytest>=6.2.0\n   :pypi:`pytest-recorder`                                  Pytest plugin, meant to facilitate unit tests writing for tools consumming Web APIs.                                                                                                                                                                                                                                                                                                    Mar 12, 2026    N/A                    pytest>=8.4.1\n   :pypi:`pytest-recording`                                 A pytest plugin powered by VCR.py to record and replay HTTP traffic                                                                                                                                                                                                                                                                                                                     May 08, 2025    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-recordings`                                Provides pytest plugins for reporting request/response traffic, screenshots, and more to ReportPortal                                                                                                                                                                                                                                                                                   Aug 13, 2020    N/A                    N/A\n   :pypi:`pytest-record-video`                              用例执行过程中录制视频                                                                                                                                                                                                                                                                                                                                                                  Oct 31, 2024    N/A                    N/A\n   :pypi:`pytest-redis`                                     Redis fixtures and fixture factories for Pytest.                                                                                                                                                                                                                                                                                                                                        Feb 28, 2026    5 - Production/Stable  pytest>=8.4.0\n   :pypi:`pytest-redislite`                                 Pytest plugin for testing code using Redis                                                                                                                                                                                                                                                                                                                                              Apr 05, 2022    4 - Beta               pytest\n   :pypi:`pytest-redmine`                                   Pytest plugin for redmine                                                                                                                                                                                                                                                                                                                                                               Mar 19, 2018    1 - Planning           N/A\n   :pypi:`pytest-ref`                                       A plugin to store reference files to ease regression testing                                                                                                                                                                                                                                                                                                                            Nov 23, 2019    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-reference-formatter`                       Conveniently run pytest with a dot-formatted test reference.                                                                                                                                                                                                                                                                                                                            Oct 01, 2019    4 - Beta               N/A\n   :pypi:`pytest-regex`                                     Select pytest tests with regular expressions                                                                                                                                                                                                                                                                                                                                            May 29, 2023    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-regex-dependency`                          Management of Pytest dependencies via regex patterns                                                                                                                                                                                                                                                                                                                                    Jun 12, 2022    N/A                    pytest\n   :pypi:`pytest-regressions`                               Easy to use fixtures to write regression tests.                                                                                                                                                                                                                                                                                                                                         Feb 10, 2026    5 - Production/Stable  pytest>=6.2.0\n   :pypi:`pytest-regtest`                                   pytest plugin for snapshot regression testing                                                                                                                                                                                                                                                                                                                                           Feb 25, 2026    N/A                    pytest>7.2\n   :pypi:`pytest-relative-order`                            a pytest plugin that sorts tests using \"before\" and \"after\" markers                                                                                                                                                                                                                                                                                                                     May 17, 2021    4 - Beta               N/A\n   :pypi:`pytest-relative-path`                             Handle relative path in pytest options or ini configs                                                                                                                                                                                                                                                                                                                                   Nov 13, 2025    N/A                    pytest\n   :pypi:`pytest-relaxed`                                   Relaxed test discovery/organization for pytest                                                                                                                                                                                                                                                                                                                                          Mar 29, 2024    5 - Production/Stable  pytest>=7\n   :pypi:`pytest_relay`                                     A plugin to relay test information and control from and to pytest                                                                                                                                                                                                                                                                                                                       Jan 31, 2026    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-relay-run`                                 A pytest wrapper using for pytest-relay with pytest-relay-ws to control pytest executions.                                                                                                                                                                                                                                                                                              Jan 31, 2026    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest_relay_ws`                                  An extension plugin to pytest-relay to relay pytest information via websockets                                                                                                                                                                                                                                                                                                          Jan 31, 2026    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-remfiles`                                  Pytest plugin to create a temporary directory with remote files                                                                                                                                                                                                                                                                                                                         Jul 01, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-remotedata`                                Pytest plugin for controlling remote data access.                                                                                                                                                                                                                                                                                                                                       Sep 26, 2023    5 - Production/Stable  pytest >=4.6\n   :pypi:`pytest-remote-response`                           Pytest plugin for capturing and mocking connection requests.                                                                                                                                                                                                                                                                                                                            Apr 26, 2023    5 - Production/Stable  pytest (>=4.6)\n   :pypi:`pytest-remove-stale-bytecode`                     py.test plugin to remove stale byte code files.                                                                                                                                                                                                                                                                                                                                         Nov 19, 2025    4 - Beta               pytest\n   :pypi:`pytest-reorder`                                   Reorder tests depending on their paths and names.                                                                                                                                                                                                                                                                                                                                       May 31, 2018    4 - Beta               pytest\n   :pypi:`pytest-repeat`                                    pytest plugin for repeating tests                                                                                                                                                                                                                                                                                                                                                       Apr 07, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-repeated`                                  A pytest module for very basic statistical tests. Repeat test multiple times and pass if the underlying test passes a threshold.                                                                                                                                                                                                                                                        Feb 24, 2026    N/A                    pytest>=7.0.0\n   :pypi:`pytest_repeater`                                  py.test plugin for repeating single test multiple times.                                                                                                                                                                                                                                                                                                                                Feb 09, 2018    1 - Planning           N/A\n   :pypi:`pytest-replay`                                    Saves previous test runs and allow re-execute previous pytest runs to reproduce crashes or flaky tests                                                                                                                                                                                                                                                                                  Dec 23, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-repo-health`                               A pytest plugin to report on repository standards conformance                                                                                                                                                                                                                                                                                                                           Dec 09, 2025    3 - Alpha              pytest\n   :pypi:`pytest-report`                                    Creates json report that is compatible with atom.io's linter message format                                                                                                                                                                                                                                                                                                             May 11, 2016    4 - Beta               N/A\n   :pypi:`pytest-reporter`                                  Generate Pytest reports with templates                                                                                                                                                                                                                                                                                                                                                  Feb 28, 2024    4 - Beta               pytest\n   :pypi:`pytest-reporter-html`                             Pytest plugin that generates rich HTML test reports with step tracking, log capture, and interactive filtering                                                                                                                                                                                                                                                                          Mar 14, 2026    5 - Production/Stable  pytest>=7.0\n   :pypi:`pytest-reporter-html1`                            A basic HTML report template for Pytest                                                                                                                                                                                                                                                                                                                                                 Oct 10, 2025    4 - Beta               N/A\n   :pypi:`pytest-reporter-html-dots`                        A basic HTML report for pytest using Jinja2 template engine.                                                                                                                                                                                                                                                                                                                            Apr 26, 2025    N/A                    N/A\n   :pypi:`pytest-reporter-plus`                             Lightweight enhanced HTML reporter for Pytest                                                                                                                                                                                                                                                                                                                                           Jul 16, 2025    N/A                    N/A\n   :pypi:`pytest-report-extras`                             Pytest plugin to enhance pytest-html and allure reports by adding comments, screenshots, webpage sources and attachments.                                                                                                                                                                                                                                                               Dec 24, 2025    N/A                    pytest>=8.4.0\n   :pypi:`pytest-reportinfra`                               Pytest plugin for reportinfra                                                                                                                                                                                                                                                                                                                                                           Aug 11, 2019    3 - Alpha              N/A\n   :pypi:`pytest-reporting`                                 A plugin to report summarized results in a table format                                                                                                                                                                                                                                                                                                                                 Oct 25, 2019    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-reportlog`                                 Replacement for the --resultlog option, focused in simplicity and extensibility                                                                                                                                                                                                                                                                                                         Nov 11, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-report-me`                                 A pytest plugin to generate report.                                                                                                                                                                                                                                                                                                                                                     Dec 31, 2020    N/A                    pytest\n   :pypi:`pytest-report-parameters`                         pytest plugin for adding tests' parameters to junit report                                                                                                                                                                                                                                                                                                                              Jun 18, 2020    3 - Alpha              pytest (>=2.4.2)\n   :pypi:`pytest-reportportal`                              Agent for Reporting results of tests to the Report Portal                                                                                                                                                                                                                                                                                                                               Dec 02, 2025    N/A                    pytest>=4.6.10\n   :pypi:`pytest-report-stream`                             A pytest plugin which allows to stream test reports at runtime                                                                                                                                                                                                                                                                                                                          Oct 22, 2023    4 - Beta               N/A\n   :pypi:`pytest-repo-structure`                            Pytest Repo Structure                                                                                                                                                                                                                                                                                                                                                                   Mar 18, 2024    1 - Planning           N/A\n   :pypi:`pytest-req`                                       pytest requests plugin                                                                                                                                                                                                                                                                                                                                                                  Mar 02, 2026    5 - Production/Stable  pytest>=8.4.2\n   :pypi:`pytest-reqcov`                                    A pytest plugin for requirement coverage tracking                                                                                                                                                                                                                                                                                                                                       Jul 04, 2025    3 - Alpha              pytest>=6.0\n   :pypi:`pytest-reqs`                                      pytest plugin to check pinned requirements                                                                                                                                                                                                                                                                                                                                              May 12, 2019    N/A                    pytest (>=2.4.2)\n   :pypi:`pytest-requests`                                  A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Jun 24, 2019    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-requestselapsed`                           collect and show http requests elapsed time                                                                                                                                                                                                                                                                                                                                             Aug 14, 2022    N/A                    N/A\n   :pypi:`pytest-requests-futures`                          Pytest Plugin to Mock Requests Futures                                                                                                                                                                                                                                                                                                                                                  Jul 06, 2022    5 - Production/Stable  pytest\n   :pypi:`pytest-requirements`                              pytest plugin for using custom markers to relate tests to requirements and usecases                                                                                                                                                                                                                                                                                                     Mar 10, 2026    N/A                    pytest\n   :pypi:`pytest-requires`                                  A pytest plugin to elegantly skip tests with optional requirements                                                                                                                                                                                                                                                                                                                      Dec 21, 2021    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-reqyaml`                                   This is a plugin where generate requests test cases from yaml.                                                                                                                                                                                                                                                                                                                          Aug 16, 2025    N/A                    pytest>=8.4.1\n   :pypi:`pytest-reraise`                                   Make multi-threaded pytest test cases fail when they should                                                                                                                                                                                                                                                                                                                             Sep 20, 2022    5 - Production/Stable  pytest (>=4.6)\n   :pypi:`pytest-rerun`                                     Re-run only changed files in specified branch                                                                                                                                                                                                                                                                                                                                           Jul 08, 2019    N/A                    pytest (>=3.6)\n   :pypi:`pytest-rerun-all`                                 Rerun testsuite for a certain time or iterations                                                                                                                                                                                                                                                                                                                                        Jul 30, 2025    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-rerunclassfailures`                        pytest rerun class failures plugin                                                                                                                                                                                                                                                                                                                                                      Apr 24, 2024    5 - Production/Stable  pytest>=7.2\n   :pypi:`pytest-rerunfailures`                             pytest plugin to re-run tests to eliminate flaky failures                                                                                                                                                                                                                                                                                                                               Oct 10, 2025    5 - Production/Stable  pytest!=8.2.2,>=7.4\n   :pypi:`pytest-rerunfailures-all-logs`                    pytest plugin to re-run tests to eliminate flaky failures                                                                                                                                                                                                                                                                                                                               Mar 07, 2022    5 - Production/Stable  N/A\n   :pypi:`pytest-reserial`                                  Pytest fixture for recording and replaying serial port traffic.                                                                                                                                                                                                                                                                                                                         Dec 30, 2025    4 - Beta               pytest\n   :pypi:`pytest-resilient-circuits`                        Resilient Circuits fixtures for PyTest                                                                                                                                                                                                                                                                                                                                                  Nov 13, 2025    N/A                    pytest~=7.0\n   :pypi:`pytest-resource`                                  Load resource fixture plugin to use with pytest                                                                                                                                                                                                                                                                                                                                         Nov 14, 2018    4 - Beta               N/A\n   :pypi:`pytest-resource-path`                             Provides path for uniform access to test resources in isolated directory                                                                                                                                                                                                                                                                                                                Sep 18, 2025    5 - Production/Stable  pytest>=3.5.0\n   :pypi:`pytest-resource-usage`                            Pytest plugin for reporting running time and peak memory usage                                                                                                                                                                                                                                                                                                                          Nov 06, 2022    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-respect`                                   Pytest plugin to load resource files relative to test code and to expect values to match them.                                                                                                                                                                                                                                                                                          Oct 21, 2025    5 - Production/Stable  pytest>=8.0.0\n   :pypi:`pytest-responsemock`                              Simplified requests calls mocking for pytest                                                                                                                                                                                                                                                                                                                                            Mar 10, 2022    5 - Production/Stable  N/A\n   :pypi:`pytest-responses`                                 py.test integration for responses                                                                                                                                                                                                                                                                                                                                                       Oct 11, 2022    N/A                    pytest (>=2.5)\n   :pypi:`pytest-rest-api`                                                                                                                                                                                                                                                                                                                                                                                                                          Aug 08, 2022    N/A                    pytest (>=7.1.2,<8.0.0)\n   :pypi:`pytest-restrict`                                  Pytest plugin to restrict the test types allowed                                                                                                                                                                                                                                                                                                                                        Feb 09, 2026    5 - Production/Stable  pytest\n   :pypi:`pytest-resttest`                                  A REST API testing framework for Python, as plugin for pytest. Uses simple and readable YAML files for specifying test cases.                                                                                                                                                                                                                                                           Jan 01, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-result-log`                                A pytest plugin that records the start, end, and result information of each use case in a log file                                                                                                                                                                                                                                                                                      Jan 10, 2024    N/A                    pytest>=7.2.0\n   :pypi:`pytest-result-notify`                             Default template for PDM package                                                                                                                                                                                                                                                                                                                                                        Apr 27, 2025    N/A                    pytest>=8.3.5\n   :pypi:`pytest-results`                                   Easily spot regressions in your tests.                                                                                                                                                                                                                                                                                                                                                  Oct 08, 2025    4 - Beta               pytest\n   :pypi:`pytest-result-sender`                                                                                                                                                                                                                                                                                                                                                                                                                     Apr 20, 2023    N/A                    pytest>=7.3.1\n   :pypi:`pytest-result-sender-fanrenbufan`                 Default template for PDM package                                                                                                                                                                                                                                                                                                                                                        Mar 12, 2026    N/A                    pytest>=8.4.2\n   :pypi:`pytest-result-sender-jms`                         Default template for PDM package                                                                                                                                                                                                                                                                                                                                                        May 22, 2025    N/A                    pytest>=8.3.5\n   :pypi:`pytest-result-sender-lj`                          Default template for PDM package                                                                                                                                                                                                                                                                                                                                                        Dec 17, 2024    N/A                    pytest>=8.3.4\n   :pypi:`pytest-result-sender-lyt`                         Default template for PDM package                                                                                                                                                                                                                                                                                                                                                        Mar 14, 2025    N/A                    pytest>=8.3.5\n   :pypi:`pytest-result-sender-misszhang`                   Default template for PDM package                                                                                                                                                                                                                                                                                                                                                        Mar 21, 2025    N/A                    pytest>=8.3.5\n   :pypi:`pytest-result-sender-r`                           Default template for PDM package                                                                                                                                                                                                                                                                                                                                                        Dec 26, 2025    N/A                    pytest>=8.4.2\n   :pypi:`pytest-resume`                                    A Pytest plugin to resuming from the last run test                                                                                                                                                                                                                                                                                                                                      Apr 22, 2023    4 - Beta               pytest (>=7.0)\n   :pypi:`pytest-rethinkdb`                                 A RethinkDB plugin for pytest.                                                                                                                                                                                                                                                                                                                                                          Jul 24, 2016    4 - Beta               N/A\n   :pypi:`pytest-retry`                                     Adds the ability to retry flaky tests in CI environments                                                                                                                                                                                                                                                                                                                                Jan 19, 2025    N/A                    pytest>=7.0.0\n   :pypi:`pytest-retry-class`                               A pytest plugin to rerun entire class on failure                                                                                                                                                                                                                                                                                                                                        Nov 24, 2024    N/A                    pytest>=5.3\n   :pypi:`pytest-reusable-testcases`                                                                                                                                                                                                                                                                                                                                                                                                                Apr 28, 2023    N/A                    N/A\n   :pypi:`pytest-revealtype-injector`                       Pytest plugin for replacing reveal_type() calls inside test functions with static and runtime type checking result comparison, for confirming type annotation validity.                                                                                                                                                                                                                 Feb 03, 2026    4 - Beta               pytest>=7.0\n   :pypi:`pytest-reverse`                                   Pytest plugin to reverse test order.                                                                                                                                                                                                                                                                                                                                                    Sep 09, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-review`                                    A pytest plugin that reviews the quality of your tests                                                                                                                                                                                                                                                                                                                                  Mar 12, 2026    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-rich`                                      Leverage rich for richer test session output                                                                                                                                                                                                                                                                                                                                            Dec 12, 2024    4 - Beta               pytest>=7.0\n   :pypi:`pytest-richer`                                    Pytest plugin providing a Rich based reporter.                                                                                                                                                                                                                                                                                                                                          Oct 27, 2023    3 - Alpha              pytest\n   :pypi:`pytest-rich-reporter`                             A pytest plugin using Rich for beautiful test result formatting.                                                                                                                                                                                                                                                                                                                        Feb 17, 2022    1 - Planning           pytest (>=5.0.0)\n   :pypi:`pytest-richtrace`                                 A pytest plugin that displays the names and information of the pytest hook functions as they are executed.                                                                                                                                                                                                                                                                              Jun 20, 2023    N/A                    N/A\n   :pypi:`pytest-ringo`                                     pytest plugin to test webapplications using the Ringo webframework                                                                                                                                                                                                                                                                                                                      Sep 27, 2017    3 - Alpha              N/A\n   :pypi:`pytest-rmsis`                                     Sycronise pytest results to Jira RMsis                                                                                                                                                                                                                                                                                                                                                  Aug 10, 2022    N/A                    pytest (>=5.3.5)\n   :pypi:`pytest-rmysql`                                    This is a plugin which is able to connet MySQL easyly.                                                                                                                                                                                                                                                                                                                                  Aug 17, 2025    N/A                    pytest>=8.4.1\n   :pypi:`pytest-rng`                                       Fixtures for seeding tests and making randomness reproducible                                                                                                                                                                                                                                                                                                                           Aug 08, 2019    5 - Production/Stable  pytest\n   :pypi:`pytest-roast`                                     pytest plugin for ROAST configuration override and fixtures                                                                                                                                                                                                                                                                                                                             Nov 09, 2022    5 - Production/Stable  pytest\n   :pypi:`pytest_robotframework`                            a pytest plugin that can run both python and robotframework tests while generating robot reports for them                                                                                                                                                                                                                                                                               Dec 22, 2025    N/A                    pytest<10,>=7\n   :pypi:`pytest-rocketchat`                                Pytest to Rocket.Chat reporting plugin                                                                                                                                                                                                                                                                                                                                                  Apr 18, 2021    5 - Production/Stable  N/A\n   :pypi:`pytest-rotest`                                    Pytest integration with rotest                                                                                                                                                                                                                                                                                                                                                          Sep 08, 2019    N/A                    pytest (>=3.5.0)\n   :pypi:`pytest-routes`                                    Property-based smoke testing for ASGI application routes                                                                                                                                                                                                                                                                                                                                Dec 01, 2025    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-rpc`                                       Extend py.test for RPC OpenStack testing.                                                                                                                                                                                                                                                                                                                                               Feb 22, 2019    4 - Beta               pytest (~=3.6)\n   :pypi:`pytest-r-snapshot`                                A pytest plugin for snapshot testing against R code outputs                                                                                                                                                                                                                                                                                                                             Jan 02, 2026    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-rst`                                       Test code from RST documents with pytest                                                                                                                                                                                                                                                                                                                                                Feb 22, 2026    N/A                    N/A\n   :pypi:`pytest-rt`                                        pytest data collector plugin for Testgr                                                                                                                                                                                                                                                                                                                                                 May 05, 2022    N/A                    N/A\n   :pypi:`pytest-rts`                                       Coverage-based regression test selection (RTS) plugin for pytest                                                                                                                                                                                                                                                                                                                        May 17, 2021    N/A                    pytest\n   :pypi:`pytest-ruff`                                      pytest plugin to check ruff requirements.                                                                                                                                                                                                                                                                                                                                               Jun 19, 2025    4 - Beta               pytest>=5\n   :pypi:`pytest-run-changed`                               Pytest plugin that runs changed tests only                                                                                                                                                                                                                                                                                                                                              Apr 02, 2021    3 - Alpha              pytest\n   :pypi:`pytest-runfailed`                                 implement a --failed option for pytest                                                                                                                                                                                                                                                                                                                                                  Mar 24, 2016    N/A                    N/A\n   :pypi:`pytest-run-parallel`                              A simple pytest plugin to run tests concurrently                                                                                                                                                                                                                                                                                                                                        Jan 14, 2026    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-run-subprocess`                            Pytest Plugin for running and testing subprocesses.                                                                                                                                                                                                                                                                                                                                     Nov 12, 2022    5 - Production/Stable  pytest\n   :pypi:`pytest-runtime-types`                             Checks type annotations on runtime while running tests.                                                                                                                                                                                                                                                                                                                                 Feb 09, 2023    N/A                    pytest\n   :pypi:`pytest-runtime-xfail`                             Call runtime_xfail() to mark running test as xfail.                                                                                                                                                                                                                                                                                                                                     Oct 10, 2025    5 - Production/Stable  pytest>=5.0.0\n   :pypi:`pytest-runtime-yoyo`                              run case mark timeout                                                                                                                                                                                                                                                                                                                                                                   Jun 12, 2023    N/A                    pytest (>=7.2.0)\n   :pypi:`pytest-saccharin`                                 pytest-saccharin is a updated fork of pytest-sugar, a plugin for pytest that changes the default look and feel of pytest (e.g. progressbar, show tests that fail instantly).                                                                                                                                                                                                            Oct 31, 2022    3 - Alpha              N/A\n   :pypi:`pytest-salt`                                      Pytest Salt Plugin                                                                                                                                                                                                                                                                                                                                                                      Jan 27, 2020    4 - Beta               N/A\n   :pypi:`pytest-salt-containers`                           A Pytest plugin that builds and creates docker containers                                                                                                                                                                                                                                                                                                                               Nov 09, 2016    4 - Beta               N/A\n   :pypi:`pytest-salt-factories`                            Pytest Salt Plugin                                                                                                                                                                                                                                                                                                                                                                      Jul 08, 2025    5 - Production/Stable  pytest>=7.4.0\n   :pypi:`pytest-salt-from-filenames`                       Simple PyTest Plugin For Salt's Test Suite Specifically                                                                                                                                                                                                                                                                                                                                 Jan 29, 2019    4 - Beta               pytest (>=4.1)\n   :pypi:`pytest-salt-runtests-bridge`                      Simple PyTest Plugin For Salt's Test Suite Specifically                                                                                                                                                                                                                                                                                                                                 Dec 05, 2019    4 - Beta               pytest (>=4.1)\n   :pypi:`pytest-sample-argvalues`                          A utility function to help choose a random sample from your argvalues in pytest.                                                                                                                                                                                                                                                                                                        May 07, 2024    N/A                    pytest\n   :pypi:`pytest-sanic`                                     a pytest plugin for Sanic                                                                                                                                                                                                                                                                                                                                                               Oct 25, 2021    N/A                    pytest (>=5.2)\n   :pypi:`pytest-sanitizer`                                 A pytest plugin to sanitize output for LLMs (personal tool, no warranty or liability)                                                                                                                                                                                                                                                                                                   Mar 16, 2025    3 - Alpha              pytest>=6.0.0\n   :pypi:`pytest-sanity`                                                                                                                                                                                                                                                                                                                                                                                                                            Dec 07, 2020    N/A                    N/A\n   :pypi:`pytest-sa-pg`                                                                                                                                                                                                                                                                                                                                                                                                                             May 14, 2019    N/A                    N/A\n   :pypi:`pytest_sauce`                                     pytest_sauce provides sane and helpful methods worked    out in clearcode to run py.test tests with selenium/saucelabs                                                                                                                                                                                                                                                                  Jul 14, 2014    3 - Alpha              N/A\n   :pypi:`pytest-sbase`                                     A complete web automation framework for end-to-end testing.                                                                                                                                                                                                                                                                                                                             Mar 13, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-scenario`                                  pytest plugin for test scenarios                                                                                                                                                                                                                                                                                                                                                        Feb 06, 2017    3 - Alpha              N/A\n   :pypi:`pytest-scenario-files`                            A pytest plugin that generates unit test scenarios from data files.                                                                                                                                                                                                                                                                                                                     Feb 17, 2026    5 - Production/Stable  pytest<10,>=7.4\n   :pypi:`pytest-scenarios`                                 Add your description here                                                                                                                                                                                                                                                                                                                                                               Jan 03, 2026    N/A                    N/A\n   :pypi:`pytest-schedule`                                  Automate and customize test scheduling effortlessly on local machines.                                                                                                                                                                                                                                                                                                                  Oct 31, 2024    N/A                    N/A\n   :pypi:`pytest-schema`                                    👍 Validate return values against a schema-like object in testing                                                                                                                                                                                                                                                                                                                       Feb 16, 2024    5 - Production/Stable  pytest >=3.5.0\n   :pypi:`pytest-scim2-server`                              SCIM2 server fixture for Pytest                                                                                                                                                                                                                                                                                                                                                         Nov 14, 2025    4 - Beta               pytest>=8.3.4\n   :pypi:`pytest-screenshot-on-failure`                     Saves a screenshot when a test case from a pytest execution fails                                                                                                                                                                                                                                                                                                                       Jul 21, 2023    4 - Beta               N/A\n   :pypi:`pytest-scrutinize`                                Scrutinize your pytest test suites for slow fixtures, tests and more.                                                                                                                                                                                                                                                                                                                   Aug 19, 2024    4 - Beta               pytest>=6\n   :pypi:`pytest-securestore`                               An encrypted password store for use within pytest cases                                                                                                                                                                                                                                                                                                                                 Nov 08, 2021    4 - Beta               N/A\n   :pypi:`pytest-select`                                    A pytest plugin which allows to (de-)select tests from a file.                                                                                                                                                                                                                                                                                                                          Jan 18, 2019    3 - Alpha              pytest (>=3.0)\n   :pypi:`pytest-selenium`                                  pytest plugin for Selenium                                                                                                                                                                                                                                                                                                                                                              Feb 01, 2024    5 - Production/Stable  pytest>=6.0.0\n   :pypi:`pytest-selenium-auto`                             pytest plugin to automatically capture screenshots upon selenium webdriver events                                                                                                                                                                                                                                                                                                       Nov 07, 2023    N/A                    pytest >= 7.0.0\n   :pypi:`pytest-seleniumbase`                              A complete web automation framework for end-to-end testing.                                                                                                                                                                                                                                                                                                                             Mar 13, 2026    5 - Production/Stable  N/A\n   :pypi:`pytest-selenium-driver`                           A zero-boilerplate Selenium WebDriver fixture for pytest                                                                                                                                                                                                                                                                                                                                Mar 07, 2026    4 - Beta               pytest>=7.0\n   :pypi:`pytest-selenium-enhancer`                         pytest plugin for Selenium                                                                                                                                                                                                                                                                                                                                                              Apr 29, 2022    5 - Production/Stable  N/A\n   :pypi:`pytest-selenium-pdiff`                            A pytest package implementing perceptualdiff for Selenium tests.                                                                                                                                                                                                                                                                                                                        Apr 06, 2017    2 - Pre-Alpha          N/A\n   :pypi:`pytest-selfie`                                    A pytest plugin for selfie snapshot testing.                                                                                                                                                                                                                                                                                                                                            Dec 16, 2024    N/A                    pytest>=8.0.0\n   :pypi:`pytest-semantic`                                  A pytest plugin for testing LLM outputs using semantic similarity matching                                                                                                                                                                                                                                                                                                              Nov 11, 2025    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-semantic-assert`                           Pytest plugin for semantic LLM output assertions using embeddings. Test meaning, not strings.                                                                                                                                                                                                                                                                                           Jan 09, 2026    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-semantic-llm`                              Semantic assertions for pytest using LLMs                                                                                                                                                                                                                                                                                                                                               Mar 10, 2026    N/A                    pytest>=7.0.0\n   :pypi:`pytest-send-email`                                Send pytest execution result email                                                                                                                                                                                                                                                                                                                                                      Sep 02, 2024    N/A                    pytest\n   :pypi:`pytest-sentry`                                    A pytest plugin to send testrun information to Sentry.io                                                                                                                                                                                                                                                                                                                                Jul 01, 2025    N/A                    pytest\n   :pypi:`pytest-sequence-markers`                          Pytest plugin for sequencing markers for execution of tests                                                                                                                                                                                                                                                                                                                             May 23, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-server`                                    test server exec cmd                                                                                                                                                                                                                                                                                                                                                                    Sep 09, 2024    N/A                    N/A\n   :pypi:`pytest-server-fixtures`                           Extensible server fixtures for py.test                                                                                                                                                                                                                                                                                                                                                  Nov 29, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-serverless`                                Automatically mocks resources from serverless.yml in pytest using moto.                                                                                                                                                                                                                                                                                                                 May 09, 2022    4 - Beta               N/A\n   :pypi:`pytest-servers`                                   pytest servers                                                                                                                                                                                                                                                                                                                                                                          Dec 21, 2025    3 - Alpha              pytest>=6.2\n   :pypi:`pytest-service`                                                                                                                                                                                                                                                                                                                                                                                                                           Aug 06, 2024    5 - Production/Stable  pytest>=6.0.0\n   :pypi:`pytest-services`                                  Services plugin for pytest testing framework                                                                                                                                                                                                                                                                                                                                            Jul 16, 2025    6 - Mature             pytest\n   :pypi:`pytest-session2file`                              pytest-session2file (aka: pytest-session_to_file for v0.1.0 - v0.1.2) is a py.test plugin for capturing and saving to file the stdout of py.test.                                                                                                                                                                                                                                       Jan 26, 2021    3 - Alpha              pytest\n   :pypi:`pytest-session-fixture-globalize`                 py.test plugin to make session fixtures behave as if written in conftest, even if it is written in some modules                                                                                                                                                                                                                                                                         May 15, 2018    4 - Beta               N/A\n   :pypi:`pytest-session_to_file`                           pytest-session_to_file is a py.test plugin for capturing and saving to file the stdout of py.test.                                                                                                                                                                                                                                                                                      Oct 01, 2015    3 - Alpha              N/A\n   :pypi:`pytest-setupinfo`                                 Displaying setup info during pytest command run                                                                                                                                                                                                                                                                                                                                         Jan 23, 2023    N/A                    N/A\n   :pypi:`pytest-sftpserver`                                py.test plugin to locally test sftp server connections.                                                                                                                                                                                                                                                                                                                                 Sep 16, 2019    4 - Beta               N/A\n   :pypi:`pytest-shard`                                                                                                                                                                                                                                                                                                                                                                                                                             Dec 11, 2020    4 - Beta               pytest\n   :pypi:`pytest-shard-fork`                                Shard tests to support parallelism across multiple machines                                                                                                                                                                                                                                                                                                                             Jun 13, 2025    4 - Beta               pytest\n   :pypi:`pytest-shared-session-scope`                      Pytest session-scoped fixture that works with xdist                                                                                                                                                                                                                                                                                                                                     Oct 31, 2025    N/A                    pytest>=7.0.0\n   :pypi:`pytest-share-hdf`                                 Plugin to save test data in HDF files and retrieve them for comparison                                                                                                                                                                                                                                                                                                                  Sep 21, 2022    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-sharkreport`                               this is pytest report plugin.                                                                                                                                                                                                                                                                                                                                                           Jul 11, 2022    N/A                    pytest (>=3.5)\n   :pypi:`pytest-shell`                                     A pytest plugin to help with testing shell scripts / black box commands                                                                                                                                                                                                                                                                                                                 Mar 27, 2022    N/A                    N/A\n   :pypi:`pytest-shell-utilities`                           Pytest plugin to simplify running shell commands against the system                                                                                                                                                                                                                                                                                                                     Oct 22, 2024    5 - Production/Stable  pytest>=7.4.0\n   :pypi:`pytest-sheraf`                                    Versatile ZODB abstraction layer - pytest fixtures                                                                                                                                                                                                                                                                                                                                      Feb 11, 2020    N/A                    pytest\n   :pypi:`pytest-sherlock`                                  pytest plugin help to find coupled tests                                                                                                                                                                                                                                                                                                                                                Aug 14, 2023    5 - Production/Stable  pytest >=3.5.1\n   :pypi:`pytest-shortcuts`                                 Expand command-line shortcuts listed in pytest configuration                                                                                                                                                                                                                                                                                                                            Oct 29, 2020    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-shutil`                                    A goodie-bag of unix shell and environment tools for py.test                                                                                                                                                                                                                                                                                                                            Nov 29, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-sigil`                                     Proper fixture resource cleanup by handling signals                                                                                                                                                                                                                                                                                                                                     Oct 21, 2025    N/A                    pytest<9.0.0,>=7.0.0\n   :pypi:`pytest-simbind`                                   Pytest plugin to operate with objects generated by Simbind tool.                                                                                                                                                                                                                                                                                                                        Mar 28, 2024    N/A                    pytest>=7.0.0\n   :pypi:`pytest-simplehttpserver`                          Simple pytest fixture to spin up an HTTP server                                                                                                                                                                                                                                                                                                                                         Jun 24, 2021    4 - Beta               N/A\n   :pypi:`pytest-simple-plugin`                             Simple pytest plugin                                                                                                                                                                                                                                                                                                                                                                    Nov 27, 2019    N/A                    N/A\n   :pypi:`pytest-simple-settings`                           simple-settings plugin for pytest                                                                                                                                                                                                                                                                                                                                                       Nov 17, 2020    4 - Beta               pytest\n   :pypi:`pytest-simplified`                                A PyTest plugin to simplify testing classes.                                                                                                                                                                                                                                                                                                                                            Jan 19, 2026    4 - Beta               pytest<9.0.0,>=8.3.5\n   :pypi:`pytest-single-file-logging`                       Allow for multiple processes to log to a single file                                                                                                                                                                                                                                                                                                                                    May 05, 2016    4 - Beta               pytest (>=2.8.1)\n   :pypi:`pytest-skill-engineering`                         The testing framework for skill engineering. Test tool descriptions, prompt templates, agent skills, and custom agents with real LLMs. AI analyzes results and tells you what to fix.                                                                                                                                                                                                   Mar 01, 2026    3 - Alpha              pytest>=9.0\n   :pypi:`pytest-skip`                                      A pytest plugin which allows to (de-)select or skip tests from a file.                                                                                                                                                                                                                                                                                                                  Sep 12, 2025    3 - Alpha              pytest\n   :pypi:`pytest-skip-markers`                              Pytest Salt Plugin                                                                                                                                                                                                                                                                                                                                                                      Aug 09, 2024    5 - Production/Stable  pytest>=7.1.0\n   :pypi:`pytest-skipper`                                   A plugin that selects only tests with changes in execution path                                                                                                                                                                                                                                                                                                                         Mar 26, 2017    3 - Alpha              pytest (>=3.0.6)\n   :pypi:`pytest-skippy`                                    Automatically skip tests that don't need to run!                                                                                                                                                                                                                                                                                                                                        Jan 27, 2018    3 - Alpha              pytest (>=2.3.4)\n   :pypi:`pytest-skip-slow`                                 A pytest plugin to skip \\`@pytest.mark.slow\\` tests by default.                                                                                                                                                                                                                                                                                                                         Feb 09, 2023    N/A                    pytest>=6.2.0\n   :pypi:`pytest-skipuntil`                                 A simple pytest plugin to skip flapping test with deadline                                                                                                                                                                                                                                                                                                                              Nov 25, 2023    4 - Beta               pytest >=3.8.0\n   :pypi:`pytest-slack`                                     Pytest to Slack reporting plugin                                                                                                                                                                                                                                                                                                                                                        Dec 15, 2020    5 - Production/Stable  N/A\n   :pypi:`pytest-slow`                                      A pytest plugin to skip \\`@pytest.mark.slow\\` tests by default.                                                                                                                                                                                                                                                                                                                         Sep 28, 2021    N/A                    N/A\n   :pypi:`pytest-slowest-first`                             Sort tests by their last duration, slowest first                                                                                                                                                                                                                                                                                                                                        Dec 11, 2022    4 - Beta               N/A\n   :pypi:`pytest-slow-first`                                Prioritize running the slowest tests first.                                                                                                                                                                                                                                                                                                                                             Jan 30, 2024    4 - Beta               pytest >=3.5.0\n   :pypi:`pytest-slow-last`                                 Run tests in order of execution time (faster tests first)                                                                                                                                                                                                                                                                                                                               Mar 16, 2025    4 - Beta               pytest>=3.5.0\n   :pypi:`pytest-smartcollect`                              A plugin for collecting tests that touch changed code                                                                                                                                                                                                                                                                                                                                   Oct 04, 2018    N/A                    pytest (>=3.5.0)\n   :pypi:`pytest-smartcov`                                  Smart coverage plugin for pytest.                                                                                                                                                                                                                                                                                                                                                       Sep 30, 2017    3 - Alpha              N/A\n   :pypi:`pytest-smart-debugger-backend`                    Backend server for Pytest Smart Debugger                                                                                                                                                                                                                                                                                                                                                Sep 17, 2025    N/A                    N/A\n   :pypi:`pytest-smart-rerun`                               A Pytest plugin for intelligent retrying of flaky tests.                                                                                                                                                                                                                                                                                                                                Oct 12, 2025    3 - Alpha              N/A\n   :pypi:`pytest-smell`                                     Automated bad smell detection tool for Pytest                                                                                                                                                                                                                                                                                                                                           Jun 26, 2022    N/A                    N/A\n   :pypi:`pytest-smoke`                                     Pytest plugin for smoke testing                                                                                                                                                                                                                                                                                                                                                         Nov 09, 2025    4 - Beta               pytest<10,>=7.0.0\n   :pypi:`pytest-smtp`                                      Send email with pytest execution result                                                                                                                                                                                                                                                                                                                                                 Feb 20, 2021    N/A                    pytest\n   :pypi:`pytest-smtp4dev`                                  Plugin for smtp4dev API                                                                                                                                                                                                                                                                                                                                                                 Jun 27, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-smtpd`                                     An SMTP server for testing built on aiosmtpd                                                                                                                                                                                                                                                                                                                                            May 15, 2023    N/A                    pytest\n   :pypi:`pytest-smtp-test-server`                          pytest plugin for using \\`smtp-test-server\\` as a fixture                                                                                                                                                                                                                                                                                                                               Dec 03, 2023    2 - Pre-Alpha          pytest (>=7.4.3,<8.0.0)\n   :pypi:`pytest-snail`                                     Plugin for adding a marker to slow running tests. 🐌                                                                                                                                                                                                                                                                                                                                    Nov 04, 2019    3 - Alpha              pytest (>=5.0.1)\n   :pypi:`pytest-snap`                                      A text-based snapshot testing library implemented as a pytest plugin                                                                                                                                                                                                                                                                                                                    Aug 25, 2025    N/A                    pytest>=8.0.0\n   :pypi:`pytest-snapcheck`                                 Minimal deterministic test-run snapshot capture for pytest.                                                                                                                                                                                                                                                                                                                             Sep 07, 2025    N/A                    pytest>=8.0\n   :pypi:`pytest-snapci`                                    py.test plugin for Snap-CI                                                                                                                                                                                                                                                                                                                                                              Nov 12, 2015    N/A                    N/A\n   :pypi:`pytest-snapmock`                                  Snapshots for your mocks.                                                                                                                                                                                                                                                                                                                                                               Nov 15, 2024    N/A                    N/A\n   :pypi:`pytest-snapshot`                                  A plugin for snapshot testing with pytest.                                                                                                                                                                                                                                                                                                                                              Apr 23, 2022    4 - Beta               pytest (>=3.0.0)\n   :pypi:`pytest-snapshot-with-message-generator`           A plugin for snapshot testing with pytest.                                                                                                                                                                                                                                                                                                                                              Jul 25, 2023    4 - Beta               pytest (>=3.0.0)\n   :pypi:`pytest-snmpserver`                                                                                                                                                                                                                                                                                                                                                                                                                        May 12, 2021    N/A                    N/A\n   :pypi:`pytest-snob`                                      A pytest plugin that only selects meaningful python tests to run.                                                                                                                                                                                                                                                                                                                       Jan 12, 2025    N/A                    pytest\n   :pypi:`pytest-snowflake-bdd`                             Setup test data and run tests on snowflake in BDD style!                                                                                                                                                                                                                                                                                                                                Jan 05, 2022    4 - Beta               pytest (>=6.2.0)\n   :pypi:`pytest-socket`                                    Pytest Plugin to disable socket calls during tests                                                                                                                                                                                                                                                                                                                                      Jan 28, 2024    4 - Beta               pytest (>=6.2.5)\n   :pypi:`pytest-sofaepione`                                Test the installation of SOFA and the SofaEpione plugin.                                                                                                                                                                                                                                                                                                                                Aug 17, 2022    N/A                    N/A\n   :pypi:`pytest-soft-assert`                               Pytest plugin for soft assertions.                                                                                                                                                                                                                                                                                                                                                      Dec 07, 2025    N/A                    pytest>=8.4.0\n   :pypi:`pytest-soft-assertions`                                                                                                                                                                                                                                                                                                                                                                                                                   May 05, 2020    3 - Alpha              pytest\n   :pypi:`pytest-solidity`                                  A PyTest library plugin for Solidity language.                                                                                                                                                                                                                                                                                                                                          Jan 15, 2022    1 - Planning           pytest (<7,>=6.0.1) ; extra == 'tests'\n   :pypi:`pytest-solr`                                      Solr process and client fixtures for py.test.                                                                                                                                                                                                                                                                                                                                           May 11, 2020    3 - Alpha              pytest (>=3.0.0)\n   :pypi:`pytest-sort`                                      Tools for sorting test cases                                                                                                                                                                                                                                                                                                                                                            Mar 22, 2025    N/A                    pytest>=7.4.0\n   :pypi:`pytest-sorter`                                    A simple plugin to first execute tests that historically failed more                                                                                                                                                                                                                                                                                                                    Apr 20, 2021    4 - Beta               pytest (>=3.1.1)\n   :pypi:`pytest-sosu`                                      Unofficial PyTest plugin for Sauce Labs                                                                                                                                                                                                                                                                                                                                                 Aug 04, 2023    2 - Pre-Alpha          pytest\n   :pypi:`pytest-sourceorder`                               Test-ordering plugin for pytest                                                                                                                                                                                                                                                                                                                                                         Sep 01, 2021    4 - Beta               pytest\n   :pypi:`pytest-spark`                                     pytest plugin to run the tests with support of pyspark.                                                                                                                                                                                                                                                                                                                                 May 21, 2025    4 - Beta               pytest\n   :pypi:`pytest-spawner`                                   py.test plugin to spawn process and communicate with them.                                                                                                                                                                                                                                                                                                                              Jul 31, 2015    4 - Beta               N/A\n   :pypi:`pytest-spec`                                      Library pytest-spec is a pytest plugin to display test execution output like a SPECIFICATION.                                                                                                                                                                                                                                                                                           Feb 22, 2026    N/A                    pytest; extra == \"test\"\n   :pypi:`pytest-spec2md`                                   Library pytest-spec2md is a pytest plugin to create a markdown specification while running pytest.                                                                                                                                                                                                                                                                                      Apr 10, 2024    N/A                    pytest>7.0\n   :pypi:`pytest-speed`                                     Modern benchmarking library for python with pytest integration.                                                                                                                                                                                                                                                                                                                         Jan 22, 2023    3 - Alpha              pytest>=7\n   :pypi:`pytest-sphinx`                                    Doctest plugin for pytest with support for Sphinx-specific doctest-directives                                                                                                                                                                                                                                                                                                           Jan 21, 2026    4 - Beta               pytest>=8.1.1\n   :pypi:`pytest-spiratest`                                 Exports unit tests as test runs in Spira (SpiraTest/Team/Plan)                                                                                                                                                                                                                                                                                                                          Feb 09, 2026    N/A                    pytest>=3.0.0\n   :pypi:`pytest-splinter`                                  Splinter plugin for pytest testing framework                                                                                                                                                                                                                                                                                                                                            Sep 09, 2022    6 - Mature             pytest (>=3.0.0)\n   :pypi:`pytest-splinter4`                                 Pytest plugin for the splinter automation library                                                                                                                                                                                                                                                                                                                                       Feb 01, 2024    6 - Mature             pytest >=8.0.0\n   :pypi:`pytest-split`                                     Pytest plugin which splits the test suite to equally sized sub suites based on test execution time.                                                                                                                                                                                                                                                                                     Feb 03, 2026    4 - Beta               pytest<10,>=5\n   :pypi:`pytest-split-ct`                                  Pytest plugin which splits the test suite to equally sized sub suites based on test execution time.                                                                                                                                                                                                                                                                                     Jan 23, 2026    4 - Beta               pytest<10,>=5\n   :pypi:`pytest-split-ext`                                 Pytest plugin which splits the test suite to equally sized sub suites based on test execution time.                                                                                                                                                                                                                                                                                     Sep 23, 2023    4 - Beta               pytest (>=5,<8)\n   :pypi:`pytest-splitio`                                   Split.io SDK integration for e2e tests                                                                                                                                                                                                                                                                                                                                                  Sep 22, 2020    N/A                    pytest (<7,>=5.0)\n   :pypi:`pytest-split-ng`                                  Pytest plugin which splits the test suite to equally sized sub suites based on test execution time.                                                                                                                                                                                                                                                                                     Jan 05, 2026    4 - Beta               pytest<10,>=5\n   :pypi:`pytest-split-tests`                               A Pytest plugin for running a subset of your tests by splitting them in to equally sized groups. Forked from Mark Adams' original project pytest-test-groups.                                                                                                                                                                                                                           Jul 30, 2021    5 - Production/Stable  pytest (>=2.5)\n   :pypi:`pytest-split-tests-tresorit`                                                                                                                                                                                                                                                                                                                                                                                                              Feb 22, 2021    1 - Planning           N/A\n   :pypi:`pytest-split-v2`                                  Pytest plugin which splits the test suite to equally sized sub suites based on test execution time.                                                                                                                                                                                                                                                                                     Jan 14, 2026    4 - Beta               pytest<10,>=5\n   :pypi:`pytest-splunk-addon`                              A Dynamic test tool for Splunk Apps and Add-ons                                                                                                                                                                                                                                                                                                                                         Aug 19, 2025    N/A                    pytest<8,>5.4.0\n   :pypi:`pytest-splunk-addon-ui-smartx`                    Library to support testing Splunk Add-on UX                                                                                                                                                                                                                                                                                                                                             Nov 24, 2025    N/A                    N/A\n   :pypi:`pytest-splunk-env`                                pytest fixtures for interaction with Splunk Enterprise and Splunk Cloud                                                                                                                                                                                                                                                                                                                 Oct 22, 2020    N/A                    pytest (>=6.1.1,<7.0.0)\n   :pypi:`pytest-sqitch`                                    sqitch for pytest                                                                                                                                                                                                                                                                                                                                                                       Apr 06, 2020    4 - Beta               N/A\n   :pypi:`pytest-sqlalchemy`                                pytest plugin with sqlalchemy related fixtures                                                                                                                                                                                                                                                                                                                                          Apr 19, 2025    3 - Alpha              pytest>=8.0\n   :pypi:`pytest-sqlalchemy-mock`                           pytest sqlalchemy plugin for mock                                                                                                                                                                                                                                                                                                                                                       Aug 10, 2024    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-sqlalchemy-session`                        A pytest plugin for preserving test isolation that use SQLAlchemy.                                                                                                                                                                                                                                                                                                                      May 19, 2023    4 - Beta               pytest (>=7.0)\n   :pypi:`pytest-sql-bigquery`                              Yet another SQL-testing framework for BigQuery provided by pytest plugin                                                                                                                                                                                                                                                                                                                Dec 19, 2019    N/A                    pytest\n   :pypi:`pytest-sqlfluff`                                  A pytest plugin to use sqlfluff to enable format checking of sql files.                                                                                                                                                                                                                                                                                                                 Dec 21, 2022    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-sqlguard`                                  Pytest fixture to record and check SQL Queries made by SQLAlchemy                                                                                                                                                                                                                                                                                                                       Jun 06, 2025    4 - Beta               pytest>=7\n   :pypi:`pytest-squadcast`                                 Pytest report plugin for Squadcast                                                                                                                                                                                                                                                                                                                                                      Feb 22, 2022    5 - Production/Stable  pytest\n   :pypi:`pytest-srcpaths`                                  Add paths to sys.path                                                                                                                                                                                                                                                                                                                                                                   Oct 15, 2021    N/A                    pytest>=6.2.0\n   :pypi:`pytest-ssh`                                       pytest plugin for ssh command run                                                                                                                                                                                                                                                                                                                                                       May 27, 2019    N/A                    pytest\n   :pypi:`pytest-start-from`                                Start pytest run from a given point                                                                                                                                                                                                                                                                                                                                                     Apr 11, 2016    N/A                    N/A\n   :pypi:`pytest-static`                                    pytest-static                                                                                                                                                                                                                                                                                                                                                                           May 25, 2025    3 - Alpha              pytest<8.0.0,>=7.4.3\n   :pypi:`pytest-stats`                                     Collects tests metadata for future analysis, easy to extend for any data store                                                                                                                                                                                                                                                                                                          Jul 18, 2024    N/A                    pytest>=8.0.0\n   :pypi:`pytest-statsd`                                    pytest plugin for reporting to graphite                                                                                                                                                                                                                                                                                                                                                 Nov 30, 2018    5 - Production/Stable  pytest (>=3.0.0)\n   :pypi:`pytest-status`                                    Add status mark for tests                                                                                                                                                                                                                                                                                                                                                               Aug 22, 2024    N/A                    pytest\n   :pypi:`pytest-stderr-db`                                 Add your description here                                                                                                                                                                                                                                                                                                                                                               Sep 14, 2025    N/A                    N/A\n   :pypi:`pytest-stdout-db`                                 Add your description here                                                                                                                                                                                                                                                                                                                                                               Sep 14, 2025    N/A                    N/A\n   :pypi:`pytest-stepfunctions`                             A small description                                                                                                                                                                                                                                                                                                                                                                     May 08, 2021    4 - Beta               pytest\n   :pypi:`pytest-step-logger`                               Live Rich-rendered step trees in pytest terminal output                                                                                                                                                                                                                                                                                                                                 Mar 11, 2026    3 - Alpha              pytest>=7.0\n   :pypi:`pytest-steps`                                     Create step-wise / incremental tests in pytest.                                                                                                                                                                                                                                                                                                                                         Sep 23, 2021    5 - Production/Stable  N/A\n   :pypi:`pytest-stepthrough`                               Pause and wait for Enter after each test with --step                                                                                                                                                                                                                                                                                                                                    Aug 14, 2025    N/A                    N/A\n   :pypi:`pytest-stepwise`                                  Run a test suite one failing test at a time.                                                                                                                                                                                                                                                                                                                                            Dec 01, 2015    4 - Beta               N/A\n   :pypi:`pytest-stf`                                       pytest plugin for openSTF                                                                                                                                                                                                                                                                                                                                                               Sep 23, 2025    N/A                    pytest>=5.0\n   :pypi:`pytest-stochastic`                                A pytest plugin for principled stochastic unit testing using concentration inequalities                                                                                                                                                                                                                                                                                                 Feb 24, 2026    4 - Beta               pytest>=7.0\n   :pypi:`pytest-stochastics`                               pytest plugin that allows selectively running tests several times and accepting \\*some\\* failures.                                                                                                                                                                                                                                                                                      Dec 01, 2024    N/A                    pytest<9.0.0,>=8.0.0\n   :pypi:`pytest-stoq`                                      A plugin to pytest stoq                                                                                                                                                                                                                                                                                                                                                                 Feb 09, 2021    4 - Beta               N/A\n   :pypi:`pytest-storage`                                   Pytest plugin to store test artifacts                                                                                                                                                                                                                                                                                                                                                   Sep 12, 2025    3 - Alpha              pytest>=8.4.2\n   :pypi:`pytest-store`                                     Pytest plugin to store values from test runs                                                                                                                                                                                                                                                                                                                                            Jul 30, 2025    3 - Alpha              pytest>=7.0.0\n   :pypi:`pytest-streaming`                                 Plugin for testing pubsub, pulsar, and kafka systems with pytest locally and in ci/cd                                                                                                                                                                                                                                                                                                   Jan 14, 2026    5 - Production/Stable  pytest>=8.3.5\n   :pypi:`pytest-stress`                                    A Pytest plugin that allows you to loop tests for a user defined amount of time.                                                                                                                                                                                                                                                                                                        Dec 07, 2019    4 - Beta               pytest (>=3.6.0)\n   :pypi:`pytest-structlog`                                 Structured logging assertions                                                                                                                                                                                                                                                                                                                                                           Sep 10, 2025    N/A                    pytest\n   :pypi:`pytest-structmpd`                                 provide structured temporary directory                                                                                                                                                                                                                                                                                                                                                  Oct 17, 2018    N/A                    N/A\n   :pypi:`pytest-stub`                                      Stub packages, modules and attributes.                                                                                                                                                                                                                                                                                                                                                  Apr 28, 2020    5 - Production/Stable  N/A\n   :pypi:`pytest-stubprocess`                               Provide stub implementations for subprocesses in Python tests                                                                                                                                                                                                                                                                                                                           Sep 17, 2018    3 - Alpha              pytest (>=3.5.0)\n   :pypi:`pytest-study`                                     A pytest plugin to organize long run tests (named studies) without interfering the regular tests                                                                                                                                                                                                                                                                                        Sep 26, 2017    3 - Alpha              pytest (>=2.0)\n   :pypi:`pytest-subinterpreter`                            Run pytest in a subinterpreter                                                                                                                                                                                                                                                                                                                                                          Nov 25, 2023    N/A                    pytest>=7.0.0\n   :pypi:`pytest-subket`                                    Pytest Plugin to disable socket calls during tests                                                                                                                                                                                                                                                                                                                                      Jul 31, 2025    4 - Beta               N/A\n   :pypi:`pytest-subprocess`                                A plugin to fake subprocess for pytest                                                                                                                                                                                                                                                                                                                                                  Jan 04, 2025    5 - Production/Stable  pytest>=4.0.0\n   :pypi:`pytest-subtesthack`                               A hack to explicitly set up and tear down fixtures.                                                                                                                                                                                                                                                                                                                                     Jul 16, 2022    N/A                    N/A\n   :pypi:`pytest-subtests`                                  unittest subTest() support and subtests fixture                                                                                                                                                                                                                                                                                                                                         Oct 20, 2025    4 - Beta               pytest>=7.4\n   :pypi:`pytest-subunit`                                   pytest-subunit is a plugin for py.test which outputs testsresult in subunit format.                                                                                                                                                                                                                                                                                                     Sep 17, 2023    N/A                    pytest (>=2.3)\n   :pypi:`pytest-sugar`                                     pytest-sugar is a plugin for pytest that changes the default look and feel of pytest (e.g. progressbar, show tests that fail instantly).                                                                                                                                                                                                                                                Aug 23, 2025    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-suitemanager`                              A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Apr 28, 2023    4 - Beta               N/A\n   :pypi:`pytest-suite-timeout`                             A pytest plugin for ensuring max suite time                                                                                                                                                                                                                                                                                                                                             Jan 26, 2024    N/A                    pytest>=7.0.0\n   :pypi:`pytest-supercov`                                  Pytest plugin for measuring explicit test-file to source-file coverage                                                                                                                                                                                                                                                                                                                  Jul 02, 2023    N/A                    N/A\n   :pypi:`pytest-svn`                                       SVN repository fixture for py.test                                                                                                                                                                                                                                                                                                                                                      Oct 17, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-symbols`                                   pytest-symbols is a pytest plugin that adds support for passing test environment symbols into pytest tests.                                                                                                                                                                                                                                                                             Nov 20, 2017    3 - Alpha              N/A\n   :pypi:`pytest-system-statistics`                         Pytest plugin to track and report system usage statistics                                                                                                                                                                                                                                                                                                                               Feb 16, 2022    5 - Production/Stable  pytest (>=6.0.0)\n   :pypi:`pytest-system-test-plugin`                        Pyst - Pytest System-Test Plugin                                                                                                                                                                                                                                                                                                                                                        Feb 03, 2022    N/A                    N/A\n   :pypi:`pytest_tagging`                                   a pytest plugin to tag tests                                                                                                                                                                                                                                                                                                                                                            Nov 08, 2024    N/A                    pytest>=7.1.3\n   :pypi:`pytest-takeltest`                                 Fixtures for ansible, testinfra and molecule                                                                                                                                                                                                                                                                                                                                            Sep 07, 2024    N/A                    N/A\n   :pypi:`pytest-talisker`                                                                                                                                                                                                                                                                                                                                                                                                                          Nov 28, 2021    N/A                    N/A\n   :pypi:`pytest-tally`                                     A Pytest plugin to generate realtime summary stats, and display them in-console using a text-based dashboard.                                                                                                                                                                                                                                                                           May 22, 2023    4 - Beta               pytest (>=6.2.5)\n   :pypi:`pytest-tap`                                       Test Anything Protocol (TAP) reporting plugin for pytest                                                                                                                                                                                                                                                                                                                                Jan 30, 2025    5 - Production/Stable  pytest>=3.0\n   :pypi:`pytest-tape`                                      easy assertion with expected results saved to yaml files                                                                                                                                                                                                                                                                                                                                Mar 17, 2021    4 - Beta               N/A\n   :pypi:`pytest-target`                                    Pytest plugin for remote target orchestration.                                                                                                                                                                                                                                                                                                                                          Jan 21, 2021    3 - Alpha              pytest (>=6.1.2,<7.0.0)\n   :pypi:`pytest-taskgraph`                                 Add your description here                                                                                                                                                                                                                                                                                                                                                               Apr 09, 2025    N/A                    pytest\n   :pypi:`pytest-tblineinfo`                                tblineinfo is a py.test plugin that insert the node id in the final py.test report when --tb=line option is used                                                                                                                                                                                                                                                                        Dec 01, 2015    3 - Alpha              pytest (>=2.0)\n   :pypi:`pytest-tcpclient`                                 A pytest plugin for testing TCP clients                                                                                                                                                                                                                                                                                                                                                 Nov 16, 2022    N/A                    pytest (<8,>=7.1.3)\n   :pypi:`pytest-tdd`                                       run pytest on a python module                                                                                                                                                                                                                                                                                                                                                           Aug 18, 2023    4 - Beta               N/A\n   :pypi:`pytest-teamcity-logblock`                         py.test plugin to introduce block structure in teamcity build log, if output is not captured                                                                                                                                                                                                                                                                                            May 15, 2018    4 - Beta               N/A\n   :pypi:`pytest-teardown`                                                                                                                                                                                                                                                                                                                                                                                                                          Apr 15, 2025    N/A                    pytest<9.0.0,>=7.4.1\n   :pypi:`pytest-telegram`                                  Pytest to Telegram reporting plugin                                                                                                                                                                                                                                                                                                                                                     Apr 25, 2024    5 - Production/Stable  N/A\n   :pypi:`pytest-telegram-notifier`                         Telegram notification plugin for Pytest                                                                                                                                                                                                                                                                                                                                                 Jun 27, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-tempdir`                                   Predictable and repeatable tempdir support.                                                                                                                                                                                                                                                                                                                                             Oct 11, 2019    4 - Beta               pytest (>=2.8.1)\n   :pypi:`pytest-terra-fixt`                                Terraform and Terragrunt fixtures for pytest                                                                                                                                                                                                                                                                                                                                            Sep 15, 2022    N/A                    pytest (==6.2.5)\n   :pypi:`pytest-terraform`                                 A pytest plugin for using terraform fixtures                                                                                                                                                                                                                                                                                                                                            May 21, 2024    N/A                    pytest>=6.0\n   :pypi:`pytest-terraform-fixture`                         generate terraform resources to use with pytest                                                                                                                                                                                                                                                                                                                                         Nov 14, 2018    4 - Beta               N/A\n   :pypi:`pytest-test-analyzer`                             A powerful tool for analyzing pytest test files and generating detailed reports                                                                                                                                                                                                                                                                                                         Jun 14, 2025    4 - Beta               N/A\n   :pypi:`pytest-testbook`                                  A plugin to run tests written in Jupyter notebook                                                                                                                                                                                                                                                                                                                                       Dec 11, 2016    3 - Alpha              N/A\n   :pypi:`pytest-test-categories`                           A pytest plugin to enforce test timing constraints and size distributions.                                                                                                                                                                                                                                                                                                              Mar 04, 2026    5 - Production/Stable  pytest>=8.4.2\n   :pypi:`pytest-testconfig`                                Test configuration plugin for pytest.                                                                                                                                                                                                                                                                                                                                                   Jan 11, 2020    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-testcontainers-compose`                    Pytest plugin for Docker Compose                                                                                                                                                                                                                                                                                                                                                        Feb 11, 2026    N/A                    N/A\n   :pypi:`pytest-testdata`                                  Get and load testdata in pytest projects                                                                                                                                                                                                                                                                                                                                                Aug 30, 2024    N/A                    pytest\n   :pypi:`pytest-testdirectory`                             A py.test plugin providing temporary directories in unit tests.                                                                                                                                                                                                                                                                                                                         May 02, 2023    5 - Production/Stable  pytest\n   :pypi:`pytest-testdox`                                   A testdox format reporter for pytest                                                                                                                                                                                                                                                                                                                                                    Jul 22, 2023    5 - Production/Stable  pytest (>=4.6.0)\n   :pypi:`pytest-test-grouping`                             A Pytest plugin for running a subset of your tests by splitting them in to equally sized groups.                                                                                                                                                                                                                                                                                        Feb 01, 2023    5 - Production/Stable  pytest (>=2.5)\n   :pypi:`pytest-test-groups`                               A Pytest plugin for running a subset of your tests by splitting them in to equally sized groups.                                                                                                                                                                                                                                                                                        May 08, 2025    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-testinel`                                  Testinel’s pytest plugin captures structured test execution data directly from pytest and sends it to Testinel, where your test results become searchable, comparable, and actually useful.                                                                                                                                                                                             Mar 13, 2026    4 - Beta               pytest>=7\n   :pypi:`pytest-testinfra`                                 Test infrastructures                                                                                                                                                                                                                                                                                                                                                                    Mar 30, 2025    5 - Production/Stable  pytest>=6\n   :pypi:`pytest-testinfra-jpic`                            Test infrastructures                                                                                                                                                                                                                                                                                                                                                                    Sep 21, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-testinfra-winrm-transport`                 Test infrastructures                                                                                                                                                                                                                                                                                                                                                                    Sep 21, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-testit-parametrize`                        A pytest plugin for uploading parameterized tests parameters into TMS TestIT                                                                                                                                                                                                                                                                                                            Dec 04, 2024    4 - Beta               pytest>=8.3.3\n   :pypi:`pytest-testlink-adaptor`                          pytest reporting plugin for testlink                                                                                                                                                                                                                                                                                                                                                    Dec 20, 2018    4 - Beta               pytest (>=2.6)\n   :pypi:`pytest-testmon`                                   selects tests affected by changed files and methods                                                                                                                                                                                                                                                                                                                                     Dec 01, 2025    4 - Beta               pytest<10,>=5\n   :pypi:`pytest-testmon-dev`                               selects tests affected by changed files and methods                                                                                                                                                                                                                                                                                                                                     Mar 30, 2023    4 - Beta               pytest (<8,>=5)\n   :pypi:`pytest-testmon-oc`                                nOly selects tests affected by changed files and methods                                                                                                                                                                                                                                                                                                                                Jun 01, 2022    4 - Beta               pytest (<8,>=5)\n   :pypi:`pytest-testmon-skip-libraries`                    selects tests affected by changed files and methods                                                                                                                                                                                                                                                                                                                                     Mar 03, 2023    4 - Beta               pytest (<8,>=5)\n   :pypi:`pytest-testobject`                                Plugin to use TestObject Suites with Pytest                                                                                                                                                                                                                                                                                                                                             Sep 24, 2019    4 - Beta               pytest (>=3.1.1)\n   :pypi:`pytest-testpluggy`                                set your encoding                                                                                                                                                                                                                                                                                                                                                                       Jan 07, 2022    N/A                    pytest\n   :pypi:`pytest-testrail`                                  A pytest plugin for creating TestRail runs and adding results                                                                                                                                                                                                                                                                                                                           Jan 25, 2026    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-testrail2`                                 A pytest plugin to upload results to TestRail.                                                                                                                                                                                                                                                                                                                                          Feb 10, 2023    N/A                    pytest (<8.0,>=7.2.0)\n   :pypi:`pytest-testrail-api`                              TestRail Api Python Client                                                                                                                                                                                                                                                                                                                                                              Mar 17, 2025    N/A                    pytest\n   :pypi:`pytest-testrail-api-client`                       TestRail Api Python Client                                                                                                                                                                                                                                                                                                                                                              Dec 14, 2021    N/A                    pytest\n   :pypi:`pytest-testrail-appetize`                         pytest plugin for creating TestRail runs and adding results                                                                                                                                                                                                                                                                                                                             Sep 29, 2021    N/A                    N/A\n   :pypi:`pytest-testrail-client`                           pytest plugin for Testrail                                                                                                                                                                                                                                                                                                                                                              Sep 29, 2020    5 - Production/Stable  N/A\n   :pypi:`pytest-testrail-e2e`                              pytest plugin for creating TestRail runs and adding results                                                                                                                                                                                                                                                                                                                             Oct 11, 2021    N/A                    pytest (>=3.6)\n   :pypi:`pytest-testrail-integrator`                       Pytest plugin for sending report to testrail system.                                                                                                                                                                                                                                                                                                                                    Aug 01, 2022    N/A                    pytest (>=6.2.5)\n   :pypi:`pytest-testrail-ns`                               pytest plugin for creating TestRail runs and adding results                                                                                                                                                                                                                                                                                                                             Aug 12, 2022    N/A                    N/A\n   :pypi:`pytest-testrail-reporter`                                                                                                                                                                                                                                                                                                                                                                                                                 Sep 10, 2018    N/A                    N/A\n   :pypi:`pytest-testrail-results`                          A pytest plugin to upload results to TestRail.                                                                                                                                                                                                                                                                                                                                          Mar 04, 2024    N/A                    pytest >=7.2.0\n   :pypi:`pytest-testreport`                                                                                                                                                                                                                                                                                                                                                                                                                        Dec 01, 2022    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-testreport-new`                                                                                                                                                                                                                                                                                                                                                                                                                    Oct 07, 2023    4 - Beta               pytest >=3.5.0\n   :pypi:`pytest-testslide`                                 TestSlide fixture for pytest                                                                                                                                                                                                                                                                                                                                                            Jan 07, 2021    5 - Production/Stable  pytest (~=6.2)\n   :pypi:`pytest-test-this`                                 Plugin for py.test to run relevant tests, based on naively checking if a test contains a reference to the symbol you supply                                                                                                                                                                                                                                                             Sep 15, 2019    2 - Pre-Alpha          pytest (>=2.3)\n   :pypi:`pytest-test-tracer-for-pytest`                    A plugin that allows coll test data for use on Test Tracer                                                                                                                                                                                                                                                                                                                              Jun 28, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-test-tracer-for-pytest-bdd`                A plugin that allows coll test data for use on Test Tracer                                                                                                                                                                                                                                                                                                                              Aug 20, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-test-utils`                                                                                                                                                                                                                                                                                                                                                                                                                        Feb 08, 2024    N/A                    pytest >=3.9\n   :pypi:`pytest-tesults`                                   Tesults plugin for pytest                                                                                                                                                                                                                                                                                                                                                               Nov 12, 2024    5 - Production/Stable  pytest>=3.5.0\n   :pypi:`pytest-texts-score`                               Texts content similarity scoring plugin                                                                                                                                                                                                                                                                                                                                                 Dec 17, 2025    4 - Beta               pytest>=8.4.2\n   :pypi:`pytest-textual-snapshot`                          Snapshot testing for Textual apps                                                                                                                                                                                                                                                                                                                                                       Jan 23, 2025    5 - Production/Stable  pytest>=8.0.0\n   :pypi:`pytest-tezos`                                     pytest-ligo                                                                                                                                                                                                                                                                                                                                                                             Jan 16, 2020    4 - Beta               N/A\n   :pypi:`pytest-tf`                                        Test your OpenTofu and Terraform config using a PyTest plugin                                                                                                                                                                                                                                                                                                                           May 29, 2024    N/A                    pytest<9.0.0,>=8.2.1\n   :pypi:`pytest-th2-bdd`                                   pytest_th2_bdd                                                                                                                                                                                                                                                                                                                                                                          May 13, 2022    N/A                    N/A\n   :pypi:`pytest-thawgun`                                   Pytest plugin for time travel                                                                                                                                                                                                                                                                                                                                                           May 26, 2020    3 - Alpha              N/A\n   :pypi:`pytest-thread`                                                                                                                                                                                                                                                                                                                                                                                                                            Jul 07, 2023    N/A                    N/A\n   :pypi:`pytest-threadleak`                                Detects thread leaks                                                                                                                                                                                                                                                                                                                                                                    Jul 03, 2022    4 - Beta               pytest (>=3.1.1)\n   :pypi:`pytest-tick`                                      Ticking on tests                                                                                                                                                                                                                                                                                                                                                                        Aug 31, 2021    5 - Production/Stable  pytest (>=6.2.5,<7.0.0)\n   :pypi:`pytest_time`                                                                                                                                                                                                                                                                                                                                                                                                                              Dec 01, 2025    3 - Alpha              pytest\n   :pypi:`pytest-timeassert-ethan`                          execution duration                                                                                                                                                                                                                                                                                                                                                                      Dec 25, 2023    N/A                    pytest\n   :pypi:`pytest-timeit`                                    A pytest plugin to time test function runs                                                                                                                                                                                                                                                                                                                                              Oct 13, 2016    4 - Beta               N/A\n   :pypi:`pytest-timeout`                                   pytest plugin to abort hanging tests                                                                                                                                                                                                                                                                                                                                                    May 05, 2025    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-timeouts`                                  Linux-only Pytest plugin to control durations of various test case execution phases                                                                                                                                                                                                                                                                                                     Sep 21, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-timer`                                     A timer plugin for pytest                                                                                                                                                                                                                                                                                                                                                               Dec 26, 2023    N/A                    pytest\n   :pypi:`pytest-timestamper`                               Pytest plugin to add a timestamp prefix to the pytest output                                                                                                                                                                                                                                                                                                                            Mar 27, 2024    N/A                    N/A\n   :pypi:`pytest-timestamps`                                A simple plugin to view timestamps for each test                                                                                                                                                                                                                                                                                                                                        Sep 11, 2023    N/A                    pytest (>=7.3,<8.0)\n   :pypi:`pytest-timing-plugin`                             pytest插件开发demo                                                                                                                                                                                                                                                                                                                                                                      Jul 21, 2025    N/A                    N/A\n   :pypi:`pytest-tiny-api-client`                           The companion pytest plugin for tiny-api-client                                                                                                                                                                                                                                                                                                                                         Jan 04, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-tinybird`                                  A pytest plugin to report test results to tinybird                                                                                                                                                                                                                                                                                                                                      May 07, 2025    4 - Beta               pytest>=3.8.0\n   :pypi:`pytest-tipsi-django`                              Better fixtures for django                                                                                                                                                                                                                                                                                                                                                              Feb 05, 2024    5 - Production/Stable  pytest>=6.0.0\n   :pypi:`pytest-tipsi-testing`                             Better fixtures management. Various helpers                                                                                                                                                                                                                                                                                                                                             Feb 04, 2024    5 - Production/Stable  pytest>=3.3.0\n   :pypi:`pytest-tldr`                                      A pytest plugin that limits the output to just the things you need.                                                                                                                                                                                                                                                                                                                     Nov 10, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-tm4j-reporter`                             Cloud Jira Test Management (TM4J) PyTest reporter plugin                                                                                                                                                                                                                                                                                                                                Sep 01, 2020    N/A                    pytest\n   :pypi:`pytest-tmnet`                                     A small example package                                                                                                                                                                                                                                                                                                                                                                 Mar 01, 2022    N/A                    N/A\n   :pypi:`pytest-tmp-files`                                 Utilities to create temporary file hierarchies in pytest.                                                                                                                                                                                                                                                                                                                               Dec 08, 2023    N/A                    pytest\n   :pypi:`pytest-tmpfs`                                     A pytest plugin that helps you on using a temporary filesystem for testing.                                                                                                                                                                                                                                                                                                             Aug 29, 2022    N/A                    pytest\n   :pypi:`pytest-tmreport`                                  this is a vue-element ui report for pytest                                                                                                                                                                                                                                                                                                                                              Aug 12, 2022    N/A                    N/A\n   :pypi:`pytest-tmux`                                      A pytest plugin that enables tmux driven tests                                                                                                                                                                                                                                                                                                                                          Sep 01, 2025    4 - Beta               N/A\n   :pypi:`pytest-todo`                                      A small plugin for the pytest testing framework, marking TODO comments as failure                                                                                                                                                                                                                                                                                                       May 23, 2019    4 - Beta               pytest\n   :pypi:`pytest-tomato`                                                                                                                                                                                                                                                                                                                                                                                                                            Mar 01, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-toolbelt`                                  This is just a collection of utilities for pytest, but don't really belong in pytest proper.                                                                                                                                                                                                                                                                                            Aug 12, 2019    3 - Alpha              N/A\n   :pypi:`pytest-toolbox`                                   Numerous useful plugins for pytest.                                                                                                                                                                                                                                                                                                                                                     Apr 07, 2018    N/A                    pytest (>=3.5.0)\n   :pypi:`pytest-toolkit`                                   Useful utils for testing                                                                                                                                                                                                                                                                                                                                                                Jun 07, 2024    N/A                    N/A\n   :pypi:`pytest-tools`                                     Pytest tools                                                                                                                                                                                                                                                                                                                                                                            Oct 21, 2022    4 - Beta               N/A\n   :pypi:`pytest-topo`                                      Topological sorting for pytest                                                                                                                                                                                                                                                                                                                                                          Jun 05, 2024    N/A                    pytest>=7.0.0\n   :pypi:`pytest-tornado`                                   A py.test plugin providing fixtures and markers to simplify testing of asynchronous tornado applications.                                                                                                                                                                                                                                                                               Jun 17, 2020    5 - Production/Stable  pytest (>=3.6)\n   :pypi:`pytest-tornado5`                                  A py.test plugin providing fixtures and markers to simplify testing of asynchronous tornado applications.                                                                                                                                                                                                                                                                               Nov 16, 2018    5 - Production/Stable  pytest (>=3.6)\n   :pypi:`pytest-tornado-yen3`                              A py.test plugin providing fixtures and markers to simplify testing of asynchronous tornado applications.                                                                                                                                                                                                                                                                               Oct 15, 2018    5 - Production/Stable  N/A\n   :pypi:`pytest-tornasync`                                 py.test plugin for testing Python 3.5+ Tornado code                                                                                                                                                                                                                                                                                                                                     Jul 15, 2019    3 - Alpha              pytest (>=3.0)\n   :pypi:`pytest-trace`                                     Save OpenTelemetry spans generated during testing                                                                                                                                                                                                                                                                                                                                       Jun 19, 2022    N/A                    pytest (>=4.6)\n   :pypi:`pytest-track`                                                                                                                                                                                                                                                                                                                                                                                                                             Feb 26, 2021    3 - Alpha              pytest (>=3.0)\n   :pypi:`pytest-translations`                              Test your translation files.                                                                                                                                                                                                                                                                                                                                                            Sep 11, 2023    5 - Production/Stable  pytest (>=7)\n   :pypi:`pytest-travis-fold`                               Folds captured output sections in Travis CI build log                                                                                                                                                                                                                                                                                                                                   Nov 29, 2017    4 - Beta               pytest (>=2.6.0)\n   :pypi:`pytest-trello`                                    Plugin for py.test that integrates trello using markers                                                                                                                                                                                                                                                                                                                                 Nov 20, 2015    5 - Production/Stable  N/A\n   :pypi:`pytest-trepan`                                    Pytest plugin for trepan debugger.                                                                                                                                                                                                                                                                                                                                                      Sep 11, 2025    5 - Production/Stable  pytest>=4.0.0\n   :pypi:`pytest-trialtemp`                                 py.test plugin for using the same _trial_temp working directory as trial                                                                                                                                                                                                                                                                                                                Jun 08, 2015    N/A                    N/A\n   :pypi:`pytest-trio`                                      Pytest plugin for trio                                                                                                                                                                                                                                                                                                                                                                  Nov 01, 2022    N/A                    pytest (>=7.2.0)\n   :pypi:`pytest-trytond`                                   Pytest plugin for the Tryton server framework                                                                                                                                                                                                                                                                                                                                           Nov 04, 2022    4 - Beta               pytest (>=5)\n   :pypi:`pytest-tspwplib`                                  A simple plugin to use with tspwplib                                                                                                                                                                                                                                                                                                                                                    Jan 08, 2021    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-tst`                                       Customize pytest options, output and exit code to make it compatible with tst                                                                                                                                                                                                                                                                                                           Apr 27, 2022    N/A                    pytest (>=5.0.0)\n   :pypi:`pytest-tstcls`                                    Test Class Base                                                                                                                                                                                                                                                                                                                                                                         Mar 23, 2020    5 - Production/Stable  N/A\n   :pypi:`pytest-tui`                                       Text User Interface (TUI) and HTML report for Pytest test runs                                                                                                                                                                                                                                                                                                                          Dec 08, 2023    4 - Beta               N/A\n   :pypi:`pytest-tui-runner`                                Textual-based terminal UI for running pytest tests                                                                                                                                                                                                                                                                                                                                      Dec 12, 2025    N/A                    pytest<=9.0.1,>=7.4\n   :pypi:`pytest-tuitest`                                   pytest plugin for testing TUI and regular command-line applications.                                                                                                                                                                                                                                                                                                                    Apr 11, 2025    N/A                    pytest>=7.4.0\n   :pypi:`pytest-tutorials`                                                                                                                                                                                                                                                                                                                                                                                                                         Mar 11, 2023    N/A                    N/A\n   :pypi:`pytest-twilio-conversations-client-mock`                                                                                                                                                                                                                                                                                                                                                                                                  Aug 02, 2022    N/A                    N/A\n   :pypi:`pytest-twisted`                                   A twisted plugin for pytest.                                                                                                                                                                                                                                                                                                                                                            Sep 10, 2024    5 - Production/Stable  pytest>=2.3\n   :pypi:`pytest-ty`                                        A pytest plugin to run the ty type checker                                                                                                                                                                                                                                                                                                                                              Mar 08, 2026    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-typechecker`                               Run type checkers on specified test files                                                                                                                                                                                                                                                                                                                                               Feb 04, 2022    N/A                    pytest (>=6.2.5,<7.0.0)\n   :pypi:`pytest-typed-schema-shot`                         Pytest plugin for automatic JSON Schema generation and validation from examples                                                                                                                                                                                                                                                                                                         Jun 14, 2025    N/A                    pytest\n   :pypi:`pytest-typhoon-config`                            A Typhoon HIL plugin that facilitates test parameter configuration at runtime                                                                                                                                                                                                                                                                                                           Apr 07, 2022    5 - Production/Stable  N/A\n   :pypi:`pytest-typhoon-polarion`                          Typhoontest plugin for Siemens Polarion                                                                                                                                                                                                                                                                                                                                                 Feb 01, 2024    4 - Beta               N/A\n   :pypi:`pytest-typhoon-xray`                              Typhoon HIL plugin for pytest                                                                                                                                                                                                                                                                                                                                                           Aug 15, 2023    4 - Beta               N/A\n   :pypi:`pytest-typing-runner`                             Pytest plugin to make it easier to run and check python code against static type checkers                                                                                                                                                                                                                                                                                               May 31, 2025    N/A                    N/A\n   :pypi:`pytest-tytest`                                    Typhoon HIL plugin for pytest                                                                                                                                                                                                                                                                                                                                                           May 25, 2020    4 - Beta               pytest (>=5.4.2)\n   :pypi:`pytest-tzshift`                                   A Pytest plugin that transparently re-runs tests under a matrix of timezones and locales.                                                                                                                                                                                                                                                                                               Jun 25, 2025    4 - Beta               pytest>=7.0\n   :pypi:`pytest-ubersmith`                                 Easily mock calls to ubersmith at the \\`requests\\` level.                                                                                                                                                                                                                                                                                                                               Apr 13, 2015    N/A                    N/A\n   :pypi:`pytest-ui`                                        Text User Interface for running python tests                                                                                                                                                                                                                                                                                                                                            Jul 05, 2021    4 - Beta               pytest\n   :pypi:`pytest-ui-failed-screenshot`                      UI自动测试失败时自动截图，并将截图加入到测试报告中                                                                                                                                                                                                                                                                                                                                      Dec 06, 2022    N/A                    N/A\n   :pypi:`pytest-ui-failed-screenshot-allure`               UI自动测试失败时自动截图，并将截图加入到Allure测试报告中                                                                                                                                                                                                                                                                                                                                Dec 06, 2022    N/A                    N/A\n   :pypi:`pytest-uncollect-if`                              A plugin to uncollect pytests tests rather than using skipif                                                                                                                                                                                                                                                                                                                            Dec 26, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-unflakable`                                Unflakable plugin for PyTest                                                                                                                                                                                                                                                                                                                                                            Apr 30, 2024    4 - Beta               pytest>=6.2.0\n   :pypi:`pytest-unhandled-exception-exit-code`             Plugin for py.test set a different exit code on uncaught exceptions                                                                                                                                                                                                                                                                                                                     Jun 22, 2020    5 - Production/Stable  pytest (>=2.3)\n   :pypi:`pytest-unique`                                    Pytest fixture to generate unique values.                                                                                                                                                                                                                                                                                                                                               Dec 08, 2025    N/A                    pytest<10.0.0,>=9.0.0\n   :pypi:`pytest-unittest-filter`                           A pytest plugin for filtering unittest-based test classes                                                                                                                                                                                                                                                                                                                               Jan 12, 2019    4 - Beta               pytest (>=3.1.0)\n   :pypi:`pytest-unittest-id-runner`                        A pytest plugin to run tests using unittest-style test IDs                                                                                                                                                                                                                                                                                                                              Feb 09, 2025    N/A                    pytest>=6.0.0\n   :pypi:`pytest-unmagic`                                   Pytest fixtures with conventional import semantics                                                                                                                                                                                                                                                                                                                                      Jul 14, 2025    5 - Production/Stable  pytest\n   :pypi:`pytest-unmarked`                                  Run only unmarked tests                                                                                                                                                                                                                                                                                                                                                                 Aug 27, 2019    5 - Production/Stable  N/A\n   :pypi:`pytest-unordered`                                 Test equality of unordered collections in pytest                                                                                                                                                                                                                                                                                                                                        Jun 03, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-unstable`                                  Set a test as unstable to return 0 even if it failed                                                                                                                                                                                                                                                                                                                                    Sep 27, 2022    4 - Beta               N/A\n   :pypi:`pytest-unused-fixtures`                           A pytest plugin to list unused fixtures after a test run.                                                                                                                                                                                                                                                                                                                               Dec 23, 2025    4 - Beta               pytest>7.3.2\n   :pypi:`pytest-unused-port`                               pytest fixture finding an unused local port                                                                                                                                                                                                                                                                                                                                             Oct 22, 2025    N/A                    pytest\n   :pypi:`pytest-upload-report`                             pytest-upload-report is a plugin for pytest that upload your test report for test results.                                                                                                                                                                                                                                                                                              Jun 18, 2021    5 - Production/Stable  N/A\n   :pypi:`pytest-urllib3`                                   A pytest plugin to mock urllib3 requests                                                                                                                                                                                                                                                                                                                                                Mar 09, 2026    3 - Alpha              pytest>=7\n   :pypi:`pytest-utils`                                     Some helpers for pytest.                                                                                                                                                                                                                                                                                                                                                                Feb 02, 2023    4 - Beta               pytest (>=7.0.0,<8.0.0)\n   :pypi:`pytest-uuid`                                      A pytest plugin for mocking uuid.uuid4() calls                                                                                                                                                                                                                                                                                                                                          Feb 27, 2026    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-vagrant`                                   A py.test plugin providing access to vagrant.                                                                                                                                                                                                                                                                                                                                           Sep 07, 2021    5 - Production/Stable  pytest\n   :pypi:`pytest-valgrind`                                                                                                                                                                                                                                                                                                                                                                                                                          May 19, 2021    N/A                    N/A\n   :pypi:`pytest-variables`                                 pytest plugin for providing variables to tests/fixtures                                                                                                                                                                                                                                                                                                                                 Feb 01, 2024    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-variant`                                   Variant support for Pytest                                                                                                                                                                                                                                                                                                                                                              Jun 06, 2022    N/A                    N/A\n   :pypi:`pytest-vcr`                                       Plugin for managing VCR.py cassettes                                                                                                                                                                                                                                                                                                                                                    Apr 26, 2019    5 - Production/Stable  pytest (>=3.6.0)\n   :pypi:`pytest-vcr-delete-on-fail`                        A pytest plugin that automates vcrpy cassettes deletion on test failure.                                                                                                                                                                                                                                                                                                                Feb 16, 2024    5 - Production/Stable  pytest (>=8.0.0,<9.0.0)\n   :pypi:`pytest-vcrpandas`                                 Test from HTTP interactions to dataframe processed.                                                                                                                                                                                                                                                                                                                                     Jan 12, 2019    4 - Beta               pytest\n   :pypi:`pytest-vcs`                                                                                                                                                                                                                                                                                                                                                                                                                               Sep 22, 2022    4 - Beta               N/A\n   :pypi:`pytest-venv`                                      py.test fixture for creating a virtual environment                                                                                                                                                                                                                                                                                                                                      Nov 23, 2023    4 - Beta               pytest\n   :pypi:`pytest-verbose-parametrize`                       More descriptive output for parametrized py.test tests                                                                                                                                                                                                                                                                                                                                  Nov 29, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-verify`                                    A pytest plugin for snapshot verification with optional visual diff viewer.                                                                                                                                                                                                                                                                                                             Oct 25, 2025    5 - Production/Stable  N/A\n   :pypi:`pytest-vigil`                                     A pytest plugin for enhanced test reliability and monitoring                                                                                                                                                                                                                                                                                                                            Mar 13, 2026    5 - Production/Stable  pytest>=9.0.0\n   :pypi:`pytest-vimqf`                                     A simple pytest plugin that will shrink pytest output when specified, to fit vim quickfix window.                                                                                                                                                                                                                                                                                       Feb 08, 2021    4 - Beta               pytest (>=6.2.2,<7.0.0)\n   :pypi:`pytest-virtualenv`                                Virtualenv fixture for py.test                                                                                                                                                                                                                                                                                                                                                          Nov 29, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-visual`                                                                                                                                                                                                                                                                                                                                                                                                                            Nov 28, 2024    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-vnc`                                       VNC client for Pytest                                                                                                                                                                                                                                                                                                                                                                   Nov 06, 2023    N/A                    pytest\n   :pypi:`pytest-voluptuous`                                Pytest plugin for asserting data against voluptuous schema.                                                                                                                                                                                                                                                                                                                             Jun 09, 2020    N/A                    pytest\n   :pypi:`pytest-vscodedebug`                               A pytest plugin to easily enable debugging tests within Visual Studio Code                                                                                                                                                                                                                                                                                                              Dec 04, 2020    4 - Beta               N/A\n   :pypi:`pytest-vscode-pycharm-cls`                        A PyTest helper to enable start remote debugger on test start or failure or when pytest.set_trace is used.                                                                                                                                                                                                                                                                              Feb 01, 2023    N/A                    pytest\n   :pypi:`pytest-vtestify`                                  A pytest plugin for visual assertion using SSIM and image comparison.                                                                                                                                                                                                                                                                                                                   Feb 04, 2025    N/A                    pytest\n   :pypi:`pytest-vts`                                       pytest plugin for automatic recording of http stubbed tests                                                                                                                                                                                                                                                                                                                             Jun 05, 2019    N/A                    pytest (>=2.3)\n   :pypi:`pytest-vulture`                                   A pytest plugin to checks dead code with vulture                                                                                                                                                                                                                                                                                                                                        Nov 25, 2024    N/A                    pytest>=7.0.0\n   :pypi:`pytest-vw`                                        pytest-vw makes your failing test cases succeed under CI tools scrutiny                                                                                                                                                                                                                                                                                                                 Oct 07, 2015    4 - Beta               N/A\n   :pypi:`pytest-vyper`                                     Plugin for the vyper smart contract language.                                                                                                                                                                                                                                                                                                                                           May 28, 2020    2 - Pre-Alpha          N/A\n   :pypi:`pytest-wa-e2e-plugin`                             Pytest plugin for testing whatsapp bots with end to end tests                                                                                                                                                                                                                                                                                                                           Feb 18, 2020    4 - Beta               pytest (>=3.5.0)\n   :pypi:`pytest-wake`                                                                                                                                                                                                                                                                                                                                                                                                                              Nov 19, 2024    N/A                    pytest\n   :pypi:`pytest-watch`                                     Local continuous test runner with pytest and watchdog.                                                                                                                                                                                                                                                                                                                                  May 20, 2018    N/A                    N/A\n   :pypi:`pytest-watcher`                                   Automatically rerun your tests on file modifications                                                                                                                                                                                                                                                                                                                                    Jan 10, 2026    4 - Beta               N/A\n   :pypi:`pytest-watch-plugin`                              Placeholder for internal package                                                                                                                                                                                                                                                                                                                                                        Sep 12, 2024    N/A                    N/A\n   :pypi:`pytest_wdb`                                       Trace pytest tests with wdb to halt on error with --wdb.                                                                                                                                                                                                                                                                                                                                Jul 04, 2016    N/A                    N/A\n   :pypi:`pytest-wdl`                                       Pytest plugin for testing WDL workflows.                                                                                                                                                                                                                                                                                                                                                Nov 17, 2020    5 - Production/Stable  N/A\n   :pypi:`pytest-web3-data`                                 A pytest plugin to fetch test data from IPFS HTTP gateways during pytest execution.                                                                                                                                                                                                                                                                                                     Oct 04, 2023    4 - Beta               pytest\n   :pypi:`pytest-webdriver`                                 Selenium webdriver fixture for py.test                                                                                                                                                                                                                                                                                                                                                  Oct 17, 2024    5 - Production/Stable  pytest\n   :pypi:`pytest-webstage`                                  Test web apps with pytest                                                                                                                                                                                                                                                                                                                                                               Sep 20, 2024    N/A                    pytest<9.0,>=7.0\n   :pypi:`pytest-webtestpilot`                              Pytest plugin for running WebTestPilot JSON tests                                                                                                                                                                                                                                                                                                                                       Dec 28, 2025    N/A                    pytest>=9.0.2\n   :pypi:`pytest-wetest`                                    Welian API Automation test framework pytest plugin                                                                                                                                                                                                                                                                                                                                      Nov 10, 2018    4 - Beta               N/A\n   :pypi:`pytest-when`                                      Utility which makes mocking more readable and controllable                                                                                                                                                                                                                                                                                                                              Sep 25, 2025    N/A                    pytest>=7.3.1\n   :pypi:`pytest-whirlwind`                                 Testing Tornado.                                                                                                                                                                                                                                                                                                                                                                        Jun 12, 2020    N/A                    N/A\n   :pypi:`pytest-wholenodeid`                               pytest addon for displaying the whole node id for failures                                                                                                                                                                                                                                                                                                                              Aug 26, 2015    4 - Beta               pytest (>=2.0)\n   :pypi:`pytest-win32consoletitle`                         Pytest progress in console title (Win32 only)                                                                                                                                                                                                                                                                                                                                           Aug 08, 2021    N/A                    N/A\n   :pypi:`pytest-winnotify`                                 Windows tray notifications for py.test results.                                                                                                                                                                                                                                                                                                                                         Apr 22, 2016    N/A                    N/A\n   :pypi:`pytest-wirefracture`                              Pytest fixtures for wirefracture                                                                                                                                                                                                                                                                                                                                                        Dec 31, 2025    N/A                    N/A\n   :pypi:`pytest-wiremock`                                  A pytest plugin for programmatically using wiremock in integration tests                                                                                                                                                                                                                                                                                                                Mar 27, 2022    N/A                    pytest (>=7.1.1,<8.0.0)\n   :pypi:`pytest-wiretap`                                   \\`pytest\\` plugin for recording call stacks                                                                                                                                                                                                                                                                                                                                             Mar 18, 2025    N/A                    pytest\n   :pypi:`pytest-with-docker`                               pytest with docker helpers.                                                                                                                                                                                                                                                                                                                                                             Nov 09, 2021    N/A                    pytest\n   :pypi:`pytest-workaround-12888`                          forces an import of readline early in the process to work around pytest bug #12888                                                                                                                                                                                                                                                                                                      Jan 15, 2025    N/A                    N/A\n   :pypi:`pytest-workflow`                                  A pytest plugin for configuring workflow/pipeline tests using YAML files                                                                                                                                                                                                                                                                                                                Mar 18, 2024    5 - Production/Stable  pytest >=7.0.0\n   :pypi:`pytest-xdist`                                     pytest xdist plugin for distributed testing, most importantly across multiple CPUs                                                                                                                                                                                                                                                                                                      Jul 01, 2025    5 - Production/Stable  pytest>=7.0.0\n   :pypi:`pytest-xdist-debug-for-graingert`                 pytest xdist plugin for distributed testing and loop-on-failing modes                                                                                                                                                                                                                                                                                                                   Jul 24, 2019    5 - Production/Stable  pytest (>=4.4.0)\n   :pypi:`pytest-xdist-forked`                              forked from pytest-xdist                                                                                                                                                                                                                                                                                                                                                                Feb 10, 2020    5 - Production/Stable  pytest (>=4.4.0)\n   :pypi:`pytest-xdist-gnumake`                             A small example package                                                                                                                                                                                                                                                                                                                                                                 Jun 22, 2025    N/A                    pytest\n   :pypi:`pytest-xdist-load-testing`                        xdist scheduler to repeately run tests                                                                                                                                                                                                                                                                                                                                                  Nov 22, 2025    4 - Beta               pytest>=8.4.2\n   :pypi:`pytest-xdist-rate-limit`                          Shared state management and rate limiting for pytest-xdist workers                                                                                                                                                                                                                                                                                                                      Dec 31, 2025    4 - Beta               pytest>=8.4.2\n   :pypi:`pytest-xdist-tracker`                             pytest plugin helps to reproduce failures for particular xdist node                                                                                                                                                                                                                                                                                                                     Nov 18, 2021    3 - Alpha              pytest (>=3.5.1)\n   :pypi:`pytest-xdist-worker-stats`                        A pytest plugin to list worker statistics after a xdist run.                                                                                                                                                                                                                                                                                                                            Feb 16, 2026    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-xdocker`                                   Pytest fixture to run docker across test runs.                                                                                                                                                                                                                                                                                                                                          Dec 08, 2025    N/A                    pytest<10.0.0,>=9.0.0\n   :pypi:`pytest-xfaillist`                                 Maintain a xfaillist in an additional file to avoid merge-conflicts.                                                                                                                                                                                                                                                                                                                    Sep 17, 2021    N/A                    pytest (>=6.2.2,<7.0.0)\n   :pypi:`pytest-xfiles`                                    Pytest fixtures providing data read from function, module or package related (x)files.                                                                                                                                                                                                                                                                                                  Feb 27, 2018    N/A                    N/A\n   :pypi:`pytest-xflaky`                                    A simple plugin to use with pytest                                                                                                                                                                                                                                                                                                                                                      Oct 14, 2024    4 - Beta               pytest>=8.2.1\n   :pypi:`pytest-xhtml`                                     pytest plugin for generating HTML reports                                                                                                                                                                                                                                                                                                                                               Feb 26, 2026    5 - Production/Stable  pytest>=7\n   :pypi:`pytest-xiuyu`                                     This is a pytest plugin                                                                                                                                                                                                                                                                                                                                                                 Jul 25, 2023    5 - Production/Stable  N/A\n   :pypi:`pytest-xlog`                                      Extended logging for test and decorators                                                                                                                                                                                                                                                                                                                                                May 31, 2020    4 - Beta               N/A\n   :pypi:`pytest-xlsx`                                      pytest plugin for generating test cases by xlsx(excel)                                                                                                                                                                                                                                                                                                                                  Aug 07, 2024    N/A                    pytest~=8.2.2\n   :pypi:`pytest-xml`                                       Create simple XML results for parsing                                                                                                                                                                                                                                                                                                                                                   Nov 14, 2024    4 - Beta               pytest>=8.0.0\n   :pypi:`pytest-xpara`                                     An extended parametrizing plugin of pytest.                                                                                                                                                                                                                                                                                                                                             Aug 07, 2024    3 - Alpha              pytest\n   :pypi:`pytest-xprocess`                                  A pytest plugin for managing processes across test runs.                                                                                                                                                                                                                                                                                                                                May 19, 2024    4 - Beta               pytest>=2.8\n   :pypi:`pytest-xray`                                                                                                                                                                                                                                                                                                                                                                                                                              May 30, 2019    3 - Alpha              N/A\n   :pypi:`pytest-xrayjira`                                                                                                                                                                                                                                                                                                                                                                                                                          Mar 17, 2020    3 - Alpha              pytest (==4.3.1)\n   :pypi:`pytest-xray-reporter`                             Pytest plugin for generating Xray JSON reports                                                                                                                                                                                                                                                                                                                                          May 21, 2025    4 - Beta               pytest>=7.0.0\n   :pypi:`pytest-xray-server`                                                                                                                                                                                                                                                                                                                                                                                                                       May 03, 2022    3 - Alpha              pytest (>=5.3.1)\n   :pypi:`pytest-xstress`                                                                                                                                                                                                                                                                                                                                                                                                                           Jun 01, 2024    N/A                    pytest<9.0.0,>=8.0.0\n   :pypi:`pytest-xtime`                                     pytest plugin for recording execution time                                                                                                                                                                                                                                                                                                                                              Jun 05, 2025    4 - Beta               pytest\n   :pypi:`pytest-xvfb`                                      A pytest plugin to run Xvfb (or Xephyr/Xvnc) for tests.                                                                                                                                                                                                                                                                                                                                 Mar 12, 2025    4 - Beta               pytest>=2.8.1\n   :pypi:`pytest-xvirt`                                     A pytest plugin to virtualize test. For example to transparently running them on a remote box.                                                                                                                                                                                                                                                                                          Dec 15, 2024    4 - Beta               pytest>=7.2.2\n   :pypi:`pytest-yaml`                                      This plugin is used to load yaml output to your test using pytest framework.                                                                                                                                                                                                                                                                                                            Oct 05, 2018    N/A                    pytest\n   :pypi:`pytest-yaml-fei`                                  a pytest yaml allure package                                                                                                                                                                                                                                                                                                                                                            Jul 27, 2025    N/A                    pytest\n   :pypi:`pytest-yaml-sanmu`                                Pytest plugin for generating test cases with YAML. In test cases, you can use markers, fixtures, variables, and even call Python functions.                                                                                                                                                                                                                                             Sep 16, 2025    N/A                    pytest>=8.2.2\n   :pypi:`pytest-yamltree`                                  Create or check file/directory trees described by YAML                                                                                                                                                                                                                                                                                                                                  Mar 02, 2020    4 - Beta               pytest (>=3.1.1)\n   :pypi:`pytest-yamlwsgi`                                  Run tests against wsgi apps defined in yaml                                                                                                                                                                                                                                                                                                                                             May 11, 2010    N/A                    N/A\n   :pypi:`pytest-yaml-yoyo`                                 http/https API run by yaml                                                                                                                                                                                                                                                                                                                                                              Jun 19, 2023    N/A                    pytest (>=7.2.0)\n   :pypi:`pytest-yapf`                                      Run yapf                                                                                                                                                                                                                                                                                                                                                                                Jul 06, 2017    4 - Beta               pytest (>=3.1.1)\n   :pypi:`pytest-yapf3`                                     Validate your Python file format with yapf                                                                                                                                                                                                                                                                                                                                              Mar 29, 2023    5 - Production/Stable  pytest (>=7)\n   :pypi:`pytest-yield`                                     PyTest plugin to run tests concurrently, each \\`yield\\` switch context to other one                                                                                                                                                                                                                                                                                                     Jan 23, 2019    N/A                    N/A\n   :pypi:`pytest-yls`                                       Pytest plugin to test the YLS as a whole.                                                                                                                                                                                                                                                                                                                                               Apr 09, 2025    N/A                    pytest<9.0.0,>=8.3.3\n   :pypi:`pytest-youqu-playwright`                          pytest-youqu-playwright                                                                                                                                                                                                                                                                                                                                                                 Jun 12, 2024    N/A                    pytest\n   :pypi:`pytest-yuk`                                       Display tests you are uneasy with, using 🤢/🤮 for pass/fail of tests marked with yuk.                                                                                                                                                                                                                                                                                                  Mar 26, 2021    N/A                    pytest>=5.0.0\n   :pypi:`pytest-zafira`                                    A Zafira plugin for pytest                                                                                                                                                                                                                                                                                                                                                              Sep 18, 2019    5 - Production/Stable  pytest (==4.1.1)\n   :pypi:`pytest-zap`                                       OWASP ZAP plugin for py.test.                                                                                                                                                                                                                                                                                                                                                           May 12, 2014    4 - Beta               N/A\n   :pypi:`pytest-zcc`                                       eee                                                                                                                                                                                                                                                                                                                                                                                     Jun 02, 2024    N/A                    N/A\n   :pypi:`pytest-zebrunner`                                 Pytest connector for Zebrunner reporting                                                                                                                                                                                                                                                                                                                                                Jul 04, 2024    5 - Production/Stable  pytest>=4.5.0\n   :pypi:`pytest-zeebe`                                     Pytest fixtures for testing Camunda 8 processes using a Zeebe test engine.                                                                                                                                                                                                                                                                                                              Feb 01, 2024    N/A                    pytest (>=7.4.2,<8.0.0)\n   :pypi:`pytest-zephyr-scale-integration`                  A library for integrating Jira Zephyr Scale (Adaptavist\\TM4J) with pytest                                                                                                                                                                                                                                                                                                               Jun 26, 2025    N/A                    pytest\n   :pypi:`pytest-zephyr-telegram`                           Плагин для отправки данных автотестов в Телеграм и Зефир                                                                                                                                                                                                                                                                                                                                Sep 30, 2024    N/A                    pytest==8.3.2\n   :pypi:`pytest-zest`                                      Zesty additions to pytest.                                                                                                                                                                                                                                                                                                                                                              Nov 17, 2022    N/A                    N/A\n   :pypi:`pytest-zhongwen-wendang`                          PyTest 中文文档                                                                                                                                                                                                                                                                                                                                                                         Mar 04, 2024    4 - Beta               N/A\n   :pypi:`pytest-zigzag`                                    Extend py.test for RPC OpenStack testing.                                                                                                                                                                                                                                                                                                                                               Feb 27, 2019    4 - Beta               pytest (~=3.6)\n   :pypi:`pytest-zulip`                                     Pytest report plugin for Zulip                                                                                                                                                                                                                                                                                                                                                          May 07, 2022    5 - Production/Stable  pytest\n   :pypi:`pytest-zy`                                        接口自动化测试框架                                                                                                                                                                                                                                                                                                                                                                      Mar 24, 2024    N/A                    pytest~=7.2.0\n   :pypi:`tursu`                                            🎬 A pytest plugin that transpiles Gherkin feature files to Python using AST, enforcing typing for ease of use and debugging.                                                                                                                                                                                                                                                           Mar 02, 2026    5 - Production/Stable  pytest>=8.3.5\n   =======================================================  ======================================================================================================================================================================================================================================================================================================================================================================================  ==============  =====================  ================================================\n\n.. only:: latex\n\n\n  :pypi:`databricks-labs-pytester`\n     *last release*: Oct 17, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.3\n\n     Python Testing for Databricks\n\n  :pypi:`logassert`\n     *last release*: Aug 14, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest; extra == \"dev\"\n\n     Simple but powerful assertion and verification of logged lines\n\n  :pypi:`logot`\n     *last release*: Feb 22, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<10,>=7; extra == \"pytest\"\n\n     Test whether your code is logging correctly 🪵\n\n  :pypi:`nuts`\n     *last release*: Nov 17, 2025,\n     *status*: N/A,\n     *requires*: pytest<8,>=7\n\n     Network Unit Testing System\n\n  :pypi:`pytest-abort`\n     *last release*: Feb 11, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     Pytest plugin + helpers for attributing hard crashes (SIGSEGV/SIGABRT) to the last running test and keeping pytest-html reports mergeable.\n\n  :pypi:`pytest-abq`\n     *last release*: Apr 07, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest integration for the ABQ universal test runner.\n\n  :pypi:`pytest-abstracts`\n     *last release*: May 25, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A contextmanager pytest fixture for handling multiple mock abstracts\n\n  :pypi:`pytest-accept`\n     *last release*: Mar 01, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7\n\n\n\n  :pypi:`pytest-adaptavist`\n     *last release*: Oct 13, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=5.4.0)\n\n     pytest plugin for generating test execution results within Jira Test Management (tm4j)\n\n  :pypi:`pytest-adaptavist-fixed`\n     *last release*: Jan 17, 2025,\n     *status*: N/A,\n     *requires*: pytest>=5.4.0\n\n     pytest plugin for generating test execution results within Jira Test Management (tm4j)\n\n  :pypi:`pytest-adbc-replay`\n     *last release*: Mar 13, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.0\n\n     pytest plugin to record and replay ADBC database queries\n\n  :pypi:`pytest-addons-test`\n     *last release*: Aug 02, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=6.2.4,<7.0.0)\n\n     用于测试pytest的插件\n\n  :pypi:`pytest-adf`\n     *last release*: May 10, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Pytest plugin for writing Azure Data Factory integration tests\n\n  :pypi:`pytest-adf-azure-identity`\n     *last release*: Mar 06, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Pytest plugin for writing Azure Data Factory integration tests\n\n  :pypi:`pytest-ads-testplan`\n     *last release*: Sep 15, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Azure DevOps Test Case reporting for pytest tests\n\n  :pypi:`pytest-adversarial`\n     *last release*: Jan 22, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     Generate adversarial pytest tests using LLM\n\n  :pypi:`pytest-affected`\n     *last release*: Nov 06, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-agent`\n     *last release*: Nov 25, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Service that exposes a REST API that can be used to interract remotely with Pytest. It is shipped with a dashboard that enables running tests in a more convenient way.\n\n  :pypi:`pytest-agentcontract`\n     *last release*: Feb 18, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     Deterministic CI tests for LLM agent trajectories — record once, replay offline, assert contracts\n\n  :pypi:`pytest-agent-evals`\n     *last release*: Mar 13, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     Pytest plugin for evaluating AI Agents\n\n  :pypi:`pytest-agents`\n     *last release*: Feb 20, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8.0.0\n\n     Pytest plugin framework with AI agent capabilities for multi-agent testing\n\n  :pypi:`pytest-aggreport`\n     *last release*: Mar 07, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.2.2)\n\n     pytest plugin for pytest-repeat that generate aggregate report of the same test cases with additional statistics details.\n\n  :pypi:`pytest-ai`\n     *last release*: Jan 22, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     A Python package to generate regular, edge-case, and security HTTP tests.\n\n  :pypi:`pytest-ai1899`\n     *last release*: Mar 13, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin for connecting to ai1899 smart system stack\n\n  :pypi:`pytest-aio`\n     *last release*: Feb 12, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest plugin for testing async python code\n\n  :pypi:`pytest-aioboto3`\n     *last release*: Jan 17, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Aioboto3 Pytest with Moto\n\n  :pypi:`pytest-aiofiles`\n     *last release*: May 14, 2017,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest fixtures for writing aiofiles tests with pyfakefs\n\n  :pypi:`pytest-aiogram`\n     *last release*: May 06, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-aiohttp`\n     *last release*: Jan 23, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.1.0\n\n     Pytest plugin for aiohttp support\n\n  :pypi:`pytest-aiohttp-client`\n     *last release*: Jan 10, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.2.0,<8.0.0)\n\n     Pytest \\`client\\` fixture for the Aiohttp\n\n  :pypi:`pytest-aiohttp-mock`\n     *last release*: Sep 13, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8\n\n     Send responses to aiohttp.\n\n  :pypi:`pytest-aiohutils`\n     *last release*: Feb 10, 2026,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin providing fixtures and configuration for aiohutils projects (offline, record, cleanup modes).\n\n  :pypi:`pytest-aiomoto`\n     *last release*: Jun 24, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.0,<8.0)\n\n     pytest-aiomoto\n\n  :pypi:`pytest-aioresponses`\n     *last release*: Jan 02, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     py.test integration for aioresponses\n\n  :pypi:`pytest-aioworkers`\n     *last release*: Dec 26, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.3.4\n\n     A plugin to test aioworkers project with pytest\n\n  :pypi:`pytest-airflow`\n     *last release*: Apr 03, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=4.4.0)\n\n     pytest support for airflow.\n\n  :pypi:`pytest-airflow-utils`\n     *last release*: Nov 15, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-aitest`\n     *last release*: Feb 20, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=9.0\n\n     Pytest plugin for testing AI agents with MCP and CLI servers\n\n  :pypi:`pytest-alembic`\n     *last release*: May 27, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     A pytest plugin for verifying alembic migrations.\n\n  :pypi:`pytest-alerts`\n     *last release*: Feb 21, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.4.0\n\n     A pytest plugin for sending test results to Slack and Telegram\n\n  :pypi:`pytest-allclose`\n     *last release*: Jul 30, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest fixture extending Numpy's allclose function\n\n  :pypi:`pytest-allure-adaptor`\n     *last release*: Jan 10, 2018,\n     *status*: N/A,\n     *requires*: pytest (>=2.7.3)\n\n     Plugin for py.test to generate allure xml reports\n\n  :pypi:`pytest-allure-adaptor2`\n     *last release*: Oct 14, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=2.7.3)\n\n     Plugin for py.test to generate allure xml reports\n\n  :pypi:`pytest-allure-collection`\n     *last release*: Apr 13, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest plugin to collect allure markers without running any tests\n\n  :pypi:`pytest-allure-dsl`\n     *last release*: Oct 25, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     pytest plugin to test case doc string dls instructions\n\n  :pypi:`pytest-allure-host`\n     *last release*: Nov 03, 2025,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Publish Allure static reports to private S3 behind CloudFront with history preservation\n\n  :pypi:`pytest-allure-id2history`\n     *last release*: May 14, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     Overwrite allure history id with testcase full name and testcase id if testcase has id, exclude parameters.\n\n  :pypi:`pytest-allure-intersection`\n     *last release*: Oct 27, 2022,\n     *status*: N/A,\n     *requires*: pytest (<5)\n\n\n\n  :pypi:`pytest-allure-spec-coverage`\n     *last release*: Oct 26, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     The pytest plugin aimed to display test coverage of the specs(requirements) in Allure\n\n  :pypi:`pytest-allure-step`\n     *last release*: Jul 13, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=6.0.0\n\n     Enhanced logging integration with Allure reports for pytest\n\n  :pypi:`pytest-alphamoon`\n     *last release*: Dec 30, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.5.0)\n\n     Static code checks used at Alphamoon\n\n  :pypi:`pytest-amaranth-sim`\n     *last release*: Feb 18, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     Fixture to automate running Amaranth simulations\n\n  :pypi:`pytest-ampel-core`\n     *last release*: Dec 17, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A plugin to provide AmpelContext fixtures in pytest\n\n  :pypi:`pytest-analyzer`\n     *last release*: Feb 21, 2024,\n     *status*: N/A,\n     *requires*: pytest <8.0.0,>=7.3.1\n\n     this plugin allows to analyze tests in pytest project, collect test metadata and sync it with testomat.io TCM system\n\n  :pypi:`pytest-android`\n     *last release*: Feb 21, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     This fixture provides a configured \"driver\" for Android Automated Testing, using uiautomator2.\n\n  :pypi:`pytest-anki`\n     *last release*: Jul 31, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A pytest plugin for testing Anki add-ons\n\n  :pypi:`pytest-annotate`\n     *last release*: Jun 07, 2022,\n     *status*: 3 - Alpha,\n     *requires*: pytest (<8.0.0,>=3.2.0)\n\n     pytest-annotate: Generate PyAnnotate annotations from your pytest tests.\n\n  :pypi:`pytest-annotated`\n     *last release*: Sep 30, 2024,\n     *status*: N/A,\n     *requires*: pytest>=8.3.3\n\n     Pytest plugin to allow use of Annotated in tests to resolve fixtures\n\n  :pypi:`pytest-ansible`\n     *last release*: Feb 24, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6\n\n     Plugin for pytest to simplify calling ansible modules from tests or fixtures\n\n  :pypi:`pytest-ansible-playbook`\n     *last release*: Mar 08, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Pytest fixture which runs given ansible playbook file.\n\n  :pypi:`pytest-ansible-playbook-runner`\n     *last release*: Dec 02, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.1.0)\n\n     Pytest fixture which runs given ansible playbook file.\n\n  :pypi:`pytest-ansible-units`\n     *last release*: Apr 14, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin for running unit tests within an ansible collection\n\n  :pypi:`pytest-antilru`\n     *last release*: Jul 28, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7; python_version >= \"3.10\"\n\n     Bust functools.lru_cache when running pytest to avoid test pollution\n\n  :pypi:`pytest-anyio`\n     *last release*: Jun 29, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     The pytest anyio plugin is built into anyio. You don't need this package.\n\n  :pypi:`pytest-anything`\n     *last release*: Jan 18, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest fixtures to assert anything and something\n\n  :pypi:`pytest-aoc`\n     *last release*: Dec 02, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest ; extra == 'test'\n\n     Downloads puzzle inputs for Advent of Code and synthesizes PyTest fixtures\n\n  :pypi:`pytest-aoreporter`\n     *last release*: Jun 27, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest report\n\n  :pypi:`pytest-api`\n     *last release*: May 12, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.1.1,<8.0.0)\n\n     An ASGI middleware to populate OpenAPI Specification examples from pytest functions\n\n  :pypi:`pytest-apibean`\n     *last release*: Dec 30, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin providing apibean-based API testing fixtures integrated with apibean-client, designed for testing apibean REST services and datacore backends.\n\n  :pypi:`pytest-api-cov`\n     *last release*: Feb 05, 2026,\n     *status*: N/A,\n     *requires*: pytest>=6.0.0\n\n     Pytest Plugin to provide API Coverage statistics for Python Web Frameworks\n\n  :pypi:`pytest-api-framework`\n     *last release*: Jun 22, 2025,\n     *status*: N/A,\n     *requires*: pytest==7.2.2\n\n     pytest framework\n\n  :pypi:`pytest-api-framework-alpha`\n     *last release*: Mar 03, 2026,\n     *status*: N/A,\n     *requires*: pytest==7.2.2\n\n\n\n  :pypi:`pytest-api-soup`\n     *last release*: Aug 27, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Validate multiple endpoints with unit testing using a single source of truth.\n\n  :pypi:`pytest-apistellar`\n     *last release*: Jun 18, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     apistellar plugin for pytest.\n\n  :pypi:`pytest-apiver`\n     *last release*: Jun 21, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-appengine`\n     *last release*: Feb 27, 2017,\n     *status*: N/A,\n     *requires*: N/A\n\n     AppEngine integration that works well with pytest-django\n\n  :pypi:`pytest-appium`\n     *last release*: Dec 05, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin for appium\n\n  :pypi:`pytest-approval`\n     *last release*: Jan 27, 2026,\n     *status*: N/A,\n     *requires*: pytest>=8.3.5\n\n     A simple approval test library utilizing external diff programs such as PyCharm and Visual Studio Code to compare approved and received output.\n\n  :pypi:`pytest-approvaltests`\n     *last release*: May 08, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=7.0.1)\n\n     A plugin to use approvaltests with pytest\n\n  :pypi:`pytest-approvaltests-geo`\n     *last release*: Jul 14, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Extension for ApprovalTests.Python specific to geo data verification\n\n  :pypi:`pytest-archon`\n     *last release*: Sep 19, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.2\n\n     Rule your architecture like a real developer\n\n  :pypi:`pytest-argus`\n     *last release*: Jun 24, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=6.2.4)\n\n     pyest results colection plugin\n\n  :pypi:`pytest-argus-reporter`\n     *last release*: Mar 03, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest~=9.0.0; extra == \"dev\"\n\n     A simple plugin to report results of test into argus\n\n  :pypi:`pytest-argus-server`\n     *last release*: Mar 05, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A plugin that provides a running Argus API server for tests\n\n  :pypi:`pytest-arrakis`\n     *last release*: Mar 05, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Pytest plugin providing Arrakis fixtures for testing\n\n  :pypi:`pytest-arraydiff`\n     *last release*: Nov 27, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest >=4.6\n\n     pytest plugin to help with comparing array output from tests\n\n  :pypi:`pytest-artifact`\n     *last release*: Feb 09, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     Pytest plugin for managing test artifacts\n\n  :pypi:`pytest-asdf-plugin`\n     *last release*: Aug 18, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7\n\n     Pytest plugin for testing ASDF schemas\n\n  :pypi:`pytest-asgi-server`\n     *last release*: Dec 12, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=5.4.1)\n\n     Convenient ASGI client/server fixtures for Pytest\n\n  :pypi:`pytest-aspec`\n     *last release*: Dec 20, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A rspec format reporter for pytest\n\n  :pypi:`pytest-asptest`\n     *last release*: Apr 28, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     test Answer Set Programming programs\n\n  :pypi:`pytest-assay`\n     *last release*: Mar 04, 2026,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Evaluation framework for Pydantic AI agents\n\n  :pypi:`pytest-assertcount`\n     *last release*: Oct 23, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=5.0.0)\n\n     Plugin to count actual number of asserts in pytest\n\n  :pypi:`pytest-assertions`\n     *last release*: Apr 27, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest Assertions\n\n  :pypi:`pytest-assert-type`\n     *last release*: Oct 26, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=6.2.0\n\n     Use typing.assert_type() to test runtime behavior\n\n  :pypi:`pytest-assertutil`\n     *last release*: May 10, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest-assertutil\n\n  :pypi:`pytest-assert-utils`\n     *last release*: Apr 14, 2022,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Useful assertion utilities for use with pytest\n\n  :pypi:`pytest-assist`\n     *last release*: Oct 29, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     pytest plugin library\n\n  :pypi:`pytest-assume`\n     *last release*: Jun 24, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=2.7)\n\n     A pytest plugin that allows multiple failures per test\n\n  :pypi:`pytest-assurka`\n     *last release*: Aug 04, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin for Assurka Studio\n\n  :pypi:`pytest-ast-back-to-python`\n     *last release*: Sep 29, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A plugin for pytest devs to view how assertion rewriting recodes the AST\n\n  :pypi:`pytest-asteroid`\n     *last release*: Aug 15, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=6.2.5,<8.0.0)\n\n     PyTest plugin for docker-based testing on database images\n\n  :pypi:`pytest-astropy`\n     *last release*: Sep 26, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=4.6\n\n     Meta-package containing dependencies for testing\n\n  :pypi:`pytest-astropy-header`\n     *last release*: Sep 06, 2022,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=4.6)\n\n     pytest plugin to add diagnostic information to the header of the test output\n\n  :pypi:`pytest-ast-transformer`\n     *last release*: May 04, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest_async`\n     *last release*: Feb 26, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest-async - Run your coroutine in event loop without decorator\n\n  :pypi:`pytest-async-benchmark`\n     *last release*: May 28, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.3.5\n\n     pytest-async-benchmark: Modern pytest benchmarking for async code. 🚀\n\n  :pypi:`pytest-async-generators`\n     *last release*: Jul 05, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest fixtures for async generators\n\n  :pypi:`pytest-asyncio`\n     *last release*: Nov 10, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<10,>=8.2\n\n     Pytest support for asyncio\n\n  :pypi:`pytest-asyncio-concurrent`\n     *last release*: May 17, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     Pytest plugin to execute python async tests concurrently.\n\n  :pypi:`pytest-asyncio-cooperative`\n     *last release*: Jun 24, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Run all your asynchronous tests cooperatively.\n\n  :pypi:`pytest-asyncio-network-simulator`\n     *last release*: Jul 31, 2018,\n     *status*: 3 - Alpha,\n     *requires*: pytest (<3.7.0,>=3.3.2)\n\n     pytest-asyncio-network-simulator: Plugin for pytest for simulator the network in tests\n\n  :pypi:`pytest-async-mongodb`\n     *last release*: Oct 18, 2017,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.5.2)\n\n     pytest plugin for async MongoDB\n\n  :pypi:`pytest-async-sqlalchemy`\n     *last release*: Oct 07, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.0.0)\n\n     Database testing fixtures using the SQLAlchemy asyncio API\n\n  :pypi:`pytest-atf-allure`\n     *last release*: Nov 29, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.4.2,<8.0.0)\n\n     基于allure-pytest进行自定义\n\n  :pypi:`pytest-atomic`\n     *last release*: Nov 24, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Skip rest of tests if previous test failed.\n\n  :pypi:`pytest-atstack`\n     *last release*: Jan 02, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-attempt-summary`\n     *last release*: Jan 04, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     Enhanced Allure Attempt Summary for Playwright + Pytest\n\n  :pypi:`pytest-attrib`\n     *last release*: May 24, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest plugin to select tests based on attributes similar to the nose-attrib plugin\n\n  :pypi:`pytest-attributes`\n     *last release*: Jun 24, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A plugin that allows users to add attributes to their tests. These attributes can then be referenced by fixtures or the test itself.\n\n  :pypi:`pytest-audioeval`\n     *last release*: Mar 13, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.0\n\n     Pytest plugin for STT/TTS integration testing with httpx, metrics, and embedded audio samples.\n\n  :pypi:`pytest-austin`\n     *last release*: Oct 11, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Austin plugin for pytest\n\n  :pypi:`pytest-autocap`\n     *last release*: May 15, 2022,\n     *status*: N/A,\n     *requires*: pytest (<7.2,>=7.1.2)\n\n     automatically capture test & fixture stdout/stderr to files\n\n  :pypi:`pytest-autochecklog`\n     *last release*: Apr 25, 2015,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     automatically check condition and log all the checks\n\n  :pypi:`pytest-autofixture`\n     *last release*: Aug 01, 2024,\n     *status*: N/A,\n     *requires*: pytest>=8\n\n     simplify pytest fixtures\n\n  :pypi:`pytest-autofocus`\n     *last release*: Dec 02, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Auto-focus plugin: run only @pytest.mark.focus tests when --auto-focus is set\n\n  :pypi:`pytest-automation`\n     *last release*: Apr 24, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     pytest plugin for building a test suite, using YAML files to extend pytest parameterize functionality.\n\n  :pypi:`pytest-automock`\n     *last release*: May 16, 2023,\n     *status*: N/A,\n     *requires*: pytest ; extra == 'dev'\n\n     Pytest plugin for automatical mocks creation\n\n  :pypi:`pytest-auto-parametrize`\n     *last release*: Oct 02, 2016,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin: avoid repeating arguments in parametrize\n\n  :pypi:`pytest-autoprofile`\n     *last release*: Mar 13, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     \\`line_profiler.autoprofile\\`-ing your \\`pytest\\` test suite\n\n  :pypi:`pytest-autotest`\n     *last release*: Aug 25, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     This fixture provides a configured \"driver\" for Android Automated Testing, using uiautomator2.\n\n  :pypi:`pytest-aviator`\n     *last release*: Nov 04, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Aviator's Flakybot pytest plugin that automatically reruns flaky tests.\n\n  :pypi:`pytest-avoidance`\n     *last release*: May 23, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Makes pytest skip tests that don not need rerunning\n\n  :pypi:`pytest-awaiting-fix`\n     *last release*: Aug 09, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A simple plugin to use with pytest for traceability across Jira and disabled automated tests\n\n  :pypi:`pytest-aws`\n     *last release*: Oct 04, 2017,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest plugin for testing AWS resource configurations\n\n  :pypi:`pytest-aws-apigateway`\n     *last release*: May 24, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     pytest plugin for AWS ApiGateway\n\n  :pypi:`pytest-aws-config`\n     *last release*: May 28, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Protect your AWS credentials in unit tests\n\n  :pypi:`pytest-aws-fixtures`\n     *last release*: Nov 11, 2025,\n     *status*: N/A,\n     *requires*: pytest<10.0.0,>=8.0.0\n\n     A series of fixtures to use in integration tests involving actual AWS services.\n\n  :pypi:`pytest-aws-fixtures-293984`\n     *last release*: Dec 04, 2025,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     AWS configuration utilities for Python applications\n\n  :pypi:`pytest-axe`\n     *last release*: Nov 12, 2018,\n     *status*: N/A,\n     *requires*: pytest (>=3.0.0)\n\n     pytest plugin for axe-selenium-python\n\n  :pypi:`pytest-axe-playwright-snapshot`\n     *last release*: Jul 25, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin that runs Axe-core on Playwright pages and takes snapshots of the results.\n\n  :pypi:`pytest-azure`\n     *last release*: Jan 18, 2023,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Pytest utilities and mocks for Azure\n\n  :pypi:`pytest-azure-devops`\n     *last release*: Jul 16, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     Simplifies using azure devops parallel strategy (https://docs.microsoft.com/en-us/azure/devops/pipelines/test/parallel-testing-any-test-runner) with pytest.\n\n  :pypi:`pytest-azurepipelines`\n     *last release*: Oct 06, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=5.0.0)\n\n     Formatting PyTest output for Azure Pipelines UI\n\n  :pypi:`pytest-bandit`\n     *last release*: Feb 23, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A bandit plugin for pytest\n\n  :pypi:`pytest-bandit-xayon`\n     *last release*: Oct 17, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A bandit plugin for pytest\n\n  :pypi:`pytest-base-url`\n     *last release*: Jan 31, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     pytest plugin for URL based testing\n\n  :pypi:`pytest-bashdoctest`\n     *last release*: Oct 03, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin for testing bash command examples in markdown documentation\n\n  :pypi:`pytest-batch-regression`\n     *last release*: May 08, 2024,\n     *status*: N/A,\n     *requires*: pytest>=6.0.0\n\n     A pytest plugin to repeat the entire test suite in batches.\n\n  :pypi:`pytest-bazel`\n     *last release*: Oct 31, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A pytest runner with bazel support\n\n  :pypi:`pytest-bdd`\n     *last release*: Dec 05, 2024,\n     *status*: 6 - Mature,\n     *requires*: pytest>=7.0.0\n\n     BDD for pytest\n\n  :pypi:`pytest-bdd-html`\n     *last release*: Nov 22, 2022,\n     *status*: 3 - Alpha,\n     *requires*: pytest (!=6.0.0,>=5.0)\n\n     pytest plugin to display BDD info in HTML test report\n\n  :pypi:`pytest-bdd-md-report`\n     *last release*: Feb 07, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Markdown test report formatter for pytest-bdd with pytest-playwright screenshot support\n\n  :pypi:`pytest-bdd-ng`\n     *last release*: Nov 26, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=5.2\n\n     BDD for pytest\n\n  :pypi:`pytest-bdd-property`\n     *last release*: Mar 12, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8.0\n\n     Property-based testing plugin for pytest-bdd — express universal invariants in standard Gherkin, executed by Hypothesis\n\n  :pypi:`pytest-bdd-report`\n     *last release*: Dec 29, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.1.3\n\n     A pytest-bdd plugin for generating useful and informative BDD test reports\n\n  :pypi:`pytest-bdd-reporter`\n     *last release*: Oct 14, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.0.0\n\n     Enterprise-grade BDD test reporting with interactive dashboards, suite management, and comprehensive email integration\n\n  :pypi:`pytest-bdd-splinter`\n     *last release*: Aug 12, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=4.0.0)\n\n     Common steps for pytest bdd and splinter integration\n\n  :pypi:`pytest-bdd-web`\n     *last release*: Jan 02, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-bdd-wrappers`\n     *last release*: Feb 11, 2020,\n     *status*: 2 - Pre-Alpha,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-beakerlib`\n     *last release*: Mar 17, 2017,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A pytest plugin that reports test results to the BeakerLib framework\n\n  :pypi:`pytest-beartype`\n     *last release*: Oct 31, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin to run your tests with beartype checking enabled.\n\n  :pypi:`pytest-bec-e2e`\n     *last release*: Mar 13, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     BEC pytest plugin for end-to-end tests\n\n  :pypi:`pytest-beds`\n     *last release*: Jun 07, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Fixtures for testing Google Appengine (GAE) apps\n\n  :pypi:`pytest-beeprint`\n     *last release*: Jul 04, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     use icdiff for better error messages in pytest assertions\n\n  :pypi:`pytest-bench`\n     *last release*: Jul 21, 2014,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Benchmark utility that plugs into pytest.\n\n  :pypi:`pytest-benchmark`\n     *last release*: Nov 09, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.1\n\n     A \\`\\`pytest\\`\\` fixture for benchmarking code. It will group the tests into rounds that are calibrated to the chosen timer.\n\n  :pypi:`pytest-better-datadir`\n     *last release*: Mar 13, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     A small example package\n\n  :pypi:`pytest-better-parametrize`\n     *last release*: Mar 05, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest >=6.2.0\n\n     Better description of parametrized test cases\n\n  :pypi:`pytest-bg-process`\n     *last release*: Jan 24, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Pytest plugin to initialize background process\n\n  :pypi:`pytest-bigchaindb`\n     *last release*: Jan 24, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A BigchainDB plugin for pytest.\n\n  :pypi:`pytest-bigquery-mock`\n     *last release*: Dec 28, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=5.0)\n\n     Provides a mock fixture for python bigquery client\n\n  :pypi:`pytest-bisect-tests`\n     *last release*: Jun 09, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Find tests leaking state and affecting other\n\n  :pypi:`pytest-black`\n     *last release*: Dec 15, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin to enable format checking with black\n\n  :pypi:`pytest-black-multipy`\n     *last release*: Jan 14, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (!=3.7.3,>=3.5) ; extra == 'testing'\n\n     Allow '--black' on older Pythons\n\n  :pypi:`pytest-black-ng`\n     *last release*: Oct 20, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=7.0.0)\n\n     A pytest plugin to enable format checking with black\n\n  :pypi:`pytest-blame`\n     *last release*: May 04, 2019,\n     *status*: N/A,\n     *requires*: pytest (>=4.4.0)\n\n     A pytest plugin helps developers to debug by providing useful commits history.\n\n  :pypi:`pytest-blender`\n     *last release*: Jun 25, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Blender Pytest plugin.\n\n  :pypi:`pytest-blink1`\n     *last release*: Jan 07, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Pytest plugin to emit notifications via the Blink(1) RGB LED\n\n  :pypi:`pytest-blockage`\n     *last release*: Dec 21, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     Disable network requests during a test run.\n\n  :pypi:`pytest-blocker`\n     *last release*: Sep 07, 2015,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest plugin to mark a test as blocker and skip all other tests\n\n  :pypi:`pytest-b-logger`\n     *last release*: Dec 16, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     BLogger is a Pytest plugin for enhanced test logging and generating convenient and lightweight reports.\n\n  :pypi:`pytest-blue`\n     *last release*: Sep 05, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin that adds a \\`blue\\` fixture for printing stuff in blue.\n\n  :pypi:`pytest-board`\n     *last release*: Jan 20, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Local continuous test runner with pytest and watchdog.\n\n  :pypi:`pytest-boardfarm3`\n     *last release*: Sep 15, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Integrate boardfarm as a pytest plugin.\n\n  :pypi:`pytest-boilerplate`\n     *last release*: Sep 12, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=4.0.0\n\n     The pytest plugin for your Django Boilerplate.\n\n  :pypi:`pytest-bonsai`\n     *last release*: Apr 08, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6\n\n\n\n  :pypi:`pytest-boost-xml`\n     *last release*: Nov 30, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Plugin for pytest to generate boost xml reports\n\n  :pypi:`pytest-bootstrap`\n     *last release*: Mar 04, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-boto-mock`\n     *last release*: Jan 20, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.2.0\n\n     Thin-wrapper around the mock package for easier use with pytest\n\n  :pypi:`pytest-bpdb`\n     *last release*: Jan 19, 2015,\n     *status*: 2 - Pre-Alpha,\n     *requires*: N/A\n\n     A py.test plug-in to enable drop to bpdb debugger on test failure.\n\n  :pypi:`pytest-bq`\n     *last release*: May 08, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2\n\n     BigQuery fixtures and fixture factories for Pytest.\n\n  :pypi:`pytest-bravado`\n     *last release*: Feb 15, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest-bravado automatically generates from OpenAPI specification client fixtures.\n\n  :pypi:`pytest-breadcrumb`\n     *last release*: Mar 09, 2026,\n     *status*: 2 - Pre-Alpha,\n     *requires*: pytest>=8.0; extra == \"dev\"\n\n     Self-healing test framework for Playwright. Your tests survive app changes.\n\n  :pypi:`pytest-breakword`\n     *last release*: Aug 04, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=6.2.4,<7.0.0)\n\n     Use breakword with pytest\n\n  :pypi:`pytest-breed-adapter`\n     *last release*: Nov 07, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A simple plugin to connect with breed-server\n\n  :pypi:`pytest-briefcase`\n     *last release*: Jun 14, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A pytest plugin for running tests on a Briefcase project.\n\n  :pypi:`pytest-brightest`\n     *last release*: Jul 15, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8.4.1\n\n     Bright ideas for improving your pytest experience\n\n  :pypi:`pytest-broadcaster`\n     *last release*: Mar 02, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Pytest plugin to broadcast pytest output to various destinations\n\n  :pypi:`pytest-browser`\n     *last release*: Dec 10, 2016,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     A pytest plugin for console based browser test selection just after the collection phase\n\n  :pypi:`pytest-browsermob-proxy`\n     *last release*: Jun 11, 2013,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     BrowserMob proxy plugin for py.test.\n\n  :pypi:`pytest_browserstack`\n     *last release*: Jan 27, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Py.test plugin for BrowserStack\n\n  :pypi:`pytest-browserstack-local`\n     *last release*: Feb 09, 2018,\n     *status*: N/A,\n     *requires*: N/A\n\n     \\`\\`py.test\\`\\` plugin to run \\`\\`BrowserStackLocal\\`\\` in background.\n\n  :pypi:`pytest-budosystems`\n     *last release*: May 07, 2023,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Budo Systems is a martial arts school management system. This module is the Budo Systems Pytest Plugin.\n\n  :pypi:`pytest-bug`\n     *last release*: Dec 30, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=9.0.0\n\n     Pytest plugin for marking tests as a bug\n\n  :pypi:`pytest-bugtong-tag`\n     *last release*: Jan 16, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest-bugtong-tag is a plugin for pytest\n\n  :pypi:`pytest-bugzilla`\n     *last release*: May 05, 2010,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     py.test bugzilla integration plugin\n\n  :pypi:`pytest-bugzilla-notifier`\n     *last release*: Jun 15, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.9.2)\n\n     A plugin that allows you to execute create, update, and read information from BugZilla bugs\n\n  :pypi:`pytest-buildkite`\n     *last release*: Jul 13, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Plugin for pytest that automatically publishes coverage and pytest report annotations to Buildkite.\n\n  :pypi:`pytest-builtin-types`\n     *last release*: Nov 17, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-bwrap`\n     *last release*: Feb 25, 2024,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Run your tests in Bubblewrap sandboxes\n\n  :pypi:`pytest-cache`\n     *last release*: Jun 04, 2013,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin with mechanisms for caching across test runs\n\n  :pypi:`pytest-cache-assert`\n     *last release*: Aug 14, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=6.0.0)\n\n     Cache assertion data to simplify regression testing of complex serializable data\n\n  :pypi:`pytest-cagoule`\n     *last release*: Jan 01, 2020,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Pytest plugin to only run tests affected by changes\n\n  :pypi:`pytest-cairo`\n     *last release*: Apr 17, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest support for cairo-lang and starknet\n\n  :pypi:`pytest-call-checker`\n     *last release*: Oct 16, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=7.1.3,<8.0.0)\n\n     Small pytest utility to easily create test doubles\n\n  :pypi:`pytest-camel-collect`\n     *last release*: Aug 02, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=2.9)\n\n     Enable CamelCase-aware pytest class collection\n\n  :pypi:`pytest-canonical-data`\n     *last release*: May 08, 2020,\n     *status*: 2 - Pre-Alpha,\n     *requires*: pytest (>=3.5.0)\n\n     A plugin which allows to compare results with canonical results, based on previous runs\n\n  :pypi:`pytest-canvas`\n     *last release*: Jul 22, 2025,\n     *status*: N/A,\n     *requires*: pytest<9,>=8.4\n\n     A minimal pytest plugin that streamlines testing for projects using the Canvas SDK.\n\n  :pypi:`pytest-caprng`\n     *last release*: May 02, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A plugin that replays pRNG state on failure.\n\n  :pypi:`pytest-capsqlalchemy`\n     *last release*: Mar 19, 2025,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Pytest plugin to allow capturing SQLAlchemy queries.\n\n  :pypi:`pytest-capture-deprecatedwarnings`\n     *last release*: Apr 30, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin to capture all deprecatedwarnings and put them in one file\n\n  :pypi:`pytest-capture-warnings`\n     *last release*: May 03, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest plugin to capture all warnings and put them in one file of your choice\n\n  :pypi:`pytest-case`\n     *last release*: Nov 25, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.3.3\n\n     A clean, modern, wrapper for pytest.mark.parametrize\n\n  :pypi:`pytest-case-provider`\n     *last release*: Dec 15, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8\n\n     Advanced pytest parametrization plugin that generates test case instances from sync or async factories.\n\n  :pypi:`pytest-cases`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Separate test code from test cases in pytest.\n\n  :pypi:`pytest-case-start-from`\n     *last release*: Oct 28, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.0.0\n\n     A pytest plugin to start test execution from a specific test case\n\n  :pypi:`pytest-casewise-package-install`\n     *last release*: Oct 31, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=6.0.0\n\n     A pytest plugin for test case-level dynamic dependency management\n\n  :pypi:`pytest-cassandra`\n     *last release*: Nov 04, 2017,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     Cassandra CCM Test Fixtures for pytest\n\n  :pypi:`pytest-catchlog`\n     *last release*: Jan 24, 2016,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.6)\n\n     py.test plugin to catch log messages. This is a fork of pytest-capturelog.\n\n  :pypi:`pytest-catch-server`\n     *last release*: Dec 12, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest plugin with server for catching HTTP requests.\n\n  :pypi:`pytest-cdist`\n     *last release*: Jan 08, 2026,\n     *status*: N/A,\n     *requires*: pytest>=8\n\n     A pytest plugin to split your test suite into multiple parts\n\n  :pypi:`pytest-celery`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest plugin for Celery\n\n  :pypi:`pytest-celery-py37`\n     *last release*: May 23, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest plugin for Celery (compatible with python 3.7)\n\n  :pypi:`pytest-celery-utils`\n     *last release*: Jan 28, 2026,\n     *status*: N/A,\n     *requires*: pytest>=9.0.1\n\n     Pytest plugin for inspecting Celery task queues in Redis during tests\n\n  :pypi:`pytest-cfg-fetcher`\n     *last release*: Feb 26, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pass config options to your unit tests.\n\n  :pypi:`pytest-chainmaker`\n     *last release*: Oct 15, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin for chainmaker\n\n  :pypi:`pytest-chalice`\n     *last release*: Jul 01, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A set of py.test fixtures for AWS Chalice\n\n  :pypi:`pytest-change-assert`\n     *last release*: Oct 19, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     修改报错中文为英文\n\n  :pypi:`pytest-change-demo`\n     *last release*: Mar 02, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     turn . into √，turn F into x\n\n  :pypi:`pytest-change-report`\n     *last release*: Sep 14, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     turn . into √，turn F into x\n\n  :pypi:`pytest-change-xds`\n     *last release*: Apr 16, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     turn . into √，turn F into x\n\n  :pypi:`pytest-chdir`\n     *last release*: Jan 28, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=5.0.0,<6.0.0)\n\n     A pytest fixture for changing current working directory\n\n  :pypi:`pytest-check`\n     *last release*: Mar 05, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin that allows multiple failures per test.\n\n  :pypi:`pytest-checkdocs`\n     *last release*: Dec 26, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest!=8.1.*,>=6; extra == \"test\"\n\n     check the README when running tests\n\n  :pypi:`pytest-checkers`\n     *last release*: Dec 27, 2025,\n     *status*: N/A,\n     *requires*: pytest>=9.0.2\n\n     Pytest Plugin for dry-run checks LSPs, Type Checkers, Linters, and Formatters during testing\n\n  :pypi:`pytest-checkipdb`\n     *last release*: Dec 04, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=2.9.2\n\n     plugin to check if there are ipdb debugs left\n\n  :pypi:`pytest-check-library`\n     *last release*: Jul 17, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     check your missing library\n\n  :pypi:`pytest-check-libs`\n     *last release*: Jul 17, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     check your missing library\n\n  :pypi:`pytest-check-links`\n     *last release*: Jul 29, 2020,\n     *status*: N/A,\n     *requires*: pytest<9,>=7.0\n\n     Check links in files\n\n  :pypi:`pytest-checklist`\n     *last release*: May 23, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin to track and report unit/function coverage.\n\n  :pypi:`pytest-check-mk`\n     *last release*: Nov 19, 2015,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     pytest plugin to test Check_MK checks\n\n  :pypi:`pytest-checkpoint`\n     *last release*: Oct 04, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.0.0\n\n     Restore a checkpoint in pytest\n\n  :pypi:`pytest-ch-framework`\n     *last release*: Apr 17, 2024,\n     *status*: N/A,\n     *requires*: pytest==8.0.1\n\n     My pytest framework\n\n  :pypi:`pytest-chic-report`\n     *last release*: Nov 01, 2024,\n     *status*: N/A,\n     *requires*: pytest>=6.0\n\n     Simple pytest plugin for generating and sending report to messengers.\n\n  :pypi:`pytest-chinesereport`\n     *last release*: Apr 16, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n\n\n  :pypi:`pytest-choose`\n     *last release*: Feb 04, 2024,\n     *status*: N/A,\n     *requires*: pytest >=7.0.0\n\n     Provide the pytest with the ability to collect use cases based on rules in text files\n\n  :pypi:`pytest-chronicle`\n     *last release*: Dec 15, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.0; extra == \"dev\"\n\n     Reusable pytest results ingestion tooling with database export and CLI helpers.\n\n  :pypi:`pytest-chunks`\n     *last release*: Jul 05, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=6.0.0)\n\n     Run only a chunk of your test suite\n\n  :pypi:`pytest_cid`\n     *last release*: Sep 01, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest >= 5.0, < 7.0\n\n     Compare data structures containing matching CIDs of different versions and encoding\n\n  :pypi:`pytest-circleci`\n     *last release*: May 03, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     py.test plugin for CircleCI\n\n  :pypi:`pytest-circleci-parallelized`\n     *last release*: Oct 20, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Parallelize pytest across CircleCI workers.\n\n  :pypi:`pytest-circleci-parallelized-rjp`\n     *last release*: Jun 21, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     Parallelize pytest across CircleCI workers.\n\n  :pypi:`pytest-ckan`\n     *last release*: Apr 28, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Backport of CKAN 2.9 pytest plugin and fixtures to CAKN 2.8\n\n  :pypi:`pytest-clab`\n     *last release*: Mar 02, 2026,\n     *status*: N/A,\n     *requires*: pytest>=9.0.2\n\n     A pytest plugin for managing containerlab topologies in tests.\n\n  :pypi:`pytest-clarity`\n     *last release*: Jun 11, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     A plugin providing an alternative, colourful diff output for failing assertions.\n\n  :pypi:`pytest-class-fixtures`\n     *last release*: Nov 15, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.3.3\n\n     Class as PyTest fixtures (and BDD steps)\n\n  :pypi:`pytest-claude-agent-sdk`\n     *last release*: Jan 19, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=6.0\n\n     Use Claude Code in your pytests, or pytest your own Claude Code agents — or both\n\n  :pypi:`pytest-cldf`\n     *last release*: Nov 07, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=3.6)\n\n     Easy quality control for CLDF datasets using pytest\n\n  :pypi:`pytest-clean-database`\n     *last release*: Mar 14, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest<9,>=7.0\n\n     A pytest plugin that cleans your database up after every test.\n\n  :pypi:`pytest-cleanslate`\n     *last release*: Apr 10, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Collects and executes pytest tests separately\n\n  :pypi:`pytest_cleanup`\n     *last release*: Jan 28, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     Automated, comprehensive and well-organised pytest test cases.\n\n  :pypi:`pytest-cleanuptotal`\n     *last release*: Jul 22, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A cleanup plugin for pytest\n\n  :pypi:`pytest-clerk`\n     *last release*: Feb 04, 2026,\n     *status*: N/A,\n     *requires*: pytest<10.0.0,>=8.0.0\n\n     A set of pytest fixtures to help with integration testing with Clerk.\n\n  :pypi:`pytest-clerk-mock`\n     *last release*: Mar 14, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin for mocking Clerk authentication\n\n  :pypi:`pytest-cli2-ansible`\n     *last release*: Mar 05, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-click`\n     *last release*: Feb 11, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=5.0)\n\n     Pytest plugin for Click\n\n  :pypi:`pytest-cli-fixtures`\n     *last release*: Jul 28, 2022,\n     *status*: N/A,\n     *requires*: pytest (~=7.0)\n\n     Automatically register fixtures for custom CLI arguments\n\n  :pypi:`pytest-clld`\n     *last release*: Oct 23, 2024,\n     *status*: N/A,\n     *requires*: pytest>=3.9\n\n\n\n  :pypi:`pytest-cloud`\n     *last release*: Oct 05, 2020,\n     *status*: 6 - Mature,\n     *requires*: N/A\n\n     Distributed tests planner plugin for pytest testing framework.\n\n  :pypi:`pytest-cloudflare-worker`\n     *last release*: Mar 30, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.0.0)\n\n     pytest plugin for testing cloudflare workers\n\n  :pypi:`pytest-cloudist`\n     *last release*: Sep 02, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=7.1.2,<8.0.0)\n\n     Distribute tests to cloud machines without fuss\n\n  :pypi:`pytest-cmake`\n     *last release*: Jan 03, 2026,\n     *status*: N/A,\n     *requires*: pytest<10,>=4\n\n     Provide CMake module for Pytest\n\n  :pypi:`pytest-cmake-presets`\n     *last release*: Dec 26, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.2.0,<8.0.0)\n\n     Execute CMake Presets via pytest\n\n  :pypi:`pytest-cmdline-add-args`\n     *last release*: Sep 01, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin for custom argument handling and Allure reporting. This plugin allows you to add arguments before running a test.\n\n  :pypi:`pytest-cobra`\n     *last release*: Jun 29, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest (<4.0.0,>=3.7.1)\n\n     PyTest plugin for testing Smart Contracts for Ethereum blockchain.\n\n  :pypi:`pytest-cocotb`\n     *last release*: Nov 09, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest plugin that enables using pytest as the regression manager for running cocotb tests.\n\n  :pypi:`pytest-cocotb-cov`\n     *last release*: Nov 09, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest plugin for measuring HDL coverage.\n\n  :pypi:`pytest-cocotb-fusesoc`\n     *last release*: Jan 07, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest plugin to integrate FuseSoC with Cocotb.\n\n  :pypi:`pytest-cocotb-pyuvm`\n     *last release*: Nov 09, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest plugin that enables using pytest as the regression manager for running pyuvm tests.\n\n  :pypi:`pytest-codeblock`\n     *last release*: Mar 07, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest plugin to collect and test code blocks in reStructuredText and Markdown files.\n\n  :pypi:`pytest_codeblocks`\n     *last release*: Sep 17, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >= 7.0.0\n\n     Test code blocks in your READMEs\n\n  :pypi:`pytest-codecarbon`\n     *last release*: Jun 15, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin for measuring carbon emissions\n\n  :pypi:`pytest-codecheckers`\n     *last release*: Feb 13, 2010,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin to add source code sanity checks (pep8 and friends)\n\n  :pypi:`pytest-codecov`\n     *last release*: Mar 25, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=4.6.0\n\n     Pytest plugin for uploading pytest-cov results to codecov.io\n\n  :pypi:`pytest-codegen`\n     *last release*: Aug 23, 2020,\n     *status*: 2 - Pre-Alpha,\n     *requires*: N/A\n\n     Automatically create pytest test signatures\n\n  :pypi:`pytest-codeowners`\n     *last release*: Mar 30, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.0.0)\n\n     Pytest plugin for selecting tests by GitHub CODEOWNERS.\n\n  :pypi:`pytest-codestyle`\n     *last release*: Mar 23, 2020,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin to run pycodestyle\n\n  :pypi:`pytest-codingagents`\n     *last release*: Feb 20, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=9.0\n\n     Pytest plugin for testing real coding agents via their SDK\n\n  :pypi:`pytest-codspeed`\n     *last release*: Feb 09, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=3.8\n\n     Pytest plugin to create CodSpeed benchmarks\n\n  :pypi:`pytest-collect-appoint-info`\n     *last release*: Aug 03, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     set your encoding\n\n  :pypi:`pytest-collect-formatter`\n     *last release*: Mar 29, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Formatter for pytest collect output\n\n  :pypi:`pytest-collect-formatter2`\n     *last release*: May 31, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Formatter for pytest collect output\n\n  :pypi:`pytest-collect-interface-info-plugin`\n     *last release*: Sep 25, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Get executed interface information in pytest interface automation framework\n\n  :pypi:`pytest-collect-markers`\n     *last release*: Jan 24, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin to collect and output test markers to JSON\n\n  :pypi:`pytest-collector`\n     *last release*: Aug 02, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.0,<8.0)\n\n     Python package for collecting pytest.\n\n  :pypi:`pytest-collect-pytest-interinfo`\n     *last release*: Sep 26, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-collect-requirements`\n     *last release*: Feb 07, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=9.0.1\n\n     A pytest plugin to collect test requirements from requirements marker.\n\n  :pypi:`pytest-colordots`\n     *last release*: Oct 06, 2017,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Colorizes the progress indicators\n\n  :pypi:`pytest-comfyui`\n     *last release*: Jan 09, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Integration testing framework for ComfyUI nodes and workflows.\n\n  :pypi:`pytest-commander`\n     *last release*: Aug 17, 2021,\n     *status*: N/A,\n     *requires*: pytest (<7.0.0,>=6.2.4)\n\n     An interactive GUI test runner for PyTest\n\n  :pypi:`pytest-common-subject`\n     *last release*: Oct 22, 2025,\n     *status*: N/A,\n     *requires*: pytest<9,>=3.6\n\n     pytest framework for testing different aspects of a common method\n\n  :pypi:`pytest-compare`\n     *last release*: Jun 22, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin for comparing call arguments.\n\n  :pypi:`pytest-concurrent`\n     *last release*: Jan 12, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.1.1)\n\n     Concurrently execute test cases with multithread, multiprocess and gevent\n\n  :pypi:`pytest-conductor`\n     *last release*: Jul 30, 2025,\n     *status*: N/A,\n     *requires*: pytest<8.4; python_version == \"3.8\"\n\n     Pytest plugin for coordinating the order in which marked tests run.\n\n  :pypi:`pytest-config`\n     *last release*: Nov 07, 2014,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Base configurations and utilities for developing    your Python project test suite with pytest.\n\n  :pypi:`pytest-confluence-report`\n     *last release*: Apr 17, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Package stands for pytest plugin to upload results into Confluence page.\n\n  :pypi:`pytest-console-scripts`\n     *last release*: May 31, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.0.0)\n\n     Pytest plugin for testing console scripts\n\n  :pypi:`pytest-consul`\n     *last release*: Nov 24, 2018,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     pytest plugin with fixtures for testing consul aware apps\n\n  :pypi:`pytest-container`\n     *last release*: Jun 30, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.10\n\n     Pytest fixtures for writing container based tests\n\n  :pypi:`pytest-contextfixture`\n     *last release*: Mar 12, 2013,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Define pytest fixtures as context managers.\n\n  :pypi:`pytest-contexts`\n     *last release*: May 19, 2021,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A plugin to run tests written with the Contexts framework using pytest\n\n  :pypi:`pytest-continuous`\n     *last release*: Apr 23, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin to run tests continuously until failure or interruption.\n\n  :pypi:`pytest-cookies`\n     *last release*: Mar 22, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.9.0)\n\n     The pytest plugin for your Cookiecutter templates. 🍪\n\n  :pypi:`pytest-copie`\n     *last release*: Sep 29, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     The pytest plugin for your copier templates 📒\n\n  :pypi:`pytest-copier`\n     *last release*: Dec 11, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.3.2\n\n     A pytest plugin to help testing Copier templates\n\n  :pypi:`pytest-couchdbkit`\n     *last release*: Apr 17, 2012,\n     *status*: N/A,\n     *requires*: N/A\n\n     py.test extension for per-test couchdb databases using couchdbkit\n\n  :pypi:`pytest-count`\n     *last release*: Jan 12, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     count erros and send email\n\n  :pypi:`pytest-cov`\n     *last release*: Sep 09, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7\n\n     Pytest plugin for measuring coverage.\n\n  :pypi:`pytest-cover`\n     *last release*: Aug 01, 2015,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest plugin for measuring coverage. Forked from \\`pytest-cov\\`.\n\n  :pypi:`pytest-coverage`\n     *last release*: Jun 17, 2015,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-coverage-context`\n     *last release*: Jun 28, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Coverage dynamic context support for PyTest, including sub-processes\n\n  :pypi:`pytest-coverage-impact`\n     *last release*: Jan 16, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     Sensoria: High-fidelity coverage impact analysis for Python.\n\n  :pypi:`pytest-coveragemarkers`\n     *last release*: May 15, 2025,\n     *status*: N/A,\n     *requires*: pytest<8.0.0,>=7.1.2\n\n     Using pytest markers to track functional coverage and filtering of tests\n\n  :pypi:`pytest-cov-exclude`\n     *last release*: Apr 29, 2016,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.8.0,<2.9.0); extra == 'dev'\n\n     Pytest plugin for excluding tests based on coverage data\n\n  :pypi:`pytest_covid`\n     *last release*: Jun 24, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     Too many faillure, less tests.\n\n  :pypi:`pytest-cpp`\n     *last release*: Sep 18, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Use pytest's runner to discover and execute C++ tests\n\n  :pypi:`pytest-cqase`\n     *last release*: Aug 22, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.1.2,<8.0.0)\n\n     Custom qase pytest plugin\n\n  :pypi:`pytest-cram`\n     *last release*: Aug 08, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     Run cram tests with pytest.\n\n  :pypi:`pytest-crap`\n     *last release*: Dec 02, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     pytest plugin that calculates CRAP scores to guide test writing\n\n  :pypi:`pytest-crate`\n     *last release*: May 28, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=4.0)\n\n     Manages CrateDB instances during your integration tests\n\n  :pypi:`pytest-cratedb`\n     *last release*: Jan 05, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest<10\n\n     Manage CrateDB instances for integration tests\n\n  :pypi:`pytest-cratedb-reporter`\n     *last release*: Mar 11, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.0.0\n\n     A pytest plugin for reporting test results to CrateDB\n\n  :pypi:`pytest-crayons`\n     *last release*: Oct 14, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A pytest plugin for colorful print statements\n\n  :pypi:`pytest-cream`\n     *last release*: Oct 26, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     The cream of test execution - smooth pytest workflows with intelligent orchestration\n\n  :pypi:`pytest-create`\n     *last release*: Feb 15, 2023,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     pytest-create\n\n  :pypi:`pytest-cricri`\n     *last release*: Jan 27, 2018,\n     *status*: N/A,\n     *requires*: pytest\n\n     A Cricri plugin for pytest.\n\n  :pypi:`pytest-crontab`\n     *last release*: Dec 09, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     add crontab task in crontab\n\n  :pypi:`pytest-csv`\n     *last release*: Apr 22, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=6.0)\n\n     CSV output for pytest.\n\n  :pypi:`pytest-csv-params`\n     *last release*: May 29, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<9,>=8.3\n\n     Pytest plugin for Test Case Parametrization with CSV files\n\n  :pypi:`pytest-culprit`\n     *last release*: May 15, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Find the last Git commit where a pytest test started failing\n\n  :pypi:`pytest-curio`\n     *last release*: Oct 06, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest support for curio.\n\n  :pypi:`pytest-curl-report`\n     *last release*: Dec 11, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest plugin to generate curl command line report\n\n  :pypi:`pytest-custom-concurrency`\n     *last release*: Feb 08, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Custom grouping concurrence for pytest\n\n  :pypi:`pytest-custom-exit-code`\n     *last release*: Aug 07, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.0.2)\n\n     Exit pytest test session with custom exit code in different scenarios\n\n  :pypi:`pytest-custom-nodeid`\n     *last release*: Mar 07, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Custom grouping for pytest-xdist, rename test cases name and test cases nodeid, support allure report\n\n  :pypi:`pytest-custom-outputs`\n     *last release*: Jul 10, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A plugin that allows users to create and use custom outputs instead of the standard Pass and Fail. Also allows users to retrieve test results in fixtures.\n\n  :pypi:`pytest-custom-report`\n     *last release*: Jan 30, 2019,\n     *status*: N/A,\n     *requires*: pytest\n\n     Configure the symbols displayed for test outcomes\n\n  :pypi:`pytest-custom-scheduling`\n     *last release*: Mar 01, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Custom grouping for pytest-xdist, rename test cases name and test cases nodeid, support allure report\n\n  :pypi:`pytest-custom-timeout`\n     *last release*: Jan 08, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.0.0\n\n     Use custom logic when a test times out. Based on pytest-timeout.\n\n  :pypi:`pytest-cython`\n     *last release*: Mar 11, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8\n\n     A plugin for testing Cython extension modules.\n\n  :pypi:`pytest-cython-collect`\n     *last release*: Jun 17, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-darker`\n     *last release*: Feb 25, 2024,\n     *status*: N/A,\n     *requires*: pytest <7,>=6.0.1\n\n     A pytest plugin for checking of modified code using Darker\n\n  :pypi:`pytest-dash`\n     *last release*: Mar 18, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest fixtures to run dash applications.\n\n  :pypi:`pytest-dashboard`\n     *last release*: Jun 02, 2025,\n     *status*: N/A,\n     *requires*: pytest<8.0.0,>=7.4.3\n\n\n\n  :pypi:`pytest-data`\n     *last release*: Nov 01, 2016,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Useful functions for managing data for pytest fixtures\n\n  :pypi:`pytest-databases`\n     *last release*: Mar 10, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Reusable database fixtures for any and all databases.\n\n  :pypi:`pytest-databricks`\n     *last release*: Jul 29, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin for remote Databricks notebooks testing\n\n  :pypi:`pytest-datadir`\n     *last release*: Jul 30, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0\n\n     pytest plugin for test data directories and files\n\n  :pypi:`pytest-datadir-mgr`\n     *last release*: Apr 06, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=7.1)\n\n     Manager for test data: downloads, artifact caching, and a tmpdir context.\n\n  :pypi:`pytest-datadir-ng`\n     *last release*: Dec 25, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Fixtures for pytest allowing test functions/methods to easily retrieve test resources from the local filesystem.\n\n  :pypi:`pytest-datadir-nng`\n     *last release*: Nov 09, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=7.0.0,<8.0.0)\n\n     Fixtures for pytest allowing test functions/methods to easily retrieve test resources from the local filesystem.\n\n  :pypi:`pytest-data-extractor`\n     *last release*: Jul 19, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.0.1)\n\n     A pytest plugin to extract relevant metadata about tests into an external file (currently only json support)\n\n  :pypi:`pytest-data-file`\n     *last release*: Dec 04, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Fixture \"data\" and \"case_data\" for test from yaml file\n\n  :pypi:`pytest-datafiles`\n     *last release*: Jan 04, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2.0\n\n     py.test plugin to create a 'tmp_path' containing predefined files/directories.\n\n  :pypi:`pytest-datafixtures`\n     *last release*: May 15, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Data fixtures for pytest made simple.\n\n  :pypi:`pytest-data-from-files`\n     *last release*: Oct 13, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     pytest plugin to provide data from files loaded automatically\n\n  :pypi:`pytest-dataguard`\n     *last release*: Oct 08, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.4.2\n\n     Data validation and integrity testing for your datasets using pytest.\n\n  :pypi:`pytest-data-loader`\n     *last release*: Feb 21, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest<10,>=7.0.0\n\n     Pytest plugin for loading test data for data-driven testing (DDT)\n\n  :pypi:`pytest-dataplugin`\n     *last release*: Sep 16, 2017,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     A pytest plugin for managing an archive of test data.\n\n  :pypi:`pytest-datarecorder`\n     *last release*: Jul 31, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A py.test plugin recording and comparing test output.\n\n  :pypi:`pytest-dataset`\n     *last release*: Sep 01, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Plugin for loading different datasets for pytest by prefix from json or yaml files\n\n  :pypi:`pytest-data-suites`\n     *last release*: Apr 06, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0,>=6.0\n\n     Class-based pytest parametrization\n\n  :pypi:`pytest-datatest`\n     *last release*: Oct 15, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.3)\n\n     A pytest plugin for test driven data-wrangling (this is the development version of datatest's pytest integration).\n\n  :pypi:`pytest-db`\n     *last release*: Nov 11, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Session scope fixture \"db\" for mysql query or change\n\n  :pypi:`pytest-dbfixtures`\n     *last release*: Dec 07, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Databases fixtures plugin for py.test.\n\n  :pypi:`pytest-db-plugin`\n     *last release*: Nov 27, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=5.0)\n\n\n\n  :pypi:`pytest-dbt`\n     *last release*: Jun 08, 2023,\n     *status*: 2 - Pre-Alpha,\n     *requires*: pytest (>=7.0.0,<8.0.0)\n\n     Unit test dbt models with standard python tooling\n\n  :pypi:`pytest-dbt-adapter`\n     *last release*: Nov 24, 2021,\n     *status*: N/A,\n     *requires*: pytest (<7,>=6)\n\n     A pytest plugin for testing dbt adapter plugins\n\n  :pypi:`pytest-dbt-conventions`\n     *last release*: Mar 02, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=6.2.5,<7.0.0)\n\n     A pytest plugin for linting a dbt project's conventions\n\n  :pypi:`pytest-dbt-core`\n     *last release*: Jun 04, 2024,\n     *status*: N/A,\n     *requires*: pytest>=6.2.5; extra == \"test\"\n\n     Pytest extension for dbt.\n\n  :pypi:`pytest-dbt-duckdb`\n     *last release*: Mar 06, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.3.4\n\n     Fearless testing for dbt models, powered by DuckDB.\n\n  :pypi:`pytest-dbt-postgres`\n     *last release*: Sep 03, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.3.2\n\n     Pytest tooling to unittest DBT & Postgres models\n\n  :pypi:`pytest-dbus-notification`\n     *last release*: Mar 05, 2014,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     D-BUS notifications for pytest results.\n\n  :pypi:`pytest-dbx`\n     *last release*: Nov 29, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.1.3,<8.0.0)\n\n     Pytest plugin to run unit tests for dbx (Databricks CLI extensions) related code\n\n  :pypi:`pytest-dc`\n     *last release*: Aug 16, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=3.3\n\n     Manages Docker containers during your integration tests\n\n  :pypi:`pytest-deadfixtures`\n     *last release*: Jan 15, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     A simple plugin to list unused fixtures in pytest\n\n  :pypi:`pytest-deduplicate`\n     *last release*: Aug 12, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Identifies duplicate unit tests\n\n  :pypi:`pytest-deepassert`\n     *last release*: Nov 04, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin for enhanced assertion reporting with detailed diffs\n\n  :pypi:`pytest-deepcov`\n     *last release*: Mar 30, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     deepcov\n\n  :pypi:`pytest_defer`\n     *last release*: Nov 13, 2024,\n     *status*: N/A,\n     *requires*: pytest>=8.3\n\n     A 'defer' fixture for pytest\n\n  :pypi:`pytest-delta`\n     *last release*: Feb 12, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest<10.0.0,>=9.0.2\n\n     Run only tests impacted by your code changes (delta-based selection) for pytest.\n\n  :pypi:`pytest-demo-plugin`\n     *last release*: May 15, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest示例插件\n\n  :pypi:`pytest-dependency`\n     *last release*: Feb 15, 2026,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Manage dependencies of tests\n\n  :pypi:`pytest-depends`\n     *last release*: Apr 05, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3)\n\n     Tests that depend on other tests\n\n  :pypi:`pytest-depends-on`\n     *last release*: Feb 07, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=9.0.1\n\n     A Python package for managing test dependencies in pytest.\n\n  :pypi:`pytest-depper`\n     *last release*: Oct 23, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Smart test selection based on AST-level code dependency analysis\n\n  :pypi:`pytest-deprecate`\n     *last release*: Jul 01, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Mark tests as testing a deprecated feature with a warning note.\n\n  :pypi:`pytest-deprecator`\n     *last release*: Dec 02, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-describe`\n     *last release*: Dec 12, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<10,>=6\n\n     Describe-style plugin for pytest\n\n  :pypi:`pytest-describe-beautifully`\n     *last release*: Jan 28, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     Beautiful terminal and HTML output for pytest-describe.\n\n  :pypi:`pytest-describe-it`\n     *last release*: Jul 19, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     plugin for rich text descriptions\n\n  :pypi:`pytest-deselect-if`\n     *last release*: Dec 26, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A plugin to deselect pytests tests rather than using skipif\n\n  :pypi:`pytest-devpi-server`\n     *last release*: Oct 17, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     DevPI server fixture for py.test\n\n  :pypi:`pytest-devtools`\n     *last release*: Feb 10, 2026,\n     *status*: N/A,\n     *requires*: pytest>=9.0.2\n\n     Pytest plugin providing debug fixtures, ANSI-stripped capsys, whitespace-visible assertions, and terminal column management.\n\n  :pypi:`pytest-dfm`\n     *last release*: Nov 23, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest-dfm provides a pytest integration for DV Flow Manager, a build system for silicon design\n\n  :pypi:`pytest-dhos`\n     *last release*: Sep 07, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Common fixtures for pytest in DHOS services and libraries\n\n  :pypi:`pytest-diamond`\n     *last release*: Aug 31, 2015,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest plugin for diamond\n\n  :pypi:`pytest-dicom`\n     *last release*: Dec 19, 2018,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     pytest plugin to provide DICOM fixtures\n\n  :pypi:`pytest-dictsdiff`\n     *last release*: Jul 26, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-diff`\n     *last release*: Mar 30, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-diff-selector`\n     *last release*: Feb 24, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.2.2) ; extra == 'all'\n\n     Get tests affected by code changes (using git)\n\n  :pypi:`pytest-difftest`\n     *last release*: Feb 23, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     Blazingly fast test selection for pytest - only run tests affected by your changes (Rust-powered)\n\n  :pypi:`pytest-difido`\n     *last release*: Oct 23, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.0.0)\n\n     PyTest plugin for generating Difido reports\n\n  :pypi:`pytest-directives`\n     *last release*: Aug 11, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Control your tests flow\n\n  :pypi:`pytest-dir-equal`\n     *last release*: Dec 11, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.3.2\n\n     pytest-dir-equals is a pytest plugin providing helpers to assert directories equality allowing golden testing\n\n  :pypi:`pytest-dirty`\n     *last release*: Jun 08, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8.2; extra == \"dev\"\n\n     Static import analysis for thrifty testing.\n\n  :pypi:`pytest-disable`\n     *last release*: Sep 10, 2015,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest plugin to disable a test and skip it from testrun\n\n  :pypi:`pytest-disable-plugin`\n     *last release*: Feb 28, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Disable plugins per test\n\n  :pypi:`pytest-discord`\n     *last release*: May 11, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest!=6.0.0,<9,>=3.3.2\n\n     A pytest plugin to notify test results to a Discord channel.\n\n  :pypi:`pytest-discover`\n     *last release*: Mar 26, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin to record discovered tests in a file\n\n  :pypi:`pytest-ditto`\n     *last release*: Jun 09, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     Snapshot testing pytest plugin with minimal ceremony and flexible persistence formats.\n\n  :pypi:`pytest-ditto-pandas`\n     *last release*: May 29, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     pytest-ditto plugin for pandas snapshots.\n\n  :pypi:`pytest-ditto-pyarrow`\n     *last release*: Jun 09, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     pytest-ditto plugin for pyarrow tables.\n\n  :pypi:`pytest-django`\n     *last release*: Feb 14, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     A Django plugin for pytest.\n\n  :pypi:`pytest-django-ahead`\n     *last release*: Oct 27, 2016,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.9)\n\n     A Django plugin for pytest.\n\n  :pypi:`pytest-djangoapp`\n     *last release*: Dec 13, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Nice pytest plugin to help you with Django pluggable application testing.\n\n  :pypi:`pytest-django-cache-xdist`\n     *last release*: May 12, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A djangocachexdist plugin for pytest\n\n  :pypi:`pytest-django-casperjs`\n     *last release*: Mar 15, 2015,\n     *status*: 2 - Pre-Alpha,\n     *requires*: N/A\n\n     Integrate CasperJS with your django tests as a pytest fixture.\n\n  :pypi:`pytest-django-class`\n     *last release*: Aug 08, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pytest plugin for running django in class-scoped fixtures\n\n  :pypi:`pytest-django-docker-pg`\n     *last release*: Jun 13, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<9.0.0,>=7.0.0\n\n\n\n  :pypi:`pytest-django-dotenv`\n     *last release*: Nov 26, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.6.0)\n\n     Pytest plugin used to setup environment variables with django-dotenv\n\n  :pypi:`pytest-django-factories`\n     *last release*: Nov 12, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Factories for your Django models that can be used as Pytest fixtures.\n\n  :pypi:`pytest-django-filefield`\n     *last release*: May 09, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >= 5.2\n\n     Replaces FileField.storage with something you can patch globally.\n\n  :pypi:`pytest-django-gcir`\n     *last release*: Mar 06, 2018,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A Django plugin for pytest.\n\n  :pypi:`pytest-django-haystack`\n     *last release*: Sep 03, 2017,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.3.4)\n\n     Cleanup your Haystack indexes between tests\n\n  :pypi:`pytest-django-ifactory`\n     *last release*: Apr 30, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A model instance factory for pytest-django\n\n  :pypi:`pytest-django-lite`\n     *last release*: Jan 30, 2014,\n     *status*: N/A,\n     *requires*: N/A\n\n     The bare minimum to integrate py.test with Django.\n\n  :pypi:`pytest-django-liveserver-ssl`\n     *last release*: Jan 09, 2025,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-django-model`\n     *last release*: Feb 14, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A Simple Way to Test your Django Models\n\n  :pypi:`pytest-django-ordering`\n     *last release*: Jul 25, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.3.0)\n\n     A pytest plugin for preserving the order in which Django runs tests.\n\n  :pypi:`pytest-django-queries`\n     *last release*: Mar 01, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.2.0\n\n     Generate performance reports from your django database performance tests.\n\n  :pypi:`pytest-djangorestframework`\n     *last release*: Aug 11, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A djangorestframework plugin for pytest\n\n  :pypi:`pytest-django-rq`\n     *last release*: Apr 13, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pytest plugin to help writing unit test for django-rq\n\n  :pypi:`pytest-django-sqlcounts`\n     *last release*: Jun 16, 2015,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     py.test plugin for reporting the number of SQLs executed per django testcase.\n\n  :pypi:`pytest-django-testing-postgresql`\n     *last release*: Jan 31, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Use a temporary PostgreSQL database with pytest-django\n\n  :pypi:`pytest-doc`\n     *last release*: Jun 28, 2015,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A documentation plugin for py.test.\n\n  :pypi:`pytest-docfiles`\n     *last release*: Dec 22, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.7.0)\n\n     pytest plugin to test codeblocks in your documentation.\n\n  :pypi:`pytest-docgen`\n     *last release*: Apr 17, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     An RST Documentation Generator for pytest-based test suites\n\n  :pypi:`pytest-docker`\n     *last release*: Nov 12, 2025,\n     *status*: N/A,\n     *requires*: pytest<10.0,>=4.0\n\n     Simple pytest fixtures for Docker and Docker Compose based tests\n\n  :pypi:`pytest-docker-apache-fixtures`\n     *last release*: Aug 12, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest fixtures for testing with apache2 (httpd).\n\n  :pypi:`pytest-docker-butla`\n     *last release*: Jun 16, 2019,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-dockerc`\n     *last release*: Oct 09, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.0)\n\n     Run, manage and stop Docker Compose project from Docker API\n\n  :pypi:`pytest-docker-compose`\n     *last release*: Jan 26, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.3)\n\n     Manages Docker containers during your integration tests\n\n  :pypi:`pytest-docker-compose-v2`\n     *last release*: Dec 17, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest<10,>=7.2.2\n\n     Manages Docker containers during your integration tests\n\n  :pypi:`pytest-docker-db`\n     *last release*: Mar 20, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.1.1)\n\n     A plugin to use docker databases for pytests\n\n  :pypi:`pytest-docker-fixtures`\n     *last release*: Dec 01, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     pytest docker fixtures\n\n  :pypi:`pytest-docker-git-fixtures`\n     *last release*: Aug 12, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest fixtures for testing with git scm.\n\n  :pypi:`pytest-docker-haproxy-fixtures`\n     *last release*: Aug 12, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest fixtures for testing with haproxy.\n\n  :pypi:`pytest-docker-pexpect`\n     *last release*: Jan 14, 2019,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest plugin for writing functional tests with pexpect and docker\n\n  :pypi:`pytest-docker-postgresql`\n     *last release*: Sep 24, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-docker-py`\n     *last release*: Nov 27, 2018,\n     *status*: N/A,\n     *requires*: pytest (==4.0.0)\n\n     Easy to use, simple to extend, pytest plugin that minimally leverages docker-py.\n\n  :pypi:`pytest-docker-registry-fixtures`\n     *last release*: Aug 12, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest fixtures for testing with docker registries.\n\n  :pypi:`pytest-docker-service`\n     *last release*: Jan 03, 2024,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=7.1.3)\n\n     pytest plugin to start docker container\n\n  :pypi:`pytest-docker-squid-fixtures`\n     *last release*: Aug 12, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest fixtures for testing with squid.\n\n  :pypi:`pytest-docker-tools`\n     *last release*: Mar 16, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.0.1\n\n     Docker integration tests for pytest\n\n  :pypi:`pytest-docs`\n     *last release*: Nov 11, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Documentation tool for pytest\n\n  :pypi:`pytest-docstyle`\n     *last release*: Mar 23, 2020,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin to run pydocstyle\n\n  :pypi:`pytest-doctest-custom`\n     *last release*: Jul 25, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A py.test plugin for customizing string representations of doctest results.\n\n  :pypi:`pytest-doctest-ellipsis-markers`\n     *last release*: Jan 12, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Setup additional values for ELLIPSIS_MARKER for doctests\n\n  :pypi:`pytest-doctest-import`\n     *last release*: Nov 13, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.3.0)\n\n     A simple pytest plugin to import names and add them to the doctest namespace.\n\n  :pypi:`pytest-doctest-mkdocstrings`\n     *last release*: Mar 02, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Run pytest --doctest-modules with markdown docstrings in code blocks (\\`\\`\\`)\n\n  :pypi:`pytest-doctest-only`\n     *last release*: Jul 30, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.3.0\n\n     A plugin to run only doctest\n\n  :pypi:`pytest-doctestplus`\n     *last release*: Jan 26, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0\n\n     Pytest plugin with advanced doctest features.\n\n  :pypi:`pytest-documentary`\n     *last release*: Jul 11, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     A simple pytest plugin to generate test documentation\n\n  :pypi:`pytest-dogu-report`\n     *last release*: Jul 07, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin for dogu report\n\n  :pypi:`pytest-dogu-sdk`\n     *last release*: Dec 14, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin for the Dogu\n\n  :pypi:`pytest-dolphin`\n     *last release*: Nov 30, 2016,\n     *status*: 4 - Beta,\n     *requires*: pytest (==3.0.4)\n\n     Some extra stuff that we use ininternally\n\n  :pypi:`pytest-donde`\n     *last release*: Oct 01, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest >=7.3.1\n\n     record pytest session characteristics per test item (coverage and duration) into a persistent file and use them in your own plugin or script.\n\n  :pypi:`pytest-doorstop`\n     *last release*: Jun 09, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A pytest plugin for adding test results into doorstop items.\n\n  :pypi:`pytest-dotenv`\n     *last release*: Jun 16, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=5.0.0)\n\n     A py.test plugin that parses environment files before running tests\n\n  :pypi:`pytest-dotenv-modern`\n     *last release*: Sep 27, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.0.0\n\n     A modern pytest plugin that loads environment variables from dotenv files\n\n  :pypi:`pytest-dot-only-pkcopley`\n     *last release*: Oct 27, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     A Pytest marker for only running a single test\n\n  :pypi:`pytest-dparam`\n     *last release*: Aug 27, 2024,\n     *status*: 6 - Mature,\n     *requires*: pytest\n\n     A more readable alternative to @pytest.mark.parametrize.\n\n  :pypi:`pytest-dpg`\n     *last release*: Aug 13, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest-dpg is a pytest plugin for testing Dear PyGui (DPG) applications\n\n  :pypi:`pytest-draw`\n     *last release*: Mar 21, 2023,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Pytest plugin for randomly selecting a specific number of tests\n\n  :pypi:`pytest-drf`\n     *last release*: Jul 12, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.7)\n\n     A Django REST framework plugin for pytest.\n\n  :pypi:`pytest-drill-sergeant`\n     *last release*: Feb 20, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin that enforces test quality standards through automatic marker detection and AAA structure validation\n\n  :pypi:`pytest-drivings`\n     *last release*: Jan 13, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Tool to allow webdriver automation to be ran locally or remotely\n\n  :pypi:`pytest-drop-dup-tests`\n     *last release*: Mar 04, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=7\n\n     A Pytest plugin to drop duplicated tests during collection\n\n  :pypi:`pytest-dryci`\n     *last release*: Sep 27, 2024,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Test caching plugin for pytest\n\n  :pypi:`pytest-dryrun`\n     *last release*: Jan 19, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<9,>=7.40\n\n     A Pytest plugin to ignore tests during collection without reporting them in the test summary.\n\n  :pypi:`pytest-dsl`\n     *last release*: Mar 02, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     A DSL testing framework based on pytest\n\n  :pypi:`pytest-dsl-ssh`\n     *last release*: Jul 25, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     SSH/SFTP关键字插件，为pytest-dsl提供SSH和SFTP操作能力\n\n  :pypi:`pytest-dsl-ui`\n     *last release*: Aug 21, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0; extra == \"dev\"\n\n     Playwright-based UI automation keywords for pytest-dsl framework\n\n  :pypi:`pytest-dummynet`\n     *last release*: Dec 15, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A py.test plugin providing access to a dummynet.\n\n  :pypi:`pytest-dump2json`\n     *last release*: Jun 29, 2015,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin for dumping test results to json.\n\n  :pypi:`pytest-duration-insights`\n     *last release*: Jul 15, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-durations`\n     *last release*: Mar 13, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=4.6\n\n     Pytest plugin reporting fixtures and test functions execution time.\n\n  :pypi:`pytest-dynamic-parameterize`\n     *last release*: Feb 07, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=9.0.1\n\n     A pytest plugin to dynamically parameterize tests based on external data sources.\n\n  :pypi:`pytest-dynamic-params`\n     *last release*: Mar 12, 2026,\n     *status*: N/A,\n     *requires*: pytest\n\n     Dynamic parameters plugin for pytest\n\n  :pypi:`pytest-dynamicrerun`\n     *last release*: Aug 15, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pytest plugin to rerun tests dynamically based off of test outcome and output.\n\n  :pypi:`pytest-dynamodb`\n     *last release*: Mar 13, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.4.0\n\n     DynamoDB fixtures for pytest\n\n  :pypi:`pytest-easy-addoption`\n     *last release*: Jan 22, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest-easy-addoption: Easy way to work with pytest addoption\n\n  :pypi:`pytest-easyMPI`\n     *last release*: Oct 21, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     Package that supports mpi tests in pytest\n\n  :pypi:`pytest-easyread`\n     *last release*: Nov 17, 2017,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin that makes terminal printouts of the reports easier to read\n\n  :pypi:`pytest-easy-server`\n     *last release*: May 01, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (<5.0.0,>=4.3.1) ; python_version < \"3.5\"\n\n     Pytest plugin for easy testing against servers\n\n  :pypi:`pytest-ebics-sandbox`\n     *last release*: Aug 15, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin for testing against an EBICS sandbox server. Requires docker.\n\n  :pypi:`pytest-ec2`\n     *last release*: Oct 22, 2019,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Pytest execution on EC2 instance\n\n  :pypi:`pytest-echo`\n     *last release*: Apr 27, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.3.3\n\n     pytest plugin that allows to dump environment variables, package version and generic attributes\n\n  :pypi:`pytest-edit`\n     *last release*: Nov 17, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Edit the source code of a failed test with \\`pytest --edit\\`.\n\n  :pypi:`pytest-ekstazi`\n     *last release*: Sep 10, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin to select test using Ekstazi algorithm\n\n  :pypi:`pytest-elastic-reporter`\n     *last release*: Mar 13, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n\n\n  :pypi:`pytest-elasticsearch`\n     *last release*: Feb 16, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.4.0\n\n     Elasticsearch fixtures and fixture factories for Pytest.\n\n  :pypi:`pytest-elasticsearch-test`\n     *last release*: Apr 20, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0\n\n     Elasticsearch fixtures and fixture factories for Pytest.\n\n  :pypi:`pytest-elegant`\n     *last release*: Mar 08, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin that provides elegant, beautiful test output\n\n  :pypi:`pytest-elements`\n     *last release*: Jan 13, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=5.4,<6.0)\n\n     Tool to help automate user interfaces\n\n  :pypi:`pytest-eliot`\n     *last release*: Aug 31, 2022,\n     *status*: 1 - Planning,\n     *requires*: pytest (>=5.4.0)\n\n     An eliot plugin for pytest.\n\n  :pypi:`pytest-elk-reporter`\n     *last release*: Jul 25, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-email`\n     *last release*: Jul 08, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Send execution result email\n\n  :pypi:`pytest-embedded`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0\n\n     A pytest plugin that designed for embedded testing.\n\n  :pypi:`pytest-embedded-arduino`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Make pytest-embedded plugin work with Arduino.\n\n  :pypi:`pytest-embedded-idf`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Make pytest-embedded plugin work with ESP-IDF.\n\n  :pypi:`pytest-embedded-jtag`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Make pytest-embedded plugin work with JTAG.\n\n  :pypi:`pytest-embedded-nuttx`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Make pytest-embedded plugin work with NuttX.\n\n  :pypi:`pytest-embedded-qemu`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Make pytest-embedded plugin work with QEMU.\n\n  :pypi:`pytest-embedded-serial`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Make pytest-embedded plugin work with Serial.\n\n  :pypi:`pytest-embedded-serial-esp`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Make pytest-embedded plugin work with Espressif target boards.\n\n  :pypi:`pytest-embedded-wokwi`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Make pytest-embedded plugin work with the Wokwi CLI.\n\n  :pypi:`pytest-embrace`\n     *last release*: Mar 25, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.0,<8.0)\n\n     💝  Dataclasses-as-tests. Describe the runtime once and multiply coverage with no boilerplate.\n\n  :pypi:`pytest-emoji`\n     *last release*: Feb 19, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.2.1)\n\n     A pytest plugin that adds emojis to your test result report\n\n  :pypi:`pytest-emoji-output`\n     *last release*: Apr 09, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (==7.0.1)\n\n     Pytest plugin to represent test output with emoji support\n\n  :pypi:`pytest-enabler`\n     *last release*: May 16, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest!=8.1.*,>=6; extra == \"test\"\n\n     Enable installed pytest plugins\n\n  :pypi:`pytest-encode`\n     *last release*: Nov 06, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     set your encoding and logger\n\n  :pypi:`pytest-encode-kane`\n     *last release*: Nov 16, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     set your encoding and logger\n\n  :pypi:`pytest-encoding`\n     *last release*: Aug 11, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     set your encoding and logger\n\n  :pypi:`pytest_energy_reporter`\n     *last release*: Mar 28, 2024,\n     *status*: 3 - Alpha,\n     *requires*: pytest<9.0.0,>=8.1.1\n\n     An energy estimation reporter for pytest\n\n  :pypi:`pytest-enhanced-reports`\n     *last release*: Dec 15, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Enhanced test reports for pytest\n\n  :pypi:`pytest-enhancements`\n     *last release*: Oct 30, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Improvements for pytest (rejected upstream)\n\n  :pypi:`pytest-env`\n     *last release*: Mar 12, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=9.0.2\n\n     pytest plugin that allows you to add environment variables.\n\n  :pypi:`pytest-envfiles`\n     *last release*: Oct 08, 2015,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     A py.test plugin that parses environment files before running tests\n\n  :pypi:`pytest-env-info`\n     *last release*: Nov 25, 2017,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.1.1)\n\n     Push information about the running pytest into envvars\n\n  :pypi:`pytest-environment`\n     *last release*: Mar 17, 2024,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     Pytest Environment\n\n  :pypi:`pytest-envraw`\n     *last release*: Aug 27, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.6.0)\n\n     py.test plugin that allows you to add environment variables.\n\n  :pypi:`pytest-envvars`\n     *last release*: Jun 13, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.0.0)\n\n     Pytest plugin to validate use of envvars on your tests\n\n  :pypi:`pytest-envx`\n     *last release*: Jun 28, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.4.1\n\n     Pytest plugin for managing environment variables with interpolation and .env file support.\n\n  :pypi:`pytest-env-yaml`\n     *last release*: Apr 02, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-ephemeral-container`\n     *last release*: Dec 05, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Spawn epehemeral containers in pytest\n\n  :pypi:`pytest-eradicate`\n     *last release*: Sep 08, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=2.4.2)\n\n     pytest plugin to check for commented out code\n\n  :pypi:`pytest_erp`\n     *last release*: Jan 13, 2015,\n     *status*: N/A,\n     *requires*: N/A\n\n     py.test plugin to send test info to report portal dynamically\n\n  :pypi:`pytest-error`\n     *last release*: Dec 06, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.4\n\n     A decorator for testing exceptions with pytest\n\n  :pypi:`pytest-error-for-skips`\n     *last release*: Dec 19, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.6)\n\n     Pytest plugin to treat skipped tests a test failure\n\n  :pypi:`pytest-errxfail`\n     *last release*: Jan 06, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     pytest plugin to mark a test as xfailed if it fails with the specified error message in the captured output\n\n  :pypi:`pytest-essentials`\n     *last release*: May 19, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     A Pytest plugin providing essential utilities like soft assertions.\n\n  :pypi:`pytest-eth`\n     *last release*: Aug 14, 2020,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     PyTest plugin for testing Smart Contracts for Ethereum Virtual Machine (EVM).\n\n  :pypi:`pytest-ethereum`\n     *last release*: Jun 24, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest (==3.3.2); extra == 'dev'\n\n     pytest-ethereum: Pytest library for ethereum projects.\n\n  :pypi:`pytest-eucalyptus`\n     *last release*: Jun 28, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=4.2.0)\n\n     Pytest Plugin for BDD\n\n  :pypi:`pytest-eval`\n     *last release*: Feb 11, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     LLM testing for humans.\n\n  :pypi:`pytest-evals`\n     *last release*: Feb 02, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin for running and analyzing LLM evaluation tests\n\n  :pypi:`pytest-eventlet`\n     *last release*: Oct 04, 2021,\n     *status*: N/A,\n     *requires*: pytest ; extra == 'dev'\n\n     Applies eventlet monkey-patch as a pytest plugin.\n\n  :pypi:`pytest-everyfunc`\n     *last release*: Apr 30, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A pytest plugin to detect completely untested functions using coverage\n\n  :pypi:`pytest_evm`\n     *last release*: Sep 23, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest<9.0.0,>=8.1.1\n\n     The testing package containing tools to test Web3-based projects\n\n  :pypi:`pytest_exact_fixtures`\n     *last release*: Feb 04, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Parse queries in Lucene and Elasticsearch syntaxes\n\n  :pypi:`pytest-examples`\n     *last release*: May 06, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7\n\n     Pytest plugin for testing examples in docstrings and markdown files.\n\n  :pypi:`pytest-exasol-backend`\n     *last release*: Mar 03, 2026,\n     *status*: N/A,\n     *requires*: pytest<9,>=7\n\n\n\n  :pypi:`pytest-exasol-extension`\n     *last release*: Feb 06, 2026,\n     *status*: N/A,\n     *requires*: pytest<9,>=7\n\n\n\n  :pypi:`pytest-exasol-itde`\n     *last release*: Nov 22, 2024,\n     *status*: N/A,\n     *requires*: pytest<9,>=7\n\n\n\n  :pypi:`pytest-exasol-saas`\n     *last release*: Nov 22, 2024,\n     *status*: N/A,\n     *requires*: pytest<9,>=7\n\n\n\n  :pypi:`pytest-exasol-slc`\n     *last release*: Feb 12, 2026,\n     *status*: N/A,\n     *requires*: pytest<9,>=7\n\n\n\n  :pypi:`pytest-excel`\n     *last release*: Jul 22, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     pytest plugin for generating excel reports\n\n  :pypi:`pytest-exceptional`\n     *last release*: Mar 16, 2017,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Better exceptions\n\n  :pypi:`pytest-exception-script`\n     *last release*: Aug 04, 2020,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Walk your code through exception script to check it's resiliency to failures.\n\n  :pypi:`pytest-executable`\n     *last release*: Oct 07, 2023,\n     *status*: N/A,\n     *requires*: pytest <8,>=5\n\n     pytest plugin for testing executables\n\n  :pypi:`pytest-execution-timer`\n     *last release*: Dec 24, 2021,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A timer for the phases of Pytest's execution.\n\n  :pypi:`pytest-exit-code`\n     *last release*: May 06, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A pytest plugin that overrides the built-in exit codes to retain more information about the test results.\n\n  :pypi:`pytest-exit-status`\n     *last release*: Jan 25, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.0.0\n\n     Enhance.\n\n  :pypi:`pytest-expect`\n     *last release*: Apr 21, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     py.test plugin to store test expectations and mark tests based on them\n\n  :pypi:`pytest-expectdir`\n     *last release*: Mar 19, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=5.0)\n\n     A pytest plugin to provide initial/expected directories, and check a test transforms the initial directory to the expected one\n\n  :pypi:`pytest-expected`\n     *last release*: Feb 26, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Record and play back your expectations\n\n  :pypi:`pytest-expecter`\n     *last release*: Sep 18, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Better testing with expecter and pytest.\n\n  :pypi:`pytest-expectr`\n     *last release*: Oct 05, 2018,\n     *status*: N/A,\n     *requires*: pytest (>=2.4.2)\n\n     This plugin is used to expect multiple assert using pytest framework.\n\n  :pypi:`pytest-expect-test`\n     *last release*: Apr 10, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A fixture to support expect tests in pytest\n\n  :pypi:`pytest-experiments`\n     *last release*: Dec 13, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.2.5,<7.0.0)\n\n     A pytest plugin to help developers of research-oriented software projects keep track of the results of their numerical experiments.\n\n  :pypi:`pytest-explicit`\n     *last release*: Jun 15, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A Pytest plugin to ignore certain marked tests by default\n\n  :pypi:`pytest-exploratory`\n     *last release*: Sep 18, 2024,\n     *status*: N/A,\n     *requires*: pytest>=6.2\n\n     Interactive console for pytest.\n\n  :pypi:`pytest-explorer`\n     *last release*: Aug 01, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     terminal ui for exploring and running tests\n\n  :pypi:`pytest-ext`\n     *last release*: Mar 31, 2024,\n     *status*: N/A,\n     *requires*: pytest>=5.3\n\n     pytest plugin for automation test\n\n  :pypi:`pytest-extended-mock`\n     *last release*: Mar 12, 2025,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.3.5\n\n     a pytest extension for easy mock setup\n\n  :pypi:`pytest-extensions`\n     *last release*: Aug 17, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest ; extra == 'testing'\n\n     A collection of helpers for pytest to ease testing\n\n  :pypi:`pytest-external-blockers`\n     *last release*: Oct 05, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     a special outcome for tests that are blocked for external reasons\n\n  :pypi:`pytest_extra`\n     *last release*: Aug 14, 2014,\n     *status*: N/A,\n     *requires*: N/A\n\n     Some helpers for writing tests with pytest.\n\n  :pypi:`pytest-extra-durations`\n     *last release*: Apr 21, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A pytest plugin to get durations on a per-function basis and per module basis.\n\n  :pypi:`pytest-extra-markers`\n     *last release*: Mar 05, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Additional pytest markers to dynamically enable/disable tests viia CLI flags\n\n  :pypi:`pytest-f3ts`\n     *last release*: Mar 09, 2026,\n     *status*: N/A,\n     *requires*: pytest<8.0.0,>=7.2.1\n\n     Pytest Plugin for communicating test results and information to a FixturFab Test Runner GUI\n\n  :pypi:`pytest-fabric`\n     *last release*: Sep 12, 2018,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Provides test utilities to run fabric task tests by using docker containers\n\n  :pypi:`pytest-factory`\n     *last release*: Sep 06, 2020,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>4.3)\n\n     Use factories for test setup with py.test\n\n  :pypi:`pytest-factoryboy`\n     *last release*: Jul 01, 2025,\n     *status*: 6 - Mature,\n     *requires*: pytest>=7.0\n\n     Factory Boy support for pytest.\n\n  :pypi:`pytest-factoryboy-fixtures`\n     *last release*: Jun 25, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     Generates pytest fixtures that allow the use of type hinting\n\n  :pypi:`pytest-factoryboy-state`\n     *last release*: Mar 22, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=5.0)\n\n     Simple factoryboy random state management\n\n  :pypi:`pytest-failed-screen-record`\n     *last release*: Jan 05, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=7.1.2d,<8.0.0)\n\n     Create a video of the screen when pytest fails\n\n  :pypi:`pytest-failed-screenshot`\n     *last release*: Apr 21, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Test case fails,take a screenshot,save it,attach it to the allure\n\n  :pypi:`pytest-failed-to-verify`\n     *last release*: Aug 08, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=4.1.0)\n\n     A pytest plugin that helps better distinguishing real test failures from setup flakiness.\n\n  :pypi:`pytest-fail-slow`\n     *last release*: Jun 01, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     Fail tests that take too long to run\n\n  :pypi:`pytest-failure-tracker`\n     *last release*: Jul 17, 2024,\n     *status*: N/A,\n     *requires*: pytest>=6.0.0\n\n     A pytest plugin for tracking test failures over multiple runs\n\n  :pypi:`pytest-faker`\n     *last release*: Dec 19, 2016,\n     *status*: 6 - Mature,\n     *requires*: N/A\n\n     Faker integration with the pytest framework.\n\n  :pypi:`pytest-falcon`\n     *last release*: Sep 07, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Pytest helpers for Falcon.\n\n  :pypi:`pytest-fantasy`\n     *last release*: Mar 14, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin for Flask Fantasy Framework\n\n  :pypi:`pytest-fastapi`\n     *last release*: Dec 27, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-fastapi-deps`\n     *last release*: Jul 20, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A fixture which allows easy replacement of fastapi dependencies for testing\n\n  :pypi:`pytest-fastcollect`\n     *last release*: Nov 19, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     A high-performance pytest plugin that replaces test collection with a Rust-based implementation\n\n  :pypi:`pytest-fastest`\n     *last release*: Oct 04, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.4)\n\n     Use SCM and coverage to run only needed tests\n\n  :pypi:`pytest-fast-first`\n     *last release*: Jan 19, 2023,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Pytest plugin that runs fast tests first\n\n  :pypi:`pytest-faulthandler`\n     *last release*: Jul 04, 2019,\n     *status*: 6 - Mature,\n     *requires*: pytest (>=5.0)\n\n     py.test plugin that activates the fault handler module for tests (dummy package)\n\n  :pypi:`pytest-fauna`\n     *last release*: Jan 03, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     A collection of helpful test fixtures for Fauna DB.\n\n  :pypi:`pytest-fauxfactory`\n     *last release*: Dec 06, 2017,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.2)\n\n     Integration of fauxfactory into pytest.\n\n  :pypi:`pytest-figleaf`\n     *last release*: Jan 18, 2010,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     py.test figleaf coverage plugin\n\n  :pypi:`pytest-file`\n     *last release*: Mar 18, 2024,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     Pytest File\n\n  :pypi:`pytest-filecov`\n     *last release*: Jun 27, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A pytest plugin to detect unused files\n\n  :pypi:`pytest-filedata`\n     *last release*: Apr 29, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     easily load test data from files\n\n  :pypi:`pytest-filemarker`\n     *last release*: Dec 01, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin that runs marked tests when files change.\n\n  :pypi:`pytest-file-watcher`\n     *last release*: Mar 23, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest-File-Watcher is a CLI tool that watches for changes in your code and runs pytest on the changed files.\n\n  :pypi:`pytest-filter-case`\n     *last release*: Nov 05, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     run test cases filter by mark\n\n  :pypi:`pytest-filterfixtures`\n     *last release*: Jan 09, 2026,\n     *status*: N/A,\n     *requires*: pytest>=9.0.2\n\n     pytest plugin to execute or ignore tests based on fixtures\n\n  :pypi:`pytest-filter-subpackage`\n     *last release*: Mar 04, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=4.6\n\n     Pytest plugin for filtering based on sub-packages\n\n  :pypi:`pytest-find-dependencies`\n     *last release*: Jul 16, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2.4\n\n     A pytest plugin to find dependencies between tests\n\n  :pypi:`pytest-finer-verdicts`\n     *last release*: Jun 18, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=5.4.3)\n\n     A pytest plugin to treat non-assertion failures as test errors.\n\n  :pypi:`pytest-firefox`\n     *last release*: Feb 28, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-firestore`\n     *last release*: Mar 10, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     A Pytest fixture for managing Google Cloud Firestore emulator\n\n  :pypi:`pytest-fixedpoint`\n     *last release*: Mar 12, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     Pytest plugin for recording and replaying deterministic function calls\n\n  :pypi:`pytest-fixture-cache`\n     *last release*: Jan 25, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Smart fixture caching for pytest with SQLite storage\n\n  :pypi:`pytest-fixturecheck`\n     *last release*: Jun 02, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=6.0.0\n\n     A pytest plugin to check fixture validity before test execution\n\n  :pypi:`pytest-fixture-classes`\n     *last release*: Oct 12, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Fixtures as classes that work well with dependency injection, autocompletetion, type checkers, and language servers\n\n  :pypi:`pytest-fixture-collect`\n     *last release*: Jul 25, 2025,\n     *status*: N/A,\n     *requires*: pytest; extra == \"test\"\n\n     A utility to collect pytest fixture file paths.\n\n  :pypi:`pytest-fixturecollection`\n     *last release*: Feb 22, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest >=3.5.0\n\n     A pytest plugin to collect tests based on fixtures being used by tests\n\n  :pypi:`pytest-fixture-config`\n     *last release*: Oct 17, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Fixture configuration utils for py.test\n\n  :pypi:`pytest-fixture-forms`\n     *last release*: Dec 06, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=7.0.0\n\n     A pytest plugin for creating fixtures that holds different forms between tests.\n\n  :pypi:`pytest-fixture-maker`\n     *last release*: Sep 21, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin to load fixtures from YAML files\n\n  :pypi:`pytest-fixture-marker`\n     *last release*: Oct 11, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A pytest plugin to add markers based on fixtures used.\n\n  :pypi:`pytest-fixture-order`\n     *last release*: Oct 22, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=3.0\n\n     pytest plugin to control fixture evaluation order\n\n  :pypi:`pytest-fixture-ref`\n     *last release*: Nov 17, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Lets users reference fixtures without name matching magic.\n\n  :pypi:`pytest-fixture-remover`\n     *last release*: Feb 14, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A LibCST codemod to remove pytest fixtures applied via the usefixtures decorator, as well as its parametrizations.\n\n  :pypi:`pytest-fixture-rtttg`\n     *last release*: Feb 23, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.0.1,<8.0.0)\n\n     Warn or fail on fixture name clash\n\n  :pypi:`pytest-fixtures`\n     *last release*: May 01, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Common fixtures for pytest\n\n  :pypi:`pytest-fixtures-fixtures`\n     *last release*: Nov 06, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.4.1\n\n     Handy fixtues to access your fixtures from your _pytest tests.\n\n  :pypi:`pytest-fixture-timing`\n     *last release*: Dec 11, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     Tiny plugin to report total duration per fixture\n\n  :pypi:`pytest-fixture-tools`\n     *last release*: Apr 30, 2025,\n     *status*: 6 - Mature,\n     *requires*: pytest\n\n     Plugin for pytest which provides tools for fixtures\n\n  :pypi:`pytest-fixture-typecheck`\n     *last release*: Aug 24, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin to assert type annotations at runtime.\n\n  :pypi:`pytest-fkit`\n     *last release*: Feb 19, 2026,\n     *status*: N/A,\n     *requires*: pytest>=6.0.0\n\n     A pytest plugin that prevents crashes from killing your test suite\n\n  :pypi:`pytest-flake8`\n     *last release*: Nov 09, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0\n\n     pytest plugin to check FLAKE8 requirements\n\n  :pypi:`pytest-flake8-path`\n     *last release*: Sep 09, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A pytest fixture for testing flake8 plugins.\n\n  :pypi:`pytest-flake8-v2`\n     *last release*: Mar 01, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=7.0)\n\n     pytest plugin to check FLAKE8 requirements\n\n  :pypi:`pytest-flake-detection`\n     *last release*: Nov 29, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     Continuously runs your tests to detect flaky tests\n\n  :pypi:`pytest-flakefighters`\n     *last release*: Mar 05, 2026,\n     *status*: N/A,\n     *requires*: pytest>=6.2.0\n\n     Pytest plugin implementing flaky test failure detection and classification.\n\n  :pypi:`pytest-flakefinder`\n     *last release*: Oct 26, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.7.1)\n\n     Runs tests multiple times to expose flakiness.\n\n  :pypi:`pytest-flakes`\n     *last release*: Dec 02, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=5)\n\n     pytest plugin to check source code with pyflakes\n\n  :pypi:`pytest-flakiness`\n     *last release*: Feb 28, 2026,\n     *status*: N/A,\n     *requires*: pytest>=9.0.2\n\n     Pytest reporter for Flakiness.io\n\n  :pypi:`pytest-flaptastic`\n     *last release*: Mar 17, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Flaptastic py.test plugin\n\n  :pypi:`pytest-flask`\n     *last release*: Oct 23, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=5.2\n\n     A set of py.test fixtures to test Flask applications.\n\n  :pypi:`pytest-flask-ligand`\n     *last release*: Apr 25, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (~=7.3)\n\n     Pytest fixtures and helper functions to use for testing flask-ligand microservices.\n\n  :pypi:`pytest-flask-sqlalchemy`\n     *last release*: Apr 30, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.2.1)\n\n     A pytest plugin for preserving test isolation in Flask-SQlAlchemy using database transactions.\n\n  :pypi:`pytest-flask-sqlalchemy-transactions`\n     *last release*: Aug 02, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.2.1)\n\n     Run tests in transactions using pytest, Flask, and SQLalchemy.\n\n  :pypi:`pytest-flexreport`\n     *last release*: Apr 15, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-fluent`\n     *last release*: Aug 14, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin in order to provide logs via fluentd\n\n  :pypi:`pytest-fluentbit`\n     *last release*: Jun 16, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=7.0.0)\n\n     A pytest plugin in order to provide logs via fluentbit\n\n  :pypi:`pytest-fly`\n     *last release*: Feb 23, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     pytest runner and observer\n\n  :pypi:`pytest-flyte`\n     *last release*: May 03, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest fixtures for simplifying Flyte integration testing\n\n  :pypi:`pytest-fmu-filter`\n     *last release*: Jun 23, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin to filter fmus\n\n  :pypi:`pytest-focus`\n     *last release*: May 04, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A pytest plugin that alerts user of failed test cases with screen notifications\n\n  :pypi:`pytest-forbid`\n     *last release*: Mar 07, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.2.2,<8.0.0)\n\n\n\n  :pypi:`pytest-forcefail`\n     *last release*: May 15, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     py.test plugin to make the test failing regardless of pytest.mark.xfail\n\n  :pypi:`pytest-forger`\n     *last release*: Mar 09, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.4.0\n\n     Automatic test scaffolding and mock generation for Python\n\n  :pypi:`pytest-forward-compatability`\n     *last release*: Sep 06, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     A name to avoid typosquating pytest-foward-compatibility\n\n  :pypi:`pytest-forward-compatibility`\n     *last release*: Sep 29, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin to shim pytest commandline options for fowards compatibility\n\n  :pypi:`pytest-frappe`\n     *last release*: Jul 30, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Pytest Frappe Plugin - A set of pytest fixtures to test Frappe applications\n\n  :pypi:`pytest-freethreaded`\n     *last release*: Oct 03, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     pytest plugin for running parallel tests\n\n  :pypi:`pytest-freeze`\n     *last release*: Jan 27, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin to simplify writing freeze tests.\n\n  :pypi:`pytest-freezeblaster`\n     *last release*: Oct 13, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.2.5\n\n     Wrap tests with fixtures in freeze_time\n\n  :pypi:`pytest-freezegun`\n     *last release*: Jul 19, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.0.0)\n\n     Wrap tests with fixtures in freeze_time\n\n  :pypi:`pytest-freezer`\n     *last release*: Dec 12, 2024,\n     *status*: N/A,\n     *requires*: pytest>=3.6\n\n     Pytest plugin providing a fixture interface for spulec/freezegun\n\n  :pypi:`pytest-freeze-reqs`\n     *last release*: Apr 29, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Check if requirement files are frozen\n\n  :pypi:`pytest-frozen-uuids`\n     *last release*: Apr 17, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=3.0)\n\n     Deterministically frozen UUID's for your tests\n\n  :pypi:`pytest_ftpserver`\n     *last release*: Feb 10, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A PyTest plugin which provides an FTP fixture for your tests\n\n  :pypi:`pytest-func-cov`\n     *last release*: Apr 15, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=5)\n\n     Pytest plugin for measuring function coverage\n\n  :pypi:`pytest-funcnodes`\n     *last release*: Dec 21, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     Testing plugin for funcnodes\n\n  :pypi:`pytest-funparam`\n     *last release*: Dec 02, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest >=4.6.0\n\n     An alternative way to parametrize test cases.\n\n  :pypi:`pytest-fv`\n     *last release*: Jun 06, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest extensions to support running functional-verification jobs\n\n  :pypi:`pytest-fxa`\n     *last release*: Aug 28, 2018,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin for Firefox Accounts\n\n  :pypi:`pytest-fxa-mte`\n     *last release*: Oct 02, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin for Firefox Accounts\n\n  :pypi:`pytest-fxtest`\n     *last release*: Oct 27, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-fzf`\n     *last release*: Jan 06, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.0.0\n\n     fzf-based test selector for pytest\n\n  :pypi:`pytest_gae`\n     *last release*: Aug 03, 2016,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin for apps written with Google's AppEngine\n\n  :pypi:`pytest-gak`\n     *last release*: Apr 10, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     A Pytest plugin and command line tool for interactive testing with Pytest\n\n  :pypi:`pytest-gather-fixtures`\n     *last release*: Aug 18, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     set up asynchronous pytest fixtures concurrently\n\n  :pypi:`pytest-gc`\n     *last release*: Feb 01, 2018,\n     *status*: N/A,\n     *requires*: N/A\n\n     The garbage collector plugin for py.test\n\n  :pypi:`pytest-gcov`\n     *last release*: Feb 01, 2018,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Uses gcov to measure test coverage of a C library\n\n  :pypi:`pytest-gcppubsub`\n     *last release*: Mar 10, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     A Pytest fixture for managing Google Cloud Platform PubSub emulator\n\n  :pypi:`pytest-gcpsecretmanager`\n     *last release*: Feb 18, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     A PyTest plugin for mocking GCP's Secret Manager\n\n  :pypi:`pytest-gcs`\n     *last release*: Jan 24, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2\n\n     GCS fixtures and fixture factories for Pytest.\n\n  :pypi:`pytest-gee`\n     *last release*: Oct 16, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     The Python plugin for your GEE based packages.\n\n  :pypi:`pytest-gevent`\n     *last release*: Feb 25, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Ensure that gevent is properly patched when invoking pytest\n\n  :pypi:`pytest-gherkin`\n     *last release*: Jul 27, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=5.0.0)\n\n     A flexible framework for executing BDD gherkin tests\n\n  :pypi:`pytest-gh-log-group`\n     *last release*: Jan 11, 2022,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     pytest plugin for gh actions\n\n  :pypi:`pytest-ghostinspector`\n     *last release*: May 17, 2016,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     For finding/executing Ghost Inspector tests\n\n  :pypi:`pytest-girder`\n     *last release*: Mar 04, 2026,\n     *status*: N/A,\n     *requires*: pytest>=3.6\n\n     A set of pytest fixtures for testing Girder applications.\n\n  :pypi:`pytest-git`\n     *last release*: Oct 17, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Git repository fixture for py.test\n\n  :pypi:`pytest-gitconfig`\n     *last release*: Dec 28, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.1.2\n\n     Provide a Git config sandbox for testing\n\n  :pypi:`pytest-gitcov`\n     *last release*: Jan 11, 2020,\n     *status*: 2 - Pre-Alpha,\n     *requires*: N/A\n\n     Pytest plugin for reporting on coverage of the last git commit.\n\n  :pypi:`pytest-git-diff`\n     *last release*: Apr 02, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin that allows the user to select the tests affected by a range of git commits\n\n  :pypi:`pytest-git-fixtures`\n     *last release*: Mar 11, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest fixtures for testing with git.\n\n  :pypi:`pytest-github`\n     *last release*: Mar 07, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Plugin for py.test that associates tests with github issues using a marker.\n\n  :pypi:`pytest-github-actions-annotate-failures`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     pytest plugin to annotate failed tests with a workflow command for GitHub Actions\n\n  :pypi:`pytest-github-report`\n     *last release*: Jun 03, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Generate a GitHub report using pytest in GitHub Workflows\n\n  :pypi:`pytest-gitignore`\n     *last release*: Jul 17, 2015,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     py.test plugin to ignore the same files as git\n\n  :pypi:`pytest-gitlab`\n     *last release*: Oct 16, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest Plugin for Gitlab\n\n  :pypi:`pytest-gitlabci-parallelized`\n     *last release*: Mar 08, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     Parallelize pytest across GitLab CI workers.\n\n  :pypi:`pytest-gitlab-code-quality`\n     *last release*: Nov 23, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.1.1\n\n     Collects warnings while testing and generates a GitLab Code Quality Report.\n\n  :pypi:`pytest-gitlab-fold`\n     *last release*: Dec 31, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest >=2.6.0\n\n     Folds output sections in GitLab CI build log\n\n  :pypi:`pytest-gitscope`\n     *last release*: Sep 24, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     A pragmatic pytest plugin that runs only the tests that matter, and ship faster\n\n  :pypi:`pytest-git-selector`\n     *last release*: Nov 17, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Utility to select tests that have had its dependencies modified (as identified by git diff)\n\n  :pypi:`pytest-glamor-allure`\n     *last release*: Jan 30, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<=9.0.2\n\n     Extends allure-pytest functionality\n\n  :pypi:`pytest-glow-report`\n     *last release*: Dec 08, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.0; extra == \"dev\"\n\n     Beautiful, glowing HTML test reports for PyTest and unittest.\n\n  :pypi:`pytest-gnupg-fixtures`\n     *last release*: Mar 04, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest fixtures for testing with gnupg.\n\n  :pypi:`pytest-golden`\n     *last release*: Jan 06, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.1.2\n\n     Plugin for pytest that offloads expected outputs to data files\n\n  :pypi:`pytest-goldie`\n     *last release*: May 23, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A plugin to support golden tests with pytest.\n\n  :pypi:`pytest-google-chat`\n     *last release*: Mar 27, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Notify google chat channel for test results\n\n  :pypi:`pytest-google-cloud-storage`\n     *last release*: Sep 11, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.0.0\n\n     Pytest custom features, e.g. fixtures and various tests. Aimed to emulate Google Cloud Storage service\n\n  :pypi:`pytest-grader`\n     *last release*: Aug 25, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8\n\n     Pytest extension for scoring programming assignments.\n\n  :pypi:`pytest-gradescope`\n     *last release*: Apr 29, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin for Gradescope integration\n\n  :pypi:`pytest-graphql-schema`\n     *last release*: Oct 18, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Get graphql schema as fixture for pytest\n\n  :pypi:`pytest-greendots`\n     *last release*: Feb 08, 2014,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Green progress dots\n\n  :pypi:`pytest-greener`\n     *last release*: Dec 24, 2025,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.3.3\n\n     Pytest plugin for Greener\n\n  :pypi:`pytest-green-light`\n     *last release*: Nov 03, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     Pytest plugin that gives SQLAlchemy async engines the green light - automatically fixes MissingGreenlet errors\n\n  :pypi:`pytest-greet`\n     *last release*: Oct 21, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-gremlins`\n     *last release*: Mar 14, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     Fast-first mutation testing for pytest. Let the gremlins loose, see which ones survive.\n\n  :pypi:`pytest-group-by-class`\n     *last release*: Jun 27, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.5)\n\n     A Pytest plugin for running a subset of your tests by splitting them in to groups of classes.\n\n  :pypi:`pytest-growl`\n     *last release*: Jan 13, 2014,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Growl notifications for pytest results.\n\n  :pypi:`pytest-grpc`\n     *last release*: May 01, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=3.6.0)\n\n     pytest plugin for grpc\n\n  :pypi:`pytest-grpc-aio`\n     *last release*: Oct 28, 2025,\n     *status*: N/A,\n     *requires*: pytest>=3.6.0\n\n     pytest plugin for grpc.aio\n\n  :pypi:`pytest-grunnur`\n     *last release*: Jul 26, 2024,\n     *status*: N/A,\n     *requires*: pytest>=6\n\n     Py.Test plugin for Grunnur-based packages.\n\n  :pypi:`pytest_gui_status`\n     *last release*: Jan 23, 2016,\n     *status*: N/A,\n     *requires*: pytest\n\n     Show pytest status in gui\n\n  :pypi:`pytest-hammertime`\n     *last release*: Jul 28, 2018,\n     *status*: N/A,\n     *requires*: pytest\n\n     Display \"🔨 \" instead of \".\" for passed pytest tests.\n\n  :pypi:`pytest-hardware-test-report`\n     *last release*: Apr 01, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest<9.0.0,>=8.0.0\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-harmony`\n     *last release*: Jan 17, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.2.1,<8.0.0)\n\n     Chain tests and data with pytest\n\n  :pypi:`pytest-harvest`\n     *last release*: Mar 16, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Store data created during your pytest tests execution, and retrieve it at the end of the session, e.g. for applicative benchmarking purposes.\n\n  :pypi:`pytest-helm`\n     *last release*: Feb 21, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8.0.0\n\n     Simple, ergonomic Helm manifest fixtures for pytest.\n\n  :pypi:`pytest-helm-charts`\n     *last release*: Dec 23, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest<9,>=8.0.0\n\n     A plugin to provide different types and configs of Kubernetes clusters that can be used for testing.\n\n  :pypi:`pytest-helm-templates`\n     *last release*: Aug 07, 2024,\n     *status*: N/A,\n     *requires*: pytest~=7.4.0; extra == \"dev\"\n\n     Pytest fixtures for unit testing the output of helm templates\n\n  :pypi:`pytest-helper`\n     *last release*: May 31, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Functions to help in using the pytest testing framework\n\n  :pypi:`pytest-helpers`\n     *last release*: May 17, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest helpers\n\n  :pypi:`pytest-helpers-namespace`\n     *last release*: Dec 29, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=6.0.0)\n\n     Pytest Helpers Namespace Plugin\n\n  :pypi:`pytest-henry`\n     *last release*: Aug 29, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-hidecaptured`\n     *last release*: May 04, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.8.5)\n\n     Hide captured output\n\n  :pypi:`pytest-himark`\n     *last release*: Jun 05, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     This plugin aims to create markers automatically based on a json configuration.\n\n  :pypi:`pytest-historic`\n     *last release*: Apr 08, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Custom report to display pytest historical execution records\n\n  :pypi:`pytest-historic-hook`\n     *last release*: Apr 08, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Custom listener to store execution results into MYSQL DB, which is used for pytest-historic report\n\n  :pypi:`pytest-history`\n     *last release*: Jan 14, 2024,\n     *status*: N/A,\n     *requires*: pytest (>=7.4.3,<8.0.0)\n\n     Pytest plugin to keep a history of your pytest runs\n\n  :pypi:`pytest-home`\n     *last release*: Jul 28, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Home directory fixtures\n\n  :pypi:`pytest-homeassistant`\n     *last release*: Aug 12, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pytest plugin for use with homeassistant custom components.\n\n  :pypi:`pytest-homeassistant-custom-component`\n     *last release*: Mar 07, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest==9.0.0\n\n     Experimental package to automatically extract test plugins for Home Assistant custom components\n\n  :pypi:`pytest-homeassistant-custom-component-framework`\n     *last release*: Mar 07, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest==9.0.0\n\n     Experimental package to automatically extract test plugins for Home Assistant custom components\n\n  :pypi:`pytest-honey`\n     *last release*: Jan 07, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-honors`\n     *last release*: Mar 06, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Report on tests that honor constraints, and guard against regressions\n\n  :pypi:`pytest-hot-reloading`\n     *last release*: Sep 23, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-hot-test`\n     *last release*: Dec 10, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A plugin that tracks test changes\n\n  :pypi:`pytest-houdini`\n     *last release*: Jul 15, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest plugin for testing code in Houdini.\n\n  :pypi:`pytest-hoverfly`\n     *last release*: Jan 30, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=5.0)\n\n     Simplify working with Hoverfly from pytest\n\n  :pypi:`pytest-hoverfly-wrapper`\n     *last release*: Feb 27, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.7.0)\n\n     Integrates the Hoverfly HTTP proxy into Pytest\n\n  :pypi:`pytest-hpfeeds`\n     *last release*: Feb 28, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.2.4,<7.0.0)\n\n     Helpers for testing hpfeeds in your python project\n\n  :pypi:`pytest-html`\n     *last release*: Jan 19, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7\n\n     pytest plugin for generating HTML reports\n\n  :pypi:`pytest-html5`\n     *last release*: Dec 18, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     the best report for pytest\n\n  :pypi:`pytest-html-cn`\n     *last release*: Aug 19, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest!=6.0.0,>=5.0\n\n     pytest plugin for generating HTML reports\n\n  :pypi:`pytest-html-dashboard`\n     *last release*: Nov 24, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Beautiful dashboard-style HTML reports for pytest with charts, error analysis, and visual insights\n\n  :pypi:`pytest-html-lee`\n     *last release*: Jun 30, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=5.0)\n\n     optimized pytest plugin for generating HTML reports\n\n  :pypi:`pytest-html-merger`\n     *last release*: Jul 12, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest HTML reports merging utility\n\n  :pypi:`pytest-html-nova-act`\n     *last release*: Nov 05, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     A Pytest Plugin for Amazon Nova Act Python SDK.\n\n  :pypi:`pytest-html-object-storage`\n     *last release*: Jan 17, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest report plugin for send HTML report on object-storage\n\n  :pypi:`pytest-html-plus`\n     *last release*: Feb 06, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Generate Actionable, automatic screenshots, unified Mobile friendly Pytest HTML report in less than 3 seconds — no hooks, merge plugins, no config, xdist-ready.\n\n  :pypi:`pytest-html-profiling`\n     *last release*: Feb 11, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.0)\n\n     Pytest plugin for generating HTML reports with per-test profiling and optionally call graph visualizations. Based on pytest-html by Dave Hunt.\n\n  :pypi:`pytest-html-report`\n     *last release*: Jun 24, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.0\n\n     Enhanced HTML reporting for pytest with categories, specifications, and detailed logging\n\n  :pypi:`pytest-html-reporter`\n     *last release*: Feb 13, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Generates a static html report based on pytest framework\n\n  :pypi:`pytest-html-report-merger`\n     *last release*: May 22, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-html-thread`\n     *last release*: Dec 29, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin for generating HTML reports\n\n  :pypi:`pytest-htmlx`\n     *last release*: Sep 09, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Custom HTML report plugin for Pytest with charts and tables\n\n  :pypi:`pytest-http`\n     *last release*: Aug 22, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Fixture \"http\" for http requests\n\n  :pypi:`pytest-httpbin`\n     *last release*: Sep 18, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest; extra == \"test\"\n\n     Easily test your HTTP library against a local copy of httpbin\n\n  :pypi:`pytest-httpchain`\n     *last release*: Jan 09, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin for HTTP testing using JSON files\n\n  :pypi:`pytest-httpchain-jsonref`\n     *last release*: Jan 09, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     JSON reference ($ref) support for pytest-httpchain\n\n  :pypi:`pytest-httpchain-mcp`\n     *last release*: Jan 09, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     MCP server for pytest-httpchain\n\n  :pypi:`pytest-httpchain-models`\n     *last release*: Jan 09, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pydantic models for pytest-httpchain\n\n  :pypi:`pytest-httpchain-templates`\n     *last release*: Jan 09, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Templating support for pytest-httpchain\n\n  :pypi:`pytest-httpchain-userfunc`\n     *last release*: Jan 09, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     User functions support for pytest-httpchain\n\n  :pypi:`pytest-httpdbg`\n     *last release*: Oct 26, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin to record HTTP(S) requests with stack trace.\n\n  :pypi:`pytest-http-mocker`\n     *last release*: Oct 20, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin for http mocking (via https://github.com/vilus/mocker)\n\n  :pypi:`pytest-httpretty`\n     *last release*: Feb 16, 2014,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     A thin wrapper of HTTPretty for pytest\n\n  :pypi:`pytest_httpserver`\n     *last release*: Feb 14, 2026,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest-httpserver is a httpserver for pytest\n\n  :pypi:`pytest-httptesting`\n     *last release*: Dec 19, 2024,\n     *status*: N/A,\n     *requires*: pytest>=8.2.0\n\n     http_testing framework on top of pytest\n\n  :pypi:`pytest-httpx`\n     *last release*: Dec 02, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest==9.*\n\n     Send responses to httpx.\n\n  :pypi:`pytest-httpx-blockage`\n     *last release*: Feb 16, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.2.1)\n\n     Disable httpx requests during a test run\n\n  :pypi:`pytest-httpx-recorder`\n     *last release*: Jan 04, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Recorder feature based on pytest_httpx, like recorder feature in responses.\n\n  :pypi:`pytest-hue`\n     *last release*: May 09, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Visualise PyTest status via your Phillips Hue lights\n\n  :pypi:`pytest-human`\n     *last release*: Jan 25, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8\n\n     A beautiful nested pytest HTML test report\n\n  :pypi:`pytest-hy`\n     *last release*: Feb 11, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     Pytest plugin for discovering and running Hy test files\n\n  :pypi:`pytest-hylang`\n     *last release*: Mar 28, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin to allow running tests written in hylang\n\n  :pypi:`pytest-hypo-25`\n     *last release*: Jan 12, 2020,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     help hypo module for pytest\n\n  :pypi:`pytest-hypothesis`\n     *last release*: Feb 09, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-iam`\n     *last release*: Nov 02, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A fully functional OAUTH2 / OpenID Connect (OIDC) / SCIM server to be used in your testsuite\n\n  :pypi:`pytest-ibutsu`\n     *last release*: Feb 23, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A plugin to sent pytest results to an Ibutsu server\n\n  :pypi:`pytest-icdiff`\n     *last release*: Dec 05, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     use icdiff for better error messages in pytest assertions\n\n  :pypi:`pytest-idapro`\n     *last release*: Nov 03, 2018,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin for idapython. Allows a pytest setup to run tests outside and inside IDA in an automated manner by runnig pytest inside IDA and by mocking idapython api\n\n  :pypi:`pytest-idem`\n     *last release*: Dec 13, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A pytest plugin to help with testing idem projects\n\n  :pypi:`pytest-idempotent`\n     *last release*: Jul 25, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin for testing function idempotence.\n\n  :pypi:`pytest-ignore-flaky`\n     *last release*: Apr 20, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.0\n\n     ignore failures from flaky tests (pytest plugin)\n\n  :pypi:`pytest-ignore-test-results`\n     *last release*: Feb 03, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0\n\n     A pytest plugin to ignore test results.\n\n  :pypi:`pytest-image-diff`\n     *last release*: Dec 31, 2024,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-image-snapshot`\n     *last release*: Jul 16, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     A pytest plugin for image snapshot management and comparison.\n\n  :pypi:`pytest-impacted`\n     *last release*: Feb 12, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.0.0\n\n     A pytest plugin that selectively runs tests impacted by code changes via git introspection, AST parsing, and dependency graph analysis.\n\n  :pypi:`pytest-import-check`\n     *last release*: Jul 19, 2024,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8.1\n\n     pytest plugin to check whether Python modules can be imported\n\n  :pypi:`pytest-incremental`\n     *last release*: Apr 24, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     an incremental test runner (pytest plugin)\n\n  :pypi:`pytest-in-docker`\n     *last release*: Feb 09, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=9.0.2\n\n     Seamlessly run pytest tests inside docker containers\n\n  :pypi:`pytest-infinity`\n     *last release*: Jun 09, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.0.0\n\n\n\n  :pypi:`pytest-influx`\n     *last release*: Oct 16, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.3.3\n\n     Pytest plugin for managing your influx instance between test runs\n\n  :pypi:`pytest-influxdb`\n     *last release*: Apr 20, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Plugin for influxdb and pytest integration.\n\n  :pypi:`pytest-info-collector`\n     *last release*: May 26, 2019,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin to collect information from tests\n\n  :pypi:`pytest-info-plugin`\n     *last release*: Sep 14, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     Get executed interface information in pytest interface automation framework\n\n  :pypi:`pytest-informative-node`\n     *last release*: Apr 25, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     display more node ininformation.\n\n  :pypi:`pytest-infrahouse`\n     *last release*: Jan 29, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest~=9.0\n\n     A set of fixtures to use with pytest\n\n  :pypi:`pytest-infrastructure`\n     *last release*: Apr 12, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest stack validation prior to testing executing\n\n  :pypi:`pytest-ini`\n     *last release*: Apr 26, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Reuse pytest.ini to store env variables\n\n  :pypi:`pytest-initry`\n     *last release*: Apr 30, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.1.1\n\n     Plugin for sending automation test data from Pytest to the initry\n\n  :pypi:`pytest-inject`\n     *last release*: Nov 25, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.0.0\n\n     A pytest plugin that allows you to inject arguments into fixtures and parametrized tests using pytest command-line options.\n\n  :pypi:`pytest-inline`\n     *last release*: Oct 24, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest<9.0,>=7.0\n\n     A pytest plugin for writing inline tests\n\n  :pypi:`pytest-inline-snapshot`\n     *last release*: Nov 09, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     inline-snapshot is the package you are looking for\n\n  :pypi:`pytest-inline-tdd`\n     *last release*: Mar 09, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest<9.0,>=7.0\n\n     A pytest plugin for writing inline tests\n\n  :pypi:`pytest-inmanta`\n     *last release*: Nov 18, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A py.test plugin providing fixtures to simplify inmanta modules testing.\n\n  :pypi:`pytest-inmanta-extensions`\n     *last release*: Mar 03, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Inmanta tests package\n\n  :pypi:`pytest-inmanta-lsm`\n     *last release*: Feb 12, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Common fixtures used in inmanta LSM related modules\n\n  :pypi:`pytest-inmanta-srlinux`\n     *last release*: Apr 22, 2025,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Pytest library to facilitate end to end testing of inmanta projects\n\n  :pypi:`pytest-inmanta-yang`\n     *last release*: Oct 28, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Common fixtures used in inmanta yang related modules\n\n  :pypi:`pytest-Inomaly`\n     *last release*: Feb 13, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A simple image diff plugin for pytest\n\n  :pypi:`pytest-in-robotframework`\n     *last release*: Nov 23, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     The extension enables easy execution of pytest tests within the Robot Framework environment.\n\n  :pypi:`pytest-insper`\n     *last release*: Mar 21, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin for courses at Insper\n\n  :pypi:`pytest-insta`\n     *last release*: Nov 22, 2025,\n     *status*: N/A,\n     *requires*: pytest>=9.0.0\n\n     A practical snapshot testing plugin for pytest\n\n  :pypi:`pytest-instafail`\n     *last release*: Mar 31, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=5)\n\n     pytest plugin to show failures instantly\n\n  :pypi:`pytest-instrument`\n     *last release*: Apr 05, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=5.1.0)\n\n     pytest plugin to instrument tests\n\n  :pypi:`pytest-insubprocess`\n     *last release*: Dec 08, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.4\n\n     A pytest plugin to execute test cases in a subprocess\n\n  :pypi:`pytest-integration`\n     *last release*: Nov 17, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Organizing pytests by integration or not\n\n  :pypi:`pytest-integration-mark`\n     *last release*: May 22, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=5.2)\n\n     Automatic integration test marking and excluding plugin for pytest\n\n  :pypi:`pytest-intent`\n     *last release*: Dec 17, 2025,\n     *status*: N/A,\n     *requires*: pytest<10.0.0,>=9.0.0\n\n     A pytest plugin for tracking requirement coverage.\n\n  :pypi:`pytest-interactive`\n     *last release*: Nov 30, 2017,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     A pytest plugin for console based interactive test selection just after the collection phase\n\n  :pypi:`pytest-intercept-remote`\n     *last release*: May 24, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.6)\n\n     Pytest plugin for intercepting outgoing connection requests during pytest run.\n\n  :pypi:`pytest-interface-tester`\n     *last release*: Feb 11, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest plugin for checking charm relation interface protocol compliance.\n\n  :pypi:`pytest-invenio`\n     *last release*: Jan 27, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<9.0.0,>=6\n\n     Pytest fixtures for Invenio.\n\n  :pypi:`pytest-involve`\n     *last release*: Feb 02, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Run tests covering a specific file or changeset\n\n  :pypi:`pytest-iovis`\n     *last release*: Nov 06, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.1.0\n\n     A Pytest plugin to enable Jupyter Notebook testing with Papermill\n\n  :pypi:`pytest-ipdb`\n     *last release*: Mar 20, 2013,\n     *status*: 2 - Pre-Alpha,\n     *requires*: N/A\n\n     A py.test plug-in to enable drop to ipdb debugger on test failure.\n\n  :pypi:`pytest-ipynb`\n     *last release*: Jan 29, 2019,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     THIS PROJECT IS ABANDONED\n\n  :pypi:`pytest-ipynb2`\n     *last release*: Mar 09, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin to run tests in Jupyter Notebooks\n\n  :pypi:`pytest-ipywidgets`\n     *last release*: Feb 24, 2026,\n     *status*: N/A,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-isolate`\n     *last release*: Sep 08, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Run pytest tests in isolated subprocesses\n\n  :pypi:`pytest-isolated`\n     *last release*: Mar 04, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     Run marked pytest tests in grouped subprocesses (cross-platform).\n\n  :pypi:`pytest-isolate-mpi`\n     *last release*: Feb 24, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=5\n\n     pytest-isolate-mpi allows for MPI-parallel tests being executed in a segfault and MPI_Abort safe manner\n\n  :pypi:`pytest-isort`\n     *last release*: Mar 05, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=5.0)\n\n     py.test plugin to check import ordering using isort\n\n  :pypi:`pytest-it`\n     *last release*: Jan 29, 2024,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Pytest plugin to display test reports as a plaintext spec, inspired by Rspec: https://github.com/mattduck/pytest-it.\n\n  :pypi:`pytest-item-dict`\n     *last release*: Nov 14, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.3.0\n\n     Get a hierarchical dict of session.items\n\n  :pypi:`pytest-iterassert`\n     *last release*: May 11, 2020,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Nicer list and iterable assertion messages for pytest\n\n  :pypi:`pytest-iteration`\n     *last release*: Aug 22, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Add iteration mark for tests\n\n  :pypi:`pytest-iters`\n     *last release*: May 24, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A contextmanager pytest fixture for handling multiple mock iters\n\n  :pypi:`pytest_jar_yuan`\n     *last release*: Dec 12, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A allure and pytest used package\n\n  :pypi:`pytest-jasmine`\n     *last release*: Nov 04, 2017,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     Run jasmine tests from your pytest test suite\n\n  :pypi:`pytest-jelastic`\n     *last release*: Nov 16, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.2.0,<8.0.0)\n\n     Pytest plugin defining the necessary command-line options to pass to pytests testing a Jelastic environment.\n\n  :pypi:`pytest-jest`\n     *last release*: May 22, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.3.2)\n\n     A custom jest-pytest oriented Pytest reporter\n\n  :pypi:`pytest-jinja`\n     *last release*: Oct 04, 2022,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=6.2.5,<7.0.0)\n\n     A plugin to generate customizable jinja-based HTML reports in pytest\n\n  :pypi:`pytest-jinja-check`\n     *last release*: Mar 14, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     Pytest plugin to lint Jinja2 templates in FastAPI applications\n\n  :pypi:`pytest-jira`\n     *last release*: Apr 15, 2025,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     py.test JIRA integration plugin, using markers\n\n  :pypi:`pytest-jira-xfail`\n     *last release*: Jul 09, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.2.0\n\n     Plugin skips (xfail) tests if unresolved Jira issue(s) linked\n\n  :pypi:`pytest-jira-xray`\n     *last release*: Oct 11, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.4\n\n     pytest plugin to integrate tests with JIRA XRAY\n\n  :pypi:`pytest-job-selection`\n     *last release*: Jan 30, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A pytest plugin for load balancing test suites\n\n  :pypi:`pytest-jobserver`\n     *last release*: Feb 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Limit parallel tests with posix jobserver.\n\n  :pypi:`pytest-joke`\n     *last release*: Oct 08, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.2.1)\n\n     Test failures are better served with humor.\n\n  :pypi:`pytest-json`\n     *last release*: Jan 18, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Generate JSON test reports\n\n  :pypi:`pytest-json-ctrf`\n     *last release*: Dec 28, 2025,\n     *status*: N/A,\n     *requires*: pytest>6.0.0\n\n     Pytest plugin to generate json report in CTRF (Common Test Report Format)\n\n  :pypi:`pytest-json-fixtures`\n     *last release*: Mar 14, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     JSON output for the --fixtures flag\n\n  :pypi:`pytest-jsonlint`\n     *last release*: Aug 04, 2016,\n     *status*: N/A,\n     *requires*: N/A\n\n     UNKNOWN\n\n  :pypi:`pytest-json-report`\n     *last release*: Mar 15, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.8.0)\n\n     A pytest plugin to report test results as JSON files\n\n  :pypi:`pytest-json-report-wip`\n     *last release*: Jul 23, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest >=3.8.0\n\n     A pytest plugin to report test results as JSON files\n\n  :pypi:`pytest-jsonschema`\n     *last release*: Nov 07, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2.0\n\n     A pytest plugin to perform JSONSchema validations\n\n  :pypi:`pytest-jsonschema-snapshot`\n     *last release*: Mar 08, 2026,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin for automatic JSON Schema generation and validation from examples\n\n  :pypi:`pytest-jtr`\n     *last release*: Jul 21, 2024,\n     *status*: N/A,\n     *requires*: pytest<8.0.0,>=7.1.2\n\n     pytest plugin supporting json test report output\n\n  :pypi:`pytest-jubilant`\n     *last release*: Mar 13, 2026,\n     *status*: N/A,\n     *requires*: pytest>=8.3.5\n\n     Add your description here\n\n  :pypi:`pytest-junit-logging`\n     *last release*: Nov 27, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.0\n\n     A pytest plugin for embedding log output into JUnit XML reports\n\n  :pypi:`pytest-junit-xray-xml`\n     *last release*: Jan 01, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Export test results in an augmented JUnit format for usage with Xray ()\n\n  :pypi:`pytest-jupyter`\n     *last release*: Oct 16, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     A pytest plugin for testing Jupyter libraries and extensions.\n\n  :pypi:`pytest-jupyterhub`\n     *last release*: Apr 25, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A reusable JupyterHub pytest plugin\n\n  :pypi:`pytest-jux`\n     *last release*: Jan 08, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.4\n\n     A pytest plugin for signing and publishing JUnit XML test reports to the Jux REST API\n\n  :pypi:`pytest-k8s`\n     *last release*: Jul 07, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.4.1\n\n     Kubernetes-based testing for pytest\n\n  :pypi:`pytest-kafka`\n     *last release*: Aug 14, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Zookeeper, Kafka server, and Kafka consumer fixtures for Pytest\n\n  :pypi:`pytest-kafka-broker`\n     *last release*: Feb 15, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin to run a single-broker Kafka cluster\n\n  :pypi:`pytest-kafkavents`\n     *last release*: Sep 08, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A plugin to send pytest events to Kafka\n\n  :pypi:`pytest-kairos`\n     *last release*: Aug 08, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=5.0.0\n\n     Pytest plugin with random number generation, reproducibility, and test repetition\n\n  :pypi:`pytest-kasima`\n     *last release*: Jan 26, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=7.2.1,<8.0.0)\n\n     Display horizontal lines above and below the captured standard output for easy viewing.\n\n  :pypi:`pytest-kedge`\n     *last release*: Jan 10, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     Agent-friendly structured test data collector for pytest\n\n  :pypi:`pytest-keep-together`\n     *last release*: Dec 07, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest plugin to customize test ordering by running all 'related' tests together\n\n  :pypi:`pytest-kexi`\n     *last release*: Apr 29, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.1.2,<8.0.0)\n\n\n\n  :pypi:`pytest-keyring`\n     *last release*: Dec 08, 2024,\n     *status*: N/A,\n     *requires*: pytest>=8.0.2\n\n     A Pytest plugin to access the system's keyring to provide credentials for tests\n\n  :pypi:`pytest-kind`\n     *last release*: Nov 30, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Kubernetes test support with KIND for pytest\n\n  :pypi:`pytest-kivy`\n     *last release*: Jul 06, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.6)\n\n     Kivy GUI tests fixtures using pytest\n\n  :pypi:`pytest-knows`\n     *last release*: Aug 22, 2014,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin that can automaticly skip test case based on dependence info calculated by trace\n\n  :pypi:`pytest-konira`\n     *last release*: Oct 09, 2011,\n     *status*: N/A,\n     *requires*: N/A\n\n     Run Konira DSL tests with py.test\n\n  :pypi:`pytest-kookit`\n     *last release*: Sep 10, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Your simple but kooky integration testing with pytest\n\n  :pypi:`pytest-koopmans`\n     *last release*: Nov 21, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A plugin for testing the koopmans package\n\n  :pypi:`pytest-krtech-common`\n     *last release*: Nov 28, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest krtech common library\n\n  :pypi:`pytest-kubernetes`\n     *last release*: Oct 23, 2025,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.3.0\n\n\n\n  :pypi:`pytest_kustomize`\n     *last release*: Dec 08, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Parse and validate kustomize output\n\n  :pypi:`pytest-kuunda`\n     *last release*: Feb 25, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest >=6.2.0\n\n     pytest plugin to help with test data setup for PySpark tests\n\n  :pypi:`pytest-kwparametrize`\n     *last release*: Jan 22, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=6)\n\n     Alternate syntax for @pytest.mark.parametrize with test cases as dictionaries and default value fallbacks\n\n  :pypi:`pytest-lambda`\n     *last release*: May 27, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<9,>=3.6\n\n     Define pytest fixtures with lambda functions.\n\n  :pypi:`pytest-lamp`\n     *last release*: Jan 06, 2017,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-langchain`\n     *last release*: Feb 26, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest-style test runner for langchain agents\n\n  :pypi:`pytest-language-server`\n     *last release*: Mar 04, 2026,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A blazingly fast Language Server Protocol implementation for pytest\n\n  :pypi:`pytest-lark`\n     *last release*: Nov 05, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     Create fancy and clear HTML test reports.\n\n  :pypi:`pytest-latin-hypercube`\n     *last release*: Jun 26, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Implementation of Latin Hypercube Sampling for pytest.\n\n  :pypi:`pytest-launchable`\n     *last release*: Apr 05, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=4.2.0)\n\n     Launchable Pytest Plugin\n\n  :pypi:`pytest-layab`\n     *last release*: Oct 05, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest fixtures for layab.\n\n  :pypi:`pytest-lazy-fixture`\n     *last release*: Feb 01, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.2.5)\n\n     It helps to use fixtures in pytest.mark.parametrize\n\n  :pypi:`pytest-lazy-fixtures`\n     *last release*: Sep 16, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7\n\n     Allows you to use fixtures in @pytest.mark.parametrize.\n\n  :pypi:`pytest-ldap`\n     *last release*: Aug 18, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     python-ldap fixtures for pytest\n\n  :pypi:`pytest-leak-finder`\n     *last release*: Dec 19, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     Find the test that's leaking before the one that fails\n\n  :pypi:`pytest-leaks`\n     *last release*: Nov 27, 2019,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     A pytest plugin to trace resource leaks.\n\n  :pypi:`pytest-leaping`\n     *last release*: Mar 27, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-leela`\n     *last release*: Feb 19, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     Type-aware mutation testing for Python — fast, opinionated, pytest-native\n\n  :pypi:`pytest-leo-interface`\n     *last release*: Mar 19, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest extension tool for leo projects.\n\n  :pypi:`pytest-level`\n     *last release*: Oct 21, 2019,\n     *status*: N/A,\n     *requires*: pytest\n\n     Select tests of a given level or lower\n\n  :pypi:`pytest-lf-skip`\n     *last release*: Feb 27, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.3.5\n\n     A pytest plugin which makes \\`--last-failed\\` skip instead of deselect tests.\n\n  :pypi:`pytest-libfaketime`\n     *last release*: Apr 12, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.0.0\n\n     A python-libfaketime plugin for pytest\n\n  :pypi:`pytest-libiio`\n     *last release*: Aug 15, 2025,\n     *status*: N/A,\n     *requires*: pytest>=3.5.0\n\n     A pytest plugin for testing libiio based devices\n\n  :pypi:`pytest-libnotify`\n     *last release*: Apr 02, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Pytest plugin that shows notifications about the test run\n\n  :pypi:`pytest-ligo`\n     *last release*: Jan 16, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-lineno`\n     *last release*: Dec 04, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin to show the line numbers of test functions\n\n  :pypi:`pytest-line-profiler`\n     *last release*: Aug 10, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest >=3.5.0\n\n     Profile code executed by pytest\n\n  :pypi:`pytest-line-profiler-apn`\n     *last release*: Dec 05, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=3.5.0)\n\n     Profile code executed by pytest\n\n  :pypi:`pytest-line-runner`\n     *last release*: Feb 08, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Run pytest tests by line number instead of exact test name\n\n  :pypi:`pytest-lisa`\n     *last release*: Jan 21, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=6.1.2,<7.0.0)\n\n     Pytest plugin for organizing tests.\n\n  :pypi:`pytest-listener`\n     *last release*: Nov 29, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A simple network listener\n\n  :pypi:`pytest-litf`\n     *last release*: Jan 18, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.1.1)\n\n     A pytest plugin that stream output in LITF format\n\n  :pypi:`pytest-litter`\n     *last release*: Nov 23, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest >=6.1\n\n     Pytest plugin which verifies that tests do not modify file trees.\n\n  :pypi:`pytest-live`\n     *last release*: Mar 08, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Live results for pytest\n\n  :pypi:`pytest-liveview`\n     *last release*: Mar 09, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     Pytest plugin that shows a real-time test dashboard in a local web server\n\n  :pypi:`pytest-llm`\n     *last release*: Oct 03, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     pytest-llm: A pytest plugin for testing LLM outputs with success rate thresholds.\n\n  :pypi:`pytest-llm-agent`\n     *last release*: Dec 16, 2025,\n     *status*: N/A,\n     *requires*: pytest>=9.0.2\n\n     LLM Agent for working with pytest\n\n  :pypi:`pytest-llm-assert`\n     *last release*: Feb 03, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=9.0\n\n     Simple LLM-powered assertions for any pytest test\n\n  :pypi:`pytest-llmeval`\n     *last release*: Mar 19, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A pytest plugin to evaluate/benchmark LLM prompts\n\n  :pypi:`pytest-llm-report`\n     *last release*: Jan 21, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     Human-friendly pytest test reports with optional LLM annotations\n\n  :pypi:`pytest-llmtest`\n     *last release*: Mar 08, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0; extra == \"dev\"\n\n     The pytest for LLMs — fast, Pydantic-based assertions for AI applications\n\n  :pypi:`pytest-lobster`\n     *last release*: Jul 26, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     Pytest to generate lobster tracing files\n\n  :pypi:`pytest-local-badge`\n     *last release*: Jan 15, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=6.1.0)\n\n     Generate local badges (shields) reporting your test suite status.\n\n  :pypi:`pytest-localftpserver`\n     *last release*: Nov 16, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A PyTest plugin which provides an FTP fixture for your tests\n\n  :pypi:`pytest-localserver`\n     *last release*: Nov 24, 2025,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest plugin to test server connections locally.\n\n  :pypi:`pytest-localstack`\n     *last release*: Jun 07, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.0.0,<7.0.0)\n\n     Pytest plugin for AWS integration tests\n\n  :pypi:`pytest-lock`\n     *last release*: Feb 03, 2024,\n     *status*: N/A,\n     *requires*: pytest (>=7.4.3,<8.0.0)\n\n     pytest-lock is a pytest plugin that allows you to \"lock\" the results of unit tests, storing them in a local cache. This is particularly useful for tests that are resource-intensive or don't need to be run every time. When the tests are run subsequently, pytest-lock will compare the current results with the locked results and issue a warning if there are any discrepancies.\n\n  :pypi:`pytest-lockable`\n     *last release*: Sep 08, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     lockable resource plugin for pytest\n\n  :pypi:`pytest-locker`\n     *last release*: Dec 20, 2024,\n     *status*: N/A,\n     *requires*: pytest>=5.4\n\n     Used to lock object during testing. Essentially changing assertions from being hard coded to asserting that nothing changed\n\n  :pypi:`pytest-loco`\n     *last release*: Mar 08, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest<10.0.0,>=9.0.2\n\n     Another one YAML-based DSL for testing\n\n  :pypi:`pytest-loco-allure`\n     *last release*: Mar 08, 2026,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Allure support for pytest-loco\n\n  :pypi:`pytest-loco-http`\n     *last release*: Feb 25, 2026,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     HTTP support for pytest-loco\n\n  :pypi:`pytest-loco-json`\n     *last release*: Feb 25, 2026,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     JSON support for pytest-loco\n\n  :pypi:`pytest-log`\n     *last release*: Aug 15, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=3.8)\n\n     print log\n\n  :pypi:`pytest-logbook`\n     *last release*: Nov 23, 2015,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.8)\n\n     py.test plugin to capture logbook log messages\n\n  :pypi:`pytest-logdog`\n     *last release*: Jun 15, 2021,\n     *status*: 1 - Planning,\n     *requires*: pytest (>=6.2.0)\n\n     Pytest plugin to test logging\n\n  :pypi:`pytest-logfest`\n     *last release*: Jul 21, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Pytest plugin providing three logger fixtures with basic or full writing to log files\n\n  :pypi:`pytest-log-filter`\n     *last release*: Nov 13, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Ignore some loggers' log for pytest\n\n  :pypi:`pytest-logger`\n     *last release*: Mar 10, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.2)\n\n     Plugin configuring handlers for loggers from Python logging module.\n\n  :pypi:`pytest-logger-db`\n     *last release*: Sep 14, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Add your description here\n\n  :pypi:`pytest-logging`\n     *last release*: Nov 04, 2015,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Configures logging and allows tweaking the log level with a py.test flag\n\n  :pypi:`pytest-logging-end-to-end-test-tool`\n     *last release*: Sep 23, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.1.2,<8.0.0)\n\n\n\n  :pypi:`pytest-logging-strict`\n     *last release*: May 20, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     pytest fixture logging configured from packaged YAML\n\n  :pypi:`pytest-logikal`\n     *last release*: Mar 13, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest==9.0.2\n\n     Common testing environment\n\n  :pypi:`pytest-log-report`\n     *last release*: Dec 26, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Package for creating a pytest test run reprot\n\n  :pypi:`pytest-logscanner`\n     *last release*: Sep 30, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.2.2\n\n     Pytest plugin for logscanner (A logger for python logging outputting to easily viewable (and filterable) html files. Good for people not grep savey, and color higlighting and quickly changing filters might even bye useful for commandline wizards.)\n\n  :pypi:`pytest-loguru`\n     *last release*: Mar 20, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest; extra == \"test\"\n\n     Pytest Loguru\n\n  :pypi:`pytest-loop`\n     *last release*: Oct 17, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     pytest plugin for looping tests\n\n  :pypi:`pytest-lsp`\n     *last release*: Oct 25, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.0\n\n     A pytest plugin for end-to-end testing of language servers\n\n  :pypi:`pytest-lw-realtime-result`\n     *last release*: Mar 13, 2025,\n     *status*: N/A,\n     *requires*: pytest>=3.5.0\n\n     Pytest plugin to generate realtime test results to a file\n\n  :pypi:`pytest-manifest`\n     *last release*: Apr 07, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     PyTest plugin for recording and asserting against a manifest file\n\n  :pypi:`pytest-manual-marker`\n     *last release*: Aug 04, 2022,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7\n\n     pytest marker for marking manual tests\n\n  :pypi:`pytest-mark-ac`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<10,>=8.4\n\n     Provides a marker to reference acceptance criteria from PyTest tests through annotations\n\n  :pypi:`pytest-mark-count`\n     *last release*: Nov 13, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.0.0\n\n     Get a count of the number of tests marked, unmarked, and unique tests if tests have multiple markers\n\n  :pypi:`pytest-markdir`\n     *last release*: Feb 01, 2026,\n     *status*: N/A,\n     *requires*: pytest<10,>=8.0\n\n\n\n  :pypi:`pytest-markdoctest`\n     *last release*: Jul 22, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6)\n\n     A pytest plugin to doctest your markdown files\n\n  :pypi:`pytest-markdown`\n     *last release*: Jan 15, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.0.1,<7.0.0)\n\n     Test your markdown docs with pytest\n\n  :pypi:`pytest-markdown-docs`\n     *last release*: Jan 28, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     Run markdown code fences through pytest\n\n  :pypi:`pytest-markdown-report`\n     *last release*: Jan 10, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     Token-efficient markdown test reports for LLM-based TDD agents\n\n  :pypi:`pytest-marker-bugzilla`\n     *last release*: Apr 02, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=2.2.4\n\n     py.test bugzilla integration plugin, using markers\n\n  :pypi:`pytest-markers-presence`\n     *last release*: Oct 30, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.0\n\n     A simple plugin to detect missed pytest tags and markers\"\n\n  :pypi:`pytest-mark-filter`\n     *last release*: May 11, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.3.0\n\n     Filter pytest marks by name using match kw\n\n  :pypi:`pytest-markfiltration`\n     *last release*: Nov 08, 2011,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     UNKNOWN\n\n  :pypi:`pytest-mark-integration`\n     *last release*: Jan 13, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Pytest plugin for automatic integration test marking and management\n\n  :pypi:`pytest-mark-manage`\n     *last release*: Aug 15, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     用例标签化管理\n\n  :pypi:`pytest-mark-no-py3`\n     *last release*: May 17, 2019,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest plugin and bowler codemod to help migrate tests to Python 3\n\n  :pypi:`pytest-marks`\n     *last release*: Nov 23, 2012,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     UNKNOWN\n\n  :pypi:`pytest-mask-secrets`\n     *last release*: Dec 17, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin to hide sensitive data in test reports\n\n  :pypi:`pytest-matcher`\n     *last release*: Aug 07, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Easy way to match captured \\`pytest\\` output against expectations stored in files\n\n  :pypi:`pytest-matchers`\n     *last release*: Dec 19, 2025,\n     *status*: N/A,\n     *requires*: pytest<10.0,>=7.0\n\n     Matchers for pytest\n\n  :pypi:`pytest-match-skip`\n     *last release*: May 15, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.4.1)\n\n     Skip matching marks. Matches partial marks using wildcards.\n\n  :pypi:`pytest-mat-report`\n     *last release*: Jan 20, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     this is report\n\n  :pypi:`pytest-matrix`\n     *last release*: Jun 24, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=5.4.3,<6.0.0)\n\n     Provide tools for generating tests from combinations of fixtures.\n\n  :pypi:`pytest-maxcov`\n     *last release*: Sep 24, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.4.0,<8.0.0)\n\n     Compute the maximum coverage available through pytest with the minimum execution time cost\n\n  :pypi:`pytest-max-warnings`\n     *last release*: Oct 23, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.3.3\n\n     A Pytest plugin to exit non-zero exit code when the configured maximum warnings has been exceeded.\n\n  :pypi:`pytest-maybe-context`\n     *last release*: Apr 16, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7,<8)\n\n     Simplify tests with warning and exception cases.\n\n  :pypi:`pytest-maybe-raises`\n     *last release*: May 27, 2022,\n     *status*: N/A,\n     *requires*: pytest ; extra == 'dev'\n\n     Pytest fixture for optional exception testing.\n\n  :pypi:`pytest-mccabe`\n     *last release*: Jul 22, 2020,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=5.4.0)\n\n     pytest plugin to run the mccabe code complexity checker.\n\n  :pypi:`pytest-mcp`\n     *last release*: Jul 07, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.4.0\n\n     Pytest-style framework for evaluating Model Context Protocol (MCP) servers.\n\n  :pypi:`pytest-mcp-tools`\n     *last release*: Mar 12, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0; extra == \"test\"\n\n\n\n  :pypi:`pytest-md`\n     *last release*: Jul 11, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=4.2.1)\n\n     Plugin for generating Markdown reports for pytest results\n\n  :pypi:`pytest-md-report`\n     *last release*: May 02, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest!=6.0.0,<9,>=3.3.2\n\n     A pytest plugin to generate test outcomes reports with markdown table format.\n\n  :pypi:`pytest-meilisearch`\n     *last release*: Oct 08, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.4.3\n\n     Pytest helpers for testing projects using Meilisearch\n\n  :pypi:`pytest-memlog`\n     *last release*: May 03, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.3.0,<8.0.0)\n\n     Log memory usage during tests\n\n  :pypi:`pytest-memprof`\n     *last release*: Mar 29, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Estimates memory consumption of test functions\n\n  :pypi:`pytest-memray`\n     *last release*: Aug 18, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.2\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-menu`\n     *last release*: Oct 04, 2017,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=2.4.2)\n\n     A pytest plugin for console based interactive test selection just after the collection phase\n\n  :pypi:`pytest-mercurial`\n     *last release*: Nov 21, 2020,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     pytest plugin to write integration tests for projects using Mercurial Python internals\n\n  :pypi:`pytest-mergify`\n     *last release*: Jan 26, 2026,\n     *status*: N/A,\n     *requires*: pytest>=6.0.0\n\n     Pytest plugin for Mergify\n\n  :pypi:`pytest-mesh`\n     *last release*: Aug 05, 2022,\n     *status*: N/A,\n     *requires*: pytest (==7.1.2)\n\n     pytest_mesh插件\n\n  :pypi:`pytest-message`\n     *last release*: Aug 04, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=6.2.5)\n\n     Pytest plugin for sending report message of marked tests execution\n\n  :pypi:`pytest-messenger`\n     *last release*: Nov 24, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest to Slack reporting plugin\n\n  :pypi:`pytest-metadata`\n     *last release*: Feb 12, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     pytest plugin for test session metadata\n\n  :pypi:`pytest-metaexport`\n     *last release*: Jun 24, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.1.0\n\n     Pytest plugin for exporting custom test metadata to JSON.\n\n  :pypi:`pytest-metrics`\n     *last release*: Apr 04, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Custom metrics report for pytest\n\n  :pypi:`pytest-mfd-config`\n     *last release*: Jul 11, 2025,\n     *status*: N/A,\n     *requires*: pytest<9,>=7.2.1\n\n     Pytest Plugin that handles test and topology configs and all their belongings like helper fixtures.\n\n  :pypi:`pytest-mfd-logging`\n     *last release*: Nov 14, 2025,\n     *status*: N/A,\n     *requires*: pytest<9,>=7.2.1\n\n     Module for handling PyTest logging.\n\n  :pypi:`pytest-mh`\n     *last release*: Oct 16, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest multihost plugin\n\n  :pypi:`pytest-mimesis`\n     *last release*: Mar 21, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=4.2)\n\n     Mimesis integration with the pytest test runner\n\n  :pypi:`pytest-mimic`\n     *last release*: Apr 24, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     Easily record function calls while testing\n\n  :pypi:`pytest-minecraft`\n     *last release*: Apr 06, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=6.0.1)\n\n     A pytest plugin for running tests against Minecraft releases\n\n  :pypi:`pytest-mini`\n     *last release*: Feb 06, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.2.0,<8.0.0)\n\n     A plugin to test mp\n\n  :pypi:`pytest-minio-mock`\n     *last release*: Aug 06, 2025,\n     *status*: N/A,\n     *requires*: pytest>=5.0.0\n\n     A pytest plugin for mocking Minio S3 interactions\n\n  :pypi:`pytest-mirror`\n     *last release*: Jul 30, 2025,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pluggy-based pytest plugin and CLI tool for ensuring your test suite mirrors your source code structure\n\n  :pypi:`pytest-missing-fixtures`\n     *last release*: Oct 14, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Pytest plugin that creates missing fixtures\n\n  :pypi:`pytest-missing-modules`\n     *last release*: Nov 17, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.3.2\n\n     Pytest plugin to easily fake missing modules\n\n  :pypi:`pytest-mitmproxy`\n     *last release*: Nov 13, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     pytest plugin for mitmproxy tests\n\n  :pypi:`pytest-mitmproxy-plugin`\n     *last release*: Apr 10, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.2.0\n\n     Use MITM Proxy in autotests with full control from code\n\n  :pypi:`pytest-ml`\n     *last release*: May 04, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Test your machine learning!\n\n  :pypi:`pytest-mocha`\n     *last release*: Apr 02, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=5.4.0)\n\n     pytest plugin to display test execution output like a mochajs\n\n  :pypi:`pytest-mock`\n     *last release*: Sep 16, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2.5\n\n     Thin-wrapper around the mock package for easier use with pytest\n\n  :pypi:`pytest-mock-api`\n     *last release*: Feb 13, 2019,\n     *status*: 1 - Planning,\n     *requires*: pytest (>=4.0.0)\n\n     A mock API server with configurable routes and responses available as a fixture.\n\n  :pypi:`pytest-mock-generator`\n     *last release*: May 16, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A pytest fixture wrapper for https://pypi.org/project/mock-generator\n\n  :pypi:`pytest-mock-helper`\n     *last release*: Jan 24, 2018,\n     *status*: N/A,\n     *requires*: pytest\n\n     Help you mock HTTP call and generate mock code\n\n  :pypi:`pytest-mockito`\n     *last release*: Feb 10, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6\n\n     Base fixtures for mockito\n\n  :pypi:`pytest-mockllm`\n     *last release*: Dec 22, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     🚀 Zero-config pytest plugin for mocking LLM APIs - OpenAI, Anthropic, Gemini, LangChain & more\n\n  :pypi:`pytest-mockredis`\n     *last release*: Jan 02, 2018,\n     *status*: 2 - Pre-Alpha,\n     *requires*: N/A\n\n     An in-memory mock of a Redis server that runs in a separate thread. This is to be used for unit-tests that require a Redis database.\n\n  :pypi:`pytest-mock-resources`\n     *last release*: Sep 17, 2025,\n     *status*: N/A,\n     *requires*: pytest>=1.0\n\n     A pytest plugin for easily instantiating reproducible mock resources.\n\n  :pypi:`pytest-mock-server`\n     *last release*: Jan 09, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Mock server plugin for pytest\n\n  :pypi:`pytest-mockservers`\n     *last release*: Mar 31, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=4.3.0)\n\n     A set of fixtures to test your requests to HTTP/UDP servers\n\n  :pypi:`pytest-mocktcp`\n     *last release*: Oct 11, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin for testing TCP clients\n\n  :pypi:`pytest-mock-unity-catalog`\n     *last release*: Mar 12, 2026,\n     *status*: N/A,\n     *requires*: pytest\n\n     Unity Catalog pyspark fixtures\n\n  :pypi:`pytest-modalt`\n     *last release*: Feb 27, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest >=6.2.0\n\n     Massively distributed pytest runs using modal.com\n\n  :pypi:`pytest-model-lib`\n     *last release*: Feb 22, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin for model-lib\n\n  :pypi:`pytest-modern`\n     *last release*: Aug 19, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8\n\n     A more modern pytest\n\n  :pypi:`pytest-modified-env`\n     *last release*: Jan 29, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Pytest plugin to fail a test if it leaves modified \\`os.environ\\` afterwards.\n\n  :pypi:`pytest-modifyjunit`\n     *last release*: Jan 10, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Utility for adding additional properties to junit xml for IDM QE\n\n  :pypi:`pytest-molecule`\n     *last release*: Mar 29, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=7.0.0)\n\n     PyTest Molecule Plugin :: discover and run molecule tests\n\n  :pypi:`pytest-molecule-JC`\n     *last release*: Jul 18, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=7.0.0)\n\n     PyTest Molecule Plugin :: discover and run molecule tests\n\n  :pypi:`pytest-mongo`\n     *last release*: Feb 04, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.4\n\n     MongoDB process and client fixtures plugin for Pytest.\n\n  :pypi:`pytest-mongodb`\n     *last release*: May 16, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin for MongoDB fixtures\n\n  :pypi:`pytest-mongodb-nono`\n     *last release*: Jan 07, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin for MongoDB\n\n  :pypi:`pytest-mongodb-ry`\n     *last release*: Sep 25, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin for MongoDB\n\n  :pypi:`pytest-mongo-docker`\n     *last release*: Mar 05, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.4\n\n     A tiny plugin for pytest which runs MongoDB in Docker\n\n  :pypi:`pytest-monitor`\n     *last release*: Jun 25, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest plugin for analyzing resource usage.\n\n  :pypi:`pytest-monkeyplus`\n     *last release*: Sep 18, 2012,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest's monkeypatch subclass with extra functionalities\n\n  :pypi:`pytest-monkeytype`\n     *last release*: Jul 29, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest-monkeytype: Generate Monkeytype annotations from your pytest tests.\n\n  :pypi:`pytest-moto`\n     *last release*: Aug 28, 2015,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     Fixtures for integration tests of AWS services,uses moto mocking library.\n\n  :pypi:`pytest-moto-fixtures`\n     *last release*: Nov 17, 2025,\n     *status*: 1 - Planning,\n     *requires*: pytest<9.1,>=8.3; extra == \"pytest\"\n\n     Fixtures for testing code that interacts with AWS\n\n  :pypi:`pytest-motor`\n     *last release*: Jul 21, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     A pytest plugin for motor, the non-blocking MongoDB driver.\n\n  :pypi:`pytest-mp`\n     *last release*: May 23, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A test batcher for multiprocessed Pytest runs\n\n  :pypi:`pytest-mpi`\n     *last release*: Jan 08, 2022,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     pytest plugin to collect information from tests\n\n  :pypi:`pytest-mpiexec`\n     *last release*: Jul 29, 2024,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     pytest plugin for running individual tests with mpiexec\n\n  :pypi:`pytest-mpi-tmweigand`\n     *last release*: Dec 27, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     forked pytest plugin to collect information from tests\n\n  :pypi:`pytest-mpl`\n     *last release*: Nov 15, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=5.4.0\n\n     pytest plugin to help with testing figures output from Matplotlib\n\n  :pypi:`pytest-mpl-oggm`\n     *last release*: Mar 09, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2.5\n\n     pytest plugin to help with testing figures output from Matplotlib - OGGM fork\n\n  :pypi:`pytest-mproc`\n     *last release*: Nov 15, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6)\n\n     low-startup-overhead, scalable, distributed-testing pytest plugin\n\n  :pypi:`pytest-mqtt`\n     *last release*: Jan 28, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<10; extra == \"test\"\n\n     pytest-mqtt supports testing systems based on MQTT\n\n  :pypi:`pytest-multihost`\n     *last release*: Apr 07, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Utility for writing multi-host tests for pytest\n\n  :pypi:`pytest-multilog`\n     *last release*: Dec 28, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Multi-process logs handling and other helpers for pytest\n\n  :pypi:`pytest-multithreading`\n     *last release*: Aug 05, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     a pytest plugin for th and concurrent testing\n\n  :pypi:`pytest-multithreading-allure`\n     *last release*: Nov 25, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest_multithreading_allure\n\n  :pypi:`pytest-mutagen`\n     *last release*: Jul 24, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=5.4)\n\n     Add the mutation testing feature to pytest\n\n  :pypi:`pytest-my-cool-lib`\n     *last release*: Nov 02, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.1.3,<8.0.0)\n\n\n\n  :pypi:`pytest-my-plugin`\n     *last release*: Jan 27, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.0\n\n     A pytest plugin that does awesome things\n\n  :pypi:`pytest-mypy`\n     *last release*: Apr 02, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0\n\n     A Pytest Plugin for Mypy\n\n  :pypi:`pytest-mypyd`\n     *last release*: Aug 20, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (<4.7,>=2.8) ; python_version < \"3.5\"\n\n     Mypy static type checker plugin for Pytest\n\n  :pypi:`pytest-mypy-plugins`\n     *last release*: Mar 12, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     pytest plugin for writing tests for mypy plugins\n\n  :pypi:`pytest-mypy-plugins-shim`\n     *last release*: Feb 14, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.0.0\n\n     Substitute for \"pytest-mypy-plugins\" for Python implementations which aren't supported by mypy.\n\n  :pypi:`pytest-mypy-runner`\n     *last release*: Apr 23, 2024,\n     *status*: N/A,\n     *requires*: pytest>=8.0\n\n     Run the mypy static type checker as a pytest test case\n\n  :pypi:`pytest-mypy-testing`\n     *last release*: Jan 26, 2026,\n     *status*: N/A,\n     *requires*: pytest>=8\n\n     Pytest plugin to check mypy output\n\n  :pypi:`pytest-mysql`\n     *last release*: Dec 10, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2\n\n     MySQL process and client fixtures for pytest\n\n  :pypi:`pytest-nb`\n     *last release*: Jul 26, 2025,\n     *status*: N/A,\n     *requires*: pytest==8.4.1\n\n     Seedable Jupyter Notebook testing tool\n\n  :pypi:`pytest-nb-as-test`\n     *last release*: Feb 25, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest<9.1.0,>=7.0.0; python_version < \"3.14\"\n\n     Use notebooks as pytests. Keep your notebooks working.\n\n  :pypi:`pytest-nbgrader`\n     *last release*: Nov 05, 2025,\n     *status*: 2 - Pre-Alpha,\n     *requires*: pytest>=8.3.2; extra == \"dev\"\n\n     Pytest plugin for using with nbgrader and generating test cases.\n\n  :pypi:`pytest-ndb`\n     *last release*: Apr 28, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest notebook debugger\n\n  :pypi:`pytest-needle`\n     *last release*: Dec 10, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest (<5.0.0,>=3.0.0)\n\n     pytest plugin for visual testing websites using selenium\n\n  :pypi:`pytest-neo`\n     *last release*: Jan 08, 2022,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=6.2.0)\n\n     pytest-neo is a plugin for pytest that shows tests like screen of Matrix.\n\n  :pypi:`pytest-neon`\n     *last release*: Feb 05, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     Pytest plugin for Neon database branch isolation in tests\n\n  :pypi:`pytest-neos`\n     *last release*: Sep 10, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<8.0,>=7.2; extra == \"dev\"\n\n     Pytest plugin for neos\n\n  :pypi:`pytest-netconf`\n     *last release*: Nov 03, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin that provides a mock NETCONF (RFC6241/RFC6242) server for local testing.\n\n  :pypi:`pytest-netdut`\n     *last release*: Oct 09, 2025,\n     *status*: N/A,\n     *requires*: pytest>=3.5.0\n\n     \"Automated software testing for switches using pytest\"\n\n  :pypi:`pytest-network`\n     *last release*: May 07, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     A simple plugin to disable network on socket level.\n\n  :pypi:`pytest-network-endpoints`\n     *last release*: Mar 06, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     Network endpoints plugin for pytest\n\n  :pypi:`pytest-never-sleep`\n     *last release*: May 05, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=3.5.1)\n\n     pytest plugin helps to avoid adding tests without mock \\`time.sleep\\`\n\n  :pypi:`pytest-nginx`\n     *last release*: May 03, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=3.0.0\n\n     nginx fixture for pytest\n\n  :pypi:`pytest-nginx-iplweb`\n     *last release*: Mar 01, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     nginx fixture for pytest - iplweb temporary fork\n\n  :pypi:`pytest-ngrok`\n     *last release*: Jan 20, 2022,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-ngsfixtures`\n     *last release*: Sep 06, 2019,\n     *status*: 2 - Pre-Alpha,\n     *requires*: pytest (>=5.0.0)\n\n     pytest ngs fixtures\n\n  :pypi:`pytest-nhsd-apim`\n     *last release*: Feb 13, 2026,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.2.0\n\n     Pytest plugin accessing NHSDigital's APIM proxies\n\n  :pypi:`pytest-nice`\n     *last release*: May 04, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A pytest plugin that alerts user of failed test cases with screen notifications\n\n  :pypi:`pytest-nice-parametrize`\n     *last release*: Apr 17, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A small snippet for nicer PyTest's Parametrize\n\n  :pypi:`pytest_nlcov`\n     *last release*: Aug 05, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin to get the coverage of the new lines (based on git diff) only\n\n  :pypi:`pytest-nocustom`\n     *last release*: Aug 05, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Run all tests without custom markers\n\n  :pypi:`pytest-node-dependency`\n     *last release*: Apr 10, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin for controlling execution flow\n\n  :pypi:`pytest-nodev`\n     *last release*: Jul 21, 2016,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.8.1)\n\n     Test-driven source code search for Python.\n\n  :pypi:`pytest-nogarbage`\n     *last release*: Feb 24, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=4.6.0\n\n     Ensure a test produces no garbage\n\n  :pypi:`pytest-no-problem`\n     *last release*: Jan 11, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     Pytest plugin to tell you when there's no problem\n\n  :pypi:`pytest-nose-attrib`\n     *last release*: Aug 13, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin to use nose @attrib marks decorators and pick tests based on attributes and partially uses nose-attrib plugin approach\n\n  :pypi:`pytest_notebook`\n     *last release*: Nov 28, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     A pytest plugin for testing Jupyter Notebooks.\n\n  :pypi:`pytest-notice`\n     *last release*: Nov 05, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     Send pytest execution result email\n\n  :pypi:`pytest-notification`\n     *last release*: Jun 19, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=4)\n\n     A pytest plugin for sending a desktop notification and playing a sound upon completion of tests\n\n  :pypi:`pytest-notifier`\n     *last release*: Jun 12, 2020,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     A pytest plugin to notify test result\n\n  :pypi:`pytest-notifier-plugin`\n     *last release*: Dec 22, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.0\n\n     Pytest plugin для отправки нотификаций в различные каналы связи о статуе прохождения тестов.\n\n  :pypi:`pytest_notify`\n     *last release*: Jul 05, 2017,\n     *status*: N/A,\n     *requires*: pytest>=3.0.0\n\n     Get notifications when your tests ends\n\n  :pypi:`pytest-notimplemented`\n     *last release*: Aug 27, 2019,\n     *status*: N/A,\n     *requires*: pytest (>=5.1,<6.0)\n\n     Pytest markers for not implemented features and tests.\n\n  :pypi:`pytest-notion`\n     *last release*: Aug 07, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     A PyTest Reporter to send test runs to Notion.so\n\n  :pypi:`pytest-nunit`\n     *last release*: Feb 26, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A pytest plugin for generating NUnit3 test result XML output\n\n  :pypi:`pytest-oar`\n     *last release*: May 12, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.0.1\n\n     PyTest plugin for the OAR testing framework\n\n  :pypi:`pytest-oarepo`\n     *last release*: Feb 17, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.1.2; extra == \"dev\"\n\n\n\n  :pypi:`pytest-object-getter`\n     *last release*: Jul 31, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Import any object from a 3rd party module while mocking its namespace on demand.\n\n  :pypi:`pytest-ochrus`\n     *last release*: Feb 21, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest results data-base and HTML reporter\n\n  :pypi:`pytest-odc`\n     *last release*: Aug 04, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A pytest plugin for simplifying ODC database tests\n\n  :pypi:`pytest-odoo`\n     *last release*: May 20, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8\n\n     py.test plugin to run Odoo tests\n\n  :pypi:`pytest-odoo-fixtures`\n     *last release*: Jun 25, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Project description\n\n  :pypi:`pytest-oduit`\n     *last release*: Feb 11, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8\n\n     py.test plugin to run Odoo tests\n\n  :pypi:`pytest-oerp`\n     *last release*: Feb 28, 2012,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin to test OpenERP modules\n\n  :pypi:`pytest-offline`\n     *last release*: Mar 09, 2023,\n     *status*: 1 - Planning,\n     *requires*: pytest (>=7.0.0,<8.0.0)\n\n\n\n  :pypi:`pytest-ogsm-plugin`\n     *last release*: May 16, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     针对特定项目定制化插件，优化了pytest报告展示方式,并添加了项目所需特定参数\n\n  :pypi:`pytest-ok`\n     *last release*: Apr 01, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     The ultimate pytest output plugin\n\n  :pypi:`pytest-once`\n     *last release*: Oct 10, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8.4.0\n\n     xdist-safe 'run once' fixture decorator for pytest (setup/teardown across workers)\n\n  :pypi:`pytest-only`\n     *last release*: May 27, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<9,>=3.6.0\n\n     Use @pytest.mark.only to run a single test\n\n  :pypi:`pytest-oof`\n     *last release*: Dec 11, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A Pytest plugin providing structured, programmatic access to a test run's results\n\n  :pypi:`pytest-oot`\n     *last release*: Sep 18, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Run object-oriented tests in a simple format\n\n  :pypi:`pytest-openapi`\n     *last release*: Mar 04, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     \\`pytest --openapi\\` - an opinionated, lightweight black-box contract tester against a live API using its OpenAPI specification as the source of truth\n\n  :pypi:`pytest-openfiles`\n     *last release*: Jun 05, 2024,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=4.6\n\n     Pytest plugin for detecting inadvertent open file handles\n\n  :pypi:`pytest-open-html`\n     *last release*: Mar 31, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.0\n\n     Auto-open HTML reports after pytest runs\n\n  :pypi:`pytest-opentelemetry`\n     *last release*: Apr 25, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin for instrumenting test runs via OpenTelemetry\n\n  :pypi:`pytest-opentmi`\n     *last release*: Feb 09, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=5.0\n\n     pytest plugin for publish results to opentmi\n\n  :pypi:`pytest-operator`\n     *last release*: Sep 28, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     Fixtures for Charmed Operators\n\n  :pypi:`pytest-optional`\n     *last release*: Oct 07, 2015,\n     *status*: N/A,\n     *requires*: N/A\n\n     include/exclude values of fixtures in pytest\n\n  :pypi:`pytest-optional-tests`\n     *last release*: Jul 21, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest; extra == \"dev\"\n\n     Easy declaration of optional tests (i.e., that are not run by default)\n\n  :pypi:`pytest-orchestration`\n     *last release*: Jul 18, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin for orchestrating tests\n\n  :pypi:`pytest-order`\n     *last release*: Aug 22, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=5.0; python_version < \"3.10\"\n\n     pytest plugin to run your tests in a specific order\n\n  :pypi:`pytest-ordered`\n     *last release*: Nov 09, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.2.0\n\n     Declare the order in which tests should run in your pytest.ini\n\n  :pypi:`pytest-ordering`\n     *last release*: Nov 14, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     pytest plugin to run your tests in a specific order\n\n  :pypi:`pytest-order-modify`\n     *last release*: Nov 04, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     新增run_marker 来自定义用例的执行顺序\n\n  :pypi:`pytest-osxnotify`\n     *last release*: May 15, 2015,\n     *status*: N/A,\n     *requires*: N/A\n\n     OS X notifications for py.test results.\n\n  :pypi:`pytest-ot`\n     *last release*: Mar 21, 2024,\n     *status*: N/A,\n     *requires*: pytest; extra == \"dev\"\n\n     A pytest plugin for instrumenting test runs via OpenTelemetry\n\n  :pypi:`pytest-otel`\n     *last release*: Mar 12, 2026,\n     *status*: N/A,\n     *requires*: pytest==9.0.2\n\n     OpenTelemetry plugin for Pytest\n\n  :pypi:`pytest-otelmark`\n     *last release*: Sep 14, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8.3.5\n\n     Pytest plugin for otelmark.\n\n  :pypi:`pytest-override-env-var`\n     *last release*: Feb 25, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest mark to override a value of an environment variable.\n\n  :pypi:`pytest-owner`\n     *last release*: Aug 19, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Add owner mark for tests\n\n  :pypi:`pytest-pact`\n     *last release*: Jan 07, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-pagerduty`\n     *last release*: Mar 22, 2025,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=7.4.0\n\n     Pytest plugin for PagerDuty integration via automation testing.\n\n  :pypi:`pytest-pahrametahrize`\n     *last release*: Nov 24, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.0,<7.0)\n\n     Parametrize your tests with a Boston accent.\n\n  :pypi:`pytest-paia-blockly`\n     *last release*: Mar 02, 2026,\n     *status*: N/A,\n     *requires*: pytest>=8.0\n\n     pytest plugin for PAIA Blockly: verify get_solution() against test cases\n\n  :pypi:`pytest-paraflow`\n     *last release*: Feb 26, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=9.0.0\n\n     Deterministic pytest test sharding across CI machines\n\n  :pypi:`pytest-parallel`\n     *last release*: Oct 10, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=3.0.0)\n\n     a pytest plugin for parallel and concurrent testing\n\n  :pypi:`pytest-parallel-39`\n     *last release*: Jul 12, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=3.0.0)\n\n     a pytest plugin for parallel and concurrent testing\n\n  :pypi:`pytest-parallelize-tests`\n     *last release*: Jan 27, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest plugin that parallelizes test execution across multiple hosts\n\n  :pypi:`pytest-param`\n     *last release*: Sep 11, 2016,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.6.0)\n\n     pytest plugin to test all, first, last or random params\n\n  :pypi:`pytest-parametrization`\n     *last release*: May 22, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Simpler PyTest parametrization\n\n  :pypi:`pytest-parametrization-annotation`\n     *last release*: Dec 10, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7\n\n     A pytest library for parametrizing tests using type hints.\n\n  :pypi:`pytest-parametrize`\n     *last release*: Sep 25, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<9.0.0,>=8.3.0\n\n     pytest decorator for parametrizing test cases in a dict-way\n\n  :pypi:`pytest-parametrize-cases`\n     *last release*: Mar 13, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=6.1.2)\n\n     A more user-friendly way to write parametrized tests.\n\n  :pypi:`pytest-parametrized`\n     *last release*: Dec 21, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest decorator for parametrizing tests with default iterables.\n\n  :pypi:`pytest-parametrize-suite`\n     *last release*: Jan 19, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A simple pytest extension for creating a named test suite.\n\n  :pypi:`pytest_param_files`\n     *last release*: Jul 29, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     Create pytest parametrize decorators from external files.\n\n  :pypi:`pytest-params`\n     *last release*: Mar 14, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     Simplified pytest test case parameters.\n\n  :pypi:`pytest-param-scope`\n     *last release*: Oct 18, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest parametrize scope fixture workaround\n\n  :pypi:`pytest-parawtf`\n     *last release*: Dec 03, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.6.0)\n\n     Finally spell paramete?ri[sz]e correctly\n\n  :pypi:`pytest-park`\n     *last release*: Mar 14, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Organise and analyse your pytest benchmarks\n\n  :pypi:`pytest-pass`\n     *last release*: Dec 04, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Check out https://github.com/elilutsky/pytest-pass\n\n  :pypi:`pytest-passrunner`\n     *last release*: Feb 10, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=4.6.0)\n\n     Pytest plugin providing the 'run_on_pass' marker\n\n  :pypi:`pytest-paste-config`\n     *last release*: Sep 18, 2013,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Allow setting the path to a paste config file\n\n  :pypi:`pytest-patch`\n     *last release*: Apr 29, 2023,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=7.0.0)\n\n     An automagic \\`patch\\` fixture that can patch objects directly or by name.\n\n  :pypi:`pytest-patches`\n     *last release*: Aug 30, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A contextmanager pytest fixture for handling multiple mock patches\n\n  :pypi:`pytest-patterns`\n     *last release*: Oct 22, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6\n\n     pytest plugin to make testing complicated long string output easy to write and easy to debug\n\n  :pypi:`pytest-pdb`\n     *last release*: Jul 31, 2018,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin which adds pdb helper commands related to pytest.\n\n  :pypi:`pytest-peach`\n     *last release*: Apr 12, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.8.7)\n\n     pytest plugin for fuzzing with Peach API Security\n\n  :pypi:`pytest-pep257`\n     *last release*: Jul 09, 2016,\n     *status*: N/A,\n     *requires*: N/A\n\n     py.test plugin for pep257\n\n  :pypi:`pytest-pep8`\n     *last release*: Apr 27, 2014,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin to check PEP8 requirements\n\n  :pypi:`pytest-percent`\n     *last release*: May 21, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=5.2.0)\n\n     Change the exit code of pytest test sessions when a required percent of tests pass.\n\n  :pypi:`pytest-percents`\n     *last release*: Mar 16, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-perf`\n     *last release*: May 20, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest!=8.1.*,>=6; extra == \"testing\"\n\n     Run performance tests against the mainline code.\n\n  :pypi:`pytest-performance`\n     *last release*: Sep 11, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.7.0)\n\n     A simple plugin to ensure the execution of critical sections of code has not been impacted\n\n  :pypi:`pytest-performancetotal`\n     *last release*: Aug 05, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A performance plugin for pytest\n\n  :pypi:`pytest-persistence`\n     *last release*: Aug 21, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest tool for persistent objects\n\n  :pypi:`pytest-pexpect`\n     *last release*: Sep 10, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     Pytest pexpect plugin.\n\n  :pypi:`pytest-pg`\n     *last release*: May 18, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.4\n\n     A tiny plugin for pytest which runs PostgreSQL in Docker\n\n  :pypi:`pytest-pgsql`\n     *last release*: May 13, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.0.0)\n\n     Pytest plugins and helpers for tests using a Postgres database.\n\n  :pypi:`pytest-phmdoctest`\n     *last release*: Apr 15, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=5.4.3)\n\n     pytest plugin to test Python examples in Markdown using phmdoctest.\n\n  :pypi:`pytest-phoenix-interface`\n     *last release*: Mar 19, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest extension tool for phoenix projects.\n\n  :pypi:`pytest-picked`\n     *last release*: Nov 06, 2024,\n     *status*: N/A,\n     *requires*: pytest>=3.7.0\n\n     Run the tests related to the changed files\n\n  :pypi:`pytest-pickle-cache`\n     *last release*: Feb 06, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=9\n\n     A pytest plugin for caching test results using pickle.\n\n  :pypi:`pytest-pigeonhole`\n     *last release*: Jun 25, 2018,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.4)\n\n\n\n  :pypi:`pytest-pikachu`\n     *last release*: Aug 05, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Show surprise when tests are passing\n\n  :pypi:`pytest-pilot`\n     *last release*: Dec 17, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Slice in your test base thanks to powerful markers.\n\n  :pypi:`pytest-pingguo-pytest-plugin`\n     *last release*: Oct 26, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pingguo test\n\n  :pypi:`pytest-pings`\n     *last release*: Jun 29, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=5.0.0)\n\n     🦊 The pytest plugin for Firefox Telemetry 📊\n\n  :pypi:`pytest-pinned`\n     *last release*: Sep 17, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A simple pytest plugin for pinning tests\n\n  :pypi:`pytest-pinpoint`\n     *last release*: Sep 25, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=4.4.0)\n\n     A pytest plugin which runs SBFL algorithms to detect faults.\n\n  :pypi:`pytest-pipeline`\n     *last release*: Jan 24, 2017,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Pytest plugin for functional testing of data analysispipelines\n\n  :pypi:`pytest-pitch`\n     *last release*: Nov 02, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest >=7.3.1\n\n     runs tests in an order such that coverage increases as fast as possible\n\n  :pypi:`pytest-platform-adapter`\n     *last release*: Mar 12, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2.5\n\n     Pytest集成自动化平台插件\n\n  :pypi:`pytest-platform-markers`\n     *last release*: Sep 09, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.6.0)\n\n     Markers for pytest to skip tests on specific platforms\n\n  :pypi:`pytest-play`\n     *last release*: Jun 12, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin that let you automate actions and assertions with test metrics reporting executing plain YAML files\n\n  :pypi:`pytest-playbook`\n     *last release*: Jan 21, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=6.1.2,<7.0.0)\n\n     Pytest plugin for reading playbooks.\n\n  :pypi:`pytest-playwright`\n     *last release*: Nov 24, 2025,\n     *status*: N/A,\n     *requires*: pytest<10.0.0,>=6.2.4\n\n     A pytest wrapper with fixtures for Playwright to automate web browsers\n\n  :pypi:`pytest-playwright-artifacts`\n     *last release*: Feb 19, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Capture screenshots, HTML, and console logs on Playwright test failures\n\n  :pypi:`pytest_playwright_async`\n     *last release*: Sep 28, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     ASYNC Pytest plugin for Playwright\n\n  :pypi:`pytest-playwright-asyncio`\n     *last release*: Nov 24, 2025,\n     *status*: N/A,\n     *requires*: pytest<10.0.0,>=6.2.4\n\n     A pytest wrapper with async fixtures for Playwright to automate web browsers\n\n  :pypi:`pytest-playwright-axe`\n     *last release*: Jan 12, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     An axe-core integration for accessibility testing using Playwright Python.\n\n  :pypi:`pytest-playwright-enhanced`\n     *last release*: Mar 24, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.0.0\n\n     A pytest plugin for playwright python\n\n  :pypi:`pytest-playwright-json`\n     *last release*: Jan 06, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Generate Playwright-compatible JSON reports from pytest-playwright test runs\n\n  :pypi:`pytest-playwrights`\n     *last release*: Dec 02, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest wrapper with fixtures for Playwright to automate web browsers\n\n  :pypi:`pytest-playwright-snapshot`\n     *last release*: Aug 19, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest wrapper for snapshot testing with playwright\n\n  :pypi:`pytest-playwright-visual`\n     *last release*: Apr 28, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest fixture for visual testing with Playwright\n\n  :pypi:`pytest-playwright-visual-snapshot`\n     *last release*: Feb 05, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Easy pytest visual regression testing using playwright\n\n  :pypi:`pytest-pl-grader`\n     *last release*: Nov 12, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     A pytest plugin for autograding Python code. Designed for use with the PrairieLearn platform.\n\n  :pypi:`pytest-plone`\n     *last release*: Jun 11, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest<8.0.0\n\n     Pytest plugin to test Plone addons\n\n  :pypi:`pytest-plt`\n     *last release*: Jan 17, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Fixtures for quickly making Matplotlib plots in tests\n\n  :pypi:`pytest-plugin-helpers`\n     *last release*: Nov 23, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A plugin to help developing and testing other plugins\n\n  :pypi:`pytest-plugins`\n     *last release*: Feb 07, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=9.0.1\n\n     A Python package for managing pytest plugins.\n\n  :pypi:`pytest-plugin-utils`\n     *last release*: Feb 10, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Reusable configuration and artifact utilities for building pytest plugins\n\n  :pypi:`pytest-plus`\n     *last release*: Feb 02, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.4.2\n\n     PyTest Plus Plugin :: extends pytest functionality\n\n  :pypi:`pytest-pmisc`\n     *last release*: Mar 21, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-podman`\n     *last release*: Feb 03, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin for Podman integration\n\n  :pypi:`pytest-pogo`\n     *last release*: Jan 20, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7\n\n     Pytest plugin for pogo-migrate\n\n  :pypi:`pytest-pointers`\n     *last release*: Dec 26, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin to define functions you test with special marks for better navigation and reports\n\n  :pypi:`pytest-pokie`\n     *last release*: Oct 19, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pokie plugin for pytest\n\n  :pypi:`pytest-polarion-cfme`\n     *last release*: Nov 13, 2017,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin for collecting test cases and recording test results\n\n  :pypi:`pytest-polarion-collect`\n     *last release*: Jun 18, 2020,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     pytest plugin for collecting polarion test cases data\n\n  :pypi:`pytest-polecat`\n     *last release*: Aug 12, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Provides Polecat pytest fixtures\n\n  :pypi:`pytest-polymeric-report`\n     *last release*: Feb 24, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     A polymeric test report plugin for pytest\n\n  :pypi:`pytest-ponyorm`\n     *last release*: Oct 31, 2018,\n     *status*: N/A,\n     *requires*: pytest (>=3.1.1)\n\n     PonyORM in Pytest\n\n  :pypi:`pytest-poo`\n     *last release*: Mar 25, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.3.4)\n\n     Visualize your crappy tests\n\n  :pypi:`pytest-poo-fail`\n     *last release*: Feb 12, 2015,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Visualize your failed tests with poo\n\n  :pypi:`pytest-pook`\n     *last release*: Feb 15, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest plugin for pook\n\n  :pypi:`pytest-pop`\n     *last release*: May 09, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A pytest plugin to help with testing pop projects\n\n  :pypi:`pytest-porcochu`\n     *last release*: Nov 28, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Show surprise when tests are passing\n\n  :pypi:`pytest-portion`\n     *last release*: Mar 04, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     Select a portion of the collected tests\n\n  :pypi:`pytest-postgres`\n     *last release*: Mar 22, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Run PostgreSQL in Docker container in Pytest.\n\n  :pypi:`pytest-postgresql`\n     *last release*: Jan 23, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.2\n\n     Postgresql fixtures and fixture factories for Pytest.\n\n  :pypi:`pytest-power`\n     *last release*: Dec 31, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=5.4)\n\n     pytest plugin with powerful fixtures\n\n  :pypi:`pytest-powerpack`\n     *last release*: Jan 04, 2025,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.1.1\n\n     A plugin containing extra batteries for pytest\n\n  :pypi:`pytest-prairielearn-grader`\n     *last release*: Jan 27, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     A pytest plugin for autograding Python code. Designed for use with the PrairieLearn platform.\n\n  :pypi:`pytest-prefer-nested-dup-tests`\n     *last release*: Apr 27, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=7.1.1,<8.0.0)\n\n     A Pytest plugin to drop duplicated tests during collection, but will prefer keeping nested packages.\n\n  :pypi:`pytest-pretty`\n     *last release*: Jun 04, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7\n\n     pytest plugin for printing summary data as I want it\n\n  :pypi:`pytest-pretty-terminal`\n     *last release*: Jan 31, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=3.4.1)\n\n     pytest plugin for generating prettier terminal output\n\n  :pypi:`pytest-pride`\n     *last release*: Apr 02, 2016,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Minitest-style test colors\n\n  :pypi:`pytest-print`\n     *last release*: Feb 11, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=9.0.2\n\n     pytest-print adds the printer fixture you can use to print messages to the user (directly to the pytest runner, not stdout)\n\n  :pypi:`pytest-priority`\n     *last release*: Aug 19, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest plugin for add priority for tests\n\n  :pypi:`pytest-proceed`\n     *last release*: Oct 01, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-profiles`\n     *last release*: Dec 09, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.7.0)\n\n     pytest plugin for configuration profiles\n\n  :pypi:`pytest-profiling`\n     *last release*: Nov 29, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Profiling plugin for py.test\n\n  :pypi:`pytest-progress`\n     *last release*: Nov 11, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.0\n\n     pytest plugin for instant test progress status\n\n  :pypi:`pytest-prometheus`\n     *last release*: Oct 03, 2017,\n     *status*: N/A,\n     *requires*: N/A\n\n     Report test pass / failures to a Prometheus PushGateway\n\n  :pypi:`pytest-prometheus-pushgateway`\n     *last release*: Sep 27, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest report plugin for Zulip\n\n  :pypi:`pytest-prometheus-pushgw`\n     *last release*: May 19, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.0.0\n\n     Pytest plugin to export test metrics to Prometheus Pushgateway\n\n  :pypi:`pytest-proofy`\n     *last release*: Nov 13, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Pytest plugin for Proofy test reporting\n\n  :pypi:`pytest-prosper`\n     *last release*: Sep 24, 2018,\n     *status*: N/A,\n     *requires*: N/A\n\n     Test helpers for Prosper projects\n\n  :pypi:`pytest-prysk`\n     *last release*: Dec 10, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.3.2\n\n     Pytest plugin for prysk\n\n  :pypi:`pytest-pspec`\n     *last release*: Jun 02, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.0.0)\n\n     A rspec format reporter for Python ptest\n\n  :pypi:`pytest-psqlgraph`\n     *last release*: Oct 19, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.0)\n\n     pytest plugin for testing applications that use psqlgraph\n\n  :pypi:`pytest-pt`\n     *last release*: Nov 21, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     pytest plugin to use \\*.pt files as tests\n\n  :pypi:`pytest-ptera`\n     *last release*: Mar 01, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=6.2.4,<7.0.0)\n\n     Use ptera probes in tests\n\n  :pypi:`pytest-publish`\n     *last release*: Jun 04, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.0.0\n\n\n\n  :pypi:`pytest-pudb`\n     *last release*: Oct 25, 2018,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=2.0)\n\n     Pytest PuDB debugger integration\n\n  :pypi:`pytest-pudb-resurrected`\n     *last release*: Mar 12, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     Pytest PuDB debugger integration\n\n  :pypi:`pytest-pumpkin-spice`\n     *last release*: Sep 18, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pytest plugin that makes your test reporting pumpkin-spiced\n\n  :pypi:`pytest-purkinje`\n     *last release*: Oct 28, 2017,\n     *status*: 2 - Pre-Alpha,\n     *requires*: N/A\n\n     py.test plugin for purkinje test runner\n\n  :pypi:`pytest-pusher`\n     *last release*: Jan 06, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.6)\n\n     pytest plugin for push report to minio\n\n  :pypi:`pytest-pvcr`\n     *last release*: Feb 25, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=3.5.0\n\n     PyTest Process VCR\n\n  :pypi:`pytest-pve-cloud`\n     *last release*: Feb 27, 2026,\n     *status*: N/A,\n     *requires*: pytest==8.4.2\n\n\n\n  :pypi:`pytest-pw-config-gen`\n     *last release*: Mar 14, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.4; extra == \"dev\"\n\n     Generate pytest-playwright configuration files (pytest.ini, pyproject.toml, conftest.py) via CLI\n\n  :pypi:`pytest-py125`\n     *last release*: Dec 03, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-pycharm`\n     *last release*: Aug 13, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.3)\n\n     Plugin for py.test to enter PyCharm debugger on uncaught exceptions\n\n  :pypi:`pytest-pycodestyle`\n     *last release*: Jul 20, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     pytest plugin to run pycodestyle\n\n  :pypi:`pytest-pydantic-schema-sync`\n     *last release*: Aug 29, 2024,\n     *status*: N/A,\n     *requires*: pytest>=6\n\n     Pytest plugin to synchronise Pydantic model schemas with JSONSchema files\n\n  :pypi:`pytest-pydev`\n     *last release*: Nov 15, 2017,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     py.test plugin to connect to a remote debug server with PyDev or PyCharm.\n\n  :pypi:`pytest-pydocstyle`\n     *last release*: Oct 09, 2024,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     pytest plugin to run pydocstyle\n\n  :pypi:`pytest-pyeval`\n     *last release*: Mar 14, 2026,\n     *status*: N/A,\n     *requires*: pytest>=8.0\n\n     pytest plugin integrating pydantic-evals\n\n  :pypi:`pytest-pylembic`\n     *last release*: Jul 22, 2025,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     This package provides pytest plugin for validating Alembic migrations using the pylembic package.\n\n  :pypi:`pytest-pylint`\n     *last release*: Oct 06, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=7.0\n\n     pytest plugin to check source code with pylint\n\n  :pypi:`pytest-pylyzer`\n     *last release*: Feb 15, 2025,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pytest plugin for pylyzer\n\n  :pypi:`pytest-pymysql-autorecord`\n     *last release*: Sep 02, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Record PyMySQL queries and mock with the stored data.\n\n  :pypi:`pytest-pyodide`\n     *last release*: Feb 27, 2026,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin for testing applications that use Pyodide\n\n  :pypi:`pytest-pypi`\n     *last release*: Mar 04, 2018,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Easily test your HTTP library against a local copy of pypi\n\n  :pypi:`pytest-pypom-navigation`\n     *last release*: Feb 18, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.0.7)\n\n     Core engine for cookiecutter-qa and pytest-play packages\n\n  :pypi:`pytest-pyppeteer`\n     *last release*: Apr 28, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=6.2.5,<7.0.0)\n\n     A plugin to run pyppeteer in pytest\n\n  :pypi:`pytest-pyq`\n     *last release*: Mar 10, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest fixture \"q\" for pyq\n\n  :pypi:`pytest-pyramid`\n     *last release*: Sep 30, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     pytest_pyramid - provides fixtures for testing pyramid applications with pytest test suite\n\n  :pypi:`pytest-pyramid-server`\n     *last release*: Oct 17, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pyramid server fixture for py.test\n\n  :pypi:`pytest-pyreport`\n     *last release*: May 05, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     PyReport is a lightweight reporting plugin for Pytest that provides concise HTML report\n\n  :pypi:`pytest-pyright`\n     *last release*: Jan 26, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest >=7.0.0\n\n     Pytest plugin for type checking code with Pyright\n\n  :pypi:`pytest-pyspark-plugin`\n     *last release*: Nov 23, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.0.0\n\n     Pytest pyspark plugin (p3)\n\n  :pypi:`pytest-pyspec`\n     *last release*: Nov 18, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<10,>=9\n\n     The pytest-pyspec plugin transforms pytest output into a beautiful, readable format similar to RSpec. It provides semantic meaning to your tests by organizing them into descriptive hierarchies, using the prefixes \\`Describe\\`/\\`Test\\`, \\`With\\`/\\`Without\\`/\\`When\\`, and \\`test\\`/\\`it\\`, while allowing docstrings and decorators to override the descriptions.\n\n  :pypi:`pytest-pystack`\n     *last release*: Nov 16, 2024,\n     *status*: N/A,\n     *requires*: pytest>=3.5.0\n\n     Plugin to run pystack after a timeout for a test suite.\n\n  :pypi:`pytest-pytestdb`\n     *last release*: Sep 14, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Add your description here\n\n  :pypi:`pytest-pytestrail`\n     *last release*: Aug 27, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.8.0)\n\n     Pytest plugin for interaction with TestRail\n\n  :pypi:`pytest-pytestrail-internal`\n     *last release*: Jun 12, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.8.0\n\n     Pytest plugin for interaction with TestRail, Pytest plugin for TestRail (internal fork from: https://github.com/tolstislon/pytest-pytestrail with PR #25 fix)\n\n  :pypi:`pytest-pythonhashseed`\n     *last release*: Nov 16, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.0.0\n\n     Pytest plugin to set PYTHONHASHSEED env var.\n\n  :pypi:`pytest-pythonpath`\n     *last release*: Feb 10, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (<7,>=2.5.2)\n\n     pytest plugin for adding to the PYTHONPATH from command line or configs.\n\n  :pypi:`pytest-python-test-engineer-sort`\n     *last release*: May 13, 2024,\n     *status*: N/A,\n     *requires*: pytest>=6.2.0\n\n     Sort plugin for Pytest\n\n  :pypi:`pytest-pytorch`\n     *last release*: May 25, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     pytest plugin for a better developer experience when working with the PyTorch test suite\n\n  :pypi:`pytest-pyvenv`\n     *last release*: Feb 27, 2024,\n     *status*: N/A,\n     *requires*: pytest ; extra == 'test'\n\n     A package for create venv in tests\n\n  :pypi:`pytest-pyvista`\n     *last release*: Dec 02, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     Pytest-pyvista package.\n\n  :pypi:`pytest-qanova`\n     *last release*: Sep 05, 2024,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     A pytest plugin to collect test information\n\n  :pypi:`pytest-qaseio`\n     *last release*: Dec 10, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.2.2\n\n     Pytest plugin for Qase.io integration\n\n  :pypi:`pytest-qasync`\n     *last release*: Jul 12, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=5.4.0)\n\n     Pytest support for qasync.\n\n  :pypi:`pytest-qatouch`\n     *last release*: Feb 14, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.2.0)\n\n     Pytest plugin for uploading test results to your QA Touch Testrun.\n\n  :pypi:`pytest-qgis`\n     *last release*: Jun 14, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.0\n\n     A pytest plugin for testing QGIS python plugins\n\n  :pypi:`pytest-qml`\n     *last release*: Dec 02, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.0.0)\n\n     Run QML Tests with pytest\n\n  :pypi:`pytest-qr`\n     *last release*: Nov 25, 2021,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest plugin to generate test result QR codes\n\n  :pypi:`pytest-qt`\n     *last release*: Jul 01, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     pytest support for PyQt and PySide applications\n\n  :pypi:`pytest-qt-app`\n     *last release*: Oct 17, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     QT app fixture for py.test\n\n  :pypi:`pytest-quarantine`\n     *last release*: Nov 24, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=4.6)\n\n     A plugin for pytest to manage expected test failures\n\n  :pypi:`pytest-quickcheck`\n     *last release*: Nov 05, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.0)\n\n     pytest plugin to generate random data inspired by QuickCheck\n\n  :pypi:`pytest_quickify`\n     *last release*: Jun 14, 2019,\n     *status*: N/A,\n     *requires*: pytest\n\n     Run test suites with pytest-quickify.\n\n  :pypi:`pytest-rabbitmq`\n     *last release*: Oct 15, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2\n\n     RabbitMQ process and client fixtures for pytest\n\n  :pypi:`pytest-race`\n     *last release*: Jun 07, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Race conditions tester for pytest\n\n  :pypi:`pytest-rage`\n     *last release*: Oct 21, 2011,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin to implement PEP712\n\n  :pypi:`pytest-rail`\n     *last release*: May 02, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=3.6)\n\n     pytest plugin for creating TestRail runs and adding results\n\n  :pypi:`pytest-railflow-testrail-reporter`\n     *last release*: Jun 29, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Generate json reports along with specified metadata defined in test markers.\n\n  :pypi:`pytest-raises`\n     *last release*: Apr 23, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=3.2.2)\n\n     An implementation of pytest.raises as a pytest.mark fixture\n\n  :pypi:`pytest-raisesregexp`\n     *last release*: Dec 18, 2015,\n     *status*: N/A,\n     *requires*: N/A\n\n     Simple pytest plugin to look for regex in Exceptions\n\n  :pypi:`pytest-raisin`\n     *last release*: Feb 06, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     Plugin enabling the use of exception instances with pytest.raises\n\n  :pypi:`pytest-random`\n     *last release*: Apr 28, 2013,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     py.test plugin to randomize tests\n\n  :pypi:`pytest-randomly`\n     *last release*: Sep 12, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest plugin to randomly order tests and control random.seed.\n\n  :pypi:`pytest-randomness`\n     *last release*: May 30, 2019,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Pytest plugin about random seed management\n\n  :pypi:`pytest-random-num`\n     *last release*: Oct 19, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Randomise the order in which pytest tests are run with some control over the randomness\n\n  :pypi:`pytest-random-order`\n     *last release*: Jun 22, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Randomise the order in which pytest tests are run with some control over the randomness\n\n  :pypi:`pytest-ranking`\n     *last release*: Apr 08, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.4.3\n\n     A Pytest plugin for faster fault detection via regression test prioritization\n\n  :pypi:`pytest-rca-report`\n     *last release*: Aug 04, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Interactive RCA report generator for pytest runs, with AI-based analysis and visual dashboard\n\n  :pypi:`pytest-readable`\n     *last release*: Mar 12, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest<10.0,>=9.0\n\n     Pytest plugin that renders readable test specifications and exports documentation\n\n  :pypi:`pytest-readme`\n     *last release*: Aug 01, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Test your README.md file\n\n  :pypi:`pytest-reana`\n     *last release*: Mar 03, 2026,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Pytest fixtures for REANA.\n\n  :pypi:`pytest-recap`\n     *last release*: Jun 16, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.2.0\n\n     Capture your test sessions. Recap the results.\n\n  :pypi:`pytest-recorder`\n     *last release*: Mar 12, 2026,\n     *status*: N/A,\n     *requires*: pytest>=8.4.1\n\n     Pytest plugin, meant to facilitate unit tests writing for tools consumming Web APIs.\n\n  :pypi:`pytest-recording`\n     *last release*: May 08, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     A pytest plugin powered by VCR.py to record and replay HTTP traffic\n\n  :pypi:`pytest-recordings`\n     *last release*: Aug 13, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     Provides pytest plugins for reporting request/response traffic, screenshots, and more to ReportPortal\n\n  :pypi:`pytest-record-video`\n     *last release*: Oct 31, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     用例执行过程中录制视频\n\n  :pypi:`pytest-redis`\n     *last release*: Feb 28, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.4.0\n\n     Redis fixtures and fixture factories for Pytest.\n\n  :pypi:`pytest-redislite`\n     *last release*: Apr 05, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest plugin for testing code using Redis\n\n  :pypi:`pytest-redmine`\n     *last release*: Mar 19, 2018,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     Pytest plugin for redmine\n\n  :pypi:`pytest-ref`\n     *last release*: Nov 23, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A plugin to store reference files to ease regression testing\n\n  :pypi:`pytest-reference-formatter`\n     *last release*: Oct 01, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Conveniently run pytest with a dot-formatted test reference.\n\n  :pypi:`pytest-regex`\n     *last release*: May 29, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Select pytest tests with regular expressions\n\n  :pypi:`pytest-regex-dependency`\n     *last release*: Jun 12, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     Management of Pytest dependencies via regex patterns\n\n  :pypi:`pytest-regressions`\n     *last release*: Feb 10, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.2.0\n\n     Easy to use fixtures to write regression tests.\n\n  :pypi:`pytest-regtest`\n     *last release*: Feb 25, 2026,\n     *status*: N/A,\n     *requires*: pytest>7.2\n\n     pytest plugin for snapshot regression testing\n\n  :pypi:`pytest-relative-order`\n     *last release*: May 17, 2021,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     a pytest plugin that sorts tests using \"before\" and \"after\" markers\n\n  :pypi:`pytest-relative-path`\n     *last release*: Nov 13, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Handle relative path in pytest options or ini configs\n\n  :pypi:`pytest-relaxed`\n     *last release*: Mar 29, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7\n\n     Relaxed test discovery/organization for pytest\n\n  :pypi:`pytest_relay`\n     *last release*: Jan 31, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A plugin to relay test information and control from and to pytest\n\n  :pypi:`pytest-relay-run`\n     *last release*: Jan 31, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A pytest wrapper using for pytest-relay with pytest-relay-ws to control pytest executions.\n\n  :pypi:`pytest_relay_ws`\n     *last release*: Jan 31, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     An extension plugin to pytest-relay to relay pytest information via websockets\n\n  :pypi:`pytest-remfiles`\n     *last release*: Jul 01, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest plugin to create a temporary directory with remote files\n\n  :pypi:`pytest-remotedata`\n     *last release*: Sep 26, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=4.6\n\n     Pytest plugin for controlling remote data access.\n\n  :pypi:`pytest-remote-response`\n     *last release*: Apr 26, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=4.6)\n\n     Pytest plugin for capturing and mocking connection requests.\n\n  :pypi:`pytest-remove-stale-bytecode`\n     *last release*: Nov 19, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     py.test plugin to remove stale byte code files.\n\n  :pypi:`pytest-reorder`\n     *last release*: May 31, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Reorder tests depending on their paths and names.\n\n  :pypi:`pytest-repeat`\n     *last release*: Apr 07, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     pytest plugin for repeating tests\n\n  :pypi:`pytest-repeated`\n     *last release*: Feb 24, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     A pytest module for very basic statistical tests. Repeat test multiple times and pass if the underlying test passes a threshold.\n\n  :pypi:`pytest_repeater`\n     *last release*: Feb 09, 2018,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     py.test plugin for repeating single test multiple times.\n\n  :pypi:`pytest-replay`\n     *last release*: Dec 23, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Saves previous test runs and allow re-execute previous pytest runs to reproduce crashes or flaky tests\n\n  :pypi:`pytest-repo-health`\n     *last release*: Dec 09, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     A pytest plugin to report on repository standards conformance\n\n  :pypi:`pytest-report`\n     *last release*: May 11, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Creates json report that is compatible with atom.io's linter message format\n\n  :pypi:`pytest-reporter`\n     *last release*: Feb 28, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Generate Pytest reports with templates\n\n  :pypi:`pytest-reporter-html`\n     *last release*: Mar 14, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0\n\n     Pytest plugin that generates rich HTML test reports with step tracking, log capture, and interactive filtering\n\n  :pypi:`pytest-reporter-html1`\n     *last release*: Oct 10, 2025,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A basic HTML report template for Pytest\n\n  :pypi:`pytest-reporter-html-dots`\n     *last release*: Apr 26, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     A basic HTML report for pytest using Jinja2 template engine.\n\n  :pypi:`pytest-reporter-plus`\n     *last release*: Jul 16, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Lightweight enhanced HTML reporter for Pytest\n\n  :pypi:`pytest-report-extras`\n     *last release*: Dec 24, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.4.0\n\n     Pytest plugin to enhance pytest-html and allure reports by adding comments, screenshots, webpage sources and attachments.\n\n  :pypi:`pytest-reportinfra`\n     *last release*: Aug 11, 2019,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Pytest plugin for reportinfra\n\n  :pypi:`pytest-reporting`\n     *last release*: Oct 25, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A plugin to report summarized results in a table format\n\n  :pypi:`pytest-reportlog`\n     *last release*: Nov 11, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Replacement for the --resultlog option, focused in simplicity and extensibility\n\n  :pypi:`pytest-report-me`\n     *last release*: Dec 31, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin to generate report.\n\n  :pypi:`pytest-report-parameters`\n     *last release*: Jun 18, 2020,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=2.4.2)\n\n     pytest plugin for adding tests' parameters to junit report\n\n  :pypi:`pytest-reportportal`\n     *last release*: Dec 02, 2025,\n     *status*: N/A,\n     *requires*: pytest>=4.6.10\n\n     Agent for Reporting results of tests to the Report Portal\n\n  :pypi:`pytest-report-stream`\n     *last release*: Oct 22, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pytest plugin which allows to stream test reports at runtime\n\n  :pypi:`pytest-repo-structure`\n     *last release*: Mar 18, 2024,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n     Pytest Repo Structure\n\n  :pypi:`pytest-req`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.4.2\n\n     pytest requests plugin\n\n  :pypi:`pytest-reqcov`\n     *last release*: Jul 04, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=6.0\n\n     A pytest plugin for requirement coverage tracking\n\n  :pypi:`pytest-reqs`\n     *last release*: May 12, 2019,\n     *status*: N/A,\n     *requires*: pytest (>=2.4.2)\n\n     pytest plugin to check pinned requirements\n\n  :pypi:`pytest-requests`\n     *last release*: Jun 24, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-requestselapsed`\n     *last release*: Aug 14, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     collect and show http requests elapsed time\n\n  :pypi:`pytest-requests-futures`\n     *last release*: Jul 06, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest Plugin to Mock Requests Futures\n\n  :pypi:`pytest-requirements`\n     *last release*: Mar 10, 2026,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest plugin for using custom markers to relate tests to requirements and usecases\n\n  :pypi:`pytest-requires`\n     *last release*: Dec 21, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A pytest plugin to elegantly skip tests with optional requirements\n\n  :pypi:`pytest-reqyaml`\n     *last release*: Aug 16, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.4.1\n\n     This is a plugin where generate requests test cases from yaml.\n\n  :pypi:`pytest-reraise`\n     *last release*: Sep 20, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=4.6)\n\n     Make multi-threaded pytest test cases fail when they should\n\n  :pypi:`pytest-rerun`\n     *last release*: Jul 08, 2019,\n     *status*: N/A,\n     *requires*: pytest (>=3.6)\n\n     Re-run only changed files in specified branch\n\n  :pypi:`pytest-rerun-all`\n     *last release*: Jul 30, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     Rerun testsuite for a certain time or iterations\n\n  :pypi:`pytest-rerunclassfailures`\n     *last release*: Apr 24, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.2\n\n     pytest rerun class failures plugin\n\n  :pypi:`pytest-rerunfailures`\n     *last release*: Oct 10, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest!=8.2.2,>=7.4\n\n     pytest plugin to re-run tests to eliminate flaky failures\n\n  :pypi:`pytest-rerunfailures-all-logs`\n     *last release*: Mar 07, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin to re-run tests to eliminate flaky failures\n\n  :pypi:`pytest-reserial`\n     *last release*: Dec 30, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Pytest fixture for recording and replaying serial port traffic.\n\n  :pypi:`pytest-resilient-circuits`\n     *last release*: Nov 13, 2025,\n     *status*: N/A,\n     *requires*: pytest~=7.0\n\n     Resilient Circuits fixtures for PyTest\n\n  :pypi:`pytest-resource`\n     *last release*: Nov 14, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Load resource fixture plugin to use with pytest\n\n  :pypi:`pytest-resource-path`\n     *last release*: Sep 18, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=3.5.0\n\n     Provides path for uniform access to test resources in isolated directory\n\n  :pypi:`pytest-resource-usage`\n     *last release*: Nov 06, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     Pytest plugin for reporting running time and peak memory usage\n\n  :pypi:`pytest-respect`\n     *last release*: Oct 21, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.0.0\n\n     Pytest plugin to load resource files relative to test code and to expect values to match them.\n\n  :pypi:`pytest-responsemock`\n     *last release*: Mar 10, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Simplified requests calls mocking for pytest\n\n  :pypi:`pytest-responses`\n     *last release*: Oct 11, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=2.5)\n\n     py.test integration for responses\n\n  :pypi:`pytest-rest-api`\n     *last release*: Aug 08, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.1.2,<8.0.0)\n\n\n\n  :pypi:`pytest-restrict`\n     *last release*: Feb 09, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest plugin to restrict the test types allowed\n\n  :pypi:`pytest-resttest`\n     *last release*: Jan 01, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A REST API testing framework for Python, as plugin for pytest. Uses simple and readable YAML files for specifying test cases.\n\n  :pypi:`pytest-result-log`\n     *last release*: Jan 10, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.2.0\n\n     A pytest plugin that records the start, end, and result information of each use case in a log file\n\n  :pypi:`pytest-result-notify`\n     *last release*: Apr 27, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.3.5\n\n     Default template for PDM package\n\n  :pypi:`pytest-results`\n     *last release*: Oct 08, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Easily spot regressions in your tests.\n\n  :pypi:`pytest-result-sender`\n     *last release*: Apr 20, 2023,\n     *status*: N/A,\n     *requires*: pytest>=7.3.1\n\n\n\n  :pypi:`pytest-result-sender-fanrenbufan`\n     *last release*: Mar 12, 2026,\n     *status*: N/A,\n     *requires*: pytest>=8.4.2\n\n     Default template for PDM package\n\n  :pypi:`pytest-result-sender-jms`\n     *last release*: May 22, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.3.5\n\n     Default template for PDM package\n\n  :pypi:`pytest-result-sender-lj`\n     *last release*: Dec 17, 2024,\n     *status*: N/A,\n     *requires*: pytest>=8.3.4\n\n     Default template for PDM package\n\n  :pypi:`pytest-result-sender-lyt`\n     *last release*: Mar 14, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.3.5\n\n     Default template for PDM package\n\n  :pypi:`pytest-result-sender-misszhang`\n     *last release*: Mar 21, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.3.5\n\n     Default template for PDM package\n\n  :pypi:`pytest-result-sender-r`\n     *last release*: Dec 26, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.4.2\n\n     Default template for PDM package\n\n  :pypi:`pytest-resume`\n     *last release*: Apr 22, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=7.0)\n\n     A Pytest plugin to resuming from the last run test\n\n  :pypi:`pytest-rethinkdb`\n     *last release*: Jul 24, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A RethinkDB plugin for pytest.\n\n  :pypi:`pytest-retry`\n     *last release*: Jan 19, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     Adds the ability to retry flaky tests in CI environments\n\n  :pypi:`pytest-retry-class`\n     *last release*: Nov 24, 2024,\n     *status*: N/A,\n     *requires*: pytest>=5.3\n\n     A pytest plugin to rerun entire class on failure\n\n  :pypi:`pytest-reusable-testcases`\n     *last release*: Apr 28, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-revealtype-injector`\n     *last release*: Feb 03, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     Pytest plugin for replacing reveal_type() calls inside test functions with static and runtime type checking result comparison, for confirming type annotation validity.\n\n  :pypi:`pytest-reverse`\n     *last release*: Sep 09, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest plugin to reverse test order.\n\n  :pypi:`pytest-review`\n     *last release*: Mar 12, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin that reviews the quality of your tests\n\n  :pypi:`pytest-rich`\n     *last release*: Dec 12, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     Leverage rich for richer test session output\n\n  :pypi:`pytest-richer`\n     *last release*: Oct 27, 2023,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Pytest plugin providing a Rich based reporter.\n\n  :pypi:`pytest-rich-reporter`\n     *last release*: Feb 17, 2022,\n     *status*: 1 - Planning,\n     *requires*: pytest (>=5.0.0)\n\n     A pytest plugin using Rich for beautiful test result formatting.\n\n  :pypi:`pytest-richtrace`\n     *last release*: Jun 20, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin that displays the names and information of the pytest hook functions as they are executed.\n\n  :pypi:`pytest-ringo`\n     *last release*: Sep 27, 2017,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin to test webapplications using the Ringo webframework\n\n  :pypi:`pytest-rmsis`\n     *last release*: Aug 10, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=5.3.5)\n\n     Sycronise pytest results to Jira RMsis\n\n  :pypi:`pytest-rmysql`\n     *last release*: Aug 17, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.4.1\n\n     This is a plugin which is able to connet MySQL easyly.\n\n  :pypi:`pytest-rng`\n     *last release*: Aug 08, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Fixtures for seeding tests and making randomness reproducible\n\n  :pypi:`pytest-roast`\n     *last release*: Nov 09, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     pytest plugin for ROAST configuration override and fixtures\n\n  :pypi:`pytest_robotframework`\n     *last release*: Dec 22, 2025,\n     *status*: N/A,\n     *requires*: pytest<10,>=7\n\n     a pytest plugin that can run both python and robotframework tests while generating robot reports for them\n\n  :pypi:`pytest-rocketchat`\n     *last release*: Apr 18, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest to Rocket.Chat reporting plugin\n\n  :pypi:`pytest-rotest`\n     *last release*: Sep 08, 2019,\n     *status*: N/A,\n     *requires*: pytest (>=3.5.0)\n\n     Pytest integration with rotest\n\n  :pypi:`pytest-routes`\n     *last release*: Dec 01, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     Property-based smoke testing for ASGI application routes\n\n  :pypi:`pytest-rpc`\n     *last release*: Feb 22, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (~=3.6)\n\n     Extend py.test for RPC OpenStack testing.\n\n  :pypi:`pytest-r-snapshot`\n     *last release*: Jan 02, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin for snapshot testing against R code outputs\n\n  :pypi:`pytest-rst`\n     *last release*: Feb 22, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Test code from RST documents with pytest\n\n  :pypi:`pytest-rt`\n     *last release*: May 05, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest data collector plugin for Testgr\n\n  :pypi:`pytest-rts`\n     *last release*: May 17, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     Coverage-based regression test selection (RTS) plugin for pytest\n\n  :pypi:`pytest-ruff`\n     *last release*: Jun 19, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=5\n\n     pytest plugin to check ruff requirements.\n\n  :pypi:`pytest-run-changed`\n     *last release*: Apr 02, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     Pytest plugin that runs changed tests only\n\n  :pypi:`pytest-runfailed`\n     *last release*: Mar 24, 2016,\n     *status*: N/A,\n     *requires*: N/A\n\n     implement a --failed option for pytest\n\n  :pypi:`pytest-run-parallel`\n     *last release*: Jan 14, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A simple pytest plugin to run tests concurrently\n\n  :pypi:`pytest-run-subprocess`\n     *last release*: Nov 12, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest Plugin for running and testing subprocesses.\n\n  :pypi:`pytest-runtime-types`\n     *last release*: Feb 09, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     Checks type annotations on runtime while running tests.\n\n  :pypi:`pytest-runtime-xfail`\n     *last release*: Oct 10, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=5.0.0\n\n     Call runtime_xfail() to mark running test as xfail.\n\n  :pypi:`pytest-runtime-yoyo`\n     *last release*: Jun 12, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.2.0)\n\n     run case mark timeout\n\n  :pypi:`pytest-saccharin`\n     *last release*: Oct 31, 2022,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest-saccharin is a updated fork of pytest-sugar, a plugin for pytest that changes the default look and feel of pytest (e.g. progressbar, show tests that fail instantly).\n\n  :pypi:`pytest-salt`\n     *last release*: Jan 27, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Pytest Salt Plugin\n\n  :pypi:`pytest-salt-containers`\n     *last release*: Nov 09, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A Pytest plugin that builds and creates docker containers\n\n  :pypi:`pytest-salt-factories`\n     *last release*: Jul 08, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.4.0\n\n     Pytest Salt Plugin\n\n  :pypi:`pytest-salt-from-filenames`\n     *last release*: Jan 29, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.1)\n\n     Simple PyTest Plugin For Salt's Test Suite Specifically\n\n  :pypi:`pytest-salt-runtests-bridge`\n     *last release*: Dec 05, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=4.1)\n\n     Simple PyTest Plugin For Salt's Test Suite Specifically\n\n  :pypi:`pytest-sample-argvalues`\n     *last release*: May 07, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     A utility function to help choose a random sample from your argvalues in pytest.\n\n  :pypi:`pytest-sanic`\n     *last release*: Oct 25, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=5.2)\n\n     a pytest plugin for Sanic\n\n  :pypi:`pytest-sanitizer`\n     *last release*: Mar 16, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=6.0.0\n\n     A pytest plugin to sanitize output for LLMs (personal tool, no warranty or liability)\n\n  :pypi:`pytest-sanity`\n     *last release*: Dec 07, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-sa-pg`\n     *last release*: May 14, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest_sauce`\n     *last release*: Jul 14, 2014,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest_sauce provides sane and helpful methods worked    out in clearcode to run py.test tests with selenium/saucelabs\n\n  :pypi:`pytest-sbase`\n     *last release*: Mar 13, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A complete web automation framework for end-to-end testing.\n\n  :pypi:`pytest-scenario`\n     *last release*: Feb 06, 2017,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest plugin for test scenarios\n\n  :pypi:`pytest-scenario-files`\n     *last release*: Feb 17, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest<10,>=7.4\n\n     A pytest plugin that generates unit test scenarios from data files.\n\n  :pypi:`pytest-scenarios`\n     *last release*: Jan 03, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Add your description here\n\n  :pypi:`pytest-schedule`\n     *last release*: Oct 31, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Automate and customize test scheduling effortlessly on local machines.\n\n  :pypi:`pytest-schema`\n     *last release*: Feb 16, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=3.5.0\n\n     👍 Validate return values against a schema-like object in testing\n\n  :pypi:`pytest-scim2-server`\n     *last release*: Nov 14, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.3.4\n\n     SCIM2 server fixture for Pytest\n\n  :pypi:`pytest-screenshot-on-failure`\n     *last release*: Jul 21, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Saves a screenshot when a test case from a pytest execution fails\n\n  :pypi:`pytest-scrutinize`\n     *last release*: Aug 19, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6\n\n     Scrutinize your pytest test suites for slow fixtures, tests and more.\n\n  :pypi:`pytest-securestore`\n     *last release*: Nov 08, 2021,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     An encrypted password store for use within pytest cases\n\n  :pypi:`pytest-select`\n     *last release*: Jan 18, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=3.0)\n\n     A pytest plugin which allows to (de-)select tests from a file.\n\n  :pypi:`pytest-selenium`\n     *last release*: Feb 01, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.0.0\n\n     pytest plugin for Selenium\n\n  :pypi:`pytest-selenium-auto`\n     *last release*: Nov 07, 2023,\n     *status*: N/A,\n     *requires*: pytest >= 7.0.0\n\n     pytest plugin to automatically capture screenshots upon selenium webdriver events\n\n  :pypi:`pytest-seleniumbase`\n     *last release*: Mar 13, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A complete web automation framework for end-to-end testing.\n\n  :pypi:`pytest-selenium-driver`\n     *last release*: Mar 07, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     A zero-boilerplate Selenium WebDriver fixture for pytest\n\n  :pypi:`pytest-selenium-enhancer`\n     *last release*: Apr 29, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin for Selenium\n\n  :pypi:`pytest-selenium-pdiff`\n     *last release*: Apr 06, 2017,\n     *status*: 2 - Pre-Alpha,\n     *requires*: N/A\n\n     A pytest package implementing perceptualdiff for Selenium tests.\n\n  :pypi:`pytest-selfie`\n     *last release*: Dec 16, 2024,\n     *status*: N/A,\n     *requires*: pytest>=8.0.0\n\n     A pytest plugin for selfie snapshot testing.\n\n  :pypi:`pytest-semantic`\n     *last release*: Nov 11, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin for testing LLM outputs using semantic similarity matching\n\n  :pypi:`pytest-semantic-assert`\n     *last release*: Jan 09, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     Pytest plugin for semantic LLM output assertions using embeddings. Test meaning, not strings.\n\n  :pypi:`pytest-semantic-llm`\n     *last release*: Mar 10, 2026,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     Semantic assertions for pytest using LLMs\n\n  :pypi:`pytest-send-email`\n     *last release*: Sep 02, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Send pytest execution result email\n\n  :pypi:`pytest-sentry`\n     *last release*: Jul 01, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin to send testrun information to Sentry.io\n\n  :pypi:`pytest-sequence-markers`\n     *last release*: May 23, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest plugin for sequencing markers for execution of tests\n\n  :pypi:`pytest-server`\n     *last release*: Sep 09, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     test server exec cmd\n\n  :pypi:`pytest-server-fixtures`\n     *last release*: Nov 29, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Extensible server fixtures for py.test\n\n  :pypi:`pytest-serverless`\n     *last release*: May 09, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Automatically mocks resources from serverless.yml in pytest using moto.\n\n  :pypi:`pytest-servers`\n     *last release*: Dec 21, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=6.2\n\n     pytest servers\n\n  :pypi:`pytest-service`\n     *last release*: Aug 06, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.0.0\n\n\n\n  :pypi:`pytest-services`\n     *last release*: Jul 16, 2025,\n     *status*: 6 - Mature,\n     *requires*: pytest\n\n     Services plugin for pytest testing framework\n\n  :pypi:`pytest-session2file`\n     *last release*: Jan 26, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     pytest-session2file (aka: pytest-session_to_file for v0.1.0 - v0.1.2) is a py.test plugin for capturing and saving to file the stdout of py.test.\n\n  :pypi:`pytest-session-fixture-globalize`\n     *last release*: May 15, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     py.test plugin to make session fixtures behave as if written in conftest, even if it is written in some modules\n\n  :pypi:`pytest-session_to_file`\n     *last release*: Oct 01, 2015,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest-session_to_file is a py.test plugin for capturing and saving to file the stdout of py.test.\n\n  :pypi:`pytest-setupinfo`\n     *last release*: Jan 23, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     Displaying setup info during pytest command run\n\n  :pypi:`pytest-sftpserver`\n     *last release*: Sep 16, 2019,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     py.test plugin to locally test sftp server connections.\n\n  :pypi:`pytest-shard`\n     *last release*: Dec 11, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-shard-fork`\n     *last release*: Jun 13, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Shard tests to support parallelism across multiple machines\n\n  :pypi:`pytest-shared-session-scope`\n     *last release*: Oct 31, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     Pytest session-scoped fixture that works with xdist\n\n  :pypi:`pytest-share-hdf`\n     *last release*: Sep 21, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Plugin to save test data in HDF files and retrieve them for comparison\n\n  :pypi:`pytest-sharkreport`\n     *last release*: Jul 11, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=3.5)\n\n     this is pytest report plugin.\n\n  :pypi:`pytest-shell`\n     *last release*: Mar 27, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin to help with testing shell scripts / black box commands\n\n  :pypi:`pytest-shell-utilities`\n     *last release*: Oct 22, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.4.0\n\n     Pytest plugin to simplify running shell commands against the system\n\n  :pypi:`pytest-sheraf`\n     *last release*: Feb 11, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Versatile ZODB abstraction layer - pytest fixtures\n\n  :pypi:`pytest-sherlock`\n     *last release*: Aug 14, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=3.5.1\n\n     pytest plugin help to find coupled tests\n\n  :pypi:`pytest-shortcuts`\n     *last release*: Oct 29, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Expand command-line shortcuts listed in pytest configuration\n\n  :pypi:`pytest-shutil`\n     *last release*: Nov 29, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A goodie-bag of unix shell and environment tools for py.test\n\n  :pypi:`pytest-sigil`\n     *last release*: Oct 21, 2025,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=7.0.0\n\n     Proper fixture resource cleanup by handling signals\n\n  :pypi:`pytest-simbind`\n     *last release*: Mar 28, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     Pytest plugin to operate with objects generated by Simbind tool.\n\n  :pypi:`pytest-simplehttpserver`\n     *last release*: Jun 24, 2021,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Simple pytest fixture to spin up an HTTP server\n\n  :pypi:`pytest-simple-plugin`\n     *last release*: Nov 27, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     Simple pytest plugin\n\n  :pypi:`pytest-simple-settings`\n     *last release*: Nov 17, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     simple-settings plugin for pytest\n\n  :pypi:`pytest-simplified`\n     *last release*: Jan 19, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest<9.0.0,>=8.3.5\n\n     A PyTest plugin to simplify testing classes.\n\n  :pypi:`pytest-single-file-logging`\n     *last release*: May 05, 2016,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.8.1)\n\n     Allow for multiple processes to log to a single file\n\n  :pypi:`pytest-skill-engineering`\n     *last release*: Mar 01, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=9.0\n\n     The testing framework for skill engineering. Test tool descriptions, prompt templates, agent skills, and custom agents with real LLMs. AI analyzes results and tells you what to fix.\n\n  :pypi:`pytest-skip`\n     *last release*: Sep 12, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     A pytest plugin which allows to (de-)select or skip tests from a file.\n\n  :pypi:`pytest-skip-markers`\n     *last release*: Aug 09, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.1.0\n\n     Pytest Salt Plugin\n\n  :pypi:`pytest-skipper`\n     *last release*: Mar 26, 2017,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=3.0.6)\n\n     A plugin that selects only tests with changes in execution path\n\n  :pypi:`pytest-skippy`\n     *last release*: Jan 27, 2018,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=2.3.4)\n\n     Automatically skip tests that don't need to run!\n\n  :pypi:`pytest-skip-slow`\n     *last release*: Feb 09, 2023,\n     *status*: N/A,\n     *requires*: pytest>=6.2.0\n\n     A pytest plugin to skip \\`@pytest.mark.slow\\` tests by default.\n\n  :pypi:`pytest-skipuntil`\n     *last release*: Nov 25, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest >=3.8.0\n\n     A simple pytest plugin to skip flapping test with deadline\n\n  :pypi:`pytest-slack`\n     *last release*: Dec 15, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest to Slack reporting plugin\n\n  :pypi:`pytest-slow`\n     *last release*: Sep 28, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     A pytest plugin to skip \\`@pytest.mark.slow\\` tests by default.\n\n  :pypi:`pytest-slowest-first`\n     *last release*: Dec 11, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Sort tests by their last duration, slowest first\n\n  :pypi:`pytest-slow-first`\n     *last release*: Jan 30, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest >=3.5.0\n\n     Prioritize running the slowest tests first.\n\n  :pypi:`pytest-slow-last`\n     *last release*: Mar 16, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.5.0\n\n     Run tests in order of execution time (faster tests first)\n\n  :pypi:`pytest-smartcollect`\n     *last release*: Oct 04, 2018,\n     *status*: N/A,\n     *requires*: pytest (>=3.5.0)\n\n     A plugin for collecting tests that touch changed code\n\n  :pypi:`pytest-smartcov`\n     *last release*: Sep 30, 2017,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Smart coverage plugin for pytest.\n\n  :pypi:`pytest-smart-debugger-backend`\n     *last release*: Sep 17, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Backend server for Pytest Smart Debugger\n\n  :pypi:`pytest-smart-rerun`\n     *last release*: Oct 12, 2025,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     A Pytest plugin for intelligent retrying of flaky tests.\n\n  :pypi:`pytest-smell`\n     *last release*: Jun 26, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Automated bad smell detection tool for Pytest\n\n  :pypi:`pytest-smoke`\n     *last release*: Nov 09, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest<10,>=7.0.0\n\n     Pytest plugin for smoke testing\n\n  :pypi:`pytest-smtp`\n     *last release*: Feb 20, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     Send email with pytest execution result\n\n  :pypi:`pytest-smtp4dev`\n     *last release*: Jun 27, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Plugin for smtp4dev API\n\n  :pypi:`pytest-smtpd`\n     *last release*: May 15, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     An SMTP server for testing built on aiosmtpd\n\n  :pypi:`pytest-smtp-test-server`\n     *last release*: Dec 03, 2023,\n     *status*: 2 - Pre-Alpha,\n     *requires*: pytest (>=7.4.3,<8.0.0)\n\n     pytest plugin for using \\`smtp-test-server\\` as a fixture\n\n  :pypi:`pytest-snail`\n     *last release*: Nov 04, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=5.0.1)\n\n     Plugin for adding a marker to slow running tests. 🐌\n\n  :pypi:`pytest-snap`\n     *last release*: Aug 25, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.0.0\n\n     A text-based snapshot testing library implemented as a pytest plugin\n\n  :pypi:`pytest-snapcheck`\n     *last release*: Sep 07, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.0\n\n     Minimal deterministic test-run snapshot capture for pytest.\n\n  :pypi:`pytest-snapci`\n     *last release*: Nov 12, 2015,\n     *status*: N/A,\n     *requires*: N/A\n\n     py.test plugin for Snap-CI\n\n  :pypi:`pytest-snapmock`\n     *last release*: Nov 15, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Snapshots for your mocks.\n\n  :pypi:`pytest-snapshot`\n     *last release*: Apr 23, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.0.0)\n\n     A plugin for snapshot testing with pytest.\n\n  :pypi:`pytest-snapshot-with-message-generator`\n     *last release*: Jul 25, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.0.0)\n\n     A plugin for snapshot testing with pytest.\n\n  :pypi:`pytest-snmpserver`\n     *last release*: May 12, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-snob`\n     *last release*: Jan 12, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin that only selects meaningful python tests to run.\n\n  :pypi:`pytest-snowflake-bdd`\n     *last release*: Jan 05, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.2.0)\n\n     Setup test data and run tests on snowflake in BDD style!\n\n  :pypi:`pytest-socket`\n     *last release*: Jan 28, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.2.5)\n\n     Pytest Plugin to disable socket calls during tests\n\n  :pypi:`pytest-sofaepione`\n     *last release*: Aug 17, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Test the installation of SOFA and the SofaEpione plugin.\n\n  :pypi:`pytest-soft-assert`\n     *last release*: Dec 07, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.4.0\n\n     Pytest plugin for soft assertions.\n\n  :pypi:`pytest-soft-assertions`\n     *last release*: May 05, 2020,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-solidity`\n     *last release*: Jan 15, 2022,\n     *status*: 1 - Planning,\n     *requires*: pytest (<7,>=6.0.1) ; extra == 'tests'\n\n     A PyTest library plugin for Solidity language.\n\n  :pypi:`pytest-solr`\n     *last release*: May 11, 2020,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=3.0.0)\n\n     Solr process and client fixtures for py.test.\n\n  :pypi:`pytest-sort`\n     *last release*: Mar 22, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.4.0\n\n     Tools for sorting test cases\n\n  :pypi:`pytest-sorter`\n     *last release*: Apr 20, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.1.1)\n\n     A simple plugin to first execute tests that historically failed more\n\n  :pypi:`pytest-sosu`\n     *last release*: Aug 04, 2023,\n     *status*: 2 - Pre-Alpha,\n     *requires*: pytest\n\n     Unofficial PyTest plugin for Sauce Labs\n\n  :pypi:`pytest-sourceorder`\n     *last release*: Sep 01, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Test-ordering plugin for pytest\n\n  :pypi:`pytest-spark`\n     *last release*: May 21, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     pytest plugin to run the tests with support of pyspark.\n\n  :pypi:`pytest-spawner`\n     *last release*: Jul 31, 2015,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     py.test plugin to spawn process and communicate with them.\n\n  :pypi:`pytest-spec`\n     *last release*: Feb 22, 2026,\n     *status*: N/A,\n     *requires*: pytest; extra == \"test\"\n\n     Library pytest-spec is a pytest plugin to display test execution output like a SPECIFICATION.\n\n  :pypi:`pytest-spec2md`\n     *last release*: Apr 10, 2024,\n     *status*: N/A,\n     *requires*: pytest>7.0\n\n     Library pytest-spec2md is a pytest plugin to create a markdown specification while running pytest.\n\n  :pypi:`pytest-speed`\n     *last release*: Jan 22, 2023,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7\n\n     Modern benchmarking library for python with pytest integration.\n\n  :pypi:`pytest-sphinx`\n     *last release*: Jan 21, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.1.1\n\n     Doctest plugin for pytest with support for Sphinx-specific doctest-directives\n\n  :pypi:`pytest-spiratest`\n     *last release*: Feb 09, 2026,\n     *status*: N/A,\n     *requires*: pytest>=3.0.0\n\n     Exports unit tests as test runs in Spira (SpiraTest/Team/Plan)\n\n  :pypi:`pytest-splinter`\n     *last release*: Sep 09, 2022,\n     *status*: 6 - Mature,\n     *requires*: pytest (>=3.0.0)\n\n     Splinter plugin for pytest testing framework\n\n  :pypi:`pytest-splinter4`\n     *last release*: Feb 01, 2024,\n     *status*: 6 - Mature,\n     *requires*: pytest >=8.0.0\n\n     Pytest plugin for the splinter automation library\n\n  :pypi:`pytest-split`\n     *last release*: Feb 03, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest<10,>=5\n\n     Pytest plugin which splits the test suite to equally sized sub suites based on test execution time.\n\n  :pypi:`pytest-split-ct`\n     *last release*: Jan 23, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest<10,>=5\n\n     Pytest plugin which splits the test suite to equally sized sub suites based on test execution time.\n\n  :pypi:`pytest-split-ext`\n     *last release*: Sep 23, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=5,<8)\n\n     Pytest plugin which splits the test suite to equally sized sub suites based on test execution time.\n\n  :pypi:`pytest-splitio`\n     *last release*: Sep 22, 2020,\n     *status*: N/A,\n     *requires*: pytest (<7,>=5.0)\n\n     Split.io SDK integration for e2e tests\n\n  :pypi:`pytest-split-ng`\n     *last release*: Jan 05, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest<10,>=5\n\n     Pytest plugin which splits the test suite to equally sized sub suites based on test execution time.\n\n  :pypi:`pytest-split-tests`\n     *last release*: Jul 30, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.5)\n\n     A Pytest plugin for running a subset of your tests by splitting them in to equally sized groups. Forked from Mark Adams' original project pytest-test-groups.\n\n  :pypi:`pytest-split-tests-tresorit`\n     *last release*: Feb 22, 2021,\n     *status*: 1 - Planning,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-split-v2`\n     *last release*: Jan 14, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest<10,>=5\n\n     Pytest plugin which splits the test suite to equally sized sub suites based on test execution time.\n\n  :pypi:`pytest-splunk-addon`\n     *last release*: Aug 19, 2025,\n     *status*: N/A,\n     *requires*: pytest<8,>5.4.0\n\n     A Dynamic test tool for Splunk Apps and Add-ons\n\n  :pypi:`pytest-splunk-addon-ui-smartx`\n     *last release*: Nov 24, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Library to support testing Splunk Add-on UX\n\n  :pypi:`pytest-splunk-env`\n     *last release*: Oct 22, 2020,\n     *status*: N/A,\n     *requires*: pytest (>=6.1.1,<7.0.0)\n\n     pytest fixtures for interaction with Splunk Enterprise and Splunk Cloud\n\n  :pypi:`pytest-sqitch`\n     *last release*: Apr 06, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     sqitch for pytest\n\n  :pypi:`pytest-sqlalchemy`\n     *last release*: Apr 19, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8.0\n\n     pytest plugin with sqlalchemy related fixtures\n\n  :pypi:`pytest-sqlalchemy-mock`\n     *last release*: Aug 10, 2024,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     pytest sqlalchemy plugin for mock\n\n  :pypi:`pytest-sqlalchemy-session`\n     *last release*: May 19, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=7.0)\n\n     A pytest plugin for preserving test isolation that use SQLAlchemy.\n\n  :pypi:`pytest-sql-bigquery`\n     *last release*: Dec 19, 2019,\n     *status*: N/A,\n     *requires*: pytest\n\n     Yet another SQL-testing framework for BigQuery provided by pytest plugin\n\n  :pypi:`pytest-sqlfluff`\n     *last release*: Dec 21, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A pytest plugin to use sqlfluff to enable format checking of sql files.\n\n  :pypi:`pytest-sqlguard`\n     *last release*: Jun 06, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7\n\n     Pytest fixture to record and check SQL Queries made by SQLAlchemy\n\n  :pypi:`pytest-squadcast`\n     *last release*: Feb 22, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest report plugin for Squadcast\n\n  :pypi:`pytest-srcpaths`\n     *last release*: Oct 15, 2021,\n     *status*: N/A,\n     *requires*: pytest>=6.2.0\n\n     Add paths to sys.path\n\n  :pypi:`pytest-ssh`\n     *last release*: May 27, 2019,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest plugin for ssh command run\n\n  :pypi:`pytest-start-from`\n     *last release*: Apr 11, 2016,\n     *status*: N/A,\n     *requires*: N/A\n\n     Start pytest run from a given point\n\n  :pypi:`pytest-static`\n     *last release*: May 25, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest<8.0.0,>=7.4.3\n\n     pytest-static\n\n  :pypi:`pytest-stats`\n     *last release*: Jul 18, 2024,\n     *status*: N/A,\n     *requires*: pytest>=8.0.0\n\n     Collects tests metadata for future analysis, easy to extend for any data store\n\n  :pypi:`pytest-statsd`\n     *last release*: Nov 30, 2018,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.0.0)\n\n     pytest plugin for reporting to graphite\n\n  :pypi:`pytest-status`\n     *last release*: Aug 22, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Add status mark for tests\n\n  :pypi:`pytest-stderr-db`\n     *last release*: Sep 14, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Add your description here\n\n  :pypi:`pytest-stdout-db`\n     *last release*: Sep 14, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Add your description here\n\n  :pypi:`pytest-stepfunctions`\n     *last release*: May 08, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A small description\n\n  :pypi:`pytest-step-logger`\n     *last release*: Mar 11, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0\n\n     Live Rich-rendered step trees in pytest terminal output\n\n  :pypi:`pytest-steps`\n     *last release*: Sep 23, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Create step-wise / incremental tests in pytest.\n\n  :pypi:`pytest-stepthrough`\n     *last release*: Aug 14, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pause and wait for Enter after each test with --step\n\n  :pypi:`pytest-stepwise`\n     *last release*: Dec 01, 2015,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Run a test suite one failing test at a time.\n\n  :pypi:`pytest-stf`\n     *last release*: Sep 23, 2025,\n     *status*: N/A,\n     *requires*: pytest>=5.0\n\n     pytest plugin for openSTF\n\n  :pypi:`pytest-stochastic`\n     *last release*: Feb 24, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     A pytest plugin for principled stochastic unit testing using concentration inequalities\n\n  :pypi:`pytest-stochastics`\n     *last release*: Dec 01, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.0.0\n\n     pytest plugin that allows selectively running tests several times and accepting \\*some\\* failures.\n\n  :pypi:`pytest-stoq`\n     *last release*: Feb 09, 2021,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A plugin to pytest stoq\n\n  :pypi:`pytest-storage`\n     *last release*: Sep 12, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=8.4.2\n\n     Pytest plugin to store test artifacts\n\n  :pypi:`pytest-store`\n     *last release*: Jul 30, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7.0.0\n\n     Pytest plugin to store values from test runs\n\n  :pypi:`pytest-streaming`\n     *last release*: Jan 14, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.3.5\n\n     Plugin for testing pubsub, pulsar, and kafka systems with pytest locally and in ci/cd\n\n  :pypi:`pytest-stress`\n     *last release*: Dec 07, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.6.0)\n\n     A Pytest plugin that allows you to loop tests for a user defined amount of time.\n\n  :pypi:`pytest-structlog`\n     *last release*: Sep 10, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Structured logging assertions\n\n  :pypi:`pytest-structmpd`\n     *last release*: Oct 17, 2018,\n     *status*: N/A,\n     *requires*: N/A\n\n     provide structured temporary directory\n\n  :pypi:`pytest-stub`\n     *last release*: Apr 28, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Stub packages, modules and attributes.\n\n  :pypi:`pytest-stubprocess`\n     *last release*: Sep 17, 2018,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=3.5.0)\n\n     Provide stub implementations for subprocesses in Python tests\n\n  :pypi:`pytest-study`\n     *last release*: Sep 26, 2017,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=2.0)\n\n     A pytest plugin to organize long run tests (named studies) without interfering the regular tests\n\n  :pypi:`pytest-subinterpreter`\n     *last release*: Nov 25, 2023,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     Run pytest in a subinterpreter\n\n  :pypi:`pytest-subket`\n     *last release*: Jul 31, 2025,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Pytest Plugin to disable socket calls during tests\n\n  :pypi:`pytest-subprocess`\n     *last release*: Jan 04, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=4.0.0\n\n     A plugin to fake subprocess for pytest\n\n  :pypi:`pytest-subtesthack`\n     *last release*: Jul 16, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A hack to explicitly set up and tear down fixtures.\n\n  :pypi:`pytest-subtests`\n     *last release*: Oct 20, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.4\n\n     unittest subTest() support and subtests fixture\n\n  :pypi:`pytest-subunit`\n     *last release*: Sep 17, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=2.3)\n\n     pytest-subunit is a plugin for py.test which outputs testsresult in subunit format.\n\n  :pypi:`pytest-sugar`\n     *last release*: Aug 23, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     pytest-sugar is a plugin for pytest that changes the default look and feel of pytest (e.g. progressbar, show tests that fail instantly).\n\n  :pypi:`pytest-suitemanager`\n     *last release*: Apr 28, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-suite-timeout`\n     *last release*: Jan 26, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin for ensuring max suite time\n\n  :pypi:`pytest-supercov`\n     *last release*: Jul 02, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin for measuring explicit test-file to source-file coverage\n\n  :pypi:`pytest-svn`\n     *last release*: Oct 17, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     SVN repository fixture for py.test\n\n  :pypi:`pytest-symbols`\n     *last release*: Nov 20, 2017,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     pytest-symbols is a pytest plugin that adds support for passing test environment symbols into pytest tests.\n\n  :pypi:`pytest-system-statistics`\n     *last release*: Feb 16, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=6.0.0)\n\n     Pytest plugin to track and report system usage statistics\n\n  :pypi:`pytest-system-test-plugin`\n     *last release*: Feb 03, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pyst - Pytest System-Test Plugin\n\n  :pypi:`pytest_tagging`\n     *last release*: Nov 08, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.1.3\n\n     a pytest plugin to tag tests\n\n  :pypi:`pytest-takeltest`\n     *last release*: Sep 07, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Fixtures for ansible, testinfra and molecule\n\n  :pypi:`pytest-talisker`\n     *last release*: Nov 28, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-tally`\n     *last release*: May 22, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.2.5)\n\n     A Pytest plugin to generate realtime summary stats, and display them in-console using a text-based dashboard.\n\n  :pypi:`pytest-tap`\n     *last release*: Jan 30, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=3.0\n\n     Test Anything Protocol (TAP) reporting plugin for pytest\n\n  :pypi:`pytest-tape`\n     *last release*: Mar 17, 2021,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     easy assertion with expected results saved to yaml files\n\n  :pypi:`pytest-target`\n     *last release*: Jan 21, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=6.1.2,<7.0.0)\n\n     Pytest plugin for remote target orchestration.\n\n  :pypi:`pytest-taskgraph`\n     *last release*: Apr 09, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Add your description here\n\n  :pypi:`pytest-tblineinfo`\n     *last release*: Dec 01, 2015,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=2.0)\n\n     tblineinfo is a py.test plugin that insert the node id in the final py.test report when --tb=line option is used\n\n  :pypi:`pytest-tcpclient`\n     *last release*: Nov 16, 2022,\n     *status*: N/A,\n     *requires*: pytest (<8,>=7.1.3)\n\n     A pytest plugin for testing TCP clients\n\n  :pypi:`pytest-tdd`\n     *last release*: Aug 18, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     run pytest on a python module\n\n  :pypi:`pytest-teamcity-logblock`\n     *last release*: May 15, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     py.test plugin to introduce block structure in teamcity build log, if output is not captured\n\n  :pypi:`pytest-teardown`\n     *last release*: Apr 15, 2025,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=7.4.1\n\n\n\n  :pypi:`pytest-telegram`\n     *last release*: Apr 25, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest to Telegram reporting plugin\n\n  :pypi:`pytest-telegram-notifier`\n     *last release*: Jun 27, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Telegram notification plugin for Pytest\n\n  :pypi:`pytest-tempdir`\n     *last release*: Oct 11, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.8.1)\n\n     Predictable and repeatable tempdir support.\n\n  :pypi:`pytest-terra-fixt`\n     *last release*: Sep 15, 2022,\n     *status*: N/A,\n     *requires*: pytest (==6.2.5)\n\n     Terraform and Terragrunt fixtures for pytest\n\n  :pypi:`pytest-terraform`\n     *last release*: May 21, 2024,\n     *status*: N/A,\n     *requires*: pytest>=6.0\n\n     A pytest plugin for using terraform fixtures\n\n  :pypi:`pytest-terraform-fixture`\n     *last release*: Nov 14, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     generate terraform resources to use with pytest\n\n  :pypi:`pytest-test-analyzer`\n     *last release*: Jun 14, 2025,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A powerful tool for analyzing pytest test files and generating detailed reports\n\n  :pypi:`pytest-testbook`\n     *last release*: Dec 11, 2016,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     A plugin to run tests written in Jupyter notebook\n\n  :pypi:`pytest-test-categories`\n     *last release*: Mar 04, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.4.2\n\n     A pytest plugin to enforce test timing constraints and size distributions.\n\n  :pypi:`pytest-testconfig`\n     *last release*: Jan 11, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Test configuration plugin for pytest.\n\n  :pypi:`pytest-testcontainers-compose`\n     *last release*: Feb 11, 2026,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin for Docker Compose\n\n  :pypi:`pytest-testdata`\n     *last release*: Aug 30, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     Get and load testdata in pytest projects\n\n  :pypi:`pytest-testdirectory`\n     *last release*: May 02, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A py.test plugin providing temporary directories in unit tests.\n\n  :pypi:`pytest-testdox`\n     *last release*: Jul 22, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=4.6.0)\n\n     A testdox format reporter for pytest\n\n  :pypi:`pytest-test-grouping`\n     *last release*: Feb 01, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.5)\n\n     A Pytest plugin for running a subset of your tests by splitting them in to equally sized groups.\n\n  :pypi:`pytest-test-groups`\n     *last release*: May 08, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     A Pytest plugin for running a subset of your tests by splitting them in to equally sized groups.\n\n  :pypi:`pytest-testinel`\n     *last release*: Mar 13, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7\n\n     Testinel’s pytest plugin captures structured test execution data directly from pytest and sends it to Testinel, where your test results become searchable, comparable, and actually useful.\n\n  :pypi:`pytest-testinfra`\n     *last release*: Mar 30, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6\n\n     Test infrastructures\n\n  :pypi:`pytest-testinfra-jpic`\n     *last release*: Sep 21, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Test infrastructures\n\n  :pypi:`pytest-testinfra-winrm-transport`\n     *last release*: Sep 21, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Test infrastructures\n\n  :pypi:`pytest-testit-parametrize`\n     *last release*: Dec 04, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.3.3\n\n     A pytest plugin for uploading parameterized tests parameters into TMS TestIT\n\n  :pypi:`pytest-testlink-adaptor`\n     *last release*: Dec 20, 2018,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.6)\n\n     pytest reporting plugin for testlink\n\n  :pypi:`pytest-testmon`\n     *last release*: Dec 01, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest<10,>=5\n\n     selects tests affected by changed files and methods\n\n  :pypi:`pytest-testmon-dev`\n     *last release*: Mar 30, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (<8,>=5)\n\n     selects tests affected by changed files and methods\n\n  :pypi:`pytest-testmon-oc`\n     *last release*: Jun 01, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (<8,>=5)\n\n     nOly selects tests affected by changed files and methods\n\n  :pypi:`pytest-testmon-skip-libraries`\n     *last release*: Mar 03, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (<8,>=5)\n\n     selects tests affected by changed files and methods\n\n  :pypi:`pytest-testobject`\n     *last release*: Sep 24, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.1.1)\n\n     Plugin to use TestObject Suites with Pytest\n\n  :pypi:`pytest-testpluggy`\n     *last release*: Jan 07, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     set your encoding\n\n  :pypi:`pytest-testrail`\n     *last release*: Jan 25, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin for creating TestRail runs and adding results\n\n  :pypi:`pytest-testrail2`\n     *last release*: Feb 10, 2023,\n     *status*: N/A,\n     *requires*: pytest (<8.0,>=7.2.0)\n\n     A pytest plugin to upload results to TestRail.\n\n  :pypi:`pytest-testrail-api`\n     *last release*: Mar 17, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     TestRail Api Python Client\n\n  :pypi:`pytest-testrail-api-client`\n     *last release*: Dec 14, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     TestRail Api Python Client\n\n  :pypi:`pytest-testrail-appetize`\n     *last release*: Sep 29, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin for creating TestRail runs and adding results\n\n  :pypi:`pytest-testrail-client`\n     *last release*: Sep 29, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest plugin for Testrail\n\n  :pypi:`pytest-testrail-e2e`\n     *last release*: Oct 11, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=3.6)\n\n     pytest plugin for creating TestRail runs and adding results\n\n  :pypi:`pytest-testrail-integrator`\n     *last release*: Aug 01, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=6.2.5)\n\n     Pytest plugin for sending report to testrail system.\n\n  :pypi:`pytest-testrail-ns`\n     *last release*: Aug 12, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest plugin for creating TestRail runs and adding results\n\n  :pypi:`pytest-testrail-reporter`\n     *last release*: Sep 10, 2018,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-testrail-results`\n     *last release*: Mar 04, 2024,\n     *status*: N/A,\n     *requires*: pytest >=7.2.0\n\n     A pytest plugin to upload results to TestRail.\n\n  :pypi:`pytest-testreport`\n     *last release*: Dec 01, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n\n\n  :pypi:`pytest-testreport-new`\n     *last release*: Oct 07, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest >=3.5.0\n\n\n\n  :pypi:`pytest-testslide`\n     *last release*: Jan 07, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (~=6.2)\n\n     TestSlide fixture for pytest\n\n  :pypi:`pytest-test-this`\n     *last release*: Sep 15, 2019,\n     *status*: 2 - Pre-Alpha,\n     *requires*: pytest (>=2.3)\n\n     Plugin for py.test to run relevant tests, based on naively checking if a test contains a reference to the symbol you supply\n\n  :pypi:`pytest-test-tracer-for-pytest`\n     *last release*: Jun 28, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A plugin that allows coll test data for use on Test Tracer\n\n  :pypi:`pytest-test-tracer-for-pytest-bdd`\n     *last release*: Aug 20, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A plugin that allows coll test data for use on Test Tracer\n\n  :pypi:`pytest-test-utils`\n     *last release*: Feb 08, 2024,\n     *status*: N/A,\n     *requires*: pytest >=3.9\n\n\n\n  :pypi:`pytest-tesults`\n     *last release*: Nov 12, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=3.5.0\n\n     Tesults plugin for pytest\n\n  :pypi:`pytest-texts-score`\n     *last release*: Dec 17, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.4.2\n\n     Texts content similarity scoring plugin\n\n  :pypi:`pytest-textual-snapshot`\n     *last release*: Jan 23, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.0.0\n\n     Snapshot testing for Textual apps\n\n  :pypi:`pytest-tezos`\n     *last release*: Jan 16, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest-ligo\n\n  :pypi:`pytest-tf`\n     *last release*: May 29, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.2.1\n\n     Test your OpenTofu and Terraform config using a PyTest plugin\n\n  :pypi:`pytest-th2-bdd`\n     *last release*: May 13, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest_th2_bdd\n\n  :pypi:`pytest-thawgun`\n     *last release*: May 26, 2020,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     Pytest plugin for time travel\n\n  :pypi:`pytest-thread`\n     *last release*: Jul 07, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-threadleak`\n     *last release*: Jul 03, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.1.1)\n\n     Detects thread leaks\n\n  :pypi:`pytest-tick`\n     *last release*: Aug 31, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=6.2.5,<7.0.0)\n\n     Ticking on tests\n\n  :pypi:`pytest_time`\n     *last release*: Dec 01, 2025,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-timeassert-ethan`\n     *last release*: Dec 25, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     execution duration\n\n  :pypi:`pytest-timeit`\n     *last release*: Oct 13, 2016,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pytest plugin to time test function runs\n\n  :pypi:`pytest-timeout`\n     *last release*: May 05, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     pytest plugin to abort hanging tests\n\n  :pypi:`pytest-timeouts`\n     *last release*: Sep 21, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Linux-only Pytest plugin to control durations of various test case execution phases\n\n  :pypi:`pytest-timer`\n     *last release*: Dec 26, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     A timer plugin for pytest\n\n  :pypi:`pytest-timestamper`\n     *last release*: Mar 27, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin to add a timestamp prefix to the pytest output\n\n  :pypi:`pytest-timestamps`\n     *last release*: Sep 11, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.3,<8.0)\n\n     A simple plugin to view timestamps for each test\n\n  :pypi:`pytest-timing-plugin`\n     *last release*: Jul 21, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     pytest插件开发demo\n\n  :pypi:`pytest-tiny-api-client`\n     *last release*: Jan 04, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     The companion pytest plugin for tiny-api-client\n\n  :pypi:`pytest-tinybird`\n     *last release*: May 07, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=3.8.0\n\n     A pytest plugin to report test results to tinybird\n\n  :pypi:`pytest-tipsi-django`\n     *last release*: Feb 05, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=6.0.0\n\n     Better fixtures for django\n\n  :pypi:`pytest-tipsi-testing`\n     *last release*: Feb 04, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=3.3.0\n\n     Better fixtures management. Various helpers\n\n  :pypi:`pytest-tldr`\n     *last release*: Nov 10, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin that limits the output to just the things you need.\n\n  :pypi:`pytest-tm4j-reporter`\n     *last release*: Sep 01, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Cloud Jira Test Management (TM4J) PyTest reporter plugin\n\n  :pypi:`pytest-tmnet`\n     *last release*: Mar 01, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     A small example package\n\n  :pypi:`pytest-tmp-files`\n     *last release*: Dec 08, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     Utilities to create temporary file hierarchies in pytest.\n\n  :pypi:`pytest-tmpfs`\n     *last release*: Aug 29, 2022,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin that helps you on using a temporary filesystem for testing.\n\n  :pypi:`pytest-tmreport`\n     *last release*: Aug 12, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     this is a vue-element ui report for pytest\n\n  :pypi:`pytest-tmux`\n     *last release*: Sep 01, 2025,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pytest plugin that enables tmux driven tests\n\n  :pypi:`pytest-todo`\n     *last release*: May 23, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A small plugin for the pytest testing framework, marking TODO comments as failure\n\n  :pypi:`pytest-tomato`\n     *last release*: Mar 01, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-toolbelt`\n     *last release*: Aug 12, 2019,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n     This is just a collection of utilities for pytest, but don't really belong in pytest proper.\n\n  :pypi:`pytest-toolbox`\n     *last release*: Apr 07, 2018,\n     *status*: N/A,\n     *requires*: pytest (>=3.5.0)\n\n     Numerous useful plugins for pytest.\n\n  :pypi:`pytest-toolkit`\n     *last release*: Jun 07, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Useful utils for testing\n\n  :pypi:`pytest-tools`\n     *last release*: Oct 21, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Pytest tools\n\n  :pypi:`pytest-topo`\n     *last release*: Jun 05, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     Topological sorting for pytest\n\n  :pypi:`pytest-tornado`\n     *last release*: Jun 17, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.6)\n\n     A py.test plugin providing fixtures and markers to simplify testing of asynchronous tornado applications.\n\n  :pypi:`pytest-tornado5`\n     *last release*: Nov 16, 2018,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.6)\n\n     A py.test plugin providing fixtures and markers to simplify testing of asynchronous tornado applications.\n\n  :pypi:`pytest-tornado-yen3`\n     *last release*: Oct 15, 2018,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A py.test plugin providing fixtures and markers to simplify testing of asynchronous tornado applications.\n\n  :pypi:`pytest-tornasync`\n     *last release*: Jul 15, 2019,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=3.0)\n\n     py.test plugin for testing Python 3.5+ Tornado code\n\n  :pypi:`pytest-trace`\n     *last release*: Jun 19, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=4.6)\n\n     Save OpenTelemetry spans generated during testing\n\n  :pypi:`pytest-track`\n     *last release*: Feb 26, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=3.0)\n\n\n\n  :pypi:`pytest-translations`\n     *last release*: Sep 11, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=7)\n\n     Test your translation files.\n\n  :pypi:`pytest-travis-fold`\n     *last release*: Nov 29, 2017,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.6.0)\n\n     Folds captured output sections in Travis CI build log\n\n  :pypi:`pytest-trello`\n     *last release*: Nov 20, 2015,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Plugin for py.test that integrates trello using markers\n\n  :pypi:`pytest-trepan`\n     *last release*: Sep 11, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=4.0.0\n\n     Pytest plugin for trepan debugger.\n\n  :pypi:`pytest-trialtemp`\n     *last release*: Jun 08, 2015,\n     *status*: N/A,\n     *requires*: N/A\n\n     py.test plugin for using the same _trial_temp working directory as trial\n\n  :pypi:`pytest-trio`\n     *last release*: Nov 01, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.2.0)\n\n     Pytest plugin for trio\n\n  :pypi:`pytest-trytond`\n     *last release*: Nov 04, 2022,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=5)\n\n     Pytest plugin for the Tryton server framework\n\n  :pypi:`pytest-tspwplib`\n     *last release*: Jan 08, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     A simple plugin to use with tspwplib\n\n  :pypi:`pytest-tst`\n     *last release*: Apr 27, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=5.0.0)\n\n     Customize pytest options, output and exit code to make it compatible with tst\n\n  :pypi:`pytest-tstcls`\n     *last release*: Mar 23, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Test Class Base\n\n  :pypi:`pytest-tui`\n     *last release*: Dec 08, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Text User Interface (TUI) and HTML report for Pytest test runs\n\n  :pypi:`pytest-tui-runner`\n     *last release*: Dec 12, 2025,\n     *status*: N/A,\n     *requires*: pytest<=9.0.1,>=7.4\n\n     Textual-based terminal UI for running pytest tests\n\n  :pypi:`pytest-tuitest`\n     *last release*: Apr 11, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.4.0\n\n     pytest plugin for testing TUI and regular command-line applications.\n\n  :pypi:`pytest-tutorials`\n     *last release*: Mar 11, 2023,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-twilio-conversations-client-mock`\n     *last release*: Aug 02, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-twisted`\n     *last release*: Sep 10, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=2.3\n\n     A twisted plugin for pytest.\n\n  :pypi:`pytest-ty`\n     *last release*: Mar 08, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin to run the ty type checker\n\n  :pypi:`pytest-typechecker`\n     *last release*: Feb 04, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=6.2.5,<7.0.0)\n\n     Run type checkers on specified test files\n\n  :pypi:`pytest-typed-schema-shot`\n     *last release*: Jun 14, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin for automatic JSON Schema generation and validation from examples\n\n  :pypi:`pytest-typhoon-config`\n     *last release*: Apr 07, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A Typhoon HIL plugin that facilitates test parameter configuration at runtime\n\n  :pypi:`pytest-typhoon-polarion`\n     *last release*: Feb 01, 2024,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Typhoontest plugin for Siemens Polarion\n\n  :pypi:`pytest-typhoon-xray`\n     *last release*: Aug 15, 2023,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Typhoon HIL plugin for pytest\n\n  :pypi:`pytest-typing-runner`\n     *last release*: May 31, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest plugin to make it easier to run and check python code against static type checkers\n\n  :pypi:`pytest-tytest`\n     *last release*: May 25, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=5.4.2)\n\n     Typhoon HIL plugin for pytest\n\n  :pypi:`pytest-tzshift`\n     *last release*: Jun 25, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0\n\n     A Pytest plugin that transparently re-runs tests under a matrix of timezones and locales.\n\n  :pypi:`pytest-ubersmith`\n     *last release*: Apr 13, 2015,\n     *status*: N/A,\n     *requires*: N/A\n\n     Easily mock calls to ubersmith at the \\`requests\\` level.\n\n  :pypi:`pytest-ui`\n     *last release*: Jul 05, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Text User Interface for running python tests\n\n  :pypi:`pytest-ui-failed-screenshot`\n     *last release*: Dec 06, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     UI自动测试失败时自动截图，并将截图加入到测试报告中\n\n  :pypi:`pytest-ui-failed-screenshot-allure`\n     *last release*: Dec 06, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     UI自动测试失败时自动截图，并将截图加入到Allure测试报告中\n\n  :pypi:`pytest-uncollect-if`\n     *last release*: Dec 26, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     A plugin to uncollect pytests tests rather than using skipif\n\n  :pypi:`pytest-unflakable`\n     *last release*: Apr 30, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=6.2.0\n\n     Unflakable plugin for PyTest\n\n  :pypi:`pytest-unhandled-exception-exit-code`\n     *last release*: Jun 22, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=2.3)\n\n     Plugin for py.test set a different exit code on uncaught exceptions\n\n  :pypi:`pytest-unique`\n     *last release*: Dec 08, 2025,\n     *status*: N/A,\n     *requires*: pytest<10.0.0,>=9.0.0\n\n     Pytest fixture to generate unique values.\n\n  :pypi:`pytest-unittest-filter`\n     *last release*: Jan 12, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.1.0)\n\n     A pytest plugin for filtering unittest-based test classes\n\n  :pypi:`pytest-unittest-id-runner`\n     *last release*: Feb 09, 2025,\n     *status*: N/A,\n     *requires*: pytest>=6.0.0\n\n     A pytest plugin to run tests using unittest-style test IDs\n\n  :pypi:`pytest-unmagic`\n     *last release*: Jul 14, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest fixtures with conventional import semantics\n\n  :pypi:`pytest-unmarked`\n     *last release*: Aug 27, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Run only unmarked tests\n\n  :pypi:`pytest-unordered`\n     *last release*: Jun 03, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Test equality of unordered collections in pytest\n\n  :pypi:`pytest-unstable`\n     *last release*: Sep 27, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Set a test as unstable to return 0 even if it failed\n\n  :pypi:`pytest-unused-fixtures`\n     *last release*: Dec 23, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>7.3.2\n\n     A pytest plugin to list unused fixtures after a test run.\n\n  :pypi:`pytest-unused-port`\n     *last release*: Oct 22, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest fixture finding an unused local port\n\n  :pypi:`pytest-upload-report`\n     *last release*: Jun 18, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     pytest-upload-report is a plugin for pytest that upload your test report for test results.\n\n  :pypi:`pytest-urllib3`\n     *last release*: Mar 09, 2026,\n     *status*: 3 - Alpha,\n     *requires*: pytest>=7\n\n     A pytest plugin to mock urllib3 requests\n\n  :pypi:`pytest-utils`\n     *last release*: Feb 02, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=7.0.0,<8.0.0)\n\n     Some helpers for pytest.\n\n  :pypi:`pytest-uuid`\n     *last release*: Feb 27, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin for mocking uuid.uuid4() calls\n\n  :pypi:`pytest-vagrant`\n     *last release*: Sep 07, 2021,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     A py.test plugin providing access to vagrant.\n\n  :pypi:`pytest-valgrind`\n     *last release*: May 19, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-variables`\n     *last release*: Feb 01, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     pytest plugin for providing variables to tests/fixtures\n\n  :pypi:`pytest-variant`\n     *last release*: Jun 06, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Variant support for Pytest\n\n  :pypi:`pytest-vcr`\n     *last release*: Apr 26, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=3.6.0)\n\n     Plugin for managing VCR.py cassettes\n\n  :pypi:`pytest-vcr-delete-on-fail`\n     *last release*: Feb 16, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=8.0.0,<9.0.0)\n\n     A pytest plugin that automates vcrpy cassettes deletion on test failure.\n\n  :pypi:`pytest-vcrpandas`\n     *last release*: Jan 12, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     Test from HTTP interactions to dataframe processed.\n\n  :pypi:`pytest-vcs`\n     *last release*: Sep 22, 2022,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-venv`\n     *last release*: Nov 23, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     py.test fixture for creating a virtual environment\n\n  :pypi:`pytest-verbose-parametrize`\n     *last release*: Nov 29, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     More descriptive output for parametrized py.test tests\n\n  :pypi:`pytest-verify`\n     *last release*: Oct 25, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     A pytest plugin for snapshot verification with optional visual diff viewer.\n\n  :pypi:`pytest-vigil`\n     *last release*: Mar 13, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=9.0.0\n\n     A pytest plugin for enhanced test reliability and monitoring\n\n  :pypi:`pytest-vimqf`\n     *last release*: Feb 08, 2021,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=6.2.2,<7.0.0)\n\n     A simple pytest plugin that will shrink pytest output when specified, to fit vim quickfix window.\n\n  :pypi:`pytest-virtualenv`\n     *last release*: Nov 29, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Virtualenv fixture for py.test\n\n  :pypi:`pytest-visual`\n     *last release*: Nov 28, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n\n\n  :pypi:`pytest-vnc`\n     *last release*: Nov 06, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     VNC client for Pytest\n\n  :pypi:`pytest-voluptuous`\n     *last release*: Jun 09, 2020,\n     *status*: N/A,\n     *requires*: pytest\n\n     Pytest plugin for asserting data against voluptuous schema.\n\n  :pypi:`pytest-vscodedebug`\n     *last release*: Dec 04, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     A pytest plugin to easily enable debugging tests within Visual Studio Code\n\n  :pypi:`pytest-vscode-pycharm-cls`\n     *last release*: Feb 01, 2023,\n     *status*: N/A,\n     *requires*: pytest\n\n     A PyTest helper to enable start remote debugger on test start or failure or when pytest.set_trace is used.\n\n  :pypi:`pytest-vtestify`\n     *last release*: Feb 04, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     A pytest plugin for visual assertion using SSIM and image comparison.\n\n  :pypi:`pytest-vts`\n     *last release*: Jun 05, 2019,\n     *status*: N/A,\n     *requires*: pytest (>=2.3)\n\n     pytest plugin for automatic recording of http stubbed tests\n\n  :pypi:`pytest-vulture`\n     *last release*: Nov 25, 2024,\n     *status*: N/A,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin to checks dead code with vulture\n\n  :pypi:`pytest-vw`\n     *last release*: Oct 07, 2015,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     pytest-vw makes your failing test cases succeed under CI tools scrutiny\n\n  :pypi:`pytest-vyper`\n     *last release*: May 28, 2020,\n     *status*: 2 - Pre-Alpha,\n     *requires*: N/A\n\n     Plugin for the vyper smart contract language.\n\n  :pypi:`pytest-wa-e2e-plugin`\n     *last release*: Feb 18, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.5.0)\n\n     Pytest plugin for testing whatsapp bots with end to end tests\n\n  :pypi:`pytest-wake`\n     *last release*: Nov 19, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n\n\n  :pypi:`pytest-watch`\n     *last release*: May 20, 2018,\n     *status*: N/A,\n     *requires*: N/A\n\n     Local continuous test runner with pytest and watchdog.\n\n  :pypi:`pytest-watcher`\n     *last release*: Jan 10, 2026,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Automatically rerun your tests on file modifications\n\n  :pypi:`pytest-watch-plugin`\n     *last release*: Sep 12, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     Placeholder for internal package\n\n  :pypi:`pytest_wdb`\n     *last release*: Jul 04, 2016,\n     *status*: N/A,\n     *requires*: N/A\n\n     Trace pytest tests with wdb to halt on error with --wdb.\n\n  :pypi:`pytest-wdl`\n     *last release*: Nov 17, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     Pytest plugin for testing WDL workflows.\n\n  :pypi:`pytest-web3-data`\n     *last release*: Oct 04, 2023,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     A pytest plugin to fetch test data from IPFS HTTP gateways during pytest execution.\n\n  :pypi:`pytest-webdriver`\n     *last release*: Oct 17, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Selenium webdriver fixture for py.test\n\n  :pypi:`pytest-webstage`\n     *last release*: Sep 20, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0,>=7.0\n\n     Test web apps with pytest\n\n  :pypi:`pytest-webtestpilot`\n     *last release*: Dec 28, 2025,\n     *status*: N/A,\n     *requires*: pytest>=9.0.2\n\n     Pytest plugin for running WebTestPilot JSON tests\n\n  :pypi:`pytest-wetest`\n     *last release*: Nov 10, 2018,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Welian API Automation test framework pytest plugin\n\n  :pypi:`pytest-when`\n     *last release*: Sep 25, 2025,\n     *status*: N/A,\n     *requires*: pytest>=7.3.1\n\n     Utility which makes mocking more readable and controllable\n\n  :pypi:`pytest-whirlwind`\n     *last release*: Jun 12, 2020,\n     *status*: N/A,\n     *requires*: N/A\n\n     Testing Tornado.\n\n  :pypi:`pytest-wholenodeid`\n     *last release*: Aug 26, 2015,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=2.0)\n\n     pytest addon for displaying the whole node id for failures\n\n  :pypi:`pytest-win32consoletitle`\n     *last release*: Aug 08, 2021,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest progress in console title (Win32 only)\n\n  :pypi:`pytest-winnotify`\n     *last release*: Apr 22, 2016,\n     *status*: N/A,\n     *requires*: N/A\n\n     Windows tray notifications for py.test results.\n\n  :pypi:`pytest-wirefracture`\n     *last release*: Dec 31, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest fixtures for wirefracture\n\n  :pypi:`pytest-wiremock`\n     *last release*: Mar 27, 2022,\n     *status*: N/A,\n     *requires*: pytest (>=7.1.1,<8.0.0)\n\n     A pytest plugin for programmatically using wiremock in integration tests\n\n  :pypi:`pytest-wiretap`\n     *last release*: Mar 18, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     \\`pytest\\` plugin for recording call stacks\n\n  :pypi:`pytest-with-docker`\n     *last release*: Nov 09, 2021,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest with docker helpers.\n\n  :pypi:`pytest-workaround-12888`\n     *last release*: Jan 15, 2025,\n     *status*: N/A,\n     *requires*: N/A\n\n     forces an import of readline early in the process to work around pytest bug #12888\n\n  :pypi:`pytest-workflow`\n     *last release*: Mar 18, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest >=7.0.0\n\n     A pytest plugin for configuring workflow/pipeline tests using YAML files\n\n  :pypi:`pytest-xdist`\n     *last release*: Jul 01, 2025,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7.0.0\n\n     pytest xdist plugin for distributed testing, most importantly across multiple CPUs\n\n  :pypi:`pytest-xdist-debug-for-graingert`\n     *last release*: Jul 24, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=4.4.0)\n\n     pytest xdist plugin for distributed testing and loop-on-failing modes\n\n  :pypi:`pytest-xdist-forked`\n     *last release*: Feb 10, 2020,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=4.4.0)\n\n     forked from pytest-xdist\n\n  :pypi:`pytest-xdist-gnumake`\n     *last release*: Jun 22, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     A small example package\n\n  :pypi:`pytest-xdist-load-testing`\n     *last release*: Nov 22, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.4.2\n\n     xdist scheduler to repeately run tests\n\n  :pypi:`pytest-xdist-rate-limit`\n     *last release*: Dec 31, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.4.2\n\n     Shared state management and rate limiting for pytest-xdist workers\n\n  :pypi:`pytest-xdist-tracker`\n     *last release*: Nov 18, 2021,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=3.5.1)\n\n     pytest plugin helps to reproduce failures for particular xdist node\n\n  :pypi:`pytest-xdist-worker-stats`\n     *last release*: Feb 16, 2026,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     A pytest plugin to list worker statistics after a xdist run.\n\n  :pypi:`pytest-xdocker`\n     *last release*: Dec 08, 2025,\n     *status*: N/A,\n     *requires*: pytest<10.0.0,>=9.0.0\n\n     Pytest fixture to run docker across test runs.\n\n  :pypi:`pytest-xfaillist`\n     *last release*: Sep 17, 2021,\n     *status*: N/A,\n     *requires*: pytest (>=6.2.2,<7.0.0)\n\n     Maintain a xfaillist in an additional file to avoid merge-conflicts.\n\n  :pypi:`pytest-xfiles`\n     *last release*: Feb 27, 2018,\n     *status*: N/A,\n     *requires*: N/A\n\n     Pytest fixtures providing data read from function, module or package related (x)files.\n\n  :pypi:`pytest-xflaky`\n     *last release*: Oct 14, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.2.1\n\n     A simple plugin to use with pytest\n\n  :pypi:`pytest-xhtml`\n     *last release*: Feb 26, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=7\n\n     pytest plugin for generating HTML reports\n\n  :pypi:`pytest-xiuyu`\n     *last release*: Jul 25, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: N/A\n\n     This is a pytest plugin\n\n  :pypi:`pytest-xlog`\n     *last release*: May 31, 2020,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     Extended logging for test and decorators\n\n  :pypi:`pytest-xlsx`\n     *last release*: Aug 07, 2024,\n     *status*: N/A,\n     *requires*: pytest~=8.2.2\n\n     pytest plugin for generating test cases by xlsx(excel)\n\n  :pypi:`pytest-xml`\n     *last release*: Nov 14, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=8.0.0\n\n     Create simple XML results for parsing\n\n  :pypi:`pytest-xpara`\n     *last release*: Aug 07, 2024,\n     *status*: 3 - Alpha,\n     *requires*: pytest\n\n     An extended parametrizing plugin of pytest.\n\n  :pypi:`pytest-xprocess`\n     *last release*: May 19, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=2.8\n\n     A pytest plugin for managing processes across test runs.\n\n  :pypi:`pytest-xray`\n     *last release*: May 30, 2019,\n     *status*: 3 - Alpha,\n     *requires*: N/A\n\n\n\n  :pypi:`pytest-xrayjira`\n     *last release*: Mar 17, 2020,\n     *status*: 3 - Alpha,\n     *requires*: pytest (==4.3.1)\n\n\n\n  :pypi:`pytest-xray-reporter`\n     *last release*: May 21, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.0.0\n\n     Pytest plugin for generating Xray JSON reports\n\n  :pypi:`pytest-xray-server`\n     *last release*: May 03, 2022,\n     *status*: 3 - Alpha,\n     *requires*: pytest (>=5.3.1)\n\n\n\n  :pypi:`pytest-xstress`\n     *last release*: Jun 01, 2024,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.0.0\n\n\n\n  :pypi:`pytest-xtime`\n     *last release*: Jun 05, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest\n\n     pytest plugin for recording execution time\n\n  :pypi:`pytest-xvfb`\n     *last release*: Mar 12, 2025,\n     *status*: 4 - Beta,\n     *requires*: pytest>=2.8.1\n\n     A pytest plugin to run Xvfb (or Xephyr/Xvnc) for tests.\n\n  :pypi:`pytest-xvirt`\n     *last release*: Dec 15, 2024,\n     *status*: 4 - Beta,\n     *requires*: pytest>=7.2.2\n\n     A pytest plugin to virtualize test. For example to transparently running them on a remote box.\n\n  :pypi:`pytest-yaml`\n     *last release*: Oct 05, 2018,\n     *status*: N/A,\n     *requires*: pytest\n\n     This plugin is used to load yaml output to your test using pytest framework.\n\n  :pypi:`pytest-yaml-fei`\n     *last release*: Jul 27, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     a pytest yaml allure package\n\n  :pypi:`pytest-yaml-sanmu`\n     *last release*: Sep 16, 2025,\n     *status*: N/A,\n     *requires*: pytest>=8.2.2\n\n     Pytest plugin for generating test cases with YAML. In test cases, you can use markers, fixtures, variables, and even call Python functions.\n\n  :pypi:`pytest-yamltree`\n     *last release*: Mar 02, 2020,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.1.1)\n\n     Create or check file/directory trees described by YAML\n\n  :pypi:`pytest-yamlwsgi`\n     *last release*: May 11, 2010,\n     *status*: N/A,\n     *requires*: N/A\n\n     Run tests against wsgi apps defined in yaml\n\n  :pypi:`pytest-yaml-yoyo`\n     *last release*: Jun 19, 2023,\n     *status*: N/A,\n     *requires*: pytest (>=7.2.0)\n\n     http/https API run by yaml\n\n  :pypi:`pytest-yapf`\n     *last release*: Jul 06, 2017,\n     *status*: 4 - Beta,\n     *requires*: pytest (>=3.1.1)\n\n     Run yapf\n\n  :pypi:`pytest-yapf3`\n     *last release*: Mar 29, 2023,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (>=7)\n\n     Validate your Python file format with yapf\n\n  :pypi:`pytest-yield`\n     *last release*: Jan 23, 2019,\n     *status*: N/A,\n     *requires*: N/A\n\n     PyTest plugin to run tests concurrently, each \\`yield\\` switch context to other one\n\n  :pypi:`pytest-yls`\n     *last release*: Apr 09, 2025,\n     *status*: N/A,\n     *requires*: pytest<9.0.0,>=8.3.3\n\n     Pytest plugin to test the YLS as a whole.\n\n  :pypi:`pytest-youqu-playwright`\n     *last release*: Jun 12, 2024,\n     *status*: N/A,\n     *requires*: pytest\n\n     pytest-youqu-playwright\n\n  :pypi:`pytest-yuk`\n     *last release*: Mar 26, 2021,\n     *status*: N/A,\n     *requires*: pytest>=5.0.0\n\n     Display tests you are uneasy with, using 🤢/🤮 for pass/fail of tests marked with yuk.\n\n  :pypi:`pytest-zafira`\n     *last release*: Sep 18, 2019,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest (==4.1.1)\n\n     A Zafira plugin for pytest\n\n  :pypi:`pytest-zap`\n     *last release*: May 12, 2014,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     OWASP ZAP plugin for py.test.\n\n  :pypi:`pytest-zcc`\n     *last release*: Jun 02, 2024,\n     *status*: N/A,\n     *requires*: N/A\n\n     eee\n\n  :pypi:`pytest-zebrunner`\n     *last release*: Jul 04, 2024,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=4.5.0\n\n     Pytest connector for Zebrunner reporting\n\n  :pypi:`pytest-zeebe`\n     *last release*: Feb 01, 2024,\n     *status*: N/A,\n     *requires*: pytest (>=7.4.2,<8.0.0)\n\n     Pytest fixtures for testing Camunda 8 processes using a Zeebe test engine.\n\n  :pypi:`pytest-zephyr-scale-integration`\n     *last release*: Jun 26, 2025,\n     *status*: N/A,\n     *requires*: pytest\n\n     A library for integrating Jira Zephyr Scale (Adaptavist\\TM4J) with pytest\n\n  :pypi:`pytest-zephyr-telegram`\n     *last release*: Sep 30, 2024,\n     *status*: N/A,\n     *requires*: pytest==8.3.2\n\n     Плагин для отправки данных автотестов в Телеграм и Зефир\n\n  :pypi:`pytest-zest`\n     *last release*: Nov 17, 2022,\n     *status*: N/A,\n     *requires*: N/A\n\n     Zesty additions to pytest.\n\n  :pypi:`pytest-zhongwen-wendang`\n     *last release*: Mar 04, 2024,\n     *status*: 4 - Beta,\n     *requires*: N/A\n\n     PyTest 中文文档\n\n  :pypi:`pytest-zigzag`\n     *last release*: Feb 27, 2019,\n     *status*: 4 - Beta,\n     *requires*: pytest (~=3.6)\n\n     Extend py.test for RPC OpenStack testing.\n\n  :pypi:`pytest-zulip`\n     *last release*: May 07, 2022,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest\n\n     Pytest report plugin for Zulip\n\n  :pypi:`pytest-zy`\n     *last release*: Mar 24, 2024,\n     *status*: N/A,\n     *requires*: pytest~=7.2.0\n\n     接口自动化测试框架\n\n  :pypi:`tursu`\n     *last release*: Mar 02, 2026,\n     *status*: 5 - Production/Stable,\n     *requires*: pytest>=8.3.5\n\n     🎬 A pytest plugin that transpiles Gherkin feature files to Python using AST, enforcing typing for ease of use and debugging.\n"
  },
  {
    "path": "doc/en/reference/reference.rst",
    "content": ":tocdepth: 3\n\n.. _`api-reference`:\n\nAPI Reference\n=============\n\nThis page contains the full reference to pytest's API.\n\n\nConstants\n---------\n\npytest.__version__\n~~~~~~~~~~~~~~~~~~\n\nThe current pytest version, as a string::\n\n    >>> import pytest\n    >>> pytest.__version__\n    '9.0.2'\n\n.. _`hidden-param`:\n\npytest.HIDDEN_PARAM\n~~~~~~~~~~~~~~~~~~~\n\n.. versionadded:: 8.4\n\nCan be passed to ``ids`` of :py:func:`Metafunc.parametrize <pytest.Metafunc.parametrize>`\nor to ``id`` of :func:`pytest.param` to hide a parameter set from the test name.\nCan only be used at most 1 time, as test names need to be unique.\n\n.. _`version-tuple`:\n\npytest.version_tuple\n~~~~~~~~~~~~~~~~~~~~\n\n.. versionadded:: 7.0\n\nThe current pytest version, as a tuple::\n\n    >>> import pytest\n    >>> pytest.version_tuple\n    (7, 0, 0)\n\nFor pre-releases, the last component will be a string with the prerelease version::\n\n    >>> import pytest\n    >>> pytest.version_tuple\n    (7, 0, '0rc1')\n\n\nFunctions\n---------\n\npytest.approx\n~~~~~~~~~~~~~\n\n.. autofunction:: pytest.approx\n\npytest.fail\n~~~~~~~~~~~\n\n**Tutorial**: :ref:`skipping`\n\n.. autofunction:: pytest.fail(reason, [pytrace=True])\n\n.. class:: pytest.fail.Exception\n\n    The exception raised by :func:`pytest.fail`.\n\npytest.skip\n~~~~~~~~~~~\n\n.. autofunction:: pytest.skip(reason, [allow_module_level=False])\n\n.. class:: pytest.skip.Exception\n\n    The exception raised by :func:`pytest.skip`.\n\n.. _`pytest.importorskip ref`:\n\npytest.importorskip\n~~~~~~~~~~~~~~~~~~~\n\n.. autofunction:: pytest.importorskip\n\npytest.xfail\n~~~~~~~~~~~~\n\n.. autofunction:: pytest.xfail\n\n.. class:: pytest.xfail.Exception\n\n    The exception raised by :func:`pytest.xfail`.\n\npytest.exit\n~~~~~~~~~~~\n\n.. autofunction:: pytest.exit(reason, [returncode=None])\n\n.. class:: pytest.exit.Exception\n\n    The exception raised by :func:`pytest.exit`.\n\npytest.main\n~~~~~~~~~~~\n\n**Tutorial**: :ref:`pytest.main-usage`\n\n.. autofunction:: pytest.main\n\npytest.param\n~~~~~~~~~~~~\n\n.. autofunction:: pytest.param(*values, [id], [marks])\n\npytest.raises\n~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`assertraises`\n\n.. autofunction:: pytest.raises(expected_exception: Exception [, *, match])\n    :with: excinfo\n\npytest.deprecated_call\n~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`ensuring_function_triggers`\n\n.. autofunction:: pytest.deprecated_call([match])\n    :with:\n\npytest.register_assert_rewrite\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`assertion-rewriting`\n\n.. autofunction:: pytest.register_assert_rewrite\n\npytest.warns\n~~~~~~~~~~~~\n\n**Tutorial**: :ref:`assertwarnings`\n\n.. autofunction:: pytest.warns(expected_warning: Exception, [match])\n    :with:\n\npytest.freeze_includes\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`freezing-pytest`\n\n.. autofunction:: pytest.freeze_includes\n\n.. _`marks ref`:\n\nMarks\n-----\n\nMarks can be used to apply metadata to *test functions* (but not fixtures), which can then be accessed by\nfixtures or plugins.\n\n\n\n\n.. _`pytest.mark.filterwarnings ref`:\n\npytest.mark.filterwarnings\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`filterwarnings`\n\nAdd warning filters to marked test items.\n\n.. py:function:: pytest.mark.filterwarnings(filter)\n\n    :keyword str filter:\n        A *warning specification string*, which is composed of contents of the tuple ``(action, message, category, module, lineno)``\n        as specified in :ref:`python:warning-filter` section of\n        the Python documentation, separated by ``\":\"``. Optional fields can be omitted.\n        Module names passed for filtering are not regex-escaped.\n\n        For example:\n\n        .. code-block:: python\n\n            @pytest.mark.filterwarnings(r\"ignore:.*usage will be deprecated.*:DeprecationWarning\")\n            def test_foo(): ...\n\n\n.. _`pytest.mark.parametrize ref`:\n\npytest.mark.parametrize\n~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`parametrize`\n\nThis mark has the same signature as :py:meth:`pytest.Metafunc.parametrize`; see there.\n\n\n.. _`pytest.mark.skip ref`:\n\npytest.mark.skip\n~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`skip`\n\nUnconditionally skip a test function.\n\n.. py:function:: pytest.mark.skip(reason=None)\n\n    :keyword str reason: Reason why the test function is being skipped.\n\n\n.. _`pytest.mark.skipif ref`:\n\npytest.mark.skipif\n~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`skipif`\n\nSkip a test function if a condition is ``True``.\n\n.. py:function:: pytest.mark.skipif(condition, *, reason=None)\n\n    :type condition: bool or str\n    :param condition: ``True/False`` if the condition should be skipped or a :ref:`condition string <string conditions>`.\n    :keyword str reason: Reason why the test function is being skipped.\n\n\n.. _`pytest.mark.usefixtures ref`:\n\npytest.mark.usefixtures\n~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`usefixtures`\n\nMark a test function as using the given fixture names.\n\n.. py:function:: pytest.mark.usefixtures(*names)\n\n    :param args: The names of the fixture to use, as strings.\n\n.. note::\n\n    When using `usefixtures` in hooks, it can only load fixtures when applied to a test function before test setup\n    (for example in the `pytest_collection_modifyitems` hook).\n\n    Also note that this mark has no effect when applied to **fixtures**.\n\n\n\n.. _`pytest.mark.xfail ref`:\n\npytest.mark.xfail\n~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`xfail`\n\nMarks a test function as *expected to fail*.\n\n.. py:function:: pytest.mark.xfail(condition=False, *, reason=None, raises=None, run=True, strict=strict_xfail)\n\n    :keyword Union[bool, str] condition:\n        Condition for marking the test function as xfail (``True/False`` or a\n        :ref:`condition string <string conditions>`). If a ``bool``, you also have\n        to specify ``reason`` (see :ref:`condition string <string conditions>`).\n    :keyword str reason:\n        Reason why the test function is marked as xfail.\n    :keyword raises:\n        Exception class (or tuple of classes) expected to be raised by the test function; other exceptions will fail the test.\n        Note that subclasses of the classes passed will also result in a match (similar to how the ``except`` statement works).\n    :type raises: Type[:py:exc:`Exception`]\n\n    :keyword bool run:\n        Whether the test function should actually be executed. If ``False``, the function will always xfail and will\n        not be executed (useful if a function is segfaulting).\n    :keyword bool strict:\n        * If ``False`` the function will be shown in the terminal output as ``xfailed`` if it fails\n          and as ``xpass`` if it passes. In both cases this will not cause the test suite to fail as a whole. This\n          is particularly useful to mark *flaky* tests (tests that fail at random) to be tackled later.\n        * If ``True``, the function will be shown in the terminal output as ``xfailed`` if it fails, but if it\n          unexpectedly passes then it will **fail** the test suite. This is particularly useful to mark functions\n          that are always failing and there should be a clear indication if they unexpectedly start to pass (for example\n          a new release of a library fixes a known bug).\n\n        Defaults to :confval:`strict_xfail`, which is ``False`` by default.\n\n\nCustom marks\n~~~~~~~~~~~~\n\nMarks are created dynamically using the factory object ``pytest.mark`` and applied as a decorator.\n\nFor example:\n\n.. code-block:: python\n\n    @pytest.mark.timeout(10, \"slow\", method=\"thread\")\n    def test_function(): ...\n\nWill create and attach a :class:`Mark <pytest.Mark>` object to the collected\n:class:`Item <pytest.Item>`, which can then be accessed by fixtures or hooks with\n:meth:`Node.iter_markers <_pytest.nodes.Node.iter_markers>`. The ``mark`` object will have the following attributes:\n\n.. code-block:: python\n\n    mark.args == (10, \"slow\")\n    mark.kwargs == {\"method\": \"thread\"}\n\nExample for using multiple custom markers:\n\n.. code-block:: python\n\n    @pytest.mark.timeout(10, \"slow\", method=\"thread\")\n    @pytest.mark.slow\n    def test_function(): ...\n\nWhen :meth:`Node.iter_markers <_pytest.nodes.Node.iter_markers>` or :meth:`Node.iter_markers_with_node <_pytest.nodes.Node.iter_markers_with_node>` is used with multiple markers, the marker closest to the function will be iterated over first. The above example will result in ``@pytest.mark.slow`` followed by ``@pytest.mark.timeout(...)``.\n\n.. _`fixtures-api`:\n\nFixtures\n--------\n\n**Tutorial**: :ref:`fixture`\n\nFixtures are requested by test functions or other fixtures by declaring them as argument names.\n\n\nExample of a test requiring a fixture:\n\n.. code-block:: python\n\n    def test_output(capsys):\n        print(\"hello\")\n        out, err = capsys.readouterr()\n        assert out == \"hello\\n\"\n\n\nExample of a fixture requiring another fixture:\n\n.. code-block:: python\n\n    @pytest.fixture\n    def db_session(tmp_path):\n        fn = tmp_path / \"db.file\"\n        return connect(fn)\n\nFor more details, consult the full :ref:`fixtures docs <fixture>`.\n\n\n.. _`pytest.fixture-api`:\n\n@pytest.fixture\n~~~~~~~~~~~~~~~\n\n.. autofunction:: pytest.fixture\n    :decorator:\n\n\n.. fixture:: capfd\n\ncapfd\n~~~~~~\n\n**Tutorial**: :ref:`captures`\n\n.. autofunction:: _pytest.capture.capfd()\n    :no-auto-options:\n\n\n.. fixture:: capfdbinary\n\ncapfdbinary\n~~~~~~~~~~~~\n\n**Tutorial**: :ref:`captures`\n\n.. autofunction:: _pytest.capture.capfdbinary()\n    :no-auto-options:\n\n\n.. fixture:: caplog\n\ncaplog\n~~~~~~\n\n**Tutorial**: :ref:`logging`\n\n.. autofunction:: _pytest.logging.caplog()\n    :no-auto-options:\n\n    Returns a :class:`pytest.LogCaptureFixture` instance.\n\n.. autoclass:: pytest.LogCaptureFixture()\n    :members:\n\n\n.. fixture:: capsys\n\ncapsys\n~~~~~~\n\n**Tutorial**: :ref:`captures`\n\n.. autofunction:: _pytest.capture.capsys()\n    :no-auto-options:\n\n.. autoclass:: pytest.CaptureFixture()\n    :members:\n\n.. fixture:: capteesys\n\ncapteesys\n~~~~~~~~~\n\n**Tutorial**: :ref:`captures`\n\n.. autofunction:: _pytest.capture.capteesys()\n    :no-auto-options:\n\n.. fixture:: capsysbinary\n\ncapsysbinary\n~~~~~~~~~~~~\n\n**Tutorial**: :ref:`captures`\n\n.. autofunction:: _pytest.capture.capsysbinary()\n    :no-auto-options:\n\n\n.. fixture:: cache\n\nconfig.cache\n~~~~~~~~~~~~\n\n**Tutorial**: :ref:`cache`\n\nThe ``config.cache`` object allows other plugins and fixtures\nto store and retrieve values across test runs. To access it from fixtures\nrequest ``pytestconfig`` into your fixture and get it with ``pytestconfig.cache``.\n\nUnder the hood, the cache plugin uses the simple\n``dumps``/``loads`` API of the :py:mod:`json` stdlib module.\n\n``config.cache`` is an instance of :class:`pytest.Cache`:\n\n.. autoclass:: pytest.Cache()\n   :members:\n\n\n.. fixture:: doctest_namespace\n\ndoctest_namespace\n~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`doctest`\n\n.. autofunction:: _pytest.doctest.doctest_namespace()\n\n\n.. fixture:: monkeypatch\n\nmonkeypatch\n~~~~~~~~~~~\n\n**Tutorial**: :ref:`monkeypatching`\n\n.. autofunction:: _pytest.monkeypatch.monkeypatch()\n    :no-auto-options:\n\n    Returns a :class:`~pytest.MonkeyPatch` instance.\n\n.. autoclass:: pytest.MonkeyPatch\n    :members:\n\n\n.. fixture:: pytestconfig\n\npytestconfig\n~~~~~~~~~~~~\n\n.. autofunction:: _pytest.fixtures.pytestconfig()\n\n\n.. fixture:: pytester\n\npytester\n~~~~~~~~\n\n.. versionadded:: 6.2\n\nProvides a :class:`~pytest.Pytester` instance that can be used to run and test pytest itself.\n\nIt provides an empty directory where pytest can be executed in isolation, and contains facilities\nto write tests, configuration files, and match against expected output.\n\nTo use it, include in your topmost ``conftest.py`` file:\n\n.. code-block:: python\n\n    pytest_plugins = \"pytester\"\n\n\n\n.. autoclass:: pytest.Pytester()\n    :members:\n\n.. autoclass:: pytest.RunResult()\n    :members:\n\n.. autoclass:: pytest.LineMatcher()\n    :members:\n    :special-members: __str__\n\n.. autoclass:: pytest.HookRecorder()\n    :members:\n\n.. autoclass:: pytest.RecordedHookCall()\n    :members:\n\n\n.. fixture:: record_property\n\nrecord_property\n~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`record_property example`\n\n.. autofunction:: _pytest.junitxml.record_property()\n\n\n.. fixture:: record_testsuite_property\n\nrecord_testsuite_property\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`record_testsuite_property example`\n\n.. autofunction:: _pytest.junitxml.record_testsuite_property()\n\n\n.. fixture:: recwarn\n\nrecwarn\n~~~~~~~\n\n**Tutorial**: :ref:`recwarn`\n\n.. autofunction:: _pytest.recwarn.recwarn()\n    :no-auto-options:\n\n.. autoclass:: pytest.WarningsRecorder()\n    :members:\n    :special-members: __getitem__, __iter__, __len__\n\n\n.. fixture:: request\n\nrequest\n~~~~~~~\n\n**Example**: :ref:`request example`\n\nThe ``request`` fixture is a special fixture providing information of the requesting test function.\n\n.. autoclass:: pytest.FixtureRequest()\n    :members:\n\n\n.. fixture:: subtests\n\nsubtests\n~~~~~~~~\n\nThe ``subtests`` fixture enables declaring subtests inside test functions.\n\n**Tutorial**: :ref:`subtests`\n\n.. autoclass:: pytest.Subtests()\n    :members:\n\n\n.. fixture:: testdir\n\ntestdir\n~~~~~~~\n\nIdentical to :fixture:`pytester`, but provides an instance whose methods return\nlegacy ``py.path.local`` objects instead when applicable.\n\nNew code should avoid using :fixture:`testdir` in favor of :fixture:`pytester`.\n\n.. autoclass:: pytest.Testdir()\n    :members:\n    :noindex: TimeoutExpired\n\n\n.. fixture:: tmp_path\n\ntmp_path\n~~~~~~~~\n\n**Tutorial**: :ref:`tmp_path`\n\n.. autofunction:: _pytest.tmpdir.tmp_path()\n    :no-auto-options:\n\n\n.. fixture:: tmp_path_factory\n\ntmp_path_factory\n~~~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`tmp_path_factory example`\n\n.. _`tmp_path_factory factory api`:\n\n``tmp_path_factory`` is an instance of :class:`~pytest.TempPathFactory`:\n\n.. autoclass:: pytest.TempPathFactory()\n    :members:\n\n\n.. fixture:: tmpdir\n\ntmpdir\n~~~~~~\n\n**Tutorial**: :ref:`tmpdir and tmpdir_factory`\n\n.. autofunction:: _pytest.legacypath.LegacyTmpdirPlugin.tmpdir()\n    :no-auto-options:\n\n\n.. fixture:: tmpdir_factory\n\ntmpdir_factory\n~~~~~~~~~~~~~~\n\n**Tutorial**: :ref:`tmpdir and tmpdir_factory`\n\n``tmpdir_factory`` is an instance of :class:`~pytest.TempdirFactory`:\n\n.. autoclass:: pytest.TempdirFactory()\n    :members:\n\n\n.. _`hook-reference`:\n\nHooks\n-----\n\n**Tutorial**: :ref:`writing-plugins`\n\nReference to all hooks which can be implemented by :ref:`conftest.py files <localplugin>` and :ref:`plugins <plugins>`.\n\n@pytest.hookimpl\n~~~~~~~~~~~~~~~~\n\n.. function:: pytest.hookimpl\n    :decorator:\n\n    pytest's decorator for marking functions as hook implementations.\n\n    See :ref:`writinghooks` and :func:`pluggy.HookimplMarker`.\n\n@pytest.hookspec\n~~~~~~~~~~~~~~~~\n\n.. function:: pytest.hookspec\n    :decorator:\n\n    pytest's decorator for marking functions as hook specifications.\n\n    See :ref:`declaringhooks` and :func:`pluggy.HookspecMarker`.\n\n.. currentmodule:: _pytest.hookspec\n\nBootstrapping hooks\n~~~~~~~~~~~~~~~~~~~\n\nBootstrapping hooks called for plugins registered early enough (internal and third-party plugins).\n\n.. hook:: pytest_load_initial_conftests\n.. autofunction:: pytest_load_initial_conftests\n.. hook:: pytest_cmdline_parse\n.. autofunction:: pytest_cmdline_parse\n.. hook:: pytest_cmdline_main\n.. autofunction:: pytest_cmdline_main\n\n.. _`initialization-hooks`:\n\nInitialization hooks\n~~~~~~~~~~~~~~~~~~~~\n\nInitialization hooks called for plugins and ``conftest.py`` files.\n\n.. hook:: pytest_addoption\n.. autofunction:: pytest_addoption\n.. hook:: pytest_addhooks\n.. autofunction:: pytest_addhooks\n.. hook:: pytest_configure\n.. autofunction:: pytest_configure\n.. hook:: pytest_unconfigure\n.. autofunction:: pytest_unconfigure\n.. hook:: pytest_sessionstart\n.. autofunction:: pytest_sessionstart\n.. hook:: pytest_sessionfinish\n.. autofunction:: pytest_sessionfinish\n\n.. hook:: pytest_plugin_registered\n.. autofunction:: pytest_plugin_registered\n\nCollection hooks\n~~~~~~~~~~~~~~~~\n\n``pytest`` calls the following hooks for collecting files and directories:\n\n.. hook:: pytest_collection\n.. autofunction:: pytest_collection\n.. hook:: pytest_ignore_collect\n.. autofunction:: pytest_ignore_collect\n.. hook:: pytest_collect_directory\n.. autofunction:: pytest_collect_directory\n.. hook:: pytest_collect_file\n.. autofunction:: pytest_collect_file\n.. hook:: pytest_pycollect_makemodule\n.. autofunction:: pytest_pycollect_makemodule\n\nFor influencing the collection of objects in Python modules\nyou can use the following hook:\n\n.. hook:: pytest_pycollect_makeitem\n.. autofunction:: pytest_pycollect_makeitem\n.. hook:: pytest_generate_tests\n.. autofunction:: pytest_generate_tests\n.. hook:: pytest_make_parametrize_id\n.. autofunction:: pytest_make_parametrize_id\n\nHooks for influencing test skipping:\n\n.. hook:: pytest_markeval_namespace\n.. autofunction:: pytest_markeval_namespace\n\nAfter collection is complete, you can modify the order of\nitems, delete or otherwise amend the test items:\n\n.. hook:: pytest_collection_modifyitems\n.. autofunction:: pytest_collection_modifyitems\n\n.. note::\n    If this hook is implemented in ``conftest.py`` files, it always receives all collected items, not only those\n    under the ``conftest.py`` where it is implemented.\n\n.. hook:: pytest_collection_finish\n.. autofunction:: pytest_collection_finish\n\nTest running (runtest) hooks\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAll runtest related hooks receive a :py:class:`pytest.Item <pytest.Item>` object.\n\n.. hook:: pytest_runtestloop\n.. autofunction:: pytest_runtestloop\n.. hook:: pytest_runtest_protocol\n.. autofunction:: pytest_runtest_protocol\n.. hook:: pytest_runtest_logstart\n.. autofunction:: pytest_runtest_logstart\n.. hook:: pytest_runtest_logfinish\n.. autofunction:: pytest_runtest_logfinish\n.. hook:: pytest_runtest_setup\n.. autofunction:: pytest_runtest_setup\n.. hook:: pytest_runtest_call\n.. autofunction:: pytest_runtest_call\n.. hook:: pytest_runtest_teardown\n.. autofunction:: pytest_runtest_teardown\n.. hook:: pytest_runtest_makereport\n.. autofunction:: pytest_runtest_makereport\n\nFor deeper understanding you may look at the default implementation of\nthese hooks in ``_pytest.runner`` and maybe also\nin ``_pytest.pdb`` which interacts with ``_pytest.capture``\nand its input/output capturing in order to immediately drop\ninto interactive debugging when a test failure occurs.\n\n.. hook:: pytest_pyfunc_call\n.. autofunction:: pytest_pyfunc_call\n\nReporting hooks\n~~~~~~~~~~~~~~~\n\nSession related reporting hooks:\n\n.. hook:: pytest_collectstart\n.. autofunction:: pytest_collectstart\n.. hook:: pytest_make_collect_report\n.. autofunction:: pytest_make_collect_report\n.. hook:: pytest_itemcollected\n.. autofunction:: pytest_itemcollected\n.. hook:: pytest_collectreport\n.. autofunction:: pytest_collectreport\n.. hook:: pytest_deselected\n.. autofunction:: pytest_deselected\n.. hook:: pytest_report_header\n.. autofunction:: pytest_report_header\n.. hook:: pytest_report_collectionfinish\n.. autofunction:: pytest_report_collectionfinish\n.. hook:: pytest_report_teststatus\n.. autofunction:: pytest_report_teststatus\n.. hook:: pytest_report_to_serializable\n.. autofunction:: pytest_report_to_serializable\n.. hook:: pytest_report_from_serializable\n.. autofunction:: pytest_report_from_serializable\n.. hook:: pytest_terminal_summary\n.. autofunction:: pytest_terminal_summary\n.. hook:: pytest_fixture_setup\n.. autofunction:: pytest_fixture_setup\n.. hook:: pytest_fixture_post_finalizer\n.. autofunction:: pytest_fixture_post_finalizer\n.. hook:: pytest_warning_recorded\n.. autofunction:: pytest_warning_recorded\n\nCentral hook for reporting about test execution:\n\n.. hook:: pytest_runtest_logreport\n.. autofunction:: pytest_runtest_logreport\n\nAssertion related hooks:\n\n.. hook:: pytest_assertrepr_compare\n.. autofunction:: pytest_assertrepr_compare\n.. hook:: pytest_assertion_pass\n.. autofunction:: pytest_assertion_pass\n\n\nDebugging/Interaction hooks\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere are few hooks which can be used for special\nreporting or interaction with exceptions:\n\n.. hook:: pytest_internalerror\n.. autofunction:: pytest_internalerror\n.. hook:: pytest_keyboard_interrupt\n.. autofunction:: pytest_keyboard_interrupt\n.. hook:: pytest_exception_interact\n.. autofunction:: pytest_exception_interact\n.. hook:: pytest_enter_pdb\n.. autofunction:: pytest_enter_pdb\n.. hook:: pytest_leave_pdb\n.. autofunction:: pytest_leave_pdb\n\n\nCollection tree objects\n-----------------------\n\nThese are the collector and item classes (collectively called \"nodes\") which\nmake up the collection tree.\n\nNode\n~~~~\n\n.. autoclass:: _pytest.nodes.Node()\n    :members:\n    :show-inheritance:\n\nCollector\n~~~~~~~~~\n\n.. autoclass:: pytest.Collector()\n    :members:\n    :show-inheritance:\n\nItem\n~~~~\n\n.. autoclass:: pytest.Item()\n    :members:\n    :show-inheritance:\n\nFile\n~~~~\n\n.. autoclass:: pytest.File()\n    :members:\n    :show-inheritance:\n\nFSCollector\n~~~~~~~~~~~\n\n.. autoclass:: _pytest.nodes.FSCollector()\n    :members:\n    :show-inheritance:\n\nSession\n~~~~~~~\n\n.. autoclass:: pytest.Session()\n    :members:\n    :show-inheritance:\n\nPackage\n~~~~~~~\n\n.. autoclass:: pytest.Package()\n    :members:\n    :show-inheritance:\n\nModule\n~~~~~~\n\n.. autoclass:: pytest.Module()\n    :members:\n    :show-inheritance:\n\nClass\n~~~~~\n\n.. autoclass:: pytest.Class()\n    :members:\n    :show-inheritance:\n\nFunction\n~~~~~~~~\n\n.. autoclass:: pytest.Function()\n    :members:\n    :show-inheritance:\n\nFunctionDefinition\n~~~~~~~~~~~~~~~~~~\n\n.. autoclass:: _pytest.python.FunctionDefinition()\n    :members:\n    :show-inheritance:\n\n\nObjects\n-------\n\nObjects accessible from :ref:`fixtures <fixture>` or :ref:`hooks <hook-reference>`\nor importable from ``pytest``.\n\n\nCallInfo\n~~~~~~~~\n\n.. autoclass:: pytest.CallInfo()\n    :members:\n\nCollectReport\n~~~~~~~~~~~~~\n\n.. autoclass:: pytest.CollectReport()\n    :members:\n    :show-inheritance:\n    :inherited-members:\n\nConfig\n~~~~~~\n\n.. autoclass:: pytest.Config()\n    :members:\n\nDir\n~~~\n\n.. autoclass:: pytest.Dir()\n    :members:\n\nDirectory\n~~~~~~~~~\n\n.. autoclass:: pytest.Directory()\n    :members:\n\nExceptionInfo\n~~~~~~~~~~~~~\n\n.. autoclass:: pytest.ExceptionInfo()\n    :members:\n\n\nExitCode\n~~~~~~~~\n\n.. autoclass:: pytest.ExitCode\n    :members:\n\n\nFixtureDef\n~~~~~~~~~~\n\n.. autoclass:: pytest.FixtureDef()\n    :members:\n    :show-inheritance:\n\nMarkDecorator\n~~~~~~~~~~~~~\n\n.. autoclass:: pytest.MarkDecorator()\n    :members:\n\n\nMarkGenerator\n~~~~~~~~~~~~~\n\n.. autoclass:: pytest.MarkGenerator()\n    :members:\n\n\nMark\n~~~~\n\n.. autoclass:: pytest.Mark()\n    :members:\n\n\nMetafunc\n~~~~~~~~\n\n.. autoclass:: pytest.Metafunc()\n    :members:\n\nParser\n~~~~~~\n\n.. autoclass:: pytest.Parser()\n    :members:\n\nOptionGroup\n~~~~~~~~~~~\n\n.. autoclass:: pytest.OptionGroup()\n    :members:\n\nPytestPluginManager\n~~~~~~~~~~~~~~~~~~~\n\n.. autoclass:: pytest.PytestPluginManager()\n    :members:\n    :undoc-members:\n    :inherited-members:\n    :show-inheritance:\n\nRaisesExc\n~~~~~~~~~\n\n.. autoclass:: pytest.RaisesExc()\n    :members:\n\n    .. autoattribute:: fail_reason\n\nRaisesGroup\n~~~~~~~~~~~\n**Tutorial**: :ref:`assert-matching-exception-groups`\n\n.. autoclass:: pytest.RaisesGroup()\n    :members:\n\n    .. autoattribute:: fail_reason\n\nTerminalReporter\n~~~~~~~~~~~~~~~~\n\n.. autoclass:: pytest.TerminalReporter\n    :members:\n    :inherited-members:\n\nTestReport\n~~~~~~~~~~\n\n.. autoclass:: pytest.TestReport()\n    :members:\n    :show-inheritance:\n    :inherited-members:\n\nTestShortLogReport\n~~~~~~~~~~~~~~~~~~\n\n.. autoclass:: pytest.TestShortLogReport()\n    :members:\n\nResult\n~~~~~~~\n\nResult object used within :ref:`hook wrappers <hookwrapper>`, see :py:class:`Result in the pluggy documentation <pluggy.Result>` for more information.\n\nStash\n~~~~~\n\n.. autoclass:: pytest.Stash\n    :special-members: __setitem__, __getitem__, __delitem__, __contains__, __len__\n    :members:\n\n.. autoclass:: pytest.StashKey\n    :show-inheritance:\n    :members:\n\n\nGlobal Variables\n----------------\n\npytest treats some global variables in a special manner when defined in a test module or\n``conftest.py`` files.\n\n\n.. globalvar:: collect_ignore\n\n**Tutorial**: :ref:`customizing-test-collection`\n\nCan be declared in *conftest.py files* to exclude test directories or modules.\nNeeds to be a list of paths (``str``, :class:`pathlib.Path` or any :class:`os.PathLike`).\n\n.. code-block:: python\n\n  collect_ignore = [\"setup.py\"]\n\n\n.. globalvar:: collect_ignore_glob\n\n**Tutorial**: :ref:`customizing-test-collection`\n\nCan be declared in *conftest.py files* to exclude test directories or modules\nwith Unix shell-style wildcards. Needs to be ``list[str]`` where ``str`` can\ncontain glob patterns.\n\n.. code-block:: python\n\n  collect_ignore_glob = [\"*_ignore.py\"]\n\n\n.. globalvar:: pytest_plugins\n\n**Tutorial**: :ref:`available installable plugins`\n\nCan be declared at the **global** level in *test modules* and *conftest.py files* to register additional plugins.\nCan be either a ``str`` or ``Sequence[str]``.\n\n.. code-block:: python\n\n    pytest_plugins = \"myapp.testsupport.myplugin\"\n\n.. code-block:: python\n\n    pytest_plugins = (\"myapp.testsupport.tools\", \"myapp.testsupport.regression\")\n\n\n.. globalvar:: pytestmark\n\n**Tutorial**: :ref:`scoped-marking`\n\nCan be declared at the **global** level in *test modules* to apply one or more :ref:`marks <marks ref>` to all\ntest functions and methods. Can be either a single mark or a list of marks (applied in left-to-right order).\n\n.. code-block:: python\n\n    import pytest\n\n    pytestmark = pytest.mark.webtest\n\n\n.. code-block:: python\n\n    import pytest\n\n    pytestmark = [pytest.mark.integration, pytest.mark.slow]\n\n\nEnvironment Variables\n---------------------\n\nEnvironment variables that can be used to change pytest's behavior.\n\n.. envvar:: CI\n\n   When set to a non-empty value, pytest acknowledges that it is running in a CI process. See also :ref:`ci-pipelines`.\n\n.. envvar:: BUILD_NUMBER\n\n   When set to a non-empty value, pytest acknowledges that it is running in a CI process. Alternative to :envvar:`CI`. See also :ref:`ci-pipelines`.\n\n.. envvar:: PYTEST_ADDOPTS\n\n   This contains a command-line (parsed by the py:mod:`shlex` module) that will be **prepended** to the command line given\n   by the user, see :ref:`adding default options` for more information.\n\n.. envvar:: PYTEST_VERSION\n\n   This environment variable is defined at the start of the pytest session and is undefined afterwards.\n   It contains the value of ``pytest.__version__``, and among other things can be used to easily check if a code is running from within a pytest run.\n\n.. envvar:: PYTEST_CURRENT_TEST\n\n   This is not meant to be set by users, but is set by pytest internally with the name of the current test so other\n   processes can inspect it, see :ref:`pytest current test env` for more information.\n\n.. envvar:: PYTEST_DEBUG\n\n   When set, pytest will print tracing and debug information.\n\n.. envvar:: PYTEST_DEBUG_TEMPROOT\n\n   Root for temporary directories produced by fixtures like :fixture:`tmp_path`\n   as discussed in :ref:`temporary directory location and retention`.\n\n.. envvar:: PYTEST_DISABLE_PLUGIN_AUTOLOAD\n\n   When set, disables plugin auto-loading through :std:doc:`entry point packaging\n   metadata <packaging:guides/creating-and-discovering-plugins>`. Only plugins\n   explicitly specified in :envvar:`PYTEST_PLUGINS` or with :option:`-p` will be loaded.\n   See also :ref:`--disable-plugin-autoload <disable_plugin_autoload>`.\n\n.. envvar:: PYTEST_PLUGINS\n\n   Contains comma-separated list of modules that should be loaded as plugins:\n\n   .. code-block:: bash\n\n       export PYTEST_PLUGINS=mymodule.plugin,xdist\n\n   See also :option:`-p`.\n\n.. envvar:: PYTEST_THEME\n\n   Sets a `pygment style <https://pygments.org/docs/styles/>`_ to use for the code output.\n\n.. envvar:: PYTEST_THEME_MODE\n\n   Sets the :envvar:`PYTEST_THEME` to be either *dark* or *light*.\n\n.. envvar:: PY_COLORS\n\n   When set to ``1``, pytest will use color in terminal output.\n   When set to ``0``, pytest will not use color.\n   ``PY_COLORS`` takes precedence over ``NO_COLOR`` and ``FORCE_COLOR``.\n\n.. envvar:: NO_COLOR\n\n   When set to a non-empty string (regardless of value), pytest will not use color in terminal output.\n   ``PY_COLORS`` takes precedence over ``NO_COLOR``, which takes precedence over ``FORCE_COLOR``.\n   See `no-color.org <https://no-color.org/>`__ for other libraries supporting this community standard.\n\n.. envvar:: FORCE_COLOR\n\n   When set to a non-empty string (regardless of value), pytest will use color in terminal output.\n   ``PY_COLORS`` and ``NO_COLOR`` take precedence over ``FORCE_COLOR``.\n\nExceptions\n----------\n\n.. autoexception:: pytest.UsageError()\n    :show-inheritance:\n\n.. autoexception:: pytest.FixtureLookupError()\n    :show-inheritance:\n\n.. _`warnings ref`:\n\nWarnings\n--------\n\nCustom warnings generated in some situations such as improper usage or deprecated features.\n\n.. autoclass:: pytest.PytestWarning\n   :show-inheritance:\n\n.. autoclass:: pytest.PytestAssertRewriteWarning\n   :show-inheritance:\n\n.. autoclass:: pytest.PytestCacheWarning\n   :show-inheritance:\n\n.. autoclass:: pytest.PytestCollectionWarning\n   :show-inheritance:\n\n.. autoclass:: pytest.PytestConfigWarning\n   :show-inheritance:\n\n.. autoclass:: pytest.PytestDeprecationWarning\n   :show-inheritance:\n\n.. autoclass:: pytest.PytestExperimentalApiWarning\n   :show-inheritance:\n\n.. autoclass:: pytest.PytestReturnNotNoneWarning\n  :show-inheritance:\n\n.. autoclass:: pytest.PytestRemovedIn9Warning\n  :show-inheritance:\n\n.. autoclass:: pytest.PytestUnknownMarkWarning\n   :show-inheritance:\n\n.. autoclass:: pytest.PytestUnraisableExceptionWarning\n   :show-inheritance:\n\n.. autoclass:: pytest.PytestUnhandledThreadExceptionWarning\n   :show-inheritance:\n\n\nConsult the :ref:`internal-warnings` section in the documentation for more information.\n\n\n.. _`ini options ref`:\n\nConfiguration Options\n---------------------\n\nHere is a list of builtin configuration options that may be written in a ``pytest.ini`` (or ``.pytest.ini``),\n``pyproject.toml``, ``tox.ini``, or ``setup.cfg`` file, usually located at the root of your repository.\n\nTo see each file format in detail, see :ref:`config file formats`.\n\n.. warning::\n    Usage of ``setup.cfg`` is not recommended except for very simple use cases. ``.cfg``\n    files use a different parser than ``pytest.ini`` and ``tox.ini`` which might cause hard to track\n    down problems.\n    When possible, it is recommended to use the latter files, or ``pytest.toml`` or ``pyproject.toml``, to hold your pytest configuration.\n\nConfiguration options may be overwritten in the command-line by using ``-o/--override-ini``, which can also be\npassed multiple times. The expected format is ``name=value``. For example::\n\n   pytest -o console_output_style=classic -o cache_dir=/tmp/mycache\n\n\n.. confval:: addopts\n\n   Add the specified ``OPTS`` to the set of command line arguments as if they\n   had been specified by the user. Example: if you have this configuration file content:\n\n   .. code-block:: toml\n\n        # content of pytest.toml\n        [pytest]\n        addopts = [\"--maxfail=2\", \"-rf\"]  # exit after 2 failures, report fail info\n\n   issuing ``pytest test_hello.py`` actually means:\n\n   .. code-block:: bash\n\n        pytest --maxfail=2 -rf test_hello.py\n\n   Default is to add no options.\n\n\n.. confval:: cache_dir\n\n   Sets the directory where the cache plugin's content is stored. Default directory is\n   ``.pytest_cache`` which is created in :ref:`rootdir <rootdir>`. Directory may be\n   relative or absolute path. If setting relative path, then directory is created\n   relative to :ref:`rootdir <rootdir>`. Additionally, a path may contain environment\n   variables, that will be expanded. For more information about cache plugin\n   please refer to :ref:`cache_provider`.\n\n.. confval:: collect_imported_tests\n\n   .. versionadded:: 8.4\n\n   Setting this to ``false`` will make pytest collect classes/functions from test\n   files **only** if they are defined in that file (as opposed to imported there).\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            collect_imported_tests = false\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            collect_imported_tests = false\n\n   Default: ``true``\n\n   pytest traditionally collects classes/functions in the test module namespace even if they are imported from another file.\n\n   For example:\n\n   .. code-block:: python\n\n       # contents of src/domain.py\n       class Testament: ...\n\n\n       # contents of tests/test_testament.py\n       from domain import Testament\n\n\n       def test_testament(): ...\n\n   In this scenario, with the default options, pytest will collect the class `Testament` from `tests/test_testament.py` because it starts with `Test`, even though in this case it is a production class being imported in the test module namespace.\n\n   Set ``collected_imported_tests`` to ``false`` in the configuration file prevents that.\n\n.. confval:: consider_namespace_packages\n\n   Controls if pytest should attempt to identify `namespace packages <https://packaging.python.org/en/latest/guides/packaging-namespace-packages>`__\n   when collecting Python modules. Default is ``False``.\n\n   Set to ``True`` if the package you are testing is part of a namespace package.\n   Namespace packages are also supported as :option:`--pyargs` target.\n\n   Only `native namespace packages <https://packaging.python.org/en/latest/guides/packaging-namespace-packages/#native-namespace-packages>`__\n   are supported, with no plans to support `legacy namespace packages <https://packaging.python.org/en/latest/guides/packaging-namespace-packages/#legacy-namespace-packages>`__.\n\n   .. versionadded:: 8.1\n\n.. confval:: console_output_style\n\n   Sets the console output style while running tests:\n\n   * ``classic``: classic pytest output.\n   * ``progress``: like classic pytest output, but with a progress indicator.\n   * ``progress-even-when-capture-no``: allows the use of the progress indicator even when ``capture=no``.\n   * ``count``: like progress, but shows progress as the number of tests completed instead of a percent.\n   * ``times``: show tests duration.\n\n   The default is ``progress``, but you can fallback to ``classic`` if you prefer or\n   the new mode is causing unexpected problems:\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            console_output_style = \"classic\"\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            console_output_style = classic\n\n\n.. confval:: disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n\n   .. versionadded:: 4.4\n\n   pytest by default escapes any non-ascii characters used in unicode strings\n   for the parametrization because it has several downsides.\n   If however you would like to use unicode strings in parametrization\n   and see them in the terminal as is (non-escaped), use this option\n   in your configuration file:\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n           [pytest]\n           disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n           [pytest]\n           disable_test_id_escaping_and_forfeit_all_rights_to_community_support = true\n\n   Keep in mind however that this might cause unwanted side effects and\n   even bugs depending on the OS used and plugins currently installed,\n   so use it at your own risk.\n\n   Default: ``False``.\n\n   See :ref:`parametrizemark`.\n\n.. confval:: doctest_encoding\n\n\n\n   Default encoding to use to decode text files with docstrings.\n   :ref:`See how pytest handles doctests <doctest>`.\n\n\n.. confval:: doctest_optionflags\n\n   One or more doctest flag names from the standard ``doctest`` module.\n   :ref:`See how pytest handles doctests <doctest>`.\n\n\n.. confval:: empty_parameter_set_mark\n\n\n\n    Allows to pick the action for empty parametersets in parameterization\n\n    * ``skip`` skips tests with an empty parameterset (default)\n    * ``xfail`` marks tests with an empty parameterset as xfail(run=False)\n    * ``fail_at_collect`` raises an exception if parametrize collects an empty parameter set\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            empty_parameter_set_mark = \"xfail\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            empty_parameter_set_mark = xfail\n\n    .. note::\n\n      The default value of this option is planned to change to ``xfail`` in future releases\n      as this is considered less error prone, see :issue:`3155` for more details.\n\n\n.. confval:: enable_assertion_pass_hook\n\n   Enables the :hook:`pytest_assertion_pass` hook.\n   Make sure to delete any previously generated ``.pyc`` cache files.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            enable_assertion_pass_hook = true\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            enable_assertion_pass_hook = true\n\n\n.. confval:: faulthandler_exit_on_timeout\n\n   Exit the pytest process after the per-test timeout is reached by passing\n   `exit=True` to the :func:`faulthandler.dump_traceback_later` function. This\n   is particularly useful to avoid wasting CI resources for test suites that\n   are prone to putting the main Python interpreter into a deadlock state.\n\n   This option is set to 'false' by default.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            faulthandler_timeout = 5\n            faulthandler_exit_on_timeout = true\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            faulthandler_timeout = 5\n            faulthandler_exit_on_timeout = true\n\n\n\n.. confval:: faulthandler_timeout\n\n   Dumps the tracebacks of all threads if a test takes longer than ``X`` seconds to run (including\n   fixture setup and teardown). Implemented using the :func:`faulthandler.dump_traceback_later` function,\n   so all caveats there apply.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            faulthandler_timeout = 5\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            faulthandler_timeout = 5\n\n   For more information please refer to :ref:`faulthandler`.\n\n\n.. confval:: filterwarnings\n\n   Sets a list of filters and actions that should be taken for matched\n   warnings. By default all warnings emitted during the test session\n   will be displayed in a summary at the end of the test session.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            filterwarnings = [\n                'error',\n                'ignore::DeprecationWarning',\n                # Note the use of single quote below to denote \"raw\" strings in TOML.\n                'ignore:function ham\\(\\) should not be used:UserWarning',\n            ]\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            filterwarnings =\n                error\n                ignore::DeprecationWarning\n                ignore:function ham\\(\\) should not be used:UserWarning\n\n   This tells pytest to ignore deprecation warnings and turn all other warnings\n   into errors. For more information please refer to :ref:`warnings`.\n\n\n.. confval:: junit_duration_report\n\n    .. versionadded:: 4.1\n\n    Configures how durations are recorded into the JUnit XML report:\n\n    * ``total`` (the default): duration times reported include setup, call, and teardown times.\n    * ``call``: duration times reported include only call times, excluding setup and teardown.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            junit_duration_report = \"call\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            junit_duration_report = call\n\n\n.. confval:: junit_family\n\n    .. versionadded:: 4.2\n    .. versionchanged:: 6.1\n        Default changed to ``xunit2``.\n\n    Configures the format of the generated JUnit XML file. The possible options are:\n\n    * ``xunit1`` (or ``legacy``): produces old style output, compatible with the xunit 1.0 format.\n    * ``xunit2``: produces `xunit 2.0 style output <https://github.com/jenkinsci/xunit-plugin/blob/xunit-2.3.2/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd>`__, which should be more compatible with latest Jenkins versions.  **This is the default**.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            junit_family = \"xunit2\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            junit_family = xunit2\n\n\n.. confval:: junit_log_passing_tests\n\n    .. versionadded:: 4.6\n\n    If ``junit_logging != \"no\"``, configures if the captured output should be written\n    to the JUnit XML file for **passing** tests. Default is ``True``.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            junit_log_passing_tests = false\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            junit_log_passing_tests = False\n\n\n.. confval:: junit_logging\n\n    .. versionadded:: 3.5\n    .. versionchanged:: 5.4\n        ``log``, ``all``, ``out-err`` options added.\n\n    Configures if captured output should be written to the JUnit XML file. Valid values are:\n\n    * ``log``: write only ``logging`` captured output.\n    * ``system-out``: write captured ``stdout`` contents.\n    * ``system-err``: write captured ``stderr`` contents.\n    * ``out-err``: write both captured ``stdout`` and ``stderr`` contents.\n    * ``all``: write captured ``logging``, ``stdout`` and ``stderr`` contents.\n    * ``no`` (the default): no captured output is written.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            junit_logging = \"system-out\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            junit_logging = system-out\n\n\n.. confval:: junit_suite_name\n\n    To set the name of the root test suite xml item, you can configure the ``junit_suite_name`` option in your config file:\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            junit_suite_name = \"my_suite\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            junit_suite_name = my_suite\n\n.. confval:: log_auto_indent\n\n    Allow selective auto-indentation of multiline log messages.\n\n    Supports command line option :option:`--log-auto-indent=[value]`\n    and config option ``log_auto_indent = [value]`` to set the\n    auto-indentation behavior for all logging.\n\n    ``[value]`` can be:\n        * True or \"On\" - Dynamically auto-indent multiline log messages\n        * False or \"Off\" or 0 - Do not auto-indent multiline log messages (the default behavior)\n        * [positive integer] - auto-indent multiline log messages by [value] spaces\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_auto_indent = false\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_auto_indent = false\n\n    Supports passing kwarg ``extra={\"auto_indent\": [value]}`` to\n    calls to ``logging.log()`` to specify auto-indentation behavior for\n    a specific entry in the log. ``extra`` kwarg overrides the value specified\n    on the command line or in the config.\n\n.. confval:: log_cli\n\n    Enable log display during test run (also known as :ref:`\"live logging\" <live_logs>`).\n    The default is ``False``.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_cli = true\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_cli = true\n\n.. confval:: log_cli_date_format\n\n\n\n    Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for live logging.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_cli_date_format = \"%Y-%m-%d %H:%M:%S\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_cli_date_format = %Y-%m-%d %H:%M:%S\n\n    For more information, see :ref:`live_logs`.\n\n.. confval:: log_cli_format\n\n\n\n    Sets a :py:mod:`logging`-compatible string used to format live logging messages.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_cli_format = \"%(asctime)s %(levelname)s %(message)s\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_cli_format = %(asctime)s %(levelname)s %(message)s\n\n    For more information, see :ref:`live_logs`.\n\n\n.. confval:: log_cli_level\n\n\n\n    Sets the minimum log message level that should be captured for live logging. The integer value or\n    the names of the levels can be used. Note in TOML the integer must be quoted, as there is no support\n    for config parameters of mixed type.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_cli_level = \"INFO\"\n            log_cli_level = \"10\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_cli_level = INFO\n            log_cli_level = 10\n\n    For more information, see :ref:`live_logs`.\n\n\n.. confval:: log_date_format\n\n\n\n    Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for logging capture.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_date_format = \"%Y-%m-%d %H:%M:%S\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_date_format = %Y-%m-%d %H:%M:%S\n\n    For more information, see :ref:`logging`.\n\n\n.. confval:: log_file\n\n\n\n    Sets a file name relative to the current working directory where log messages should be written to, in addition\n    to the other logging facilities that are active.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_file = \"logs/pytest-logs.txt\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_file = logs/pytest-logs.txt\n\n    For more information, see :ref:`logging`.\n\n\n.. confval:: log_file_date_format\n\n\n\n    Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for the logging file.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_file_date_format = \"%Y-%m-%d %H:%M:%S\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_file_date_format = %Y-%m-%d %H:%M:%S\n\n    For more information, see :ref:`logging`.\n\n.. confval:: log_file_format\n\n\n\n    Sets a :py:mod:`logging`-compatible string used to format logging messages redirected to the logging file.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_file_format = \"%(asctime)s %(levelname)s %(message)s\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_file_format = %(asctime)s %(levelname)s %(message)s\n\n    For more information, see :ref:`logging`.\n\n.. confval:: log_file_level\n\n\n\n    Sets the minimum log message level that should be captured for the logging file. The integer value or\n    the names of the levels can be used. Note in TOML the integer must be quoted, as there is no support\n    for config parameters of mixed type.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_file_level = \"INFO\"\n            log_cli_level = \"10\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_file_level = INFO\n            log_cli_level = 10\n\n    For more information, see :ref:`logging`.\n\n\n.. confval:: log_file_mode\n\n    Sets the mode that the logging file is opened with.\n    The options are ``\"w\"`` to recreate the file (the default) or ``\"a\"`` to append to the file.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_file_mode = \"a\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_file_mode = a\n\n    For more information, see :ref:`logging`.\n\n\n.. confval:: log_format\n\n\n\n    Sets a :py:mod:`logging`-compatible string used to format captured logging messages.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_format = \"%(asctime)s %(levelname)s %(message)s\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_format = %(asctime)s %(levelname)s %(message)s\n\n    For more information, see :ref:`logging`.\n\n\n.. confval:: log_level\n\n\n\n    Sets the minimum log message level that should be captured for logging capture. The integer value or\n    the names of the levels can be used. Note in TOML the integer must be quoted, as there is no support\n    for config parameters of mixed type.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            log_level = \"INFO\"\n            log_cli_level = \"10\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            log_level = INFO\n            log_cli_level = 10\n\n    For more information, see :ref:`logging`.\n\n\n.. confval:: markers\n\n    When the :confval:`strict_markers` configuration option is set,\n    only known markers - defined in code by core pytest or some plugin - are allowed.\n\n    You can list additional markers in this setting to add them to the whitelist,\n    in which case you probably want to set :confval:`strict_markers` to ``true``\n    to avoid future regressions:\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            addopts = [\"--strict-markers\"]\n            markers = [\"slow\", \"serial\"]\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            strict_markers = true\n            markers =\n                slow\n                serial\n\n\n.. confval:: minversion\n\n   Specifies a minimal pytest version required for running tests.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            minversion = 3.0  # will fail if we run with pytest-2.8\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            minversion = 3.0  # will fail if we run with pytest-2.8\n\n\n.. confval:: norecursedirs\n\n   Set the directory basename patterns to avoid when recursing\n   for test discovery.  The individual (fnmatch-style) patterns are\n   applied to the basename of a directory to decide if to recurse into it.\n   Pattern matching characters::\n\n        *       matches everything\n        ?       matches any single character\n        [seq]   matches any character in seq\n        [!seq]  matches any char not in seq\n\n   Default patterns are ``'*.egg'``, ``'.*'``, ``'_darcs'``, ``'build'``,\n   ``'CVS'``, ``'dist'``, ``'node_modules'``, ``'venv'``, ``'{arch}'``.\n   Setting a ``norecursedirs`` replaces the default.  Here is an example of\n   how to avoid certain directories:\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            norecursedirs = [\".svn\", \"_build\", \"tmp*\"]\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            norecursedirs = .svn _build tmp*\n\n   This would tell ``pytest`` to not look into typical subversion or\n   sphinx-build directories or into any ``tmp`` prefixed directory.\n\n   Additionally, ``pytest`` will attempt to intelligently identify and ignore\n   a virtualenv.  Any directory deemed to be the root of a virtual environment\n   will not be considered during test collection unless\n   :option:`--collect-in-virtualenv` is given.  Note also that ``norecursedirs``\n   takes precedence over ``--collect-in-virtualenv``; e.g. if you intend to\n   run tests in a virtualenv with a base directory that matches ``'.*'`` you\n   *must* override ``norecursedirs`` in addition to using the\n   ``--collect-in-virtualenv`` flag.\n\n\n.. confval:: python_classes\n\n   One or more name prefixes or glob-style patterns determining which classes\n   are considered for test collection. Search for multiple glob patterns by\n   adding a space between patterns. By default, pytest will consider any\n   class prefixed with ``Test`` as a test collection.  Here is an example of how\n   to collect tests from classes that end in ``Suite``:\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            python_classes = [\"*Suite\"]\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            python_classes = *Suite\n\n   Note that ``unittest.TestCase`` derived classes are always collected\n   regardless of this option, as ``unittest``'s own collection framework is used\n   to collect those tests.\n\n\n.. confval:: python_files\n\n   One or more Glob-style file patterns determining which python files\n   are considered as test modules. Search for multiple glob patterns by\n   adding a space between patterns:\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            python_files = [\"test_*.py\", \"check_*.py\", \"example_*.py\"]\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            python_files = test_*.py check_*.py example_*.py\n\n       Or one per line:\n\n       .. code-block:: ini\n\n            [pytest]\n            python_files =\n                test_*.py\n                check_*.py\n                example_*.py\n\n   By default, files matching ``test_*.py`` and ``*_test.py`` will be considered\n   test modules.\n\n\n.. confval:: python_functions\n\n   One or more name prefixes or glob-patterns determining which test functions\n   and methods are considered tests. Search for multiple glob patterns by\n   adding a space between patterns. By default, pytest will consider any\n   function prefixed with ``test`` as a test.  Here is an example of how\n   to collect test functions and methods that end in ``_test``:\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            python_functions = [\"*_test\"]\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            python_functions = *_test\n\n   Note that this has no effect on methods that live on a ``unittest.TestCase``\n   derived class, as ``unittest``'s own collection framework is used\n   to collect those tests.\n\n   See :ref:`change naming conventions` for more detailed examples.\n\n\n.. confval:: pythonpath\n\n   Sets list of directories that should be added to the python search path.\n   Directories will be added to the head of :data:`sys.path`.\n   Similar to the :envvar:`PYTHONPATH` environment variable, the directories will be\n   included in where Python will look for imported modules.\n   Paths are relative to the :ref:`rootdir <rootdir>` directory.\n   Directories remain in path for the duration of the test session.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            pythonpath = [\"src1\", \"src2\"]\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            pythonpath = src1 src2\n\n\n.. confval:: required_plugins\n\n   A space separated list of plugins that must be present for pytest to run.\n   Plugins can be listed with or without version specifiers directly following\n   their name. Whitespace between different version specifiers is not allowed.\n   If any one of the plugins is not found, emit an error.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n           [pytest]\n           required_plugins = [\"pytest-django>=3.0.0,<4.0.0\", \"pytest-html\", \"pytest-xdist>=1.0.0\"]\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n           [pytest]\n           required_plugins = pytest-django>=3.0.0,<4.0.0 pytest-html pytest-xdist>=1.0.0\n\n\n.. confval:: strict\n\n    If set to ``true``, enable \"strict mode\", which enables the following options:\n\n    * :confval:`strict_config`\n    * :confval:`strict_markers`\n    * :confval:`strict_parametrization_ids`\n    * :confval:`strict_xfail`\n\n    Plugins may also enable their own strictness options.\n\n    If you explicitly set an individual strictness option, it takes precedence over ``strict``.\n\n    .. note::\n        If pytest adds new strictness options in the future, they will also be enabled in strict mode.\n        Therefore, you should only enable strict mode if you use a pinned/locked version of pytest,\n        or if you want to proactively adopt new strictness options as they are added.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            strict = true\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            strict = true\n\n    .. versionadded:: 9.0\n\n\n.. confval:: strict_config\n\n    If set to ``true``, any warnings encountered while parsing the ``pytest`` section of the configuration file will raise errors.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            strict_config = true\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            strict_config = true\n\n    You can also enable this option via the :confval:`strict` option.\n\n\n.. confval:: strict_markers\n\n    If set to ``true``, markers not registered in the ``markers`` section of the configuration file will raise errors.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            strict_markers = true\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            strict_markers = true\n\n    You can also enable this option via the :confval:`strict` option.\n\n\n.. confval:: strict_parametrization_ids\n\n    If set to ``true``, pytest emits an error if it detects non-unique parameter set IDs.\n\n    If not set (the default), pytest automatically handles this by adding `0`, `1`, ... to duplicate IDs,\n    making them unique.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            strict_parametrization_ids = true\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            strict_parametrization_ids = true\n\n    You can also enable this option via the :confval:`strict` option.\n\n    For example,\n\n    .. code-block:: python\n\n        import pytest\n\n\n        @pytest.mark.parametrize(\"letter\", [\"a\", \"a\"])\n        def test_letter_is_ascii(letter):\n            assert letter.isascii()\n\n    will emit an error because both cases (parameter sets) have the same auto-generated ID \"a\".\n\n    To fix the error, if you decide to keep the duplicates, explicitly assign unique IDs:\n\n    .. code-block:: python\n\n        import pytest\n\n\n        @pytest.mark.parametrize(\"letter\", [\"a\", \"a\"], ids=[\"a0\", \"a1\"])\n        def test_letter_is_ascii(letter):\n            assert letter.isascii()\n\n    See :func:`parametrize <pytest.Metafunc.parametrize>` and :func:`pytest.param` for other ways to set IDs.\n\n\n.. confval:: strict_xfail\n\n    If set to ``true``, tests marked with ``@pytest.mark.xfail`` that actually succeed will by default fail the\n    test suite.\n    For more information, see :ref:`xfail strict tutorial`.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            strict_xfail = true\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            strict_xfail = true\n\n    You can also enable this option via the :confval:`strict` option.\n\n    .. versionchanged:: 9.0\n        Renamed from ``xfail_strict`` to ``strict_xfail``.\n        ``xfail_strict`` is accepted as an alias for ``strict_xfail``.\n\n\n.. confval:: testpaths\n\n   Sets list of directories that should be searched for tests when\n   no specific directories, files or test ids are given in the command line when\n   executing pytest from the :ref:`rootdir <rootdir>` directory.\n   File system paths may use shell-style wildcards, including the recursive\n   ``**`` pattern.\n\n   Useful when all project tests are in a known location to speed up\n   test collection and to avoid picking up undesired tests by accident.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            testpaths = [\"testing\", \"doc\"]\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            testpaths = testing doc\n\n   This configuration means that executing:\n\n   .. code-block:: console\n\n       pytest\n\n   has the same practical effects as executing:\n\n   .. code-block:: console\n\n       pytest testing doc\n\n.. confval:: tmp_path_retention_count\n\n   How many sessions should we keep the `tmp_path` directories,\n   according to :confval:`tmp_path_retention_policy`.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            tmp_path_retention_count = \"3\"\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            tmp_path_retention_count = 3\n\n   Default: ``3``\n\n\n.. confval:: tmp_path_retention_policy\n\n\n\n   Controls which directories created by the `tmp_path` fixture are kept around,\n   based on test outcome.\n\n    * `all`: retains directories for all tests, regardless of the outcome.\n    * `failed`: retains directories only for tests with outcome `error` or `failed`.\n    * `none`: directories are always removed after each test ends, regardless of the outcome.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            tmp_path_retention_policy = \"all\"\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            tmp_path_retention_policy = all\n\n   Default: ``all``\n\n\n.. confval:: truncation_limit_chars\n\n   Controls maximum number of characters to truncate assertion message contents.\n\n   Setting value to ``0`` disables the character limit for truncation.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            truncation_limit_chars = 640\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            truncation_limit_chars = 640\n\n   pytest truncates the assert messages to a certain limit by default to prevent comparison with large data to overload the console output.\n\n   Default: ``640``\n\n   .. note::\n\n        If pytest detects it is :ref:`running on CI <ci-pipelines>`, truncation is disabled automatically.\n\n\n.. confval:: truncation_limit_lines\n\n   Controls maximum number of lines to truncate assertion message contents.\n\n   Setting value to ``0`` disables the lines limit for truncation.\n\n   .. tab:: toml\n\n       .. code-block:: toml\n\n            [pytest]\n            truncation_limit_lines = 8\n\n   .. tab:: ini\n\n       .. code-block:: ini\n\n            [pytest]\n            truncation_limit_lines = 8\n\n   pytest truncates the assert messages to a certain limit by default to prevent comparison with large data to overload the console output.\n\n   Default: ``8``\n\n   .. note::\n\n        If pytest detects it is :ref:`running on CI <ci-pipelines>`, truncation is disabled automatically.\n\n\n.. confval:: usefixtures\n\n    List of fixtures that will be applied to all test functions; this is semantically the same to apply\n    the ``@pytest.mark.usefixtures`` marker to all test functions.\n\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            usefixtures = [\"clean_db\"]\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            usefixtures =\n                clean_db\n\n\n.. confval:: verbosity_assertions\n\n    Set a verbosity level specifically for assertion related output, overriding the application wide level.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            verbosity_assertions = \"2\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            verbosity_assertions = 2\n\n    If not set, defaults to application wide verbosity level (via the :option:`-v` command-line option). A special value of\n    ``\"auto\"`` can be used to explicitly use the global verbosity level.\n\n\n.. confval:: verbosity_subtests\n\n    Set the verbosity level specifically for **passed** subtests.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            verbosity_subtests = \"1\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            verbosity_subtests = 1\n\n    A value of ``1`` or higher will show output for **passed** subtests (**failed** subtests are always reported).\n    Passed subtests output can be suppressed with the value ``0``, which overwrites the :option:`-v` command-line option.\n\n    If not set, defaults to application wide verbosity level (via the :option:`-v` command-line option). A special value of\n    ``\"auto\"`` can be used to explicitly use the global verbosity level.\n\n    See also: :ref:`subtests`.\n\n\n.. confval:: verbosity_test_cases\n\n    Set a verbosity level specifically for test case execution related output, overriding the application wide level.\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            verbosity_test_cases = \"2\"\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            verbosity_test_cases = 2\n\n    If not set, defaults to application wide verbosity level (via the :option:`-v` command-line option). A special value of\n    ``\"auto\"`` can be used to explicitly use the global verbosity level.\n\n\n.. _`command-line-flags`:\n\nCommand-line Flags\n------------------\n\nThis section documents all command-line options provided by pytest's core plugins.\n\n.. note::\n\n    External plugins can add their own command-line options.\n    This reference documents only the options from pytest's core plugins.\n    To see all available options including those from installed plugins, run ``pytest --help``.\n\nTest Selection\n~~~~~~~~~~~~~~\n\n.. option:: -k EXPRESSION\n\n    Only run tests which match the given substring expression.\n    An expression is a Python evaluable expression where all names are substring-matched against test names and their parent classes.\n\n    Examples::\n\n        pytest -k \"test_method or test_other\"  # matches names containing 'test_method' OR 'test_other'\n        pytest -k \"not test_method\"            # matches names NOT containing 'test_method'\n        pytest -k \"not test_method and not test_other\"  # excludes both\n\n    The matching is case-insensitive.\n    Keywords are also matched to classes and functions containing extra names in their ``extra_keyword_matches`` set.\n\n    See :ref:`select-tests` for more information and examples.\n\n.. option:: -m MARKEXPR\n\n    Only run tests matching given mark expression.\n    Supports ``and``, ``or``, and ``not`` operators.\n\n    Examples::\n\n        pytest -m slow                  # run tests marked with @pytest.mark.slow\n        pytest -m \"not slow\"            # run tests NOT marked slow\n        pytest -m \"mark1 and not mark2\" # run tests marked mark1 but not mark2\n\n    See :ref:`mark` for more information on markers.\n\n.. option:: --markers\n\n    Show all available markers (builtin, plugin, and per-project markers defined in configuration).\n\nTest Execution Control\n~~~~~~~~~~~~~~~~~~~~~~~\n\n.. option:: -x, --exitfirst\n\n    Exit instantly on first error or failed test.\n\n.. option:: --maxfail=NUM\n\n    Exit after first ``num`` failures or errors.\n    Useful for CI environments where you want to fail fast but see a few failures.\n\n.. option:: --last-failed, --lf\n\n    Rerun only the tests that failed at the last run.\n    If no tests failed (or no cached data exists), all tests are run.\n    See also :confval:`cache_dir` and :ref:`cache`.\n\n.. option:: --failed-first, --ff\n\n    Run all tests, but run the last failures first.\n    This may re-order tests and thus lead to repeated fixture setup/teardown.\n\n.. option:: --new-first, --nf\n\n    Run tests from new files first, then the rest of the tests sorted by file modification time.\n\n.. option:: --stepwise, --sw\n\n    Exit on test failure and continue from last failing test next time.\n    Useful for fixing multiple test failures one at a time.\n\n    See :ref:`cache stepwise` for more information.\n\n.. option:: --stepwise-skip, --sw-skip\n\n    Ignore the first failing test but stop on the next failing test.\n    Implicitly enables :option:`--stepwise`.\n\n.. option:: --stepwise-reset, --sw-reset\n\n    Resets stepwise state, restarting the stepwise workflow.\n    Implicitly enables :option:`--stepwise`.\n\n.. option:: --last-failed-no-failures, --lfnf\n\n    With :option:`--last-failed`, determines whether to execute tests when there are no previously known failures or when no cached ``lastfailed`` data was found.\n\n    * ``all`` (default): runs the full test suite again\n    * ``none``: just emits a message about no known failures and exits successfully\n\n.. option:: --runxfail\n\n    Report the results of xfail tests as if they were not marked.\n    Useful for debugging xfailed tests.\n    See :ref:`xfail`.\n\nCollection\n~~~~~~~~~~\n\n.. option:: --collect-only, --co\n\n    Only collect tests, don't execute them.\n    Shows which tests would be collected and run.\n\n.. option:: --pyargs\n\n    Try to interpret all arguments as Python packages.\n    Useful for running tests of installed packages::\n\n        pytest --pyargs pkg.testing\n\n.. option:: --ignore=PATH\n\n    Ignore path during collection (multi-allowed).\n    Can be specified multiple times.\n\n.. option:: --ignore-glob=PATTERN\n\n    Ignore path pattern during collection (multi-allowed).\n    Supports glob patterns.\n\n.. option:: --deselect=NODEID_PREFIX\n\n    Deselect item (via node id prefix) during collection (multi-allowed).\n\n.. option:: --confcutdir=DIR\n\n    Only load ``conftest.py`` files relative to specified directory.\n\n.. option:: --noconftest\n\n    Don't load any ``conftest.py`` files.\n\n.. option:: --keep-duplicates\n\n    Keep duplicate tests. By default, pytest removes duplicate test items.\n\n.. option:: --collect-in-virtualenv\n\n    Don't ignore tests in a local virtualenv directory.\n    By default, pytest skips tests in virtualenv directories.\n\n.. option:: --continue-on-collection-errors\n\n    Force test execution even if collection errors occur.\n\n.. option:: --import-mode\n\n    Prepend/append to sys.path when importing test modules and conftest files.\n\n    * ``prepend`` (default): prepend to sys.path\n    * ``append``: append to sys.path\n    * ``importlib``: use importlib to import test modules\n\n    See :ref:`pythonpath` for more information.\n\nFixtures\n~~~~~~~~\n\n.. option:: --fixtures, --funcargs\n\n    Show available fixtures, sorted by plugin appearance.\n    Fixtures with leading ``_`` are only shown with :option:`--verbose`.\n\n.. option:: --fixtures-per-test\n\n    Show fixtures per test.\n\n.. option:: --setup-only\n\n    Only setup fixtures, do not execute tests.\n    See :ref:`how-to-fixtures`.\n\n.. option:: --setup-show\n\n    Show setup of fixtures while executing tests.\n\n.. option:: --setup-plan\n\n    Show what fixtures and tests would be executed but don't execute anything.\n\nDebugging\n~~~~~~~~~\n\n.. option:: --pdb\n\n    Start the interactive Python debugger on errors or KeyboardInterrupt.\n    See :ref:`pdb-option`.\n\n.. option:: --pdbcls=MODULENAME:CLASSNAME\n\n    Specify a custom interactive Python debugger for use with :option:`--pdb`.\n\n    Example::\n\n        pytest --pdbcls=IPython.terminal.debugger:TerminalPdb\n\n.. option:: --trace\n\n    Immediately break when running each test.\n\n    See :ref:`trace-option` for more information.\n\n.. option:: --full-trace\n\n    Don't cut any tracebacks (default is to cut).\n\n    See :ref:`how-to-modifying-python-tb-printing` for more information.\n\n.. option:: --debug, --debug=DEBUG_FILE_NAME\n\n    Store internal tracing debug information in this log file.\n    This file is opened with ``'w'`` and truncated as a result, care advised.\n    Default file name if not specified: ``pytestdebug.log``.\n\n.. option:: --trace-config\n\n    Trace considerations of conftest.py files.\n\nOutput and Reporting\n~~~~~~~~~~~~~~~~~~~~\n\n.. option:: -v, --verbose\n\n    Increase verbosity.\n    Can be specified multiple times (e.g., ``-vv``) for even more verbose output.\n\n    See :ref:`pytest.fine_grained_verbosity` for fine-grained control over verbosity.\n\n.. option:: -q, --quiet\n\n    Decrease verbosity.\n\n.. option:: --verbosity=NUM\n\n    Set verbosity level explicitly. Default: 0.\n\n.. option:: -r CHARS, --report-chars=CHARS\n\n    Show extra test summary info as specified by chars:\n\n    * ``f``: failed\n    * ``E``: error\n    * ``s``: skipped\n    * ``x``: xfailed\n    * ``X``: xpassed\n    * ``p``: passed\n    * ``P``: passed with output\n    * ``a``: all except passed (p/P)\n    * ``A``: all\n    * ``w``: warnings (enabled by default)\n    * ``N``: resets the list\n\n    Default: ``'fE'``\n\n    Examples::\n\n        pytest -rA           # show all outcomes\n        pytest -rfE          # show only failed and errors (default)\n        pytest -rfs          # show failed and skipped\n\n    See :ref:`pytest.detailed_failed_tests_usage` for more information.\n\n.. option:: --no-header\n\n    Disable header.\n\n.. option:: --no-summary\n\n    Disable summary.\n\n.. option:: --no-fold-skipped\n\n    Do not fold skipped tests in short summary.\n\n.. option:: --force-short-summary\n\n    Force condensed summary output regardless of verbosity level.\n\n.. option:: -l, --showlocals\n\n    Show locals in tracebacks (disabled by default).\n\n.. option:: --no-showlocals\n\n    Hide locals in tracebacks (negate :option:`--showlocals` passed through addopts).\n\n.. option:: --tb=STYLE\n\n    Traceback print mode:\n\n    * ``auto``: intelligent traceback formatting (default)\n    * ``long``: exhaustive, informative traceback formatting\n    * ``short``: shorter traceback format\n    * ``line``: only the failing line\n    * ``native``: Python's standard traceback\n    * ``no``: no traceback\n\n    See :ref:`how-to-modifying-python-tb-printing` for examples.\n\n.. option:: --xfail-tb\n\n    Show tracebacks for xfail (as long as :option:`--tb` != ``no``).\n\n.. option:: --show-capture\n\n    Controls how captured stdout/stderr/log is shown on failed tests.\n\n    * ``no``: don't show captured output\n    * ``stdout``: show captured stdout\n    * ``stderr``: show captured stderr\n    * ``log``: show captured logging\n    * ``all`` (default): show all captured output\n\n.. option:: --color=WHEN\n\n    Color terminal output:\n\n    * ``yes``: always use color\n    * ``no``: never use color\n    * ``auto`` (default): use color if terminal supports it\n\n.. option:: --code-highlight={yes,no}\n\n    Whether code should be highlighted (only if :option:`--color` is also enabled).\n    Default: ``yes``.\n\n.. option:: --pastebin=MODE\n\n    Send failed|all info to bpaste.net pastebin service.\n\n.. option:: --durations=NUM\n\n    Show N slowest setup/test durations (N=0 for all).\n    See :ref:`durations`.\n\n.. option:: --durations-min=NUM\n\n    Minimal duration in seconds for inclusion in slowest list.\n    Default: 0.005 (or 0.0 if ``-vv`` is given).\n\nOutput Capture\n~~~~~~~~~~~~~~\n\n.. option:: --capture=METHOD\n\n    Per-test capturing method:\n\n    * ``fd``: capture at file descriptor level (default)\n    * ``sys``: capture at sys level\n    * ``no``: don't capture output\n    * ``tee-sys``: capture but also show output on terminal\n\n    See :ref:`captures`.\n\n.. option:: -s\n\n    Shortcut for :option:`--capture=no`.\n\nJUnit XML\n~~~~~~~~~\n\n.. option:: --junit-xml=PATH, --junitxml=PATH\n\n    Create junit-xml style report file at given path.\n\n.. option:: --junit-prefix=STR, --junitprefix=STR\n\n    Prepend prefix to classnames in junit-xml output.\n\nCache\n~~~~~\n\n.. option:: --cache-show[=PATTERN]\n\n    Show cache contents, don't perform collection or tests.\n    Default glob pattern: ``'*'``.\n\n.. option:: --cache-clear\n\n    Remove all cache contents at start of test run.\n    See :ref:`cache`.\n\nWarnings\n~~~~~~~~\n\n.. option:: --disable-pytest-warnings, --disable-warnings\n\n    Disable warnings summary.\n\n.. option:: -W WARNING, --pythonwarnings=WARNING\n\n    Set which warnings to report, see ``-W`` option of Python itself.\n    Can be specified multiple times.\n\nDoctest\n~~~~~~~\n\n.. option:: --doctest-modules\n\n    Run doctests in all .py modules.\n\n    See :ref:`doctest` for more information on using doctests with pytest.\n\n.. option:: --doctest-report\n\n    Choose another output format for diffs on doctest failure:\n\n    * ``none``\n    * ``cdiff``\n    * ``ndiff``\n    * ``udiff``\n    * ``only_first_failure``\n\n.. option:: --doctest-glob=PATTERN\n\n    Doctests file matching pattern.\n    Default: ``test*.txt``.\n\n.. option:: --doctest-ignore-import-errors\n\n    Ignore doctest collection errors.\n\n.. option:: --doctest-continue-on-failure\n\n    For a given doctest, continue to run after the first failure.\n\nConfiguration\n~~~~~~~~~~~~~\n\n.. option:: -c FILE, --config-file=FILE\n\n    Load configuration from ``FILE`` instead of trying to locate one of the implicit configuration files.\n\n.. option:: --rootdir=ROOTDIR\n\n    Define root directory for tests.\n    Can be relative path: ``'root_dir'``, ``'./root_dir'``, ``'root_dir/another_dir/'``; absolute path: ``'/home/user/root_dir'``; path with variables: ``'$HOME/root_dir'``.\n\n.. option:: --basetemp=DIR\n\n    Base temporary directory for this test run.\n    Warning: this directory is removed if it exists.\n\n    See :ref:`temporary directory location and retention` for more information.\n\n.. option:: -o OPTION=VALUE, --override-ini=OPTION=VALUE\n\n    Override configuration option with ``option=value`` style.\n    Can be specified multiple times.\n\n    Example::\n\n        pytest -o strict_xfail=true -o cache_dir=cache\n\n.. option:: --strict-config\n\n    Enables the :confval:`strict_config` option.\n\n.. option:: --strict-markers\n\n    Enables the :confval:`strict_markers` option.\n\n.. option:: --strict\n\n    Enables the :confval:`strict` option (which enables all strictness options).\n\n.. option:: --assert=MODE\n\n    Control assertion debugging tools:\n\n    * ``plain``: performs no assertion debugging\n    * ``rewrite`` (default): rewrites assert statements in test modules on import to provide assert expression information\n\nLogging\n~~~~~~~\n\nSee :ref:`logging` for a guide on using these flags.\n\n.. option:: --log-level=LEVEL\n\n    Level of messages to catch/display.\n    Not set by default, so it depends on the root/parent log handler's effective level, where it is ``WARNING`` by default.\n\n.. option:: --log-format=FORMAT\n\n    Log format used by the logging module.\n\n.. option:: --log-date-format=FORMAT\n\n    Log date format used by the logging module.\n\n.. option:: --log-cli-level=LEVEL\n\n    CLI logging level. See :ref:`live_logs`.\n\n.. option:: --log-cli-format=FORMAT\n\n    Log format used by the logging module for CLI output.\n\n.. option:: --log-cli-date-format=FORMAT\n\n    Log date format used by the logging module for CLI output.\n\n.. option:: --log-file=PATH\n\n    Path to a file logging will be written to.\n\n.. option:: --log-file-mode\n\n    Log file open mode:\n\n    * ``w`` (default): recreate the file\n    * ``a``: append to the file\n\n.. option:: --log-file-level=LEVEL\n\n    Log file logging level.\n\n.. option:: --log-file-format=FORMAT\n\n    Log format used by the logging module for the log file.\n\n.. option:: --log-file-date-format=FORMAT\n\n    Log date format used by the logging module for the log file.\n\n.. option:: --log-auto-indent=VALUE\n\n    Auto-indent multiline messages passed to the logging module.\n    Accepts ``true|on``, ``false|off`` or an integer.\n\n.. option:: --log-disable=LOGGER\n\n    Disable a logger by name. Can be passed multiple times.\n\nPlugin and Extension Management\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. option:: -p NAME\n\n    Early-load given plugin module name or entry point (multi-allowed).\n    To avoid loading of plugins, use the ``no:`` prefix, e.g. ``no:doctest``.\n    See also :option:`--disable-plugin-autoload`.\n\n.. option:: --disable-plugin-autoload\n\n    Disable plugin auto-loading through entry point packaging metadata.\n    Only plugins explicitly specified in :option:`-p` or env var :envvar:`PYTEST_PLUGINS` will be loaded.\n\nVersion and Help\n~~~~~~~~~~~~~~~~\n\n.. option:: -V, --version\n\n    Display pytest version and information about plugins. When given twice, also display information about plugins.\n\n.. option:: -h, --help\n\n    Show help message and configuration info.\n\nComplete Help Output\n~~~~~~~~~~~~~~~~~~~~\n\nAll the command-line flags can also be obtained by running ``pytest --help``::\n\n    $ pytest --help\n    usage: pytest [options] [file_or_dir] [file_or_dir] [...]\n\n    positional arguments:\n      file_or_dir\n\n    general:\n      -k EXPRESSION         Only run tests which match the given substring\n                            expression. An expression is a Python evaluable\n                            expression where all names are substring-matched\n                            against test names and their parent classes.\n                            Example: -k 'test_method or test_other' matches all\n                            test functions and classes whose name contains\n                            'test_method' or 'test_other', while -k 'not\n                            test_method' matches those that don't contain\n                            'test_method' in their names. -k 'not test_method\n                            and not test_other' will eliminate the matches.\n                            Additionally keywords are matched to classes and\n                            functions containing extra names in their\n                            'extra_keyword_matches' set, as well as functions\n                            which have names assigned directly to them. The\n                            matching is case-insensitive.\n      -m MARKEXPR           Only run tests matching given mark expression. For\n                            example: -m 'mark1 and not mark2'.\n      --markers             show markers (builtin, plugin and per-project ones).\n      -x, --exitfirst       Exit instantly on first error or failed test\n      --maxfail=num         Exit after first num failures or errors\n      --strict-config       Enables the strict_config option\n      --strict-markers      Enables the strict_markers option\n      --strict              Enables the strict option\n      --fixtures, --funcargs\n                            Show available fixtures, sorted by plugin appearance\n                            (fixtures with leading '_' are only shown with '-v')\n      --fixtures-per-test   Show fixtures per test\n      --pdb                 Start the interactive Python debugger on errors or\n                            KeyboardInterrupt\n      --pdbcls=modulename:classname\n                            Specify a custom interactive Python debugger for use\n                            with --pdb.For example:\n                            --pdbcls=IPython.terminal.debugger:TerminalPdb\n      --trace               Immediately break when running each test\n      --capture=method      Per-test capturing method: one of fd|sys|no|tee-sys\n      -s                    Shortcut for --capture=no\n      --runxfail            Report the results of xfail tests as if they were\n                            not marked\n      --lf, --last-failed   Rerun only the tests that failed at the last run (or\n                            all if none failed)\n      --ff, --failed-first  Run all tests, but run the last failures first. This\n                            may re-order tests and thus lead to repeated fixture\n                            setup/teardown.\n      --nf, --new-first     Run tests from new files first, then the rest of the\n                            tests sorted by file mtime\n      --cache-show=[CACHESHOW]\n                            Show cache contents, don't perform collection or\n                            tests. Optional argument: glob (default: '*').\n      --cache-clear         Remove all cache contents at start of test run\n      --lfnf, --last-failed-no-failures={all,none}\n                            With ``--lf``, determines whether to execute tests\n                            when there are no previously (known) failures or\n                            when no cached ``lastfailed`` data was found.\n                            ``all`` (the default) runs the full test suite\n                            again. ``none`` just emits a message about no known\n                            failures and exits successfully.\n      --sw, --stepwise      Exit on test failure and continue from last failing\n                            test next time\n      --sw-skip, --stepwise-skip\n                            Ignore the first failing test but stop on the next\n                            failing test. Implicitly enables --stepwise.\n      --sw-reset, --stepwise-reset\n                            Resets stepwise state, restarting the stepwise\n                            workflow. Implicitly enables --stepwise.\n\n    Reporting:\n      --durations=N         Show N slowest setup/test durations (N=0 for all)\n      --durations-min=N     Minimal duration in seconds for inclusion in slowest\n                            list. Default: 0.005 (or 0.0 if -vv is given).\n      -v, --verbose         Increase verbosity\n      --no-header           Disable header\n      --no-summary          Disable summary\n      --no-fold-skipped     Do not fold skipped tests in short summary.\n      --force-short-summary\n                            Force condensed summary output regardless of\n                            verbosity level.\n      -q, --quiet           Decrease verbosity\n      --verbosity=VERBOSE   Set verbosity. Default: 0.\n      -r chars              Show extra test summary info as specified by chars:\n                            (f)ailed, (E)rror, (s)kipped, (x)failed, (X)passed,\n                            (p)assed, (P)assed with output, (a)ll except passed\n                            (p/P), or (A)ll. (w)arnings are enabled by default\n                            (see --disable-warnings), 'N' can be used to reset\n                            the list. (default: 'fE').\n      --disable-warnings, --disable-pytest-warnings\n                            Disable warnings summary\n      -l, --showlocals      Show locals in tracebacks (disabled by default)\n      --no-showlocals       Hide locals in tracebacks (negate --showlocals\n                            passed through addopts)\n      --tb=style            Traceback print mode\n                            (auto/long/short/line/native/no)\n      --xfail-tb            Show tracebacks for xfail (as long as --tb != no)\n      --show-capture={no,stdout,stderr,log,all}\n                            Controls how captured stdout/stderr/log is shown on\n                            failed tests. Default: all.\n      --full-trace          Don't cut any tracebacks (default is to cut)\n      --color=color         Color terminal output (yes/no/auto)\n      --code-highlight={yes,no}\n                            Whether code should be highlighted (only if --color\n                            is also enabled). Default: yes.\n      --pastebin=mode       Send failed|all info to bpaste.net pastebin service\n      --junitxml, --junit-xml=path\n                            Create junit-xml style report file at given path\n      --junitprefix, --junit-prefix=str\n                            Prepend prefix to classnames in junit-xml output\n\n    pytest-warnings:\n      -W, --pythonwarnings PYTHONWARNINGS\n                            Set which warnings to report, see -W option of\n                            Python itself\n\n    collection:\n      --collect-only, --co  Only collect tests, don't execute them\n      --pyargs              Try to interpret all arguments as Python packages\n      --ignore=path         Ignore path during collection (multi-allowed)\n      --ignore-glob=path    Ignore path pattern during collection (multi-\n                            allowed)\n      --deselect=nodeid_prefix\n                            Deselect item (via node id prefix) during collection\n                            (multi-allowed)\n      --confcutdir=dir      Only load conftest.py's relative to specified dir\n      --noconftest          Don't load any conftest.py files\n      --keep-duplicates     Keep duplicate tests\n      --collect-in-virtualenv\n                            Don't ignore tests in a local virtualenv directory\n      --continue-on-collection-errors\n                            Force test execution even if collection errors occur\n      --import-mode={prepend,append,importlib}\n                            Prepend/append to sys.path when importing test\n                            modules and conftest files. Default: prepend.\n      --doctest-modules     Run doctests in all .py modules\n      --doctest-report={none,cdiff,ndiff,udiff,only_first_failure}\n                            Choose another output format for diffs on doctest\n                            failure\n      --doctest-glob=pat    Doctests file matching pattern, default: test*.txt\n      --doctest-ignore-import-errors\n                            Ignore doctest collection errors\n      --doctest-continue-on-failure\n                            For a given doctest, continue to run after the first\n                            failure\n\n    test session debugging and configuration:\n      -c, --config-file FILE\n                            Load configuration from `FILE` instead of trying to\n                            locate one of the implicit configuration files.\n      --rootdir=ROOTDIR     Define root directory for tests. Can be relative\n                            path: 'root_dir', './root_dir',\n                            'root_dir/another_dir/'; absolute path:\n                            '/home/user/root_dir'; path with variables:\n                            '$HOME/root_dir'.\n      --basetemp=dir        Base temporary directory for this test run.\n                            (Warning: this directory is removed if it exists.)\n      -V, --version         Display pytest version and information about\n                            plugins. When given twice, also display information\n                            about plugins.\n      -h, --help            Show help message and configuration info\n      -p name               Early-load given plugin module name or entry point\n                            (multi-allowed). To avoid loading of plugins, use\n                            the `no:` prefix, e.g. `no:doctest`. See also\n                            --disable-plugin-autoload.\n      --disable-plugin-autoload\n                            Disable plugin auto-loading through entry point\n                            packaging metadata. Only plugins explicitly\n                            specified in -p or env var PYTEST_PLUGINS will be\n                            loaded.\n      --trace-config        Trace considerations of conftest.py files\n      --debug=[DEBUG_FILE_NAME]\n                            Store internal tracing debug information in this log\n                            file. This file is opened with 'w' and truncated as\n                            a result, care advised. Default: pytestdebug.log.\n      -o, --override-ini OVERRIDE_INI\n                            Override configuration option with \"option=value\"\n                            style, e.g. `-o strict_xfail=True -o\n                            cache_dir=cache`.\n      --assert=MODE         Control assertion debugging tools.\n                            'plain' performs no assertion debugging.\n                            'rewrite' (the default) rewrites assert statements\n                            in test modules on import to provide assert\n                            expression information.\n      --setup-only          Only setup fixtures, do not execute tests\n      --setup-show          Show setup of fixtures while executing tests\n      --setup-plan          Show what fixtures and tests would be executed but\n                            don't execute anything\n\n    logging:\n      --log-level=LEVEL     Level of messages to catch/display. Not set by\n                            default, so it depends on the root/parent log\n                            handler's effective level, where it is \"WARNING\" by\n                            default.\n      --log-format=LOG_FORMAT\n                            Log format used by the logging module\n      --log-date-format=LOG_DATE_FORMAT\n                            Log date format used by the logging module\n      --log-cli-level=LOG_CLI_LEVEL\n                            CLI logging level\n      --log-cli-format=LOG_CLI_FORMAT\n                            Log format used by the logging module\n      --log-cli-date-format=LOG_CLI_DATE_FORMAT\n                            Log date format used by the logging module\n      --log-file=LOG_FILE   Path to a file when logging will be written to\n      --log-file-mode={w,a}\n                            Log file open mode\n      --log-file-level=LOG_FILE_LEVEL\n                            Log file logging level\n      --log-file-format=LOG_FILE_FORMAT\n                            Log format used by the logging module\n      --log-file-date-format=LOG_FILE_DATE_FORMAT\n                            Log date format used by the logging module\n      --log-auto-indent=LOG_AUTO_INDENT\n                            Auto-indent multiline messages passed to the logging\n                            module. Accepts true|on, false|off or an integer.\n      --log-disable=LOGGER_DISABLE\n                            Disable a logger by name. Can be passed multiple\n                            times.\n\n    [pytest] configuration options in the first pytest.toml|pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:\n\n      markers (linelist):   Register new markers for test functions\n      empty_parameter_set_mark (string):\n                            Default marker for empty parametersets\n      strict_config (bool): Any warnings encountered while parsing the `pytest`\n                            section of the configuration file raise errors\n      strict_markers (bool):\n                            Markers not registered in the `markers` section of\n                            the configuration file raise errors\n      strict (bool):        Enables all strictness options, currently:\n                            strict_config, strict_markers, strict_xfail,\n                            strict_parametrization_ids\n      filterwarnings (linelist):\n                            Each line specifies a pattern for\n                            warnings.filterwarnings. Processed after\n                            -W/--pythonwarnings.\n      norecursedirs (args): Directory patterns to avoid for recursion\n      testpaths (args):     Directories to search for tests when no files or\n                            directories are given on the command line\n      collect_imported_tests (bool):\n                            Whether to collect tests in imported modules outside\n                            `testpaths`\n      consider_namespace_packages (bool):\n                            Consider namespace packages when resolving module\n                            names during import\n      usefixtures (args):   List of default fixtures to be used with this\n                            project\n      python_files (args):  Glob-style file patterns for Python test module\n                            discovery\n      python_classes (args):\n                            Prefixes or glob names for Python test class\n                            discovery\n      python_functions (args):\n                            Prefixes or glob names for Python test function and\n                            method discovery\n      disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):\n                            Disable string escape non-ASCII characters, might\n                            cause unwanted side effects(use at your own risk)\n      strict_parametrization_ids (bool):\n                            Emit an error if non-unique parameter set IDs are\n                            detected\n      console_output_style (string):\n                            Console output: \"classic\", or with additional\n                            progress information (\"progress\" (percentage) |\n                            \"count\" | \"progress-even-when-capture-no\" (forces\n                            progress even when capture=no)\n      verbosity_test_cases (string):\n                            Specify a verbosity level for test case execution,\n                            overriding the main level. Higher levels will\n                            provide more detailed information about each test\n                            case executed.\n      strict_xfail (bool):  Default for the strict parameter of xfail markers\n                            when not given explicitly (default: False) (alias:\n                            xfail_strict)\n      tmp_path_retention_count (string):\n                            How many sessions should we keep the `tmp_path`\n                            directories, according to\n                            `tmp_path_retention_policy`.\n      tmp_path_retention_policy (string):\n                            Controls which directories created by the `tmp_path`\n                            fixture are kept around, based on test outcome.\n                            (all/failed/none)\n      enable_assertion_pass_hook (bool):\n                            Enables the pytest_assertion_pass hook. Make sure to\n                            delete any previously generated pyc cache files.\n      truncation_limit_lines (string):\n                            Set threshold of LINES after which truncation will\n                            take effect\n      truncation_limit_chars (string):\n                            Set threshold of CHARS after which truncation will\n                            take effect\n      verbosity_assertions (string):\n                            Specify a verbosity level for assertions, overriding\n                            the main level. Higher levels will provide more\n                            detailed explanation when an assertion fails.\n      junit_suite_name (string):\n                            Test suite name for JUnit report\n      junit_logging (string):\n                            Write captured log messages to JUnit report: one of\n                            no|log|system-out|system-err|out-err|all\n      junit_log_passing_tests (bool):\n                            Capture log information for passing tests to JUnit\n                            report:\n      junit_duration_report (string):\n                            Duration time to report: one of total|call\n      junit_family (string):\n                            Emit XML for schema: one of legacy|xunit1|xunit2\n      doctest_optionflags (args):\n                            Option flags for doctests\n      doctest_encoding (string):\n                            Encoding used for doctest files\n      cache_dir (string):   Cache directory path\n      log_level (string):   Default value for --log-level\n      log_format (string):  Default value for --log-format\n      log_date_format (string):\n                            Default value for --log-date-format\n      log_cli (bool):       Enable log display during test run (also known as\n                            \"live logging\")\n      log_cli_level (string):\n                            Default value for --log-cli-level\n      log_cli_format (string):\n                            Default value for --log-cli-format\n      log_cli_date_format (string):\n                            Default value for --log-cli-date-format\n      log_file (string):    Default value for --log-file\n      log_file_mode (string):\n                            Default value for --log-file-mode\n      log_file_level (string):\n                            Default value for --log-file-level\n      log_file_format (string):\n                            Default value for --log-file-format\n      log_file_date_format (string):\n                            Default value for --log-file-date-format\n      log_auto_indent (string):\n                            Default value for --log-auto-indent\n      faulthandler_timeout (string):\n                            Dump the traceback of all threads if a test takes\n                            more than TIMEOUT seconds to finish\n      faulthandler_exit_on_timeout (bool):\n                            Exit the test process if a test takes more than\n                            faulthandler_timeout seconds to finish\n      verbosity_subtests (string):\n                            Specify verbosity level for subtests. Higher levels\n                            will generate output for passed subtests. Failed\n                            subtests are always reported.\n      addopts (args):       Extra command line options\n      minversion (string):  Minimally required pytest version\n      pythonpath (paths):   Add paths to sys.path\n      required_plugins (args):\n                            Plugins that must be present for pytest to run\n\n    Environment variables:\n      CI                       When set to a non-empty value, pytest knows it is running in a CI process and does not truncate summary info\n      BUILD_NUMBER             Equivalent to CI\n      PYTEST_ADDOPTS           Extra command line options\n      PYTEST_PLUGINS           Comma-separated plugins to load during startup\n      PYTEST_DISABLE_PLUGIN_AUTOLOAD Set to disable plugin auto-loading\n      PYTEST_DEBUG             Set to enable debug tracing of pytest's internals\n      PYTEST_DEBUG_TEMPROOT    Override the system temporary directory\n      PYTEST_THEME             The Pygments style to use for code output\n      PYTEST_THEME_MODE        Set the PYTEST_THEME to be either 'dark' or 'light'\n\n\n    to see available markers type: pytest --markers\n    to see available fixtures type: pytest --fixtures\n    (shown according to specified file_or_dir or current dir if not specified; fixtures with leading '_' are only shown with the '-v' option\n"
  },
  {
    "path": "doc/en/requirements.txt",
    "content": "-c broken-dep-constraints.txt\npluggy>=1.5.0\npygments-pytest>=2.5.0\nsphinx-removed-in>=0.2.0\nsphinx>=9\nsphinxcontrib-trio>=1.2.0\nsphinxcontrib-svg2pdfconverter\nfuro\nsphinxcontrib-towncrier\nsphinx-issues\nsphinx-inline-tabs\n"
  },
  {
    "path": "doc/en/sponsor.rst",
    "content": "Sponsor\n=======\n\npytest is maintained by a team of volunteers from all around the world in their free time. While\nwe work on pytest because we love the project and use it daily in our jobs, monetary\ncompensation when possible is welcome to justify time away from friends, family and personal time.\n\nMoney is also used to fund local sprints, merchandising (stickers to distribute in conferences for example)\nand every few years a large sprint involving all members.\n\nOpenCollective\n--------------\n\n`Open Collective`_ is an online funding platform for open and transparent communities.\nIt provides tools to raise money and share your finances in full transparency.\n\nIt is the platform of choice for individuals and companies that want to make one-time or\nmonthly donations directly to the project.\n\nSee more details in the `pytest collective`_.\n\n\n.. _Tidelift: https://tidelift.com\n.. _Tidelift subscription: https://tidelift.com/subscription/pkg/pypi-pytest\n.. _Open Collective: https://opencollective.com\n.. _pytest collective: https://opencollective.com/pytest\n"
  },
  {
    "path": "doc/en/talks.rst",
    "content": "\nTalks and Tutorials\n==========================\n\nBooks\n---------------------------------------------\n\n- `pytest Quick Start Guide, by Bruno Oliveira (2018)\n  <https://www.packtpub.com/web-development/pytest-quick-start-guide>`_.\n\n- `Python Testing with pytest, by Brian Okken (2017)\n  <https://pragprog.com/book/bopytest/python-testing-with-pytest>`_.\n\n- `Python Testing with pytest, Second Edition, by Brian Okken (2022)\n  <https://pragprog.com/titles/bopytest2/python-testing-with-pytest-second-edition>`_.\n\nTalks and blog postings\n---------------------------------------------\n\n- Training: `pytest - simple, rapid and fun testing with Python <https://www.youtube.com/watch?v=ofPHJrAOaTE>`_, Freya Bruhin, PyConDE 2022\n\n- `pytest: Simple, rapid and fun testing with Python, <https://youtu.be/cSJ-X3TbQ1c?t=15752>`_ (@ 4:22:32), Freya Bruhin, WeAreDevelopers World Congress 2021\n\n- Webinar: `pytest: Test Driven Development für Python (German) <https://bruhin.software/ins-pytest/>`_, Freya Bruhin, via mylearning.ch, 2020\n\n- Webinar: `Simplify Your Tests with Fixtures <https://blog.jetbrains.com/pycharm/2020/08/webinar-recording-simplify-your-tests-with-fixtures-with-oliver-bestwalter/>`_, Oliver Bestwalter, via JetBrains, 2020\n\n- Training: `Introduction to pytest - simple, rapid and fun testing with Python <https://www.youtube.com/watch?v=CMuSn9cofbI>`_, Freya Bruhin, PyConDE 2019\n\n- Abridged metaprogramming classics - this episode: pytest, Oliver Bestwalter, PyConDE 2019 (`repository <https://github.com/obestwalter/abridged-meta-programming-classics>`__, `recording <https://www.youtube.com/watch?v=zHpeMTJsBRk&feature=youtu.be>`__)\n\n- Testing PySide/PyQt code easily using the pytest framework, Freya Bruhin, Qt World Summit 2019 (`slides <https://bruhin.software/talks/qtws19.pdf>`__, `recording <https://www.youtube.com/watch?v=zdsBS5BXGqQ>`__)\n\n- `pytest: recommendations, basic packages for testing in Python and Django, Andreu Vallbona, PyBCN June 2019 <https://www.slideshare.net/AndreuVallbonaPlazas/pybcn-pytest-recomendaciones-paquetes-bsicos-para-testing-en-python-y-django>`_.\n\n- pytest: recommendations, basic packages for testing in Python and Django, Andreu Vallbona, PyconES 2017 (`slides in english <http://talks.apsl.io/testing-pycones-2017/>`_, `video in spanish <https://www.youtube.com/watch?v=K20GeR-lXDk>`_)\n\n- `pytest advanced, Andrew Svetlov (Russian, PyCon Russia, 2016)\n  <https://www.youtube.com/watch?v=7KgihdKTWY4>`_.\n\n- `Pythonic testing, Igor Starikov (Russian, PyNsk, November 2016)\n  <https://www.youtube.com/watch?v=_92nfdd5nK8>`_.\n\n- `pytest - Rapid Simple Testing, Freya Bruhin, Swiss Python Summit 2016\n  <https://www.youtube.com/watch?v=rCBHkQ_LVIs>`_.\n\n- `Improve your testing with Pytest and Mock, Gabe Hollombe, PyCon SG 2015\n  <https://www.youtube.com/watch?v=RcN26hznmk4>`_.\n\n- `Introduction to pytest, Andreas Pelme, EuroPython 2014\n  <https://www.youtube.com/watch?v=LdVJj65ikRY>`_.\n\n- `Advanced Uses of py.test Fixtures, Floris Bruynooghe, EuroPython\n  2014 <https://www.youtube.com/watch?v=IBC_dxr-4ps>`_.\n\n- `Why i use py.test and maybe you should too, Andy Todd, Pycon AU 2013\n  <https://www.youtube.com/watch?v=P-AhpukDIik>`_\n\n- `3-part blog series about pytest from @pydanny alias Daniel Greenfeld (January\n  2014) <https://daniel.roygreenfeld.com/pytest-no-boilerplate-testing.html>`_\n\n- `pytest: helps you write better Django apps, Andreas Pelme, DjangoCon\n  Europe 2014 <https://www.youtube.com/watch?v=aaArYVh6XSM>`_.\n\n- `Testing Django Applications with pytest, Andreas Pelme, EuroPython\n  2013 <https://www.youtube.com/watch?v=aUf8Fkb7TaY>`_.\n\n- `Testes pythonics com py.test, Vinicius Belchior Assef Neto, Plone\n  Conf 2013, Brazil <https://www.youtube.com/watch?v=QUKoq2K7bis>`_.\n\n- `Introduction to py.test fixtures, FOSDEM 2013, Floris Bruynooghe\n  <https://www.youtube.com/watch?v=bJhRW4eZMco>`_.\n\n- `pytest feature and release highlights, Holger Krekel (GERMAN, October 2013)\n  <http://pyvideo.org/video/2429/pytest-feature-and-new-release-highlights>`_\n\n- `pytest introduction from Brian Okken (January 2013)\n  <http://pythontesting.net/framework/pytest-introduction/>`_\n\n- pycon australia 2012 pytest talk from Brianna Laugher (`video <https://www.youtube.com/watch?v=DTNejE9EraI>`_, `slides <https://www.slideshare.net/pfctdayelise/funcargs-other-fun-with-pytest>`_, `code <https://gist.github.com/3386951>`_)\n- `pycon 2012 US talk video from Holger Krekel <https://www.youtube.com/watch?v=9LVqBQcFmyw>`_\n\n- `monkey patching done right`_ (blog post, consult `monkeypatch plugin`_ for up-to-date API)\n\nTest parametrization:\n\n- `generating parametrized tests with fixtures`_.\n- `test generators and cached setup`_\n- `parametrizing tests, generalized`_ (blog post)\n- `putting test-hooks into local or global plugins`_ (blog post)\n\nAssertion introspection:\n\n- `(07/2011) Behind the scenes of pytest's new assertion rewriting\n  <http://pybites.blogspot.com/2011/07/behind-scenes-of-pytests-new-assertion.html>`_\n\nDistributed testing:\n\n- `simultaneously test your code on all platforms`_ (blog entry)\n\nPlugin specific examples:\n\n- `skipping slow tests by default in pytest`_ (blog entry)\n\n- `many examples in the docs for plugins`_\n\n.. _`skipping slow tests by default in pytest`: http://bruynooghe.blogspot.com/2009/12/skipping-slow-test-by-default-in-pytest.html\n.. _`many examples in the docs for plugins`: plugins.html\n.. _`monkeypatch plugin`: monkeypatch.html\n.. _`application setup in test functions with fixtures`: fixture.html#interdependent-fixtures\n.. _`simultaneously test your code on all platforms`: https://tetamap.wordpress.com//2009/03/23/new-simultanously-test-your-code-on-all-platforms/\n.. _`monkey patching done right`: https://tetamap.wordpress.com//2009/03/03/monkeypatching-in-unit-tests-done-right/\n.. _`putting test-hooks into local or global plugins`: https://tetamap.wordpress.com/2009/05/14/putting-test-hooks-into-local-and-global-plugins/\n.. _`parametrizing tests, generalized`: https://tetamap.wordpress.com/2009/05/13/parametrizing-python-tests-generalized/\n.. _`generating parametrized tests with fixtures`: parametrize.html#test-generators\n.. _`test generators and cached setup`: http://bruynooghe.blogspot.com/2010/06/pytest-test-generators-and-cached-setup.html\n"
  },
  {
    "path": "doc/en/tidelift.rst",
    "content": "pytest for enterprise\n=====================\n\n`Tidelift`_ is working with the maintainers of pytest and thousands of other\nopen source projects to deliver commercial support and maintenance for the open source dependencies you use\nto build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the\nexact dependencies you use.\n\n`Get more details <https://tidelift.com/subscription/pkg/pypi-pytest?utm_source=pypi-pytest&utm_medium=referral&utm_campaign=enterprise>`_\n\nThe Tidelift Subscription is a managed open source subscription for application dependencies covering millions of open source projects across JavaScript, Python, Java, PHP, Ruby, .NET, and more.\n\nYour subscription includes:\n\n* **Security updates**\n\n  - Tidelift's security response team coordinates patches for new breaking security vulnerabilities and alerts immediately through a private channel, so your software supply chain is always secure.\n\n* **Licensing verification and indemnification**\n\n  - Tidelift verifies license information to enable easy policy enforcement and adds intellectual property indemnification to cover creators and users in case something goes wrong. You always have a 100% up-to-date bill of materials for your dependencies to share with your legal team, customers, or partners.\n\n* **Maintenance and code improvement**\n\n  - Tidelift ensures the software you rely on keeps working as long as you need it to work. Your managed dependencies are actively maintained and we recruit additional maintainers where required.\n\n* **Package selection and version guidance**\n\n  - Tidelift helps you choose the best open source packages from the start—and then guide you through updates to stay on the best releases as new issues arise.\n\n* **Roadmap input**\n\n  - Take a seat at the table with the creators behind the software you use. Tidelift's participating maintainers earn more income as their software is used by more subscribers, so they're interested in knowing what you need.\n\n* **Tooling and cloud integration**\n\n  - Tidelift works with GitHub, GitLab, BitBucket, and every cloud platform (and other deployment targets, too).\n\nThe end result? All of the capabilities you expect from commercial-grade software, for the full breadth of open\nsource you use. That means less time grappling with esoteric open source trivia, and more time building your own\napplications—and your business.\n\n`Request a demo <https://tidelift.com/subscription/request-a-demo?utm_source=pypi-pytest&utm_medium=referral&utm_campaign=enterprise>`_\n\n.. _Tidelift: https://tidelift.com\n"
  },
  {
    "path": "doc/en/yieldfixture.rst",
    "content": ":orphan:\n\n.. _yieldfixture:\n\n\"yield_fixture\" functions\n---------------------------------------------------------------\n\n\n\n\n\n.. important::\n    Since pytest-3.0, fixtures using the normal ``fixture`` decorator can use a ``yield``\n    statement to provide fixture values and execute teardown code, exactly like ``yield_fixture``\n    in previous versions.\n\n    Marking functions as ``yield_fixture`` is still supported, but deprecated and should not\n    be used in new code.\n"
  },
  {
    "path": "extra/get_issues.py",
    "content": "from __future__ import annotations\n\nimport json\nfrom pathlib import Path\nimport sys\n\nimport requests\n\n\nissues_url = \"https://api.github.com/repos/pytest-dev/pytest/issues\"\n\n\ndef get_issues():\n    issues = []\n    url = issues_url\n    while 1:\n        get_data = {\"state\": \"all\"}\n        r = requests.get(url, params=get_data)\n        data = r.json()\n        if r.status_code == 403:\n            # API request limit exceeded\n            print(data[\"message\"])\n            sys.exit(1)\n        issues.extend(data)\n\n        # Look for next page\n        links = requests.utils.parse_header_links(r.headers[\"Link\"])\n        another_page = False\n        for link in links:\n            if link[\"rel\"] == \"next\":\n                url = link[\"url\"]\n                another_page = True\n        if not another_page:\n            return issues\n\n\ndef main(args):\n    cachefile = Path(args.cache)\n    if not cachefile.exists() or args.refresh:\n        issues = get_issues()\n        cachefile.write_text(json.dumps(issues), \"utf-8\")\n    else:\n        issues = json.loads(cachefile.read_text(\"utf-8\"))\n\n    open_issues = [x for x in issues if x[\"state\"] == \"open\"]\n\n    open_issues.sort(key=lambda x: x[\"number\"])\n    report(open_issues)\n\n\ndef _get_kind(issue):\n    labels = [label[\"name\"] for label in issue[\"labels\"]]\n    for key in (\"bug\", \"enhancement\", \"proposal\"):\n        if key in labels:\n            return key\n    return \"issue\"\n\n\ndef report(issues):\n    for issue in issues:\n        title = issue[\"title\"]\n        # body = issue[\"body\"]\n        kind = _get_kind(issue)\n        status = issue[\"state\"]\n        number = issue[\"number\"]\n        link = f\"https://github.com/pytest-dev/pytest/issues/{number}/\"\n        print(\"----\")\n        print(status, kind, link)\n        print(title)\n        # print()\n        # lines = body.split(\"\\n\")\n        # print(\"\\n\".join(lines[:3]))\n        # if len(lines) > 3 or len(body) > 240:\n        #    print(\"...\")\n    print(f\"\\n\\nFound {len(issues)} open issues\")\n\n\nif __name__ == \"__main__\":\n    import argparse\n\n    parser = argparse.ArgumentParser(\"process bitbucket issues\")\n    parser.add_argument(\n        \"--refresh\", action=\"store_true\", help=\"invalidate cache, refresh issues\"\n    )\n    parser.add_argument(\n        \"--cache\", action=\"store\", default=\"issues.json\", help=\"cache file\"\n    )\n    args = parser.parse_args()\n    main(args)\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nbuild-backend = \"setuptools.build_meta\"\nrequires = [\n    \"setuptools>=77\",\n    \"setuptools-scm[toml]>=6.2.3\",\n]\n\n[project]\nname = \"pytest\"\ndescription = \"pytest: simple powerful testing with Python\"\nreadme = \"README.rst\"\nkeywords = [\n    \"test\",\n    \"unittest\",\n]\nlicense = \"MIT\"\nlicense-files = [ \"LICENSE\" ]\nauthors = [\n    { name = \"Brianna Laugher\" },\n    { name = \"Bruno Oliveira\" },\n    { name = \"Floris Bruynooghe\" },\n    { name = \"Freya Bruhin\" },\n    { name = \"Holger Krekel\" },\n    { name = \"Others (See AUTHORS)\" },\n    { name = \"Ronny Pfannschmidt\" },\n]\nrequires-python = \">=3.10\"\nclassifiers = [\n    \"Development Status :: 6 - Mature\",\n    \"Intended Audience :: Developers\",\n    \"Operating System :: MacOS\",\n    \"Operating System :: Microsoft :: Windows\",\n    \"Operating System :: POSIX\",\n    \"Operating System :: Unix\",\n    \"Programming Language :: Python :: 3 :: Only\",\n    \"Programming Language :: Python :: 3.10\",\n    \"Programming Language :: Python :: 3.11\",\n    \"Programming Language :: Python :: 3.12\",\n    \"Programming Language :: Python :: 3.13\",\n    \"Programming Language :: Python :: 3.14\",\n    \"Topic :: Software Development :: Libraries\",\n    \"Topic :: Software Development :: Testing\",\n    \"Topic :: Utilities\",\n]\ndynamic = [\n    \"version\",\n]\ndependencies = [\n    \"colorama>=0.4; sys_platform=='win32'\",\n    \"exceptiongroup>=1; python_version<'3.11'\",\n    \"iniconfig>=1.0.1\",\n    \"packaging>=22\",\n    \"pluggy>=1.5,<2\",\n    \"pygments>=2.7.2\",\n    \"tomli>=1; python_version<'3.11'\",\n]\noptional-dependencies.dev = [\n    \"argcomplete\",\n    \"attrs>=19.2\",\n    \"hypothesis>=3.56\",\n    \"mock\",\n    \"requests\",\n    \"setuptools\",\n    \"xmlschema\",\n]\nurls.Changelog = \"https://docs.pytest.org/en/stable/changelog.html\"\nurls.Contact = \"https://docs.pytest.org/en/stable/contact.html\"\nurls.Funding = \"https://docs.pytest.org/en/stable/sponsor.html\"\nurls.Homepage = \"https://docs.pytest.org/en/latest/\"\nurls.Source = \"https://github.com/pytest-dev/pytest\"\nurls.Tracker = \"https://github.com/pytest-dev/pytest/issues\"\nscripts.\"py.test\" = \"pytest:console_main\"\nscripts.pytest = \"pytest:console_main\"\n\n[tool.setuptools.package-data]\n\"_pytest\" = [\n    \"py.typed\",\n]\n\"pytest\" = [\n    \"py.typed\",\n]\n\n[tool.setuptools_scm]\nwrite_to = \"src/_pytest/_version.py\"\n\n[tool.black]\n# See https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#t-target-version\ntarget-version = [ \"py310\", \"py311\", \"py312\", \"py313\" ]\n\n[tool.ruff]\ntarget-version = \"py310\"\nline-length = 88\nsrc = [\n    \"src\",\n]\nformat.docstring-code-format = true\nlint.select = [\n    \"B\",       # bugbear\n    \"D\",       # pydocstyle\n    \"E\",       # pycodestyle\n    \"F\",       # pyflakes\n    \"FA100\",   # add future annotations\n    \"I\",       # isort\n    \"PGH004\",  # pygrep-hooks - Use specific rule codes when using noqa\n    \"PIE\",     # flake8-pie\n    \"PLC\",     # pylint convention\n    \"PLE\",     # pylint error\n    \"PLR\",     # pylint refactor\n    \"PLR1714\", # Consider merging multiple comparisons\n    \"PLW\",     # pylint warning\n    \"PYI\",     # flake8-pyi\n    \"RUF\",     # ruff\n    \"T100\",    # flake8-debugger\n    \"UP\",      # pyupgrade\n    \"W\",       # pycodestyle\n]\nlint.ignore = [\n    # bugbear ignore\n    \"B004\", # Using `hasattr(x, \"__call__\")` to test if x is callable is unreliable.\n    \"B007\", # Loop control variable `i` not used within loop body\n    \"B009\", # Do not call `getattr` with a constant attribute value\n    \"B010\", # [*] Do not call `setattr` with a constant attribute value.\n    \"B011\", # Do not `assert False` (`python -O` removes these calls)\n    \"B028\", # No explicit `stacklevel` keyword argument found\n    # pydocstyle ignore\n    \"D100\", # Missing docstring in public module\n    \"D101\", # Missing docstring in public class\n    \"D102\", # Missing docstring in public method\n    \"D103\", # Missing docstring in public function\n    \"D104\", # Missing docstring in public package\n    \"D105\", # Missing docstring in magic method\n    \"D106\", # Missing docstring in public nested class\n    \"D107\", # Missing docstring in `__init__`\n    \"D205\", # 1 blank line required between summary line and description\n    \"D209\", # [*] Multi-line docstring closing quotes should be on a separate line\n    \"D400\", # First line should end with a period\n    \"D401\", # First line of docstring should be in imperative mood\n    \"D402\", # First line should not be the function's signature\n    \"D404\", # First word of the docstring should not be \"This\"\n    \"D415\", # First line should end with a period, question mark, or exclamation point\n    # pytest can do weird low-level things, and we usually know\n    # what we're doing when we use type(..) is ...\n    \"E721\", # Do not compare types, use `isinstance()`\n    # pylint ignore\n    \"PLC0105\", # `TypeVar` name \"E\" does not reflect its covariance;\n    \"PLC0414\", # Import alias does not rename original package\n    \"PLC0415\", # import should be at top level of package\n    \"PLR0124\", # Name compared with itself\n    \"PLR0133\", # Two constants compared in a comparison (lots of those in tests)\n    \"PLR0402\", # Use `from x.y import z` in lieu of alias\n    \"PLR0911\", # Too many return statements\n    \"PLR0912\", # Too many branches\n    \"PLR0913\", # Too many arguments in function definition\n    \"PLR0915\", # Too many statements\n    \"PLR2004\", # Magic value used in comparison\n    \"PLR2044\", # Line with empty comment\n    \"PLR5501\", # Use `elif` instead of `else` then `if`\n    \"PLW0120\", # remove the else and dedent its contents\n    \"PLW0603\", # Using the global statement\n    \"PLW1641\", # Does not implement the __hash__ method\n    \"PLW2901\", # for loop variable overwritten by assignment target\n    # ruff ignore\n    \"RUF012\", # Mutable class attributes should be annotated with `typing.ClassVar`\n]\nlint.per-file-ignores.\"src/_pytest/_py/**/*.py\" = [\n    \"B\",\n    \"PYI\",\n]\nlint.per-file-ignores.\"src/_pytest/_version.py\" = [\n    \"I001\",\n]\n# can't be disabled on a line-by-line basis in file\nlint.per-file-ignores.\"testing/code/test_source.py\" = [\n    \"F841\",\n]\nlint.per-file-ignores.\"testing/python/approx.py\" = [\n    \"B015\",\n]\nlint.extend-safe-fixes = [\n    \"UP006\",\n    \"UP007\",\n]\nlint.isort.combine-as-imports = true\nlint.isort.force-single-line = true\nlint.isort.force-sort-within-sections = true\nlint.isort.known-local-folder = [\n    \"pytest\",\n    \"_pytest\",\n]\nlint.isort.lines-after-imports = 2\nlint.isort.order-by-type = false\nlint.isort.required-imports = [\n    \"from __future__ import annotations\",\n]\n# In order to be able to format for 88 char in ruff format\nlint.pycodestyle.max-line-length = 120\nlint.pydocstyle.convention = \"pep257\"\nlint.pyupgrade.keep-runtime-typing = false\n\n[tool.pylint.main]\n# Maximum number of characters on a single line.\nmax-line-length = 120\ndisable = [\n    \"abstract-method\",\n    \"arguments-differ\",\n    \"arguments-renamed\",\n    \"assigning-non-slot\",\n    \"attribute-defined-outside-init\",\n    \"bad-builtin\",\n    \"bad-classmethod-argument\",\n    \"bad-dunder-name\",\n    \"bad-mcs-method-argument\",\n    \"broad-exception-caught\",\n    \"broad-exception-raised\",\n    \"cell-var-from-loop\",                     # B023 from ruff / flake8-bugbear\n    \"comparison-of-constants\",                # disabled in ruff (PLR0133)\n    \"comparison-with-callable\",\n    \"comparison-with-itself\",                 # PLR0124 from ruff\n    \"condition-evals-to-constant\",\n    \"consider-alternative-union-syntax\",\n    \"confusing-consecutive-elif\",\n    \"consider-using-assignment-expr\",\n    \"consider-using-dict-items\",\n    \"consider-using-from-import\",\n    \"consider-using-f-string\",\n    \"consider-using-in\",\n    \"consider-using-namedtuple-or-dataclass\",\n    \"consider-using-ternary\",\n    \"consider-using-tuple\",\n    \"consider-using-with\",\n    \"consider-using-from-import\",             # not activated by default, PLR0402 disabled in ruff\n    \"consider-ternary-expression\",\n    \"cyclic-import\",\n    \"differing-param-doc\",\n    \"docstring-first-line-empty\",\n    \"deprecated-argument\",\n    \"deprecated-attribute\",\n    \"deprecated-class\",\n    \"disallowed-name\",                        # foo / bar are used often in tests\n    \"duplicate-code\",\n    \"else-if-used\",                           # not activated by default, PLR5501 disabled in ruff\n    \"empty-comment\",                          # not activated by default, PLR2044 disabled in ruff\n    \"eval-used\",\n    \"eq-without-hash\",                        # PLW1641 disabled in ruff\n    \"exec-used\",\n    \"expression-not-assigned\",\n    \"fixme\",\n    \"global-statement\",                       # PLW0603 disabled in ruff\n    \"import-error\",\n    \"import-outside-toplevel\",                # PLC0415 disabled in ruff\n    \"import-private-name\",\n    \"inconsistent-return-statements\",\n    \"invalid-bool-returned\",\n    \"invalid-name\",\n    \"invalid-repr-returned\",\n    \"invalid-str-returned\",\n    \"keyword-arg-before-vararg\",\n    \"line-too-long\",\n    \"magic-value-comparison\",                 # not activated by default, PLR2004 disabled in ruff\n    \"method-hidden\",\n    \"missing-docstring\",\n    \"missing-param-doc\",\n    \"missing-raises-doc\",\n    \"missing-timeout\",\n    \"missing-type-doc\",\n    \"misplaced-bare-raise\",                   # PLE0704 from ruff\n    \"misplaced-comparison-constant\",\n    \"multiple-statements\",                    # multiple-statements-on-one-line-colon (E701) from ruff\n    \"no-else-break\",\n    \"no-else-continue\",\n    \"no-else-raise\",\n    \"no-else-return\",\n    \"no-member\",\n    \"no-name-in-module\",\n    \"no-self-argument\",\n    \"no-self-use\",\n    \"not-an-iterable\",\n    \"not-callable\",\n    \"pointless-exception-statement\",          # https://github.com/pytest-dev/pytest/pull/12379\n    \"pointless-statement\",                    # https://github.com/pytest-dev/pytest/pull/12379\n    \"pointless-string-statement\",             # https://github.com/pytest-dev/pytest/pull/12379\n    \"possibly-used-before-assignment\",\n    \"protected-access\",\n    \"raise-missing-from\",\n    \"redefined-argument-from-local\",\n    \"redefined-builtin\",\n    \"redefined-loop-name\",                    # PLW2901 disabled in ruff\n    \"redefined-outer-name\",\n    \"redefined-variable-type\",\n    \"reimported\",\n    \"simplifiable-condition\",\n    \"simplifiable-if-expression\",\n    \"singleton-comparison\",\n    \"superfluous-parens\",\n    \"super-init-not-called\",\n    \"too-complex\",\n    \"too-few-public-methods\",\n    \"too-many-ancestors\",\n    \"too-many-arguments\",                     # disabled in ruff\n    \"too-many-branches\",                      # disabled in ruff\n    \"too-many-function-args\",\n    \"too-many-instance-attributes\",\n    \"too-many-lines\",\n    \"too-many-locals\",\n    \"too-many-nested-blocks\",\n    \"too-many-positional-arguments\",\n    \"too-many-public-methods\",\n    \"too-many-return-statements\",             # disabled in ruff\n    \"too-many-statements\",                    # disabled in ruff\n    \"too-many-try-statements\",\n    \"try-except-raise\",\n    \"typevar-name-incorrect-variance\",        # PLC0105 disabled in ruff\n    \"unbalanced-tuple-unpacking\",\n    \"undefined-loop-variable\",\n    \"undefined-variable\",\n    \"unexpected-keyword-arg\",\n    \"unidiomatic-typecheck\",\n    \"unnecessary-comprehension\",\n    \"unnecessary-dunder-call\",\n    \"unnecessary-lambda\",\n    \"unnecessary-lambda-assignment\",\n    \"unpacking-non-sequence\",\n    \"unspecified-encoding\",\n    \"unsubscriptable-object\",\n    \"unused-argument\",\n    \"unused-import\",\n    \"unused-variable\",\n    \"used-before-assignment\",\n    \"use-dict-literal\",\n    \"use-implicit-booleaness-not-comparison\",\n    \"use-implicit-booleaness-not-len\",\n    \"use-set-for-membership\",\n    \"useless-else-on-loop\",                   # PLC0414 disabled in ruff\n    \"useless-import-alias\",\n    \"useless-return\",\n    \"using-constant-test\",\n    \"while-used\",\n    \"wrong-import-order\",                     # handled by isort / ruff\n    \"wrong-import-position\",                  # handled by isort / ruff\n]\n\n[tool.codespell]\nignore-words-list = \"afile,asend,asser,assertio,feld,hove,ned,noes,notin,paramete,parth,tesults,varius,wil\"\nskip = \"AUTHORS,*/plugin_list.rst\"\nwrite-changes = true\n\n[tool.check-wheel-contents]\n# check-wheel-contents is executed by the build-and-inspect-python-package action.\n# W009: Wheel contains multiple toplevel library entries\nignore = \"W009\"\n\n[tool.pyproject-fmt]\nindent = 4\nmax_supported_python = \"3.14\"\n\n[tool.pytest]\nminversion = \"2.0\"\naddopts = [ \"-rfEX\", \"-p\", \"pytester\" ]\npython_files = [\n    \"test_*.py\",\n    \"*_test.py\",\n    \"testing/python/*.py\",\n]\npython_classes = [\n    \"Test\",\n    \"Acceptance\",\n]\npython_functions = [\n    \"test\",\n]\n# NOTE: \"doc\" is not included here, but gets tested explicitly via \"doctesting\".\ntestpaths = [\n    \"testing\",\n]\nnorecursedirs = [\n    \"testing/example_scripts\",\n    \".*\",\n    \"build\",\n    \"dist\",\n]\nstrict = true\nfilterwarnings = [\n    'error',\n    'default:Using or importing the ABCs:DeprecationWarning:unittest2.*',\n    # produced by older pyparsing<=2.2.0.\n    'default:Using or importing the ABCs:DeprecationWarning:pyparsing.*',\n    'default:the imp module is deprecated in favour of importlib:DeprecationWarning:nose.*',\n    # distutils is deprecated in 3.10, scheduled for removal in 3.12\n    'ignore:The distutils package is deprecated:DeprecationWarning',\n    # produced by pytest-xdist\n    'ignore:.*type argument to addoption.*:DeprecationWarning',\n    # produced on execnet (pytest-xdist)\n    'ignore:.*inspect.getargspec.*deprecated, use inspect.signature.*:DeprecationWarning',\n    # pytest's own futurewarnings\n    'ignore::pytest.PytestExperimentalApiWarning',\n    # Do not cause SyntaxError for invalid escape sequences in py37.\n    # Those are caught/handled by pyupgrade, and not easy to filter with the\n    # module being the filename (with .py removed).\n    'default:invalid escape sequence:DeprecationWarning',\n    # ignore not yet fixed warnings for hook markers\n    'default:.*not marked using pytest.hook.*',\n    'ignore:.*not marked using pytest.hook.*::xdist.*',\n    # ignore use of unregistered marks, because we use many to test the implementation\n    'ignore::_pytest.warning_types.PytestUnknownMarkWarning',\n    # https://github.com/benjaminp/six/issues/341\n    'ignore:_SixMetaPathImporter\\.exec_module\\(\\) not found; falling back to load_module\\(\\):ImportWarning',\n    # https://github.com/benjaminp/six/pull/352\n    'ignore:_SixMetaPathImporter\\.find_spec\\(\\) not found; falling back to find_module\\(\\):ImportWarning',\n    # https://github.com/pypa/setuptools/pull/2517\n    'ignore:VendorImporter\\.find_spec\\(\\) not found; falling back to find_module\\(\\):ImportWarning',\n    # https://github.com/pytest-dev/execnet/pull/127\n    'ignore:isSet\\(\\) is deprecated, use is_set\\(\\) instead:DeprecationWarning',\n    # https://github.com/pytest-dev/pytest/issues/2366\n    # https://github.com/pytest-dev/pytest/pull/13057\n    'default::pytest.PytestFDWarning',\n]\npytester_example_dir = \"testing/example_scripts\"\nmarkers = [\n    # dummy markers for testing\n    \"foo\",\n    \"bar\",\n    \"baz\",\n    \"number_mark\",\n    \"builtin_matchers_mark\",\n    \"str_mark\",\n    # conftest.py reorders tests moving slow ones to the end of the list\n    \"slow\",\n    # experimental mark for all tests using pexpect\n    \"uses_pexpect\",\n    # Disables the `remove_ci_env_var` autouse fixture on a given test that\n    # actually inspects whether the CI environment variable is set.\n    \"keep_ci_var\",\n]\n\n[tool.coverage.paths]\nsource = [\n    'src/',\n    '*/lib/python*/site-packages/',\n    '*/pypy*/site-packages/',\n    '*\\Lib\\site-packages\\',\n]\n\n[tool.coverage.report]\nskip_covered = true\nshow_missing = true\nexclude_lines = [\n    '\\#\\s*pragma: no cover',\n    '^\\s*raise NotImplementedError\\b',\n    '^\\s*return NotImplemented\\b',\n    '^\\s*assert False(,|$)',\n    '^\\s*case unreachable:',\n    '^\\s*assert_never\\(',\n    '^\\s*if TYPE_CHECKING:',\n    '^\\s*@overload( |$)',\n    '^\\s*def .+: \\.\\.\\.$',\n    '^\\s*@pytest\\.mark\\.xfail',\n]\n\n[tool.coverage.run]\ninclude = [\n    'src/*',\n    'testing/*',\n    '*/lib/python*/site-packages/_pytest/*',\n    '*/lib/python*/site-packages/pytest.py',\n    '*/pypy*/site-packages/_pytest/*',\n    '*/pypy*/site-packages/pytest.py',\n    '*\\Lib\\site-packages\\_pytest\\*',\n    '*\\Lib\\site-packages\\pytest.py',\n]\nparallel = true\nbranch = true\npatch = [ \"subprocess\" ]\n# The sysmon core (default since Python 3.14) is much slower.\n# Perhaps: https://github.com/coveragepy/coveragepy/issues/2082\ncore = \"ctrace\"\n\n[tool.towncrier]\npackage = \"pytest\"\npackage_dir = \"src\"\nfilename = \"doc/en/changelog.rst\"\ndirectory = \"changelog/\"\ntitle_format = \"pytest {version} ({project_date})\"\ntemplate = \"changelog/_template.rst\"\n\n# NOTE: The types are declared because:\n# NOTE: - there is no mechanism to override just the value of\n# NOTE:   `tool.towncrier.type.misc.showcontent`;\n# NOTE: - and, we want to declare extra non-default types for\n# NOTE:   clarity and flexibility.\n\n[[tool.towncrier.type]]\n# When something public gets removed in a breaking way. Could be\n# deprecated in an earlier release.\ndirectory = \"breaking\"\nname = \"Removals and backward incompatible breaking changes\"\nshowcontent = true\n\n[[tool.towncrier.type]]\n# Declarations of future API removals and breaking changes in behavior.\ndirectory = \"deprecation\"\nname = \"Deprecations (removal in next major release)\"\nshowcontent = true\n\n[[tool.towncrier.type]]\n# New behaviors, public APIs. That sort of stuff.\ndirectory = \"feature\"\nname = \"New features\"\nshowcontent = true\n\n[[tool.towncrier.type]]\n# New behaviors in existing features.\ndirectory = \"improvement\"\nname = \"Improvements in existing functionality\"\nshowcontent = true\n\n[[tool.towncrier.type]]\n# Something we deemed an improper undesired behavior that got corrected\n# in the release to match pre-agreed expectations.\ndirectory = \"bugfix\"\nname = \"Bug fixes\"\nshowcontent = true\n\n[[tool.towncrier.type]]\n# Updates regarding bundling dependencies.\ndirectory = \"vendor\"\nname = \"Vendored libraries\"\nshowcontent = true\n\n[[tool.towncrier.type]]\n# Notable updates to the documentation structure or build process.\ndirectory = \"doc\"\nname = \"Improved documentation\"\nshowcontent = true\n\n[[tool.towncrier.type]]\n# Notes for downstreams about unobvious side effects and tooling. Changes\n# in the test invocation considerations and runtime assumptions.\ndirectory = \"packaging\"\nname = \"Packaging updates and notes for downstreams\"\nshowcontent = true\n\n[[tool.towncrier.type]]\n# Stuff that affects the contributor experience. e.g. Running tests,\n# building the docs, setting up the development environment.\ndirectory = \"contrib\"\nname = \"Contributor-facing changes\"\nshowcontent = true\n\n[[tool.towncrier.type]]\n# Changes that are hard to assign to any of the above categories.\ndirectory = \"misc\"\nname = \"Miscellaneous internal changes\"\nshowcontent = true\n\n[tool.mypy]\nfiles = [\n    \"src\",\n    \"testing\",\n    \"scripts\",\n]\nmypy_path = [\n    \"src\",\n]\npython_version = \"3.10\"\ncheck_untyped_defs = true\ndisallow_any_generics = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nshow_error_codes = true\nstrict_equality = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unreachable = true\nwarn_unused_configs = true\nno_implicit_reexport = true\nwarn_unused_ignores = true\nenable_error_code = [ \"deprecated\" ]\n\n[tool.pyright]\ninclude = [\n    \"src\",\n    \"testing\",\n    \"scripts\",\n]\nextraPaths = [\n    \"src\",\n]\npythonVersion = \"3.10\"\ntypeCheckingMode = \"basic\"\nreportMissingImports = \"none\"\nreportMissingModuleSource = \"none\"\n"
  },
  {
    "path": "scripts/.gitignore",
    "content": "latest-release-notes.md\n"
  },
  {
    "path": "scripts/generate-gh-release-notes.py",
    "content": "# mypy: disallow-untyped-defs\n\"\"\"\nScript used to generate a Markdown file containing only the changelog entries of a specific pytest release, which\nis then published as a GitHub Release during deploy (see workflows/deploy.yml).\n\nThe script requires ``pandoc`` to be previously installed in the system -- we need to convert from RST (the format of\nour CHANGELOG) into Markdown (which is required by GitHub Releases).\n\nRequires Python3.6+.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom pathlib import Path\nimport re\nimport sys\n\nimport pypandoc\n\n\ndef extract_changelog_entries_for(version: str) -> str:\n    p = Path(__file__).parent.parent / \"doc/en/changelog.rst\"\n    changelog_lines = p.read_text(encoding=\"UTF-8\").splitlines()\n\n    title_regex = re.compile(r\"pytest (\\d\\.\\d+\\.\\d+\\w*) \\(\\d{4}-\\d{2}-\\d{2}\\)\")\n    consuming_version = False\n    version_lines = []\n    for line in changelog_lines:\n        m = title_regex.match(line)\n        if m:\n            # Found the version we want: start to consume lines until we find the next version title.\n            if m.group(1) == version:\n                consuming_version = True\n            # Found a new version title while parsing the version we want: break out.\n            elif consuming_version:\n                break\n        if consuming_version:\n            version_lines.append(line)\n\n    return \"\\n\".join(version_lines)\n\n\ndef convert_rst_to_md(text: str) -> str:\n    result = pypandoc.convert_text(\n        text, \"gfm\", format=\"rst\", extra_args=[\"--wrap=preserve\"]\n    )\n    assert isinstance(result, str), repr(result)\n    return result\n\n\ndef main(argv: Sequence[str]) -> int:\n    if len(argv) != 3:\n        print(\"Usage: generate-gh-release-notes VERSION FILE\")\n        return 2\n\n    version, filename = argv[1:3]\n    print(f\"Generating GitHub release notes for version {version}\")\n    rst_body = extract_changelog_entries_for(version)\n    md_body = convert_rst_to_md(rst_body)\n    Path(filename).write_text(md_body, encoding=\"UTF-8\")\n    print()\n    print(f\"Done: {filename}\")\n    print()\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main(sys.argv))\n"
  },
  {
    "path": "scripts/prepare-release-pr.py",
    "content": "# mypy: disallow-untyped-defs\n\"\"\"\nThis script is part of the pytest release process which is triggered manually in the Actions\ntab of the repository.\n\nThe user will need to enter the base branch to start the release from (for example\n``6.1.x`` or ``main``) and if it should be a major release.\n\nThe appropriate version will be obtained based on the given branch automatically.\n\nAfter that, it will create a release using the `release` tox environment, and push a new PR.\n\nNote: the script uses the `gh` command-line tool, so `GH_TOKEN` must be set in the environment.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nfrom pathlib import Path\nimport re\nfrom subprocess import check_call\nfrom subprocess import check_output\nfrom subprocess import run\n\nfrom colorama import Fore\nfrom colorama import init\n\n\nclass InvalidFeatureRelease(Exception):\n    pass\n\n\nSLUG = \"pytest-dev/pytest\"\n\nPR_BODY = \"\"\"\\\nCreated by the [prepare release pr]\\\n(https://github.com/pytest-dev/pytest/actions/workflows/prepare-release-pr.yml) workflow.\n\nOnce all builds pass and it has been **approved** by one or more maintainers, start the \\\n[deploy](https://github.com/pytest-dev/pytest/actions/workflows/deploy.yml) workflow, using these parameters:\n\n* `Use workflow from`: `release-{version}`.\n* `Release version`: `{version}`.\n\nOr execute on the command line:\n\n```console\ngh workflow run deploy.yml -r release-{version} -f version={version}\n```\n\nAfter the workflow has been approved by a core maintainer, the package will be uploaded to PyPI automatically.\n\"\"\"\n\n\ndef prepare_release_pr(base_branch: str, is_major: bool, prerelease: str) -> None:\n    print()\n    print(f\"Processing release for branch {Fore.CYAN}{base_branch}\")\n\n    check_call([\"git\", \"checkout\", f\"origin/{base_branch}\"])\n\n    changelog = Path(\"changelog\")\n\n    features = list(changelog.glob(\"*.feature.rst\"))\n    breaking = list(changelog.glob(\"*.breaking.rst\"))\n    is_feature_release = bool(features or breaking)\n\n    try:\n        version = find_next_version(\n            base_branch, is_major, is_feature_release, prerelease\n        )\n    except InvalidFeatureRelease as e:\n        print(f\"{Fore.RED}{e}\")\n        raise SystemExit(1) from None\n\n    print(f\"Version: {Fore.CYAN}{version}\")\n\n    release_branch = f\"release-{version}\"\n\n    run(\n        [\"git\", \"config\", \"user.name\", \"pytest bot\"],\n        check=True,\n    )\n    run(\n        [\"git\", \"config\", \"user.email\", \"pytestbot@gmail.com\"],\n        check=True,\n    )\n\n    run(\n        [\"git\", \"checkout\", \"-b\", release_branch, f\"origin/{base_branch}\"],\n        check=True,\n    )\n\n    print(f\"Branch {Fore.CYAN}{release_branch}{Fore.RESET} created.\")\n\n    if is_major:\n        template_name = \"release.major.rst\"\n    elif prerelease:\n        template_name = \"release.pre.rst\"\n    elif is_feature_release:\n        template_name = \"release.minor.rst\"\n    else:\n        template_name = \"release.patch.rst\"\n\n    # important to use tox here because we have changed branches, so dependencies\n    # might have changed as well\n    cmdline = [\n        \"tox\",\n        \"-e\",\n        \"release\",\n        \"--\",\n        version,\n        template_name,\n        release_branch,  # doc_version\n        \"--skip-check-links\",\n    ]\n    print(\"Running\", \" \".join(cmdline))\n    run(\n        cmdline,\n        check=True,\n    )\n\n    run(\n        [\"git\", \"push\", \"origin\", f\"HEAD:{release_branch}\", \"--force\"],\n        check=True,\n    )\n    print(f\"Branch {Fore.CYAN}{release_branch}{Fore.RESET} pushed.\")\n\n    body = PR_BODY.format(version=version)\n    run(\n        [\n            \"gh\",\n            \"pr\",\n            \"create\",\n            f\"--base={base_branch}\",\n            f\"--head={release_branch}\",\n            f\"--title=Release {version}\",\n            f\"--body={body}\",\n            \"--draft\",\n        ],\n        check=True,\n    )\n\n\ndef find_next_version(\n    base_branch: str, is_major: bool, is_feature_release: bool, prerelease: str\n) -> str:\n    output = check_output([\"git\", \"tag\"], encoding=\"UTF-8\")\n    valid_versions = []\n    for v in output.splitlines():\n        m = re.match(r\"\\d.\\d.\\d+$\", v.strip())\n        if m:\n            valid_versions.append(tuple(int(x) for x in v.split(\".\")))\n\n    valid_versions.sort()\n    last_version = valid_versions[-1]\n\n    if is_major:\n        return f\"{last_version[0] + 1}.0.0{prerelease}\"\n    elif is_feature_release:\n        return f\"{last_version[0]}.{last_version[1] + 1}.0{prerelease}\"\n    else:\n        return f\"{last_version[0]}.{last_version[1]}.{last_version[2] + 1}{prerelease}\"\n\n\ndef main() -> None:\n    init(autoreset=True)\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"base_branch\")\n    parser.add_argument(\"--major\", action=\"store_true\", default=False)\n    parser.add_argument(\"--prerelease\", default=\"\")\n    options = parser.parse_args()\n    prepare_release_pr(\n        base_branch=options.base_branch,\n        is_major=options.major,\n        prerelease=options.prerelease,\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "scripts/release.major.rst",
    "content": "pytest-{version}\n=======================================\n\nThe pytest team is proud to announce the {version} release!\n\nThis release contains new features, improvements, bug fixes, and breaking changes, so users\nare encouraged to take a look at the CHANGELOG carefully:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n{contributors}\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "scripts/release.minor.rst",
    "content": "pytest-{version}\n=======================================\n\nThe pytest team is proud to announce the {version} release!\n\nThis release contains new features, improvements, and bug fixes,\nthe full list of changes is available in the changelog:\n\n    https://docs.pytest.org/en/stable/changelog.html\n\nFor complete documentation, please visit:\n\n    https://docs.pytest.org/en/stable/\n\nAs usual, you can upgrade from PyPI via:\n\n    pip install -U pytest\n\nThanks to all of the contributors to this release:\n\n{contributors}\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "scripts/release.patch.rst",
    "content": "pytest-{version}\n=======================================\n\npytest {version} has just been released to PyPI.\n\nThis is a bug-fix release, being a drop-in replacement.\n\nThe full changelog is available at https://docs.pytest.org/en/stable/changelog.html.\n\nThanks to all of the contributors to this release:\n\n{contributors}\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "scripts/release.pre.rst",
    "content": "pytest-{version}\n=======================================\n\nThe pytest team is proud to announce the {version} prerelease!\n\nThis is a prerelease, not intended for production use, but to test the upcoming features and improvements\nin order to catch any major problems before the final version is released to the major public.\n\nWe appreciate your help testing this out before the final release, making sure to report any\nregressions to our issue tracker:\n\nhttps://github.com/pytest-dev/pytest/issues\n\nWhen doing so, please include the string ``[prerelease]`` in the title.\n\nYou can upgrade from PyPI via:\n\n    pip install pytest=={version}\n\nUsers are encouraged to take a look at the CHANGELOG carefully:\n\n    https://docs.pytest.org/en/{doc_version}/changelog.html\n\nThanks to all the contributors to this release:\n\n{contributors}\n\nHappy testing,\nThe pytest Development Team\n"
  },
  {
    "path": "scripts/release.py",
    "content": "# mypy: disallow-untyped-defs\n\"\"\"Invoke development tasks.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport os\nfrom pathlib import Path\nimport re\nfrom subprocess import call\nfrom subprocess import check_call\nfrom subprocess import check_output\n\nfrom colorama import Fore\nfrom colorama import init\n\n\ndef announce(version: str, template_name: str, doc_version: str) -> None:\n    \"\"\"Generates a new release announcement entry in the docs.\"\"\"\n    # Get our list of authors and co-authors.\n    stdout = check_output([\"git\", \"describe\", \"--abbrev=0\", \"--tags\"], encoding=\"UTF-8\")\n    last_version = stdout.strip()\n    rev_range = f\"{last_version}..HEAD\"\n\n    authors = check_output(\n        [\"git\", \"log\", rev_range, \"--format=%aN\"], encoding=\"UTF-8\"\n    ).splitlines()\n\n    co_authors_output = check_output(\n        [\"git\", \"log\", rev_range, \"--format=%(trailers:key=Co-authored-by) \"],\n        encoding=\"UTF-8\",\n    )\n    co_authors: list[str] = []\n    for co_author_line in co_authors_output.splitlines():\n        if m := re.search(r\"Co-authored-by: (.+?)<\", co_author_line):\n            co_authors.append(m.group(1).strip())\n\n    contributors = {\n        name\n        for name in authors + co_authors\n        if not name.endswith(\"[bot]\") and name != \"pytest bot\"\n    }\n\n    template_text = (\n        Path(__file__).parent.joinpath(template_name).read_text(encoding=\"UTF-8\")\n    )\n\n    contributors_text = \"\\n\".join(f\"* {name}\" for name in sorted(contributors)) + \"\\n\"\n    text = template_text.format(\n        version=version, contributors=contributors_text, doc_version=doc_version\n    )\n\n    target = Path(__file__).parent.joinpath(f\"../doc/en/announce/release-{version}.rst\")\n    target.write_text(text, encoding=\"UTF-8\")\n    print(f\"{Fore.CYAN}[generate.announce] {Fore.RESET}Generated {target.name}\")\n\n    # Update index with the new release entry\n    index_path = Path(__file__).parent.joinpath(\"../doc/en/announce/index.rst\")\n    lines = index_path.read_text(encoding=\"UTF-8\").splitlines()\n    indent = \"   \"\n    for index, line in enumerate(lines):\n        if line.startswith(f\"{indent}release-\"):\n            new_line = indent + target.stem\n            if line != new_line:\n                lines.insert(index, new_line)\n                index_path.write_text(\"\\n\".join(lines) + \"\\n\", encoding=\"UTF-8\")\n                print(\n                    f\"{Fore.CYAN}[generate.announce] {Fore.RESET}Updated {index_path.name}\"\n                )\n            else:\n                print(\n                    f\"{Fore.CYAN}[generate.announce] {Fore.RESET}Skip {index_path.name} (already contains release)\"\n                )\n            break\n\n    check_call([\"git\", \"add\", str(target)])\n\n\ndef regen(version: str) -> None:\n    \"\"\"Call regendoc tool to update examples and pytest output in the docs.\"\"\"\n    print(f\"{Fore.CYAN}[generate.regen] {Fore.RESET}Updating docs\")\n    check_call(\n        [\"tox\", \"-e\", \"regen\"],\n        env={**os.environ, \"SETUPTOOLS_SCM_PRETEND_VERSION_FOR_PYTEST\": version},\n    )\n\n\ndef fix_formatting() -> None:\n    \"\"\"Runs pre-commit in all files to ensure they are formatted correctly\"\"\"\n    print(\n        f\"{Fore.CYAN}[generate.fix linting] {Fore.RESET}Fixing formatting using pre-commit\"\n    )\n    call([\"pre-commit\", \"run\", \"--all-files\"])\n\n\ndef check_links() -> None:\n    \"\"\"Runs sphinx-build to check links\"\"\"\n    print(f\"{Fore.CYAN}[generate.check_links] {Fore.RESET}Checking links\")\n    check_call([\"tox\", \"-e\", \"docs-checklinks\"])\n\n\ndef pre_release(\n    version: str, template_name: str, doc_version: str, *, skip_check_links: bool\n) -> None:\n    \"\"\"Generates new docs, release announcements and creates a local tag.\"\"\"\n    announce(version, template_name, doc_version)\n    regen(version)\n    changelog(version, write_out=True)\n    fix_formatting()\n    if not skip_check_links:\n        check_links()\n\n    msg = f\"Prepare release version {version}\"\n    check_call([\"git\", \"commit\", \"-a\", \"-m\", msg])\n\n    print()\n    print(f\"{Fore.CYAN}[generate.pre_release] {Fore.GREEN}All done!\")\n    print()\n    print(\"Please push your branch and open a PR.\")\n\n\ndef changelog(version: str, write_out: bool = False) -> None:\n    addopts = [] if write_out else [\"--draft\"]\n    check_call([\"towncrier\", \"build\", \"--yes\", \"--version\", version, *addopts])\n\n\ndef main() -> None:\n    init(autoreset=True)\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"version\", help=\"Release version\")\n    parser.add_argument(\n        \"template_name\", help=\"Name of template file to use for release announcement\"\n    )\n    parser.add_argument(\n        \"doc_version\", help=\"For prereleases, the version to link to in the docs\"\n    )\n    parser.add_argument(\"--skip-check-links\", action=\"store_true\", default=False)\n    options = parser.parse_args()\n    pre_release(\n        options.version,\n        options.template_name,\n        options.doc_version,\n        skip_check_links=options.skip_check_links,\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "scripts/update-plugin-list.py",
    "content": "# mypy: disallow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nimport datetime\nimport pathlib\nimport re\nfrom textwrap import dedent\nfrom textwrap import indent\nfrom typing import Any\nfrom typing import TypedDict\n\nimport packaging.version\nimport platformdirs\nfrom requests_cache import CachedResponse\nfrom requests_cache import CachedSession\nfrom requests_cache import OriginalResponse\nfrom requests_cache import SQLiteCache\nimport tabulate\nfrom tqdm import tqdm\nimport wcwidth\n\n\nFILE_HEAD = r\"\"\"\n.. Note this file is autogenerated by scripts/update-plugin-list.py - usually weekly via github action\n\n.. _plugin-list:\n\nPytest Plugin List\n==================\n\nBelow is an automated compilation of ``pytest`` plugins available on `PyPI <https://pypi.org>`_.\nIt includes PyPI projects whose names begin with ``pytest-`` or ``pytest_`` and a handful of manually selected projects.\nPackages classified as inactive are excluded.\n\nFor detailed insights into how this list is generated,\nplease refer to `the update script <https://github.com/pytest-dev/pytest/blob/main/scripts/update-plugin-list.py>`_.\n\n.. warning::\n\n   Please be aware that this list is not a curated collection of projects\n   and does not undergo a systematic review process.\n   It serves purely as an informational resource to aid in the discovery of ``pytest`` plugins.\n\n   Do not presume any endorsement from the ``pytest`` project or its developers,\n   and always conduct your own quality assessment before incorporating any of these plugins into your own projects.\n\n\n.. The following conditional uses a different format for this list when\n   creating a PDF, because otherwise the table gets far too wide for the\n   page.\n\n\"\"\"\nDEVELOPMENT_STATUS_CLASSIFIERS = (\n    \"Development Status :: 1 - Planning\",\n    \"Development Status :: 2 - Pre-Alpha\",\n    \"Development Status :: 3 - Alpha\",\n    \"Development Status :: 4 - Beta\",\n    \"Development Status :: 5 - Production/Stable\",\n    \"Development Status :: 6 - Mature\",\n    \"Development Status :: 7 - Inactive\",\n)\nADDITIONAL_PROJECTS = {  # set of additional projects to consider as plugins\n    \"logassert\",\n    \"logot\",\n    \"nuts\",\n    \"flask_fixture\",\n    \"databricks-labs-pytester\",\n    \"tursu\",\n}\n\n\ndef escape_rst(text: str) -> str:\n    \"\"\"Rudimentary attempt to escape special RST characters to appear as\n    plain text.\"\"\"\n    text = (\n        text.replace(\"*\", \"\\\\*\")\n        .replace(\"<\", \"\\\\<\")\n        .replace(\">\", \"\\\\>\")\n        .replace(\"`\", \"\\\\`\")\n    )\n    text = re.sub(r\"_\\b\", \"\", text)\n    return text\n\n\ndef project_response_with_refresh(\n    session: CachedSession, name: str, last_serial: int\n) -> OriginalResponse | CachedResponse:\n    \"\"\"Get a http cached pypi project\n\n    force refresh in case of last serial mismatch\n    \"\"\"\n    response = session.get(f\"https://pypi.org/pypi/{name}/json\")\n    if int(response.headers.get(\"X-PyPI-Last-Serial\", -1)) != last_serial:\n        response = session.get(f\"https://pypi.org/pypi/{name}/json\", refresh=True)\n    return response\n\n\ndef get_session() -> CachedSession:\n    \"\"\"Configures the requests-cache session\"\"\"\n    cache_path = platformdirs.user_cache_path(\"pytest-plugin-list\")\n    cache_path.mkdir(exist_ok=True, parents=True)\n    cache_file = cache_path.joinpath(\"http_cache.sqlite3\")\n    return CachedSession(backend=SQLiteCache(cache_file))\n\n\ndef pytest_plugin_projects_from_pypi(session: CachedSession) -> dict[str, int]:\n    response = session.get(\n        \"https://pypi.org/simple\",\n        headers={\"Accept\": \"application/vnd.pypi.simple.v1+json\"},\n        refresh=True,\n    )\n    return {\n        name: p[\"_last-serial\"]\n        for p in response.json()[\"projects\"]\n        if (\n            (name := p[\"name\"]).startswith((\"pytest-\", \"pytest_\"))\n            or name in ADDITIONAL_PROJECTS\n        )\n    }\n\n\nclass PluginInfo(TypedDict):\n    \"\"\"Relevant information about a plugin to generate the summary.\"\"\"\n\n    name: str\n    summary: str\n    last_release: str\n    status: str\n    requires: str\n\n\ndef iter_plugins() -> Iterator[PluginInfo]:\n    session = get_session()\n    name_2_serial = pytest_plugin_projects_from_pypi(session)\n\n    for name, last_serial in tqdm(name_2_serial.items(), smoothing=0):\n        response = project_response_with_refresh(session, name, last_serial)\n        if response.status_code == 404:\n            # Some packages, like pytest-azurepipelines42, are included in https://pypi.org/simple\n            # but return 404 on the JSON API. Skip.\n            continue\n        response.raise_for_status()\n        info = response.json()[\"info\"]\n        if \"Development Status :: 7 - Inactive\" in info[\"classifiers\"]:\n            continue\n        for classifier in DEVELOPMENT_STATUS_CLASSIFIERS:\n            if classifier in info[\"classifiers\"]:\n                status = classifier[22:]\n                break\n        else:\n            status = \"N/A\"\n        requires = \"N/A\"\n        if info[\"requires_dist\"]:\n            for requirement in info[\"requires_dist\"]:\n                if re.match(r\"pytest(?![-.\\w])\", requirement):\n                    requires = requirement\n                    break\n\n        def version_sort_key(version_string: str) -> Any:\n            \"\"\"\n            Return the sort key for the given version string\n            returned by the API.\n            \"\"\"\n            try:\n                return packaging.version.parse(version_string)\n            except packaging.version.InvalidVersion:\n                # Use a hard-coded pre-release version.\n                return packaging.version.Version(\"0.0.0alpha\")\n\n        releases = response.json()[\"releases\"]\n        for release in sorted(releases, key=version_sort_key, reverse=True):\n            if releases[release]:\n                release_date = datetime.date.fromisoformat(\n                    releases[release][-1][\"upload_time_iso_8601\"].split(\"T\")[0]\n                )\n                last_release = release_date.strftime(\"%b %d, %Y\")\n                break\n        name = f\":pypi:`{info['name']}`\"\n        summary = \"\"\n        if info[\"summary\"]:\n            summary = escape_rst(info[\"summary\"].replace(\"\\n\", \"\"))\n        yield {\n            \"name\": name,\n            \"summary\": summary.strip(),\n            \"last_release\": last_release,\n            \"status\": status,\n            \"requires\": requires,\n        }\n\n\ndef plugin_definitions(plugins: Iterable[PluginInfo]) -> Iterator[str]:\n    \"\"\"Return RST for the plugin list that fits better on a vertical page.\"\"\"\n    for plugin in plugins:\n        yield dedent(\n            f\"\"\"\n            {plugin[\"name\"]}\n               *last release*: {plugin[\"last_release\"]},\n               *status*: {plugin[\"status\"]},\n               *requires*: {plugin[\"requires\"]}\n\n               {plugin[\"summary\"]}\n            \"\"\"\n        )\n\n\ndef main() -> None:\n    plugins = [*iter_plugins()]\n\n    reference_dir = pathlib.Path(\"doc\", \"en\", \"reference\")\n\n    plugin_list = reference_dir / \"plugin_list.rst\"\n    with plugin_list.open(\"w\", encoding=\"UTF-8\") as f:\n        f.write(FILE_HEAD)\n        f.write(f\"This list contains {len(plugins)} plugins.\\n\\n\")\n        f.write(\".. only:: not latex\\n\\n\")\n\n        _ = wcwidth  # reference library that must exist for tabulate to work\n        plugin_table = tabulate.tabulate(plugins, headers=\"keys\", tablefmt=\"rst\")\n        f.write(indent(plugin_table, \"   \"))\n        f.write(\"\\n\\n\")\n\n        f.write(\".. only:: latex\\n\\n\")\n        f.write(indent(\"\".join(plugin_definitions(plugins)), \"  \"))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/_pytest/__init__.py",
    "content": "from __future__ import annotations\n\n\n__all__ = [\"__version__\", \"version_tuple\"]\n\ntry:\n    from ._version import version as __version__\n    from ._version import version_tuple\nexcept ImportError:  # pragma: no cover\n    # broken installation, we don't even try\n    # unknown only works because we do poor mans version compare\n    __version__ = \"unknown\"\n    version_tuple = (0, 0, \"unknown\")\n"
  },
  {
    "path": "src/_pytest/_argcomplete.py",
    "content": "\"\"\"Allow bash-completion for argparse with argcomplete if installed.\n\nNeeds argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail\nto find the magic string, so _ARGCOMPLETE env. var is never set, and\nthis does not need special code).\n\nFunction try_argcomplete(parser) should be called directly before\nthe call to ArgumentParser.parse_args().\n\nThe filescompleter is what you normally would use on the positional\narguments specification, in order to get \"dirname/\" after \"dirn<TAB>\"\ninstead of the default \"dirname \":\n\n   optparser.add_argument(Config._file_or_dir, nargs='*').completer=filescompleter\n\nOther, application specific, completers should go in the file\ndoing the add_argument calls as they need to be specified as .completer\nattributes as well. (If argcomplete is not installed, the function the\nattribute points to will not be used).\n\nSPEEDUP\n=======\n\nThe generic argcomplete script for bash-completion\n(/etc/bash_completion.d/python-argcomplete.sh)\nuses a python program to determine startup script generated by pip.\nYou can speed up completion somewhat by changing this script to include\n  # PYTHON_ARGCOMPLETE_OK\nso the python-argcomplete-check-easy-install-script does not\nneed to be called to find the entry point of the code and see if that is\nmarked  with PYTHON_ARGCOMPLETE_OK.\n\nINSTALL/DEBUGGING\n=================\n\nTo include this support in another application that has setup.py generated\nscripts:\n\n- Add the line:\n    # PYTHON_ARGCOMPLETE_OK\n  near the top of the main python entry point.\n\n- Include in the file calling parse_args():\n    from _argcomplete import try_argcomplete, filescompleter\n  Call try_argcomplete just before parse_args(), and optionally add\n  filescompleter to the positional arguments' add_argument().\n\nIf things do not work right away:\n\n- Switch on argcomplete debugging with (also helpful when doing custom\n  completers):\n    export _ARC_DEBUG=1\n\n- Run:\n    python-argcomplete-check-easy-install-script $(which appname)\n    echo $?\n  will echo 0 if the magic line has been found, 1 if not.\n\n- Sometimes it helps to find early on errors using:\n    _ARGCOMPLETE=1 _ARC_DEBUG=1 appname\n  which should throw a KeyError: 'COMPLINE' (which is properly set by the\n  global argcomplete script).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nfrom glob import glob\nimport os\nimport sys\nfrom typing import Any\n\n\nclass FastFilesCompleter:\n    \"\"\"Fast file completer class.\"\"\"\n\n    def __init__(self, directories: bool = True) -> None:\n        self.directories = directories\n\n    def __call__(self, prefix: str, **kwargs: Any) -> list[str]:\n        # Only called on non option completions.\n        if os.sep in prefix[1:]:\n            prefix_dir = len(os.path.dirname(prefix) + os.sep)\n        else:\n            prefix_dir = 0\n        completion = []\n        globbed = []\n        if \"*\" not in prefix and \"?\" not in prefix:\n            # We are on unix, otherwise no bash.\n            if not prefix or prefix[-1] == os.sep:\n                globbed.extend(glob(prefix + \".*\"))\n            prefix += \"*\"\n        globbed.extend(glob(prefix))\n        for x in sorted(globbed):\n            if os.path.isdir(x):\n                x += \"/\"\n            # Append stripping the prefix (like bash, not like compgen).\n            completion.append(x[prefix_dir:])\n        return completion\n\n\nif os.environ.get(\"_ARGCOMPLETE\"):\n    try:\n        import argcomplete.completers\n    except ImportError:\n        sys.exit(-1)\n    filescompleter: FastFilesCompleter | None = FastFilesCompleter()\n\n    def try_argcomplete(parser: argparse.ArgumentParser) -> None:\n        argcomplete.autocomplete(parser, always_complete_options=False)\n\nelse:\n\n    def try_argcomplete(parser: argparse.ArgumentParser) -> None:\n        pass\n\n    filescompleter = None\n"
  },
  {
    "path": "src/_pytest/_code/__init__.py",
    "content": "\"\"\"Python inspection/code generation API.\"\"\"\n\nfrom __future__ import annotations\n\nfrom .code import Code\nfrom .code import ExceptionInfo\nfrom .code import filter_traceback\nfrom .code import Frame\nfrom .code import getfslineno\nfrom .code import Traceback\nfrom .code import TracebackEntry\nfrom .source import getrawcode\nfrom .source import Source\n\n\n__all__ = [\n    \"Code\",\n    \"ExceptionInfo\",\n    \"Frame\",\n    \"Source\",\n    \"Traceback\",\n    \"TracebackEntry\",\n    \"filter_traceback\",\n    \"getfslineno\",\n    \"getrawcode\",\n]\n"
  },
  {
    "path": "src/_pytest/_code/code.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport ast\nfrom collections.abc import Callable\nfrom collections.abc import Iterable\nfrom collections.abc import Mapping\nfrom collections.abc import Sequence\nimport dataclasses\nimport inspect\nfrom inspect import CO_VARARGS\nfrom inspect import CO_VARKEYWORDS\nfrom io import StringIO\nimport os\nfrom pathlib import Path\nimport re\nimport sys\nfrom traceback import extract_tb\nfrom traceback import format_exception\nfrom traceback import format_exception_only\nfrom traceback import FrameSummary\nfrom types import CodeType\nfrom types import FrameType\nfrom types import TracebackType\nfrom typing import Any\nfrom typing import ClassVar\nfrom typing import Final\nfrom typing import final\nfrom typing import Generic\nfrom typing import Literal\nfrom typing import overload\nfrom typing import SupportsIndex\nfrom typing import TypeAlias\nfrom typing import TypeVar\n\nimport pluggy\n\nimport _pytest\nfrom _pytest._code.source import findsource\nfrom _pytest._code.source import getrawcode\nfrom _pytest._code.source import getstatementrange_ast\nfrom _pytest._code.source import Source\nfrom _pytest._io import TerminalWriter\nfrom _pytest._io.saferepr import safeformat\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest.compat import get_real_func\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.pathlib import absolutepath\nfrom _pytest.pathlib import bestrelpath\n\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import BaseExceptionGroup\n\nTracebackStyle = Literal[\"long\", \"short\", \"line\", \"no\", \"native\", \"value\", \"auto\"]\n\nEXCEPTION_OR_MORE = type[BaseException] | tuple[type[BaseException], ...]\n\n\nclass Code:\n    \"\"\"Wrapper around Python code objects.\"\"\"\n\n    __slots__ = (\"raw\",)\n\n    def __init__(self, obj: CodeType) -> None:\n        self.raw = obj\n\n    @classmethod\n    def from_function(cls, obj: object) -> Code:\n        return cls(getrawcode(obj))\n\n    def __eq__(self, other):\n        return self.raw == other.raw\n\n    # Ignore type because of https://github.com/python/mypy/issues/4266.\n    __hash__ = None  # type: ignore\n\n    @property\n    def firstlineno(self) -> int:\n        return self.raw.co_firstlineno - 1\n\n    @property\n    def name(self) -> str:\n        return self.raw.co_name\n\n    @property\n    def path(self) -> Path | str:\n        \"\"\"Return a path object pointing to source code, or an ``str`` in\n        case of ``OSError`` / non-existing file.\"\"\"\n        if not self.raw.co_filename:\n            return \"\"\n        try:\n            p = absolutepath(self.raw.co_filename)\n            # maybe don't try this checking\n            if not p.exists():\n                raise OSError(\"path check failed.\")\n            return p\n        except OSError:\n            # XXX maybe try harder like the weird logic\n            # in the standard lib [linecache.updatecache] does?\n            return self.raw.co_filename\n\n    @property\n    def fullsource(self) -> Source | None:\n        \"\"\"Return a _pytest._code.Source object for the full source file of the code.\"\"\"\n        full, _ = findsource(self.raw)\n        return full\n\n    def source(self) -> Source:\n        \"\"\"Return a _pytest._code.Source object for the code object's source only.\"\"\"\n        # return source only for that part of code\n        return Source(self.raw)\n\n    def getargs(self, var: bool = False) -> tuple[str, ...]:\n        \"\"\"Return a tuple with the argument names for the code object.\n\n        If 'var' is set True also return the names of the variable and\n        keyword arguments when present.\n        \"\"\"\n        # Handy shortcut for getting args.\n        raw = self.raw\n        argcount = raw.co_argcount\n        if var:\n            argcount += raw.co_flags & CO_VARARGS\n            argcount += raw.co_flags & CO_VARKEYWORDS\n        return raw.co_varnames[:argcount]\n\n\nclass Frame:\n    \"\"\"Wrapper around a Python frame holding f_locals and f_globals\n    in which expressions can be evaluated.\"\"\"\n\n    __slots__ = (\"raw\",)\n\n    def __init__(self, frame: FrameType) -> None:\n        self.raw = frame\n\n    @property\n    def lineno(self) -> int:\n        return self.raw.f_lineno - 1\n\n    @property\n    def f_globals(self) -> dict[str, Any]:\n        return self.raw.f_globals\n\n    @property\n    def f_locals(self) -> dict[str, Any]:\n        return self.raw.f_locals\n\n    @property\n    def code(self) -> Code:\n        return Code(self.raw.f_code)\n\n    @property\n    def statement(self) -> Source:\n        \"\"\"Statement this frame is at.\"\"\"\n        if self.code.fullsource is None:\n            return Source(\"\")\n        return self.code.fullsource.getstatement(self.lineno)\n\n    def eval(self, code, **vars):\n        \"\"\"Evaluate 'code' in the frame.\n\n        'vars' are optional additional local variables.\n\n        Returns the result of the evaluation.\n        \"\"\"\n        f_locals = self.f_locals.copy()\n        f_locals.update(vars)\n        return eval(code, self.f_globals, f_locals)\n\n    def repr(self, object: object) -> str:\n        \"\"\"Return a 'safe' (non-recursive, one-line) string repr for 'object'.\"\"\"\n        return saferepr(object)\n\n    def getargs(self, var: bool = False):\n        \"\"\"Return a list of tuples (name, value) for all arguments.\n\n        If 'var' is set True, also include the variable and keyword arguments\n        when present.\n        \"\"\"\n        retval = []\n        for arg in self.code.getargs(var):\n            try:\n                retval.append((arg, self.f_locals[arg]))\n            except KeyError:\n                pass  # this can occur when using Psyco\n        return retval\n\n\nclass TracebackEntry:\n    \"\"\"A single entry in a Traceback.\"\"\"\n\n    __slots__ = (\"_rawentry\", \"_repr_style\")\n\n    def __init__(\n        self,\n        rawentry: TracebackType,\n        repr_style: Literal[\"short\", \"long\"] | None = None,\n    ) -> None:\n        self._rawentry: Final = rawentry\n        self._repr_style: Final = repr_style\n\n    def with_repr_style(\n        self, repr_style: Literal[\"short\", \"long\"] | None\n    ) -> TracebackEntry:\n        return TracebackEntry(self._rawentry, repr_style)\n\n    @property\n    def lineno(self) -> int:\n        return self._rawentry.tb_lineno - 1\n\n    def get_python_framesummary(self) -> FrameSummary:\n        # Python's built-in traceback module implements all the nitty gritty\n        # details to get column numbers of out frames.\n        stack_summary = extract_tb(self._rawentry, limit=1)\n        return stack_summary[0]\n\n    # Column and end line numbers introduced in python 3.11\n    if sys.version_info < (3, 11):\n\n        @property\n        def end_lineno_relative(self) -> int | None:\n            return None\n\n        @property\n        def colno(self) -> int | None:\n            return None\n\n        @property\n        def end_colno(self) -> int | None:\n            return None\n    else:\n\n        @property\n        def end_lineno_relative(self) -> int | None:\n            frame_summary = self.get_python_framesummary()\n            if frame_summary.end_lineno is None:  # pragma: no cover\n                return None\n            return frame_summary.end_lineno - 1 - self.frame.code.firstlineno\n\n        @property\n        def colno(self) -> int | None:\n            \"\"\"Starting byte offset of the expression in the traceback entry.\"\"\"\n            return self.get_python_framesummary().colno\n\n        @property\n        def end_colno(self) -> int | None:\n            \"\"\"Ending byte offset of the expression in the traceback entry.\"\"\"\n            return self.get_python_framesummary().end_colno\n\n    @property\n    def frame(self) -> Frame:\n        return Frame(self._rawentry.tb_frame)\n\n    @property\n    def relline(self) -> int:\n        return self.lineno - self.frame.code.firstlineno\n\n    def __repr__(self) -> str:\n        return f\"<TracebackEntry {self.frame.code.path}:{self.lineno + 1}>\"\n\n    @property\n    def statement(self) -> Source:\n        \"\"\"_pytest._code.Source object for the current statement.\"\"\"\n        source = self.frame.code.fullsource\n        assert source is not None\n        return source.getstatement(self.lineno)\n\n    @property\n    def path(self) -> Path | str:\n        \"\"\"Path to the source code.\"\"\"\n        return self.frame.code.path\n\n    @property\n    def locals(self) -> dict[str, Any]:\n        \"\"\"Locals of underlying frame.\"\"\"\n        return self.frame.f_locals\n\n    def getfirstlinesource(self) -> int:\n        return self.frame.code.firstlineno\n\n    def getsource(\n        self, astcache: dict[str | Path, ast.AST] | None = None\n    ) -> Source | None:\n        \"\"\"Return failing source code.\"\"\"\n        # we use the passed in astcache to not reparse asttrees\n        # within exception info printing\n        source = self.frame.code.fullsource\n        if source is None:\n            return None\n        key = astnode = None\n        if astcache is not None:\n            key = self.frame.code.path\n            if key is not None:\n                astnode = astcache.get(key, None)\n        start = self.getfirstlinesource()\n        try:\n            astnode, _, end = getstatementrange_ast(\n                self.lineno, source, astnode=astnode\n            )\n        except SyntaxError:\n            end = self.lineno + 1\n        else:\n            if key is not None and astcache is not None:\n                astcache[key] = astnode\n        return source[start:end]\n\n    source = property(getsource)\n\n    def ishidden(self, excinfo: ExceptionInfo[BaseException] | None) -> bool:\n        \"\"\"Return True if the current frame has a var __tracebackhide__\n        resolving to True.\n\n        If __tracebackhide__ is a callable, it gets called with the\n        ExceptionInfo instance and can decide whether to hide the traceback.\n\n        Mostly for internal use.\n        \"\"\"\n        tbh: bool | Callable[[ExceptionInfo[BaseException] | None], bool] = False\n        for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals):\n            # in normal cases, f_locals and f_globals are dictionaries\n            # however via `exec(...)` / `eval(...)` they can be other types\n            # (even incorrect types!).\n            # as such, we suppress all exceptions while accessing __tracebackhide__\n            try:\n                tbh = maybe_ns_dct[\"__tracebackhide__\"]\n            except Exception:\n                pass\n            else:\n                break\n        if tbh and callable(tbh):\n            return tbh(excinfo)\n        return tbh\n\n    def __str__(self) -> str:\n        name = self.frame.code.name\n        try:\n            line = str(self.statement).lstrip()\n        except KeyboardInterrupt:\n            raise\n        except BaseException:\n            line = \"???\"\n        # This output does not quite match Python's repr for traceback entries,\n        # but changing it to do so would break certain plugins.  See\n        # https://github.com/pytest-dev/pytest/pull/7535/ for details.\n        return f\"  File '{self.path}':{self.lineno + 1} in {name}\\n  {line}\\n\"\n\n    @property\n    def name(self) -> str:\n        \"\"\"co_name of underlying code.\"\"\"\n        return self.frame.code.raw.co_name\n\n\nclass Traceback(list[TracebackEntry]):\n    \"\"\"Traceback objects encapsulate and offer higher level access to Traceback entries.\"\"\"\n\n    def __init__(\n        self,\n        tb: TracebackType | Iterable[TracebackEntry],\n    ) -> None:\n        \"\"\"Initialize from given python traceback object and ExceptionInfo.\"\"\"\n        if isinstance(tb, TracebackType):\n\n            def f(cur: TracebackType) -> Iterable[TracebackEntry]:\n                cur_: TracebackType | None = cur\n                while cur_ is not None:\n                    yield TracebackEntry(cur_)\n                    cur_ = cur_.tb_next\n\n            super().__init__(f(tb))\n        else:\n            super().__init__(tb)\n\n    def cut(\n        self,\n        path: os.PathLike[str] | str | None = None,\n        lineno: int | None = None,\n        firstlineno: int | None = None,\n        excludepath: os.PathLike[str] | None = None,\n    ) -> Traceback:\n        \"\"\"Return a Traceback instance wrapping part of this Traceback.\n\n        By providing any combination of path, lineno and firstlineno, the\n        first frame to start the to-be-returned traceback is determined.\n\n        This allows cutting the first part of a Traceback instance e.g.\n        for formatting reasons (removing some uninteresting bits that deal\n        with handling of the exception/traceback).\n        \"\"\"\n        path_ = None if path is None else os.fspath(path)\n        excludepath_ = None if excludepath is None else os.fspath(excludepath)\n        for x in self:\n            code = x.frame.code\n            codepath = code.path\n            if path is not None and str(codepath) != path_:\n                continue\n            if (\n                excludepath is not None\n                and isinstance(codepath, Path)\n                and excludepath_ in (str(p) for p in codepath.parents)  # type: ignore[operator]\n            ):\n                continue\n            if lineno is not None and x.lineno != lineno:\n                continue\n            if firstlineno is not None and x.frame.code.firstlineno != firstlineno:\n                continue\n            return Traceback(x._rawentry)\n        return self\n\n    @overload\n    def __getitem__(self, key: SupportsIndex) -> TracebackEntry: ...\n\n    @overload\n    def __getitem__(self, key: slice) -> Traceback: ...\n\n    def __getitem__(self, key: SupportsIndex | slice) -> TracebackEntry | Traceback:\n        if isinstance(key, slice):\n            return self.__class__(super().__getitem__(key))\n        else:\n            return super().__getitem__(key)\n\n    def filter(\n        self,\n        excinfo_or_fn: ExceptionInfo[BaseException] | Callable[[TracebackEntry], bool],\n        /,\n    ) -> Traceback:\n        \"\"\"Return a Traceback instance with certain items removed.\n\n        If the filter is an `ExceptionInfo`, removes all the ``TracebackEntry``s\n        which are hidden (see ishidden() above).\n\n        Otherwise, the filter is a function that gets a single argument, a\n        ``TracebackEntry`` instance, and should return True when the item should\n        be added to the ``Traceback``, False when not.\n        \"\"\"\n        if isinstance(excinfo_or_fn, ExceptionInfo):\n            fn = lambda x: not x.ishidden(excinfo_or_fn)  # noqa: E731\n        else:\n            fn = excinfo_or_fn\n        return Traceback(filter(fn, self))\n\n    def recursionindex(self) -> int | None:\n        \"\"\"Return the index of the frame/TracebackEntry where recursion originates if\n        appropriate, None if no recursion occurred.\"\"\"\n        cache: dict[tuple[Any, int, int], list[dict[str, Any]]] = {}\n        for i, entry in enumerate(self):\n            # id for the code.raw is needed to work around\n            # the strange metaprogramming in the decorator lib from pypi\n            # which generates code objects that have hash/value equality\n            # XXX needs a test\n            key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno\n            values = cache.setdefault(key, [])\n            # Since Python 3.13 f_locals is a proxy, freeze it.\n            loc = dict(entry.frame.f_locals)\n            if values:\n                for otherloc in values:\n                    if otherloc == loc:\n                        return i\n            values.append(loc)\n        return None\n\n\ndef stringify_exception(\n    exc: BaseException, include_subexception_msg: bool = True\n) -> str:\n    try:\n        notes = getattr(exc, \"__notes__\", [])\n    except KeyError:\n        # Workaround for https://github.com/python/cpython/issues/98778 on\n        # some 3.10 and 3.11 patch versions.\n        HTTPError = getattr(sys.modules.get(\"urllib.error\", None), \"HTTPError\", ())\n        if sys.version_info < (3, 12) and isinstance(exc, HTTPError):\n            notes = []\n        else:  # pragma: no cover\n            # exception not related to above bug, reraise\n            raise\n    if not include_subexception_msg and isinstance(exc, BaseExceptionGroup):\n        message = exc.message\n    else:\n        message = str(exc)\n\n    return \"\\n\".join(\n        [\n            message,\n            *notes,\n        ]\n    )\n\n\nE = TypeVar(\"E\", bound=BaseException, covariant=True)\n\n\n@final\n@dataclasses.dataclass\nclass ExceptionInfo(Generic[E]):\n    \"\"\"Wraps sys.exc_info() objects and offers help for navigating the traceback.\"\"\"\n\n    _assert_start_repr: ClassVar = \"AssertionError('assert \"\n\n    _excinfo: tuple[type[E], E, TracebackType] | None\n    _striptext: str\n    _traceback: Traceback | None\n\n    def __init__(\n        self,\n        excinfo: tuple[type[E], E, TracebackType] | None,\n        striptext: str = \"\",\n        traceback: Traceback | None = None,\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        self._excinfo = excinfo\n        self._striptext = striptext\n        self._traceback = traceback\n\n    @classmethod\n    def from_exception(\n        cls,\n        # Ignoring error: \"Cannot use a covariant type variable as a parameter\".\n        # This is OK to ignore because this class is (conceptually) readonly.\n        # See https://github.com/python/mypy/issues/7049.\n        exception: E,  # type: ignore[misc]\n        exprinfo: str | None = None,\n    ) -> ExceptionInfo[E]:\n        \"\"\"Return an ExceptionInfo for an existing exception.\n\n        The exception must have a non-``None`` ``__traceback__`` attribute,\n        otherwise this function fails with an assertion error. This means that\n        the exception must have been raised, or added a traceback with the\n        :py:meth:`~BaseException.with_traceback()` method.\n\n        :param exprinfo:\n            A text string helping to determine if we should strip\n            ``AssertionError`` from the output. Defaults to the exception\n            message/``__str__()``.\n\n        .. versionadded:: 7.4\n        \"\"\"\n        assert exception.__traceback__, (\n            \"Exceptions passed to ExcInfo.from_exception(...)\"\n            \" must have a non-None __traceback__.\"\n        )\n        exc_info = (type(exception), exception, exception.__traceback__)\n        return cls.from_exc_info(exc_info, exprinfo)\n\n    @classmethod\n    def from_exc_info(\n        cls,\n        exc_info: tuple[type[E], E, TracebackType],\n        exprinfo: str | None = None,\n    ) -> ExceptionInfo[E]:\n        \"\"\"Like :func:`from_exception`, but using old-style exc_info tuple.\"\"\"\n        _striptext = \"\"\n        if exprinfo is None and isinstance(exc_info[1], AssertionError):\n            exprinfo = getattr(exc_info[1], \"msg\", None)\n            if exprinfo is None:\n                exprinfo = saferepr(exc_info[1])\n            if exprinfo and exprinfo.startswith(cls._assert_start_repr):\n                _striptext = \"AssertionError: \"\n\n        return cls(exc_info, _striptext, _ispytest=True)\n\n    @classmethod\n    def from_current(cls, exprinfo: str | None = None) -> ExceptionInfo[BaseException]:\n        \"\"\"Return an ExceptionInfo matching the current traceback.\n\n        .. warning::\n\n            Experimental API\n\n        :param exprinfo:\n            A text string helping to determine if we should strip\n            ``AssertionError`` from the output. Defaults to the exception\n            message/``__str__()``.\n        \"\"\"\n        tup = sys.exc_info()\n        assert tup[0] is not None, \"no current exception\"\n        assert tup[1] is not None, \"no current exception\"\n        assert tup[2] is not None, \"no current exception\"\n        exc_info = (tup[0], tup[1], tup[2])\n        return ExceptionInfo.from_exc_info(exc_info, exprinfo)\n\n    @classmethod\n    def for_later(cls) -> ExceptionInfo[E]:\n        \"\"\"Return an unfilled ExceptionInfo.\"\"\"\n        return cls(None, _ispytest=True)\n\n    def fill_unfilled(self, exc_info: tuple[type[E], E, TracebackType]) -> None:\n        \"\"\"Fill an unfilled ExceptionInfo created with ``for_later()``.\"\"\"\n        assert self._excinfo is None, \"ExceptionInfo was already filled\"\n        self._excinfo = exc_info\n\n    @property\n    def type(self) -> type[E]:\n        \"\"\"The exception class.\"\"\"\n        assert self._excinfo is not None, (\n            \".type can only be used after the context manager exits\"\n        )\n        return self._excinfo[0]\n\n    @property\n    def value(self) -> E:\n        \"\"\"The exception value.\"\"\"\n        assert self._excinfo is not None, (\n            \".value can only be used after the context manager exits\"\n        )\n        return self._excinfo[1]\n\n    @property\n    def tb(self) -> TracebackType:\n        \"\"\"The exception raw traceback.\"\"\"\n        assert self._excinfo is not None, (\n            \".tb can only be used after the context manager exits\"\n        )\n        return self._excinfo[2]\n\n    @property\n    def typename(self) -> str:\n        \"\"\"The type name of the exception.\"\"\"\n        assert self._excinfo is not None, (\n            \".typename can only be used after the context manager exits\"\n        )\n        return self.type.__name__\n\n    @property\n    def traceback(self) -> Traceback:\n        \"\"\"The traceback.\"\"\"\n        if self._traceback is None:\n            self._traceback = Traceback(self.tb)\n        return self._traceback\n\n    @traceback.setter\n    def traceback(self, value: Traceback) -> None:\n        self._traceback = value\n\n    def __repr__(self) -> str:\n        if self._excinfo is None:\n            return \"<ExceptionInfo for raises contextmanager>\"\n        return f\"<{self.__class__.__name__} {saferepr(self._excinfo[1])} tblen={len(self.traceback)}>\"\n\n    def exconly(self, tryshort: bool = False) -> str:\n        \"\"\"Return the exception as a string.\n\n        When 'tryshort' resolves to True, and the exception is an\n        AssertionError, only the actual exception part of the exception\n        representation is returned (so 'AssertionError: ' is removed from\n        the beginning).\n        \"\"\"\n\n        def _get_single_subexc(\n            eg: BaseExceptionGroup[BaseException],\n        ) -> BaseException | None:\n            if len(eg.exceptions) != 1:\n                return None\n            if isinstance(e := eg.exceptions[0], BaseExceptionGroup):\n                return _get_single_subexc(e)\n            return e\n\n        if (\n            tryshort\n            and isinstance(self.value, BaseExceptionGroup)\n            and (subexc := _get_single_subexc(self.value)) is not None\n        ):\n            return f\"{subexc!r} [single exception in {type(self.value).__name__}]\"\n\n        lines = format_exception_only(self.type, self.value)\n        text = \"\".join(lines)\n        text = text.rstrip()\n        if tryshort:\n            if text.startswith(self._striptext):\n                text = text[len(self._striptext) :]\n        return text\n\n    def errisinstance(self, exc: EXCEPTION_OR_MORE) -> bool:\n        \"\"\"Return True if the exception is an instance of exc.\n\n        Consider using ``isinstance(excinfo.value, exc)`` instead.\n        \"\"\"\n        return isinstance(self.value, exc)\n\n    def _getreprcrash(self) -> ReprFileLocation | None:\n        # Find last non-hidden traceback entry that led to the exception of the\n        # traceback, or None if all hidden.\n        for i in range(-1, -len(self.traceback) - 1, -1):\n            entry = self.traceback[i]\n            if not entry.ishidden(self):\n                path, lineno = entry.frame.code.raw.co_filename, entry.lineno\n                exconly = self.exconly(tryshort=True)\n                return ReprFileLocation(path, lineno + 1, exconly)\n        return None\n\n    def getrepr(\n        self,\n        showlocals: bool = False,\n        style: TracebackStyle = \"long\",\n        abspath: bool = False,\n        tbfilter: bool | Callable[[ExceptionInfo[BaseException]], Traceback] = True,\n        funcargs: bool = False,\n        truncate_locals: bool = True,\n        truncate_args: bool = True,\n        chain: bool = True,\n    ) -> ReprExceptionInfo | ExceptionChainRepr:\n        \"\"\"Return str()able representation of this exception info.\n\n        :param bool showlocals:\n            Show locals per traceback entry.\n            Ignored if ``style==\"native\"``.\n\n        :param str style:\n            long|short|line|no|native|value traceback style.\n\n        :param bool abspath:\n            If paths should be changed to absolute or left unchanged.\n\n        :param tbfilter:\n            A filter for traceback entries.\n\n            * If false, don't hide any entries.\n            * If true, hide internal entries and entries that contain a local\n              variable ``__tracebackhide__ = True``.\n            * If a callable, delegates the filtering to the callable.\n\n            Ignored if ``style`` is ``\"native\"``.\n\n        :param bool funcargs:\n            Show fixtures (\"funcargs\" for legacy purposes) per traceback entry.\n\n        :param bool truncate_locals:\n            With ``showlocals==True``, make sure locals can be safely represented as strings.\n\n        :param bool truncate_args:\n            With ``showargs==True``, make sure args can be safely represented as strings.\n\n        :param bool chain:\n            If chained exceptions in Python 3 should be shown.\n\n        .. versionchanged:: 3.9\n\n            Added the ``chain`` parameter.\n        \"\"\"\n        if style == \"native\":\n            return ReprExceptionInfo(\n                reprtraceback=ReprTracebackNative(\n                    format_exception(\n                        self.type,\n                        self.value,\n                        self.traceback[0]._rawentry if self.traceback else None,\n                    )\n                ),\n                reprcrash=self._getreprcrash(),\n            )\n\n        fmt = FormattedExcinfo(\n            showlocals=showlocals,\n            style=style,\n            abspath=abspath,\n            tbfilter=tbfilter,\n            funcargs=funcargs,\n            truncate_locals=truncate_locals,\n            truncate_args=truncate_args,\n            chain=chain,\n        )\n        return fmt.repr_excinfo(self)\n\n    def match(self, regexp: str | re.Pattern[str]) -> Literal[True]:\n        \"\"\"Check whether the regular expression `regexp` matches the string\n        representation of the exception using :func:`python:re.search`.\n\n        If it matches `True` is returned, otherwise an `AssertionError` is raised.\n        \"\"\"\n        __tracebackhide__ = True\n        value = stringify_exception(self.value)\n        msg = (\n            f\"Regex pattern did not match.\\n\"\n            f\"  Expected regex: {regexp!r}\\n\"\n            f\"  Actual message: {value!r}\"\n        )\n        if regexp == value:\n            msg += \"\\n Did you mean to `re.escape()` the regex?\"\n        assert re.search(regexp, value), msg\n        # Return True to allow for \"assert excinfo.match()\".\n        return True\n\n    def _group_contains(\n        self,\n        exc_group: BaseExceptionGroup[BaseException],\n        expected_exception: EXCEPTION_OR_MORE,\n        match: str | re.Pattern[str] | None,\n        target_depth: int | None = None,\n        current_depth: int = 1,\n    ) -> bool:\n        \"\"\"Return `True` if a `BaseExceptionGroup` contains a matching exception.\"\"\"\n        if (target_depth is not None) and (current_depth > target_depth):\n            # already descended past the target depth\n            return False\n        for exc in exc_group.exceptions:\n            if isinstance(exc, BaseExceptionGroup):\n                if self._group_contains(\n                    exc, expected_exception, match, target_depth, current_depth + 1\n                ):\n                    return True\n            if (target_depth is not None) and (current_depth != target_depth):\n                # not at the target depth, no match\n                continue\n            if not isinstance(exc, expected_exception):\n                continue\n            if match is not None:\n                value = stringify_exception(exc)\n                if not re.search(match, value):\n                    continue\n            return True\n        return False\n\n    def group_contains(\n        self,\n        expected_exception: EXCEPTION_OR_MORE,\n        *,\n        match: str | re.Pattern[str] | None = None,\n        depth: int | None = None,\n    ) -> bool:\n        \"\"\"Check whether a captured exception group contains a matching exception.\n\n        :param Type[BaseException] | Tuple[Type[BaseException]] expected_exception:\n            The expected exception type, or a tuple if one of multiple possible\n            exception types are expected.\n\n        :param str | re.Pattern[str] | None match:\n            If specified, a string containing a regular expression,\n            or a regular expression object, that is tested against the string\n            representation of the exception and its `PEP-678 <https://peps.python.org/pep-0678/>` `__notes__`\n            using :func:`re.search`.\n\n            To match a literal string that may contain :ref:`special characters\n            <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.\n\n        :param Optional[int] depth:\n            If `None`, will search for a matching exception at any nesting depth.\n            If >= 1, will only match an exception if it's at the specified depth (depth = 1 being\n            the exceptions contained within the topmost exception group).\n\n        .. versionadded:: 8.0\n\n        .. warning::\n           This helper makes it easy to check for the presence of specific exceptions,\n           but it is very bad for checking that the group does *not* contain\n           *any other exceptions*.\n           You should instead consider using :class:`pytest.RaisesGroup`\n\n        \"\"\"\n        msg = \"Captured exception is not an instance of `BaseExceptionGroup`\"\n        assert isinstance(self.value, BaseExceptionGroup), msg\n        msg = \"`depth` must be >= 1 if specified\"\n        assert (depth is None) or (depth >= 1), msg\n        return self._group_contains(self.value, expected_exception, match, depth)\n\n\n# Type alias for the `tbfilter` setting:\n# bool: If True, it should be filtered using Traceback.filter()\n# callable: A callable that takes an ExceptionInfo and returns the filtered traceback.\nTracebackFilter: TypeAlias = bool | Callable[[ExceptionInfo[BaseException]], Traceback]\n\n\n@dataclasses.dataclass\nclass FormattedExcinfo:\n    \"\"\"Presenting information about failing Functions and Generators.\"\"\"\n\n    # for traceback entries\n    flow_marker: ClassVar = \">\"\n    fail_marker: ClassVar = \"E\"\n\n    showlocals: bool = False\n    style: TracebackStyle = \"long\"\n    abspath: bool = True\n    tbfilter: TracebackFilter = True\n    funcargs: bool = False\n    truncate_locals: bool = True\n    truncate_args: bool = True\n    chain: bool = True\n    astcache: dict[str | Path, ast.AST] = dataclasses.field(\n        default_factory=dict, init=False, repr=False\n    )\n\n    def _getindent(self, source: Source) -> int:\n        # Figure out indent for the given source.\n        try:\n            s = str(source.getstatement(len(source) - 1))\n        except KeyboardInterrupt:\n            raise\n        except BaseException:\n            try:\n                s = str(source[-1])\n            except KeyboardInterrupt:\n                raise\n            except BaseException:\n                return 0\n        return 4 + (len(s) - len(s.lstrip()))\n\n    def _getentrysource(self, entry: TracebackEntry) -> Source | None:\n        source = entry.getsource(self.astcache)\n        if source is not None:\n            source = source.deindent()\n        return source\n\n    def repr_args(self, entry: TracebackEntry) -> ReprFuncArgs | None:\n        if self.funcargs:\n            args = []\n            for argname, argvalue in entry.frame.getargs(var=True):\n                if self.truncate_args:\n                    str_repr = saferepr(argvalue)\n                else:\n                    str_repr = saferepr(argvalue, maxsize=None)\n                args.append((argname, str_repr))\n            return ReprFuncArgs(args)\n        return None\n\n    def get_source(\n        self,\n        source: Source | None,\n        line_index: int = -1,\n        excinfo: ExceptionInfo[BaseException] | None = None,\n        short: bool = False,\n        end_line_index: int | None = None,\n        colno: int | None = None,\n        end_colno: int | None = None,\n    ) -> list[str]:\n        \"\"\"Return formatted and marked up source lines.\"\"\"\n        lines = []\n        if source is not None and line_index < 0:\n            line_index += len(source)\n        if source is None or line_index >= len(source.lines) or line_index < 0:\n            # `line_index` could still be outside `range(len(source.lines))` if\n            # we're processing AST with pathological position attributes.\n            source = Source(\"???\")\n            line_index = 0\n        space_prefix = \"    \"\n        if short:\n            lines.append(space_prefix + source.lines[line_index].strip())\n            lines.extend(\n                self.get_highlight_arrows_for_line(\n                    raw_line=source.raw_lines[line_index],\n                    line=source.lines[line_index].strip(),\n                    lineno=line_index,\n                    end_lineno=end_line_index,\n                    colno=colno,\n                    end_colno=end_colno,\n                )\n            )\n        else:\n            for line in source.lines[:line_index]:\n                lines.append(space_prefix + line)\n            lines.append(self.flow_marker + \"   \" + source.lines[line_index])\n            lines.extend(\n                self.get_highlight_arrows_for_line(\n                    raw_line=source.raw_lines[line_index],\n                    line=source.lines[line_index],\n                    lineno=line_index,\n                    end_lineno=end_line_index,\n                    colno=colno,\n                    end_colno=end_colno,\n                )\n            )\n            for line in source.lines[line_index + 1 :]:\n                lines.append(space_prefix + line)\n        if excinfo is not None:\n            indent = 4 if short else self._getindent(source)\n            lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))\n        return lines\n\n    def get_highlight_arrows_for_line(\n        self,\n        line: str,\n        raw_line: str,\n        lineno: int | None,\n        end_lineno: int | None,\n        colno: int | None,\n        end_colno: int | None,\n    ) -> list[str]:\n        \"\"\"Return characters highlighting a source line.\n\n        Example with colno and end_colno pointing to the bar expression:\n                   \"foo() + bar()\"\n        returns    \"        ^^^^^\"\n        \"\"\"\n        if lineno != end_lineno:\n            # Don't handle expressions that span multiple lines.\n            return []\n        if colno is None or end_colno is None:\n            # Can't do anything without column information.\n            return []\n\n        num_stripped_chars = len(raw_line) - len(line)\n\n        start_char_offset = _byte_offset_to_character_offset(raw_line, colno)\n        end_char_offset = _byte_offset_to_character_offset(raw_line, end_colno)\n        num_carets = end_char_offset - start_char_offset\n        # If the highlight would span the whole line, it is redundant, don't\n        # show it.\n        if num_carets >= len(line.strip()):\n            return []\n\n        highlights = \"    \"\n        highlights += \" \" * (start_char_offset - num_stripped_chars + 1)\n        highlights += \"^\" * num_carets\n        return [highlights]\n\n    def get_exconly(\n        self,\n        excinfo: ExceptionInfo[BaseException],\n        indent: int = 4,\n        markall: bool = False,\n    ) -> list[str]:\n        lines = []\n        indentstr = \" \" * indent\n        # Get the real exception information out.\n        exlines = excinfo.exconly(tryshort=True).split(\"\\n\")\n        failindent = self.fail_marker + indentstr[1:]\n        for line in exlines:\n            lines.append(failindent + line)\n            if not markall:\n                failindent = indentstr\n        return lines\n\n    def repr_locals(self, locals: Mapping[str, object]) -> ReprLocals | None:\n        if self.showlocals:\n            lines = []\n            keys = [loc for loc in locals if loc[0] != \"@\"]\n            keys.sort()\n            for name in keys:\n                value = locals[name]\n                if name == \"__builtins__\":\n                    lines.append(\"__builtins__ = <builtins>\")\n                else:\n                    # This formatting could all be handled by the\n                    # _repr() function, which is only reprlib.Repr in\n                    # disguise, so is very configurable.\n                    if self.truncate_locals:\n                        str_repr = saferepr(value)\n                    else:\n                        str_repr = safeformat(value)\n                    # if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)):\n                    lines.append(f\"{name:<10} = {str_repr}\")\n                    # else:\n                    #    self._line(\"%-10s =\\\\\" % (name,))\n                    #    # XXX\n                    #    pprint.pprint(value, stream=self.excinfowriter)\n            return ReprLocals(lines)\n        return None\n\n    def repr_traceback_entry(\n        self,\n        entry: TracebackEntry | None,\n        excinfo: ExceptionInfo[BaseException] | None = None,\n    ) -> ReprEntry:\n        lines: list[str] = []\n        style = (\n            entry._repr_style\n            if entry is not None and entry._repr_style is not None\n            else self.style\n        )\n        if style in (\"short\", \"long\") and entry is not None:\n            source = self._getentrysource(entry)\n            if source is None:\n                source = Source(\"???\")\n                line_index = 0\n                end_line_index, colno, end_colno = None, None, None\n            else:\n                line_index = entry.relline\n                end_line_index = entry.end_lineno_relative\n                colno = entry.colno\n                end_colno = entry.end_colno\n            short = style == \"short\"\n            reprargs = self.repr_args(entry) if not short else None\n            s = self.get_source(\n                source=source,\n                line_index=line_index,\n                excinfo=excinfo,\n                short=short,\n                end_line_index=end_line_index,\n                colno=colno,\n                end_colno=end_colno,\n            )\n            lines.extend(s)\n            if short:\n                message = f\"in {entry.name}\"\n            else:\n                message = (excinfo and excinfo.typename) or \"\"\n            entry_path = entry.path\n            path = self._makepath(entry_path)\n            reprfileloc = ReprFileLocation(path, entry.lineno + 1, message)\n            localsrepr = self.repr_locals(entry.locals)\n            return ReprEntry(lines, reprargs, localsrepr, reprfileloc, style)\n        elif style == \"value\":\n            if excinfo:\n                lines.extend(str(excinfo.value).split(\"\\n\"))\n            return ReprEntry(lines, None, None, None, style)\n        else:\n            if excinfo:\n                lines.extend(self.get_exconly(excinfo, indent=4))\n            return ReprEntry(lines, None, None, None, style)\n\n    def _makepath(self, path: Path | str) -> str:\n        if not self.abspath and isinstance(path, Path):\n            try:\n                np = bestrelpath(Path.cwd(), path)\n            except OSError:\n                return str(path)\n            if len(np) < len(str(path)):\n                return np\n        return str(path)\n\n    def repr_traceback(self, excinfo: ExceptionInfo[BaseException]) -> ReprTraceback:\n        traceback = filter_excinfo_traceback(self.tbfilter, excinfo)\n\n        if isinstance(excinfo.value, RecursionError):\n            traceback, extraline = self._truncate_recursive_traceback(traceback)\n        else:\n            extraline = None\n\n        if not traceback:\n            if extraline is None:\n                extraline = \"All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames.\"\n            entries = [self.repr_traceback_entry(None, excinfo)]\n            return ReprTraceback(entries, extraline, style=self.style)\n\n        last = traceback[-1]\n        if self.style == \"value\":\n            entries = [self.repr_traceback_entry(last, excinfo)]\n            return ReprTraceback(entries, None, style=self.style)\n\n        entries = [\n            self.repr_traceback_entry(entry, excinfo if last == entry else None)\n            for entry in traceback\n        ]\n        return ReprTraceback(entries, extraline, style=self.style)\n\n    def _truncate_recursive_traceback(\n        self, traceback: Traceback\n    ) -> tuple[Traceback, str | None]:\n        \"\"\"Truncate the given recursive traceback trying to find the starting\n        point of the recursion.\n\n        The detection is done by going through each traceback entry and\n        finding the point in which the locals of the frame are equal to the\n        locals of a previous frame (see ``recursionindex()``).\n\n        Handle the situation where the recursion process might raise an\n        exception (for example comparing numpy arrays using equality raises a\n        TypeError), in which case we do our best to warn the user of the\n        error and show a limited traceback.\n        \"\"\"\n        try:\n            recursionindex = traceback.recursionindex()\n        except Exception as e:\n            max_frames = 10\n            extraline: str | None = (\n                \"!!! Recursion error detected, but an error occurred locating the origin of recursion.\\n\"\n                \"  The following exception happened when comparing locals in the stack frame:\\n\"\n                f\"    {type(e).__name__}: {e!s}\\n\"\n                f\"  Displaying first and last {max_frames} stack frames out of {len(traceback)}.\"\n            )\n            # Type ignored because adding two instances of a List subtype\n            # currently incorrectly has type List instead of the subtype.\n            traceback = traceback[:max_frames] + traceback[-max_frames:]  # type: ignore\n        else:\n            if recursionindex is not None:\n                extraline = \"!!! Recursion detected (same locals & position)\"\n                traceback = traceback[: recursionindex + 1]\n            else:\n                extraline = None\n\n        return traceback, extraline\n\n    def repr_excinfo(self, excinfo: ExceptionInfo[BaseException]) -> ExceptionChainRepr:\n        repr_chain: list[tuple[ReprTraceback, ReprFileLocation | None, str | None]] = []\n        e: BaseException | None = excinfo.value\n        excinfo_: ExceptionInfo[BaseException] | None = excinfo\n        descr = None\n        seen: set[int] = set()\n        while e is not None and id(e) not in seen:\n            seen.add(id(e))\n\n            if excinfo_:\n                # Fall back to native traceback as a temporary workaround until\n                # full support for exception groups added to ExceptionInfo.\n                # See https://github.com/pytest-dev/pytest/issues/9159\n                reprtraceback: ReprTraceback | ReprTracebackNative\n                if isinstance(e, BaseExceptionGroup):\n                    # don't filter any sub-exceptions since they shouldn't have any internal frames\n                    traceback = filter_excinfo_traceback(self.tbfilter, excinfo)\n                    reprtraceback = ReprTracebackNative(\n                        format_exception(\n                            type(excinfo.value),\n                            excinfo.value,\n                            traceback[0]._rawentry if traceback else None,\n                        )\n                    )\n                    if not traceback:\n                        reprtraceback.extraline = (\n                            \"All traceback entries are hidden. \"\n                            \"Pass `--full-trace` to see hidden and internal frames.\"\n                        )\n\n                else:\n                    reprtraceback = self.repr_traceback(excinfo_)\n                reprcrash = excinfo_._getreprcrash()\n            else:\n                # Fallback to native repr if the exception doesn't have a traceback:\n                # ExceptionInfo objects require a full traceback to work.\n                reprtraceback = ReprTracebackNative(format_exception(type(e), e, None))\n                reprcrash = None\n            repr_chain += [(reprtraceback, reprcrash, descr)]\n\n            if e.__cause__ is not None and self.chain:\n                e = e.__cause__\n                excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None\n                descr = \"The above exception was the direct cause of the following exception:\"\n            elif (\n                e.__context__ is not None and not e.__suppress_context__ and self.chain\n            ):\n                e = e.__context__\n                excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None\n                descr = \"During handling of the above exception, another exception occurred:\"\n            else:\n                e = None\n        repr_chain.reverse()\n        return ExceptionChainRepr(repr_chain)\n\n\n@dataclasses.dataclass(eq=False)\nclass TerminalRepr:\n    def __str__(self) -> str:\n        # FYI this is called from pytest-xdist's serialization of exception\n        # information.\n        io = StringIO()\n        tw = TerminalWriter(file=io)\n        self.toterminal(tw)\n        return io.getvalue().strip()\n\n    def __repr__(self) -> str:\n        return f\"<{self.__class__} instance at {id(self):0x}>\"\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        raise NotImplementedError()\n\n\n# This class is abstract -- only subclasses are instantiated.\n@dataclasses.dataclass(eq=False)\nclass ExceptionRepr(TerminalRepr):\n    # Provided by subclasses.\n    reprtraceback: ReprTraceback\n    reprcrash: ReprFileLocation | None\n    sections: list[tuple[str, str, str]] = dataclasses.field(\n        init=False, default_factory=list\n    )\n\n    def addsection(self, name: str, content: str, sep: str = \"-\") -> None:\n        self.sections.append((name, content, sep))\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        for name, content, sep in self.sections:\n            tw.sep(sep, name)\n            tw.line(content)\n\n\n@dataclasses.dataclass(eq=False)\nclass ExceptionChainRepr(ExceptionRepr):\n    chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]]\n\n    def __init__(\n        self,\n        chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]],\n    ) -> None:\n        # reprcrash and reprtraceback of the outermost (the newest) exception\n        # in the chain.\n        super().__init__(\n            reprtraceback=chain[-1][0],\n            reprcrash=chain[-1][1],\n        )\n        self.chain = chain\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        for element in self.chain:\n            element[0].toterminal(tw)\n            if element[2] is not None:\n                tw.line(\"\")\n                tw.line(element[2], yellow=True)\n        super().toterminal(tw)\n\n\n@dataclasses.dataclass(eq=False)\nclass ReprExceptionInfo(ExceptionRepr):\n    reprtraceback: ReprTraceback\n    reprcrash: ReprFileLocation | None\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        self.reprtraceback.toterminal(tw)\n        super().toterminal(tw)\n\n\n@dataclasses.dataclass(eq=False)\nclass ReprTraceback(TerminalRepr):\n    reprentries: Sequence[ReprEntry | ReprEntryNative]\n    extraline: str | None\n    style: TracebackStyle\n\n    entrysep: ClassVar = \"_ \"\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        # The entries might have different styles.\n        for i, entry in enumerate(self.reprentries):\n            if entry.style == \"long\":\n                tw.line(\"\")\n            entry.toterminal(tw)\n            if i < len(self.reprentries) - 1:\n                next_entry = self.reprentries[i + 1]\n                if entry.style == \"long\" or (\n                    entry.style == \"short\" and next_entry.style == \"long\"\n                ):\n                    tw.sep(self.entrysep)\n\n        if self.extraline:\n            tw.line(self.extraline)\n\n\nclass ReprTracebackNative(ReprTraceback):\n    def __init__(self, tblines: Sequence[str]) -> None:\n        self.reprentries = [ReprEntryNative(tblines)]\n        self.extraline = None\n        self.style = \"native\"\n\n\n@dataclasses.dataclass(eq=False)\nclass ReprEntryNative(TerminalRepr):\n    lines: Sequence[str]\n\n    style: ClassVar[TracebackStyle] = \"native\"\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        tw.write(\"\".join(self.lines))\n\n\n@dataclasses.dataclass(eq=False)\nclass ReprEntry(TerminalRepr):\n    lines: Sequence[str]\n    reprfuncargs: ReprFuncArgs | None\n    reprlocals: ReprLocals | None\n    reprfileloc: ReprFileLocation | None\n    style: TracebackStyle\n\n    def _write_entry_lines(self, tw: TerminalWriter) -> None:\n        \"\"\"Write the source code portions of a list of traceback entries with syntax highlighting.\n\n        Usually entries are lines like these:\n\n            \"     x = 1\"\n            \">    assert x == 2\"\n            \"E    assert 1 == 2\"\n\n        This function takes care of rendering the \"source\" portions of it (the lines without\n        the \"E\" prefix) using syntax highlighting, taking care to not highlighting the \">\"\n        character, as doing so might break line continuations.\n        \"\"\"\n        if not self.lines:\n            return\n\n        if self.style == \"value\":\n            # Using tw.write instead of tw.line for testing purposes due to TWMock implementation;\n            # lines written with TWMock.line and TWMock._write_source cannot be distinguished\n            # from each other, whereas lines written with TWMock.write are marked with TWMock.WRITE\n            for line in self.lines:\n                tw.write(line)\n                tw.write(\"\\n\")\n            return\n\n        # separate indents and source lines that are not failures: we want to\n        # highlight the code but not the indentation, which may contain markers\n        # such as \">   assert 0\"\n        fail_marker = f\"{FormattedExcinfo.fail_marker}   \"\n        indent_size = len(fail_marker)\n        indents: list[str] = []\n        source_lines: list[str] = []\n        failure_lines: list[str] = []\n        for index, line in enumerate(self.lines):\n            is_failure_line = line.startswith(fail_marker)\n            if is_failure_line:\n                # from this point on all lines are considered part of the failure\n                failure_lines.extend(self.lines[index:])\n                break\n            else:\n                indents.append(line[:indent_size])\n                source_lines.append(line[indent_size:])\n\n        tw._write_source(source_lines, indents)\n\n        # failure lines are always completely red and bold\n        for line in failure_lines:\n            tw.line(line, bold=True, red=True)\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        if self.style == \"short\":\n            if self.reprfileloc:\n                self.reprfileloc.toterminal(tw)\n            self._write_entry_lines(tw)\n            if self.reprlocals:\n                self.reprlocals.toterminal(tw, indent=\" \" * 8)\n            return\n\n        if self.reprfuncargs:\n            self.reprfuncargs.toterminal(tw)\n\n        self._write_entry_lines(tw)\n\n        if self.reprlocals:\n            tw.line(\"\")\n            self.reprlocals.toterminal(tw)\n        if self.reprfileloc:\n            if self.lines:\n                tw.line(\"\")\n            self.reprfileloc.toterminal(tw)\n\n    def __str__(self) -> str:\n        return \"{}\\n{}\\n{}\".format(\n            \"\\n\".join(self.lines), self.reprlocals, self.reprfileloc\n        )\n\n\n@dataclasses.dataclass(eq=False)\nclass ReprFileLocation(TerminalRepr):\n    path: str\n    lineno: int\n    message: str\n\n    def __post_init__(self) -> None:\n        self.path = str(self.path)\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        # Filename and lineno output for each entry, using an output format\n        # that most editors understand.\n        msg = self.message\n        i = msg.find(\"\\n\")\n        if i != -1:\n            msg = msg[:i]\n        tw.write(self.path, bold=True, red=True)\n        tw.line(f\":{self.lineno}: {msg}\")\n\n\n@dataclasses.dataclass(eq=False)\nclass ReprLocals(TerminalRepr):\n    lines: Sequence[str]\n\n    def toterminal(self, tw: TerminalWriter, indent=\"\") -> None:\n        for line in self.lines:\n            tw.line(indent + line)\n\n\n@dataclasses.dataclass(eq=False)\nclass ReprFuncArgs(TerminalRepr):\n    args: Sequence[tuple[str, object]]\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        if self.args:\n            linesofar = \"\"\n            for name, value in self.args:\n                ns = f\"{name} = {value}\"\n                if len(ns) + len(linesofar) + 2 > tw.fullwidth:\n                    if linesofar:\n                        tw.line(linesofar)\n                    linesofar = ns\n                else:\n                    if linesofar:\n                        linesofar += \", \" + ns\n                    else:\n                        linesofar = ns\n            if linesofar:\n                tw.line(linesofar)\n            tw.line(\"\")\n\n\ndef getfslineno(obj: object) -> tuple[str | Path, int]:\n    \"\"\"Return source location (path, lineno) for the given object.\n\n    If the source cannot be determined return (\"\", -1).\n\n    The line number is 0-based.\n    \"\"\"\n    # xxx let decorators etc specify a sane ordering\n    # NOTE: this used to be done in _pytest.compat.getfslineno, initially added\n    #       in 6ec13a2b9.  It (\"place_as\") appears to be something very custom.\n    obj = get_real_func(obj)\n    if hasattr(obj, \"place_as\"):\n        obj = obj.place_as\n\n    try:\n        code = Code.from_function(obj)\n    except TypeError:\n        try:\n            fn = inspect.getsourcefile(obj) or inspect.getfile(obj)  # type: ignore[arg-type]\n        except TypeError:\n            return \"\", -1\n\n        fspath = (fn and absolutepath(fn)) or \"\"\n        lineno = -1\n        if fspath:\n            try:\n                _, lineno = findsource(obj)\n            except OSError:\n                pass\n        return fspath, lineno\n\n    return code.path, code.firstlineno\n\n\ndef _byte_offset_to_character_offset(str, offset):\n    \"\"\"Converts a byte based offset in a string to a code-point.\"\"\"\n    as_utf8 = str.encode(\"utf-8\")\n    return len(as_utf8[:offset].decode(\"utf-8\", errors=\"replace\"))\n\n\n# Relative paths that we use to filter traceback entries from appearing to the user;\n# see filter_traceback.\n# note: if we need to add more paths than what we have now we should probably use a list\n# for better maintenance.\n\n_PLUGGY_DIR = Path(pluggy.__file__.rstrip(\"oc\"))\n# pluggy is either a package or a single module depending on the version\nif _PLUGGY_DIR.name == \"__init__.py\":\n    _PLUGGY_DIR = _PLUGGY_DIR.parent\n_PYTEST_DIR = Path(_pytest.__file__).parent\n\n\ndef filter_traceback(entry: TracebackEntry) -> bool:\n    \"\"\"Return True if a TracebackEntry instance should be included in tracebacks.\n\n    We hide traceback entries of:\n\n    * dynamically generated code (no code to show up for it);\n    * internal traceback from pytest or its internal libraries, py and pluggy.\n    \"\"\"\n    # entry.path might sometimes return a str object when the entry\n    # points to dynamically generated code.\n    # See https://bitbucket.org/pytest-dev/py/issues/71.\n    raw_filename = entry.frame.code.raw.co_filename\n    is_generated = \"<\" in raw_filename and \">\" in raw_filename\n    if is_generated:\n        return False\n\n    # entry.path might point to a non-existing file, in which case it will\n    # also return a str object. See #1133.\n    p = Path(entry.path)\n\n    parents = p.parents\n    if _PLUGGY_DIR in parents:\n        return False\n    if _PYTEST_DIR in parents:\n        return False\n\n    return True\n\n\ndef filter_excinfo_traceback(\n    tbfilter: TracebackFilter, excinfo: ExceptionInfo[BaseException]\n) -> Traceback:\n    \"\"\"Filter the exception traceback in ``excinfo`` according to ``tbfilter``.\"\"\"\n    if callable(tbfilter):\n        return tbfilter(excinfo)\n    elif tbfilter:\n        return excinfo.traceback.filter(excinfo)\n    else:\n        return excinfo.traceback\n"
  },
  {
    "path": "src/_pytest/_code/source.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport ast\nfrom bisect import bisect_right\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nimport inspect\nimport textwrap\nimport tokenize\nimport types\nfrom typing import overload\nimport warnings\n\n\nclass Source:\n    \"\"\"An immutable object holding a source code fragment.\n\n    When using Source(...), the source lines are deindented.\n    \"\"\"\n\n    def __init__(self, obj: object = None) -> None:\n        if not obj:\n            self.lines: list[str] = []\n            self.raw_lines: list[str] = []\n        elif isinstance(obj, Source):\n            self.lines = obj.lines\n            self.raw_lines = obj.raw_lines\n        elif isinstance(obj, tuple | list):\n            self.lines = deindent(x.rstrip(\"\\n\") for x in obj)\n            self.raw_lines = list(x.rstrip(\"\\n\") for x in obj)\n        elif isinstance(obj, str):\n            self.lines = deindent(obj.split(\"\\n\"))\n            self.raw_lines = obj.split(\"\\n\")\n        else:\n            try:\n                rawcode = getrawcode(obj)\n                src = inspect.getsource(rawcode)\n            except TypeError:\n                src = inspect.getsource(obj)  # type: ignore[arg-type]\n            self.lines = deindent(src.split(\"\\n\"))\n            self.raw_lines = src.split(\"\\n\")\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Source):\n            return NotImplemented\n        return self.lines == other.lines\n\n    # Ignore type because of https://github.com/python/mypy/issues/4266.\n    __hash__ = None  # type: ignore\n\n    @overload\n    def __getitem__(self, key: int) -> str: ...\n\n    @overload\n    def __getitem__(self, key: slice) -> Source: ...\n\n    def __getitem__(self, key: int | slice) -> str | Source:\n        if isinstance(key, int):\n            return self.lines[key]\n        else:\n            if key.step not in (None, 1):\n                raise IndexError(\"cannot slice a Source with a step\")\n            newsource = Source()\n            newsource.lines = self.lines[key.start : key.stop]\n            newsource.raw_lines = self.raw_lines[key.start : key.stop]\n            return newsource\n\n    def __iter__(self) -> Iterator[str]:\n        return iter(self.lines)\n\n    def __len__(self) -> int:\n        return len(self.lines)\n\n    def strip(self) -> Source:\n        \"\"\"Return new Source object with trailing and leading blank lines removed.\"\"\"\n        start, end = 0, len(self)\n        while start < end and not self.lines[start].strip():\n            start += 1\n        while end > start and not self.lines[end - 1].strip():\n            end -= 1\n        source = Source()\n        source.raw_lines = self.raw_lines\n        source.lines[:] = self.lines[start:end]\n        return source\n\n    def indent(self, indent: str = \" \" * 4) -> Source:\n        \"\"\"Return a copy of the source object with all lines indented by the\n        given indent-string.\"\"\"\n        newsource = Source()\n        newsource.raw_lines = self.raw_lines\n        newsource.lines = [(indent + line) for line in self.lines]\n        return newsource\n\n    def getstatement(self, lineno: int) -> Source:\n        \"\"\"Return Source statement which contains the given linenumber\n        (counted from 0).\"\"\"\n        start, end = self.getstatementrange(lineno)\n        return self[start:end]\n\n    def getstatementrange(self, lineno: int) -> tuple[int, int]:\n        \"\"\"Return (start, end) tuple which spans the minimal statement region\n        which containing the given lineno.\"\"\"\n        if not (0 <= lineno < len(self)):\n            raise IndexError(\"lineno out of range\")\n        _ast, start, end = getstatementrange_ast(lineno, self)\n        return start, end\n\n    def deindent(self) -> Source:\n        \"\"\"Return a new Source object deindented.\"\"\"\n        newsource = Source()\n        newsource.lines[:] = deindent(self.lines)\n        newsource.raw_lines = self.raw_lines\n        return newsource\n\n    def __str__(self) -> str:\n        return \"\\n\".join(self.lines)\n\n\n#\n# helper functions\n#\n\n\ndef findsource(obj) -> tuple[Source | None, int]:\n    try:\n        sourcelines, lineno = inspect.findsource(obj)\n    except Exception:\n        return None, -1\n    source = Source()\n    source.lines = [line.rstrip() for line in sourcelines]\n    source.raw_lines = sourcelines\n    return source, lineno\n\n\ndef getrawcode(obj: object, trycall: bool = True) -> types.CodeType:\n    \"\"\"Return code object for given function.\"\"\"\n    try:\n        return obj.__code__  # type: ignore[attr-defined,no-any-return]\n    except AttributeError:\n        pass\n    if trycall:\n        call = getattr(obj, \"__call__\", None)\n        if call and not isinstance(obj, type):\n            return getrawcode(call, trycall=False)\n    raise TypeError(f\"could not get code object for {obj!r}\")\n\n\ndef deindent(lines: Iterable[str]) -> list[str]:\n    return textwrap.dedent(\"\\n\".join(lines)).splitlines()\n\n\ndef get_statement_startend2(lineno: int, node: ast.AST) -> tuple[int, int | None]:\n    # Flatten all statements and except handlers into one lineno-list.\n    # AST's line numbers start indexing at 1.\n    values: list[int] = []\n    for x in ast.walk(node):\n        if isinstance(x, ast.stmt | ast.ExceptHandler):\n            # The lineno points to the class/def, so need to include the decorators.\n            if isinstance(x, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef):\n                for d in x.decorator_list:\n                    values.append(d.lineno - 1)\n            values.append(x.lineno - 1)\n            for name in (\"finalbody\", \"orelse\"):\n                val: list[ast.stmt] | None = getattr(x, name, None)\n                if val:\n                    # Treat the finally/orelse part as its own statement.\n                    values.append(val[0].lineno - 1 - 1)\n    values.sort()\n    insert_index = bisect_right(values, lineno)\n    if insert_index == 0:\n        return 0, None\n    start = values[insert_index - 1]\n    if insert_index >= len(values):\n        end = None\n    else:\n        end = values[insert_index]\n    return start, end\n\n\ndef getstatementrange_ast(\n    lineno: int,\n    source: Source,\n    assertion: bool = False,\n    astnode: ast.AST | None = None,\n) -> tuple[ast.AST, int, int]:\n    if astnode is None:\n        content = str(source)\n        # See #4260:\n        # Don't produce duplicate warnings when compiling source to find AST.\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            astnode = ast.parse(content, \"source\", \"exec\")\n\n    start, end = get_statement_startend2(lineno, astnode)\n    # We need to correct the end:\n    # - ast-parsing strips comments\n    # - there might be empty lines\n    # - we might have lesser indented code blocks at the end\n    if end is None:\n        end = len(source.lines)\n\n    if end > start + 1:\n        # Make sure we don't span differently indented code blocks\n        # by using the BlockFinder helper used which inspect.getsource() uses itself.\n        block_finder = inspect.BlockFinder()\n        # If we start with an indented line, put blockfinder to \"started\" mode.\n        block_finder.started = (\n            bool(source.lines[start]) and source.lines[start][0].isspace()\n        )\n        it = ((x + \"\\n\") for x in source.lines[start:end])\n        try:\n            for tok in tokenize.generate_tokens(lambda: next(it)):\n                block_finder.tokeneater(*tok)\n        except (inspect.EndOfBlock, IndentationError):\n            end = block_finder.last + start\n        except Exception:\n            pass\n\n    # The end might still point to a comment or empty line, correct it.\n    end = min(end, len(source.lines))\n    while end:\n        line = source.lines[end - 1].lstrip()\n        if line.startswith(\"#\") or not line:\n            end -= 1\n        else:\n            break\n    return astnode, start, end\n"
  },
  {
    "path": "src/_pytest/_io/__init__.py",
    "content": "from __future__ import annotations\n\nfrom .terminalwriter import get_terminal_width\nfrom .terminalwriter import TerminalWriter\n\n\n__all__ = [\n    \"TerminalWriter\",\n    \"get_terminal_width\",\n]\n"
  },
  {
    "path": "src/_pytest/_io/pprint.py",
    "content": "# mypy: allow-untyped-defs\n# This module was imported from the cpython standard library\n# (https://github.com/python/cpython/) at commit\n# c5140945c723ae6c4b7ee81ff720ac8ea4b52cfd (python3.12).\n#\n#\n#  Original Author:      Fred L. Drake, Jr.\n#                        fdrake@acm.org\n#\n#  This is a simple little module I wrote to make life easier.  I didn't\n#  see anything quite like it in the library, though I may have overlooked\n#  something.  I wrote this when I was trying to read some heavily nested\n#  tuples with fairly non-descriptive content.  This is modeled very much\n#  after Lisp/Scheme - style pretty-printing of lists.  If you find it\n#  useful, thank small children who sleep at night.\nfrom __future__ import annotations\n\nimport collections as _collections\nfrom collections.abc import Callable\nfrom collections.abc import Iterator\nimport dataclasses as _dataclasses\nfrom io import StringIO as _StringIO\nimport re\nimport types as _types\nfrom typing import Any\nfrom typing import IO\n\n\nclass _safe_key:\n    \"\"\"Helper function for key functions when sorting unorderable objects.\n\n    The wrapped-object will fallback to a Py2.x style comparison for\n    unorderable types (sorting first comparing the type name and then by\n    the obj ids).  Does not work recursively, so dict.items() must have\n    _safe_key applied to both the key and the value.\n\n    \"\"\"\n\n    __slots__ = [\"obj\"]\n\n    def __init__(self, obj):\n        self.obj = obj\n\n    def __lt__(self, other):\n        try:\n            return self.obj < other.obj\n        except TypeError:\n            return (str(type(self.obj)), id(self.obj)) < (\n                str(type(other.obj)),\n                id(other.obj),\n            )\n\n\ndef _safe_tuple(t):\n    \"\"\"Helper function for comparing 2-tuples\"\"\"\n    return _safe_key(t[0]), _safe_key(t[1])\n\n\nclass PrettyPrinter:\n    def __init__(\n        self,\n        indent: int = 4,\n        width: int = 80,\n        depth: int | None = None,\n    ) -> None:\n        \"\"\"Handle pretty printing operations onto a stream using a set of\n        configured parameters.\n\n        indent\n            Number of spaces to indent for each level of nesting.\n\n        width\n            Attempted maximum number of columns in the output.\n\n        depth\n            The maximum depth to print out nested structures.\n\n        \"\"\"\n        if indent < 0:\n            raise ValueError(\"indent must be >= 0\")\n        if depth is not None and depth <= 0:\n            raise ValueError(\"depth must be > 0\")\n        if not width:\n            raise ValueError(\"width must be != 0\")\n        self._depth = depth\n        self._indent_per_level = indent\n        self._width = width\n\n    def pformat(self, object: Any) -> str:\n        sio = _StringIO()\n        self._format(object, sio, 0, 0, set(), 0)\n        return sio.getvalue()\n\n    def _format(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        objid = id(object)\n        if objid in context:\n            stream.write(_recursion(object))\n            return\n\n        p = self._dispatch.get(type(object).__repr__, None)\n        if p is not None:\n            context.add(objid)\n            p(self, object, stream, indent, allowance, context, level + 1)\n            context.remove(objid)\n        elif (\n            _dataclasses.is_dataclass(object)\n            and not isinstance(object, type)\n            and object.__dataclass_params__.repr  # type:ignore[attr-defined]\n            and\n            # Check dataclass has generated repr method.\n            hasattr(object.__repr__, \"__wrapped__\")\n            and \"__create_fn__\" in object.__repr__.__wrapped__.__qualname__\n        ):\n            context.add(objid)\n            self._pprint_dataclass(\n                object, stream, indent, allowance, context, level + 1\n            )\n            context.remove(objid)\n        else:\n            stream.write(self._repr(object, context, level))\n\n    def _pprint_dataclass(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        cls_name = object.__class__.__name__\n        items = [\n            (f.name, getattr(object, f.name))\n            for f in _dataclasses.fields(object)\n            if f.repr\n        ]\n        stream.write(cls_name + \"(\")\n        self._format_namespace_items(items, stream, indent, allowance, context, level)\n        stream.write(\")\")\n\n    _dispatch: dict[\n        Callable[..., str],\n        Callable[[PrettyPrinter, Any, IO[str], int, int, set[int], int], None],\n    ] = {}\n\n    def _pprint_dict(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        write = stream.write\n        write(\"{\")\n        items = object.items()\n        self._format_dict_items(items, stream, indent, allowance, context, level)\n        write(\"}\")\n\n    _dispatch[dict.__repr__] = _pprint_dict\n\n    def _pprint_ordered_dict(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        if not len(object):\n            stream.write(repr(object))\n            return\n        cls = object.__class__\n        stream.write(cls.__name__ + \"(\")\n        self._pprint_dict(object, stream, indent, allowance, context, level)\n        stream.write(\")\")\n\n    _dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict\n\n    def _pprint_list(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        stream.write(\"[\")\n        self._format_items(object, stream, indent, allowance, context, level)\n        stream.write(\"]\")\n\n    _dispatch[list.__repr__] = _pprint_list\n\n    def _pprint_tuple(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        stream.write(\"(\")\n        self._format_items(object, stream, indent, allowance, context, level)\n        stream.write(\")\")\n\n    _dispatch[tuple.__repr__] = _pprint_tuple\n\n    def _pprint_set(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        if not len(object):\n            stream.write(repr(object))\n            return\n        typ = object.__class__\n        if typ is set:\n            stream.write(\"{\")\n            endchar = \"}\"\n        else:\n            stream.write(typ.__name__ + \"({\")\n            endchar = \"})\"\n        object = sorted(object, key=_safe_key)\n        self._format_items(object, stream, indent, allowance, context, level)\n        stream.write(endchar)\n\n    _dispatch[set.__repr__] = _pprint_set\n    _dispatch[frozenset.__repr__] = _pprint_set\n\n    def _pprint_str(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        write = stream.write\n        if not len(object):\n            write(repr(object))\n            return\n        chunks = []\n        lines = object.splitlines(True)\n        if level == 1:\n            indent += 1\n            allowance += 1\n        max_width1 = max_width = self._width - indent\n        for i, line in enumerate(lines):\n            rep = repr(line)\n            if i == len(lines) - 1:\n                max_width1 -= allowance\n            if len(rep) <= max_width1:\n                chunks.append(rep)\n            else:\n                # A list of alternating (non-space, space) strings\n                parts = re.findall(r\"\\S*\\s*\", line)\n                assert parts\n                assert not parts[-1]\n                parts.pop()  # drop empty last part\n                max_width2 = max_width\n                current = \"\"\n                for j, part in enumerate(parts):\n                    candidate = current + part\n                    if j == len(parts) - 1 and i == len(lines) - 1:\n                        max_width2 -= allowance\n                    if len(repr(candidate)) > max_width2:\n                        if current:\n                            chunks.append(repr(current))\n                        current = part\n                    else:\n                        current = candidate\n                if current:\n                    chunks.append(repr(current))\n        if len(chunks) == 1:\n            write(rep)\n            return\n        if level == 1:\n            write(\"(\")\n        for i, rep in enumerate(chunks):\n            if i > 0:\n                write(\"\\n\" + \" \" * indent)\n            write(rep)\n        if level == 1:\n            write(\")\")\n\n    _dispatch[str.__repr__] = _pprint_str\n\n    def _pprint_bytes(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        write = stream.write\n        if len(object) <= 4:\n            write(repr(object))\n            return\n        parens = level == 1\n        if parens:\n            indent += 1\n            allowance += 1\n            write(\"(\")\n        delim = \"\"\n        for rep in _wrap_bytes_repr(object, self._width - indent, allowance):\n            write(delim)\n            write(rep)\n            if not delim:\n                delim = \"\\n\" + \" \" * indent\n        if parens:\n            write(\")\")\n\n    _dispatch[bytes.__repr__] = _pprint_bytes\n\n    def _pprint_bytearray(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        write = stream.write\n        write(\"bytearray(\")\n        self._pprint_bytes(\n            bytes(object), stream, indent + 10, allowance + 1, context, level + 1\n        )\n        write(\")\")\n\n    _dispatch[bytearray.__repr__] = _pprint_bytearray\n\n    def _pprint_mappingproxy(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        stream.write(\"mappingproxy(\")\n        self._format(object.copy(), stream, indent, allowance, context, level)\n        stream.write(\")\")\n\n    _dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy\n\n    def _pprint_simplenamespace(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        if type(object) is _types.SimpleNamespace:\n            # The SimpleNamespace repr is \"namespace\" instead of the class\n            # name, so we do the same here. For subclasses; use the class name.\n            cls_name = \"namespace\"\n        else:\n            cls_name = object.__class__.__name__\n        items = object.__dict__.items()\n        stream.write(cls_name + \"(\")\n        self._format_namespace_items(items, stream, indent, allowance, context, level)\n        stream.write(\")\")\n\n    _dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace\n\n    def _format_dict_items(\n        self,\n        items: list[tuple[Any, Any]],\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        if not items:\n            return\n\n        write = stream.write\n        item_indent = indent + self._indent_per_level\n        delimnl = \"\\n\" + \" \" * item_indent\n        for key, ent in items:\n            write(delimnl)\n            write(self._repr(key, context, level))\n            write(\": \")\n            self._format(ent, stream, item_indent, 1, context, level)\n            write(\",\")\n\n        write(\"\\n\" + \" \" * indent)\n\n    def _format_namespace_items(\n        self,\n        items: list[tuple[Any, Any]],\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        if not items:\n            return\n\n        write = stream.write\n        item_indent = indent + self._indent_per_level\n        delimnl = \"\\n\" + \" \" * item_indent\n        for key, ent in items:\n            write(delimnl)\n            write(key)\n            write(\"=\")\n            if id(ent) in context:\n                # Special-case representation of recursion to match standard\n                # recursive dataclass repr.\n                write(\"...\")\n            else:\n                self._format(\n                    ent,\n                    stream,\n                    item_indent + len(key) + 1,\n                    1,\n                    context,\n                    level,\n                )\n\n            write(\",\")\n\n        write(\"\\n\" + \" \" * indent)\n\n    def _format_items(\n        self,\n        items: list[Any],\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        if not items:\n            return\n\n        write = stream.write\n        item_indent = indent + self._indent_per_level\n        delimnl = \"\\n\" + \" \" * item_indent\n\n        for item in items:\n            write(delimnl)\n            self._format(item, stream, item_indent, 1, context, level)\n            write(\",\")\n\n        write(\"\\n\" + \" \" * indent)\n\n    def _repr(self, object: Any, context: set[int], level: int) -> str:\n        return self._safe_repr(object, context.copy(), self._depth, level)\n\n    def _pprint_default_dict(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        rdf = self._repr(object.default_factory, context, level)\n        stream.write(f\"{object.__class__.__name__}({rdf}, \")\n        self._pprint_dict(object, stream, indent, allowance, context, level)\n        stream.write(\")\")\n\n    _dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict\n\n    def _pprint_counter(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        stream.write(object.__class__.__name__ + \"(\")\n\n        if object:\n            stream.write(\"{\")\n            items = object.most_common()\n            self._format_dict_items(items, stream, indent, allowance, context, level)\n            stream.write(\"}\")\n\n        stream.write(\")\")\n\n    _dispatch[_collections.Counter.__repr__] = _pprint_counter\n\n    def _pprint_chain_map(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        if not len(object.maps) or (len(object.maps) == 1 and not len(object.maps[0])):\n            stream.write(repr(object))\n            return\n\n        stream.write(object.__class__.__name__ + \"(\")\n        self._format_items(object.maps, stream, indent, allowance, context, level)\n        stream.write(\")\")\n\n    _dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map\n\n    def _pprint_deque(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        stream.write(object.__class__.__name__ + \"(\")\n        if object.maxlen is not None:\n            stream.write(f\"maxlen={object.maxlen}, \")\n        stream.write(\"[\")\n\n        self._format_items(object, stream, indent, allowance + 1, context, level)\n        stream.write(\"])\")\n\n    _dispatch[_collections.deque.__repr__] = _pprint_deque\n\n    def _pprint_user_dict(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        self._format(object.data, stream, indent, allowance, context, level - 1)\n\n    _dispatch[_collections.UserDict.__repr__] = _pprint_user_dict\n\n    def _pprint_user_list(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        self._format(object.data, stream, indent, allowance, context, level - 1)\n\n    _dispatch[_collections.UserList.__repr__] = _pprint_user_list\n\n    def _pprint_user_string(\n        self,\n        object: Any,\n        stream: IO[str],\n        indent: int,\n        allowance: int,\n        context: set[int],\n        level: int,\n    ) -> None:\n        self._format(object.data, stream, indent, allowance, context, level - 1)\n\n    _dispatch[_collections.UserString.__repr__] = _pprint_user_string\n\n    def _safe_repr(\n        self, object: Any, context: set[int], maxlevels: int | None, level: int\n    ) -> str:\n        typ = type(object)\n        if typ in _builtin_scalars:\n            return repr(object)\n\n        r = getattr(typ, \"__repr__\", None)\n\n        if issubclass(typ, dict) and r is dict.__repr__:\n            if not object:\n                return \"{}\"\n            objid = id(object)\n            if maxlevels and level >= maxlevels:\n                return \"{...}\"\n            if objid in context:\n                return _recursion(object)\n            context.add(objid)\n            components: list[str] = []\n            append = components.append\n            level += 1\n            for k, v in object.items():\n                krepr = self._safe_repr(k, context, maxlevels, level)\n                vrepr = self._safe_repr(v, context, maxlevels, level)\n                append(f\"{krepr}: {vrepr}\")\n            context.remove(objid)\n            return \"{{{}}}\".format(\", \".join(components))\n\n        if (issubclass(typ, list) and r is list.__repr__) or (\n            issubclass(typ, tuple) and r is tuple.__repr__\n        ):\n            if issubclass(typ, list):\n                if not object:\n                    return \"[]\"\n                format = \"[%s]\"\n            elif len(object) == 1:\n                format = \"(%s,)\"\n            else:\n                if not object:\n                    return \"()\"\n                format = \"(%s)\"\n            objid = id(object)\n            if maxlevels and level >= maxlevels:\n                return format % \"...\"\n            if objid in context:\n                return _recursion(object)\n            context.add(objid)\n            components = []\n            append = components.append\n            level += 1\n            for o in object:\n                orepr = self._safe_repr(o, context, maxlevels, level)\n                append(orepr)\n            context.remove(objid)\n            return format % \", \".join(components)\n\n        return repr(object)\n\n\n_builtin_scalars = frozenset(\n    {str, bytes, bytearray, float, complex, bool, type(None), int}\n)\n\n\ndef _recursion(object: Any) -> str:\n    return f\"<Recursion on {type(object).__name__} with id={id(object)}>\"\n\n\ndef _wrap_bytes_repr(object: Any, width: int, allowance: int) -> Iterator[str]:\n    current = b\"\"\n    last = len(object) // 4 * 4\n    for i in range(0, len(object), 4):\n        part = object[i : i + 4]\n        candidate = current + part\n        if i == last:\n            width -= allowance\n        if len(repr(candidate)) > width:\n            if current:\n                yield repr(current)\n            current = part\n        else:\n            current = candidate\n    if current:\n        yield repr(current)\n"
  },
  {
    "path": "src/_pytest/_io/saferepr.py",
    "content": "from __future__ import annotations\n\nfrom itertools import islice\nimport pprint\nimport reprlib\n\n\ndef _try_repr_or_str(obj: object) -> str:\n    try:\n        return repr(obj)\n    except (KeyboardInterrupt, SystemExit):\n        raise\n    except BaseException:\n        return f'{type(obj).__name__}(\"{obj}\")'\n\n\ndef _format_repr_exception(exc: BaseException, obj: object) -> str:\n    try:\n        exc_info = _try_repr_or_str(exc)\n    except (KeyboardInterrupt, SystemExit):\n        raise\n    except BaseException as inner_exc:\n        exc_info = f\"unpresentable exception ({_try_repr_or_str(inner_exc)})\"\n    return (\n        f\"<[{exc_info} raised in repr()] {type(obj).__name__} object at 0x{id(obj):x}>\"\n    )\n\n\ndef _ellipsize(s: str, maxsize: int) -> str:\n    if len(s) > maxsize:\n        i = max(0, (maxsize - 3) // 2)\n        j = max(0, maxsize - 3 - i)\n        return s[:i] + \"...\" + s[len(s) - j :]\n    return s\n\n\nclass SafeRepr(reprlib.Repr):\n    \"\"\"\n    repr.Repr that limits the resulting size of repr() and includes\n    information on exceptions raised during the call.\n    \"\"\"\n\n    def __init__(self, maxsize: int | None, use_ascii: bool = False) -> None:\n        \"\"\"\n        :param maxsize:\n            If not None, will truncate the resulting repr to that specific size, using ellipsis\n            somewhere in the middle to hide the extra text.\n            If None, will not impose any size limits on the returning repr.\n        \"\"\"\n        super().__init__()\n        # ``maxstring`` is used by the superclass, and needs to be an int; using a\n        # very large number in case maxsize is None, meaning we want to disable\n        # truncation.\n        self.maxstring = maxsize if maxsize is not None else 1_000_000_000\n        self.maxsize = maxsize\n        self.use_ascii = use_ascii\n\n    def repr(self, x: object) -> str:\n        try:\n            if self.use_ascii:\n                s = ascii(x)\n            else:\n                s = super().repr(x)\n        except (KeyboardInterrupt, SystemExit):\n            raise\n        except BaseException as exc:\n            s = _format_repr_exception(exc, x)\n        if self.maxsize is not None:\n            s = _ellipsize(s, self.maxsize)\n        return s\n\n    def repr_instance(self, x: object, level: int) -> str:\n        try:\n            s = repr(x)\n        except (KeyboardInterrupt, SystemExit):\n            raise\n        except BaseException as exc:\n            s = _format_repr_exception(exc, x)\n        if self.maxsize is not None:\n            s = _ellipsize(s, self.maxsize)\n\n        return s\n\n    def repr_dict(self, x: dict[object, object], level: int) -> str:\n        \"\"\"Represent a dict while preserving its insertion order.\n\n        Differs from ``reprlib.Repr.repr_dict`` by iterating directly over ``x``\n        rather than using the stdlib's sorting helper.\n        \"\"\"\n        fillvalue = \"...\"\n        n = len(x)\n        if n == 0:\n            return \"{}\"\n        if level <= 0:\n            return \"{\" + fillvalue + \"}\"\n        newlevel = level - 1\n        repr1 = self.repr1\n        pieces = []\n        for key in islice(x, self.maxdict):\n            keyrepr = repr1(key, newlevel)\n            valrepr = repr1(x[key], newlevel)\n            pieces.append(f\"{keyrepr}: {valrepr}\")\n        if n > self.maxdict:\n            pieces.append(fillvalue)\n        return \"{\" + \", \".join(pieces) + \"}\"\n\n\ndef safeformat(obj: object) -> str:\n    \"\"\"Return a pretty printed string for the given object.\n\n    Failing __repr__ functions of user instances will be represented\n    with a short exception info.\n    \"\"\"\n    try:\n        return pprint.pformat(obj)\n    except Exception as exc:\n        return _format_repr_exception(exc, obj)\n\n\n# Maximum size of overall repr of objects to display during assertion errors.\nDEFAULT_REPR_MAX_SIZE = 240\n\n\ndef saferepr(\n    obj: object, maxsize: int | None = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False\n) -> str:\n    \"\"\"Return a size-limited safe repr-string for the given object.\n\n    Failing __repr__ functions of user instances will be represented\n    with a short exception info and 'saferepr' generally takes\n    care to never raise exceptions itself.\n\n    This function is a wrapper around the Repr/reprlib functionality of the\n    stdlib.\n    \"\"\"\n    return SafeRepr(maxsize, use_ascii).repr(obj)\n\n\ndef saferepr_unlimited(obj: object, use_ascii: bool = True) -> str:\n    \"\"\"Return an unlimited-size safe repr-string for the given object.\n\n    As with saferepr, failing __repr__ functions of user instances\n    will be represented with a short exception info.\n\n    This function is a wrapper around simple repr.\n\n    Note: a cleaner solution would be to alter ``saferepr``this way\n    when maxsize=None, but that might affect some other code.\n    \"\"\"\n    try:\n        if use_ascii:\n            return ascii(obj)\n        return repr(obj)\n    except Exception as exc:\n        return _format_repr_exception(exc, obj)\n"
  },
  {
    "path": "src/_pytest/_io/terminalwriter.py",
    "content": "\"\"\"Helper functions for writing to terminals and files.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nimport os\nimport shutil\nimport sys\nfrom typing import final\nfrom typing import Literal\nfrom typing import TextIO\n\nimport pygments\nfrom pygments.formatters.terminal import TerminalFormatter\nfrom pygments.lexer import Lexer\nfrom pygments.lexers.diff import DiffLexer\nfrom pygments.lexers.python import PythonLexer\n\nfrom ..compat import assert_never\nfrom .wcwidth import wcswidth\n\n\n# This code was initially copied from py 1.8.1, file _io/terminalwriter.py.\n\n\ndef get_terminal_width() -> int:\n    width, _ = shutil.get_terminal_size(fallback=(80, 24))\n\n    # The Windows get_terminal_size may be bogus, let's sanify a bit.\n    if width < 40:\n        width = 80\n\n    return width\n\n\ndef should_do_markup(file: TextIO) -> bool:\n    if os.environ.get(\"PY_COLORS\") == \"1\":\n        return True\n    if os.environ.get(\"PY_COLORS\") == \"0\":\n        return False\n    if os.environ.get(\"NO_COLOR\"):\n        return False\n    if os.environ.get(\"FORCE_COLOR\"):\n        return True\n    return (\n        hasattr(file, \"isatty\") and file.isatty() and os.environ.get(\"TERM\") != \"dumb\"\n    )\n\n\n@final\nclass TerminalWriter:\n    _esctable = dict(\n        black=30,\n        red=31,\n        green=32,\n        yellow=33,\n        blue=34,\n        purple=35,\n        cyan=36,\n        white=37,\n        Black=40,\n        Red=41,\n        Green=42,\n        Yellow=43,\n        Blue=44,\n        Purple=45,\n        Cyan=46,\n        White=47,\n        bold=1,\n        light=2,\n        blink=5,\n        invert=7,\n    )\n\n    def __init__(self, file: TextIO | None = None) -> None:\n        if file is None:\n            file = sys.stdout\n        if hasattr(file, \"isatty\") and file.isatty() and sys.platform == \"win32\":\n            try:\n                import colorama\n            except ImportError:\n                pass\n            else:\n                file = colorama.AnsiToWin32(file).stream\n                assert file is not None\n        self._file = file\n        self.hasmarkup = should_do_markup(file)\n        self._current_line = \"\"\n        self._terminal_width: int | None = None\n        self.code_highlight = True\n\n    @property\n    def fullwidth(self) -> int:\n        if self._terminal_width is not None:\n            return self._terminal_width\n        return get_terminal_width()\n\n    @fullwidth.setter\n    def fullwidth(self, value: int) -> None:\n        self._terminal_width = value\n\n    @property\n    def width_of_current_line(self) -> int:\n        \"\"\"Return an estimate of the width so far in the current line.\"\"\"\n        return wcswidth(self._current_line)\n\n    def markup(self, text: str, **markup: bool) -> str:\n        for name in markup:\n            if name not in self._esctable:\n                raise ValueError(f\"unknown markup: {name!r}\")\n        if self.hasmarkup:\n            esc = [self._esctable[name] for name, on in markup.items() if on]\n            if esc:\n                text = \"\".join(f\"\\x1b[{cod}m\" for cod in esc) + text + \"\\x1b[0m\"\n        return text\n\n    def sep(\n        self,\n        sepchar: str,\n        title: str | None = None,\n        fullwidth: int | None = None,\n        **markup: bool,\n    ) -> None:\n        if fullwidth is None:\n            fullwidth = self.fullwidth\n        # The goal is to have the line be as long as possible\n        # under the condition that len(line) <= fullwidth.\n        if sys.platform == \"win32\":\n            # If we print in the last column on windows we are on a\n            # new line but there is no way to verify/neutralize this\n            # (we may not know the exact line width).\n            # So let's be defensive to avoid empty lines in the output.\n            fullwidth -= 1\n        if title is not None:\n            # we want 2 + 2*len(fill) + len(title) <= fullwidth\n            # i.e.    2 + 2*len(sepchar)*N + len(title) <= fullwidth\n            #         2*len(sepchar)*N <= fullwidth - len(title) - 2\n            #         N <= (fullwidth - len(title) - 2) // (2*len(sepchar))\n            N = max((fullwidth - len(title) - 2) // (2 * len(sepchar)), 1)\n            fill = sepchar * N\n            line = f\"{fill} {title} {fill}\"\n        else:\n            # we want len(sepchar)*N <= fullwidth\n            # i.e.    N <= fullwidth // len(sepchar)\n            line = sepchar * (fullwidth // len(sepchar))\n        # In some situations there is room for an extra sepchar at the right,\n        # in particular if we consider that with a sepchar like \"_ \" the\n        # trailing space is not important at the end of the line.\n        if len(line) + len(sepchar.rstrip()) <= fullwidth:\n            line += sepchar.rstrip()\n\n        self.line(line, **markup)\n\n    def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None:\n        if msg:\n            current_line = msg.rsplit(\"\\n\", 1)[-1]\n            if \"\\n\" in msg:\n                self._current_line = current_line\n            else:\n                self._current_line += current_line\n\n            msg = self.markup(msg, **markup)\n\n            self.write_raw(msg, flush=flush)\n\n    def write_raw(self, msg: str, *, flush: bool = False) -> None:\n        try:\n            self._file.write(msg)\n        except UnicodeEncodeError:\n            # Some environments don't support printing general Unicode\n            # strings, due to misconfiguration or otherwise; in that case,\n            # print the string escaped to ASCII.\n            # When the Unicode situation improves we should consider\n            # letting the error propagate instead of masking it (see #7475\n            # for one brief attempt).\n            msg = msg.encode(\"unicode-escape\").decode(\"ascii\")\n            self._file.write(msg)\n\n        if flush:\n            self.flush()\n\n    def line(self, s: str = \"\", **markup: bool) -> None:\n        self.write(s, **markup)\n        self.write(\"\\n\")\n\n    def flush(self) -> None:\n        self._file.flush()\n\n    def _write_source(self, lines: Sequence[str], indents: Sequence[str] = ()) -> None:\n        \"\"\"Write lines of source code possibly highlighted.\n\n        Keeping this private for now because the API is clunky. We should discuss how\n        to evolve the terminal writer so we can have more precise color support, for example\n        being able to write part of a line in one color and the rest in another, and so on.\n        \"\"\"\n        if indents and len(indents) != len(lines):\n            raise ValueError(\n                f\"indents size ({len(indents)}) should have same size as lines ({len(lines)})\"\n            )\n        if not indents:\n            indents = [\"\"] * len(lines)\n        source = \"\\n\".join(lines)\n        new_lines = self._highlight(source).splitlines()\n        # Would be better to strict=True but that fails some CI jobs.\n        for indent, new_line in zip(indents, new_lines, strict=False):\n            self.line(indent + new_line)\n\n    def _get_pygments_lexer(self, lexer: Literal[\"python\", \"diff\"]) -> Lexer:\n        if lexer == \"python\":\n            return PythonLexer()\n        elif lexer == \"diff\":\n            return DiffLexer()\n        else:\n            assert_never(lexer)\n\n    def _get_pygments_formatter(self) -> TerminalFormatter:\n        from _pytest.config.exceptions import UsageError\n\n        theme = os.getenv(\"PYTEST_THEME\")\n        theme_mode = os.getenv(\"PYTEST_THEME_MODE\", \"dark\")\n\n        try:\n            return TerminalFormatter(bg=theme_mode, style=theme)\n        except pygments.util.ClassNotFound as e:\n            raise UsageError(\n                f\"PYTEST_THEME environment variable has an invalid value: '{theme}'. \"\n                \"Hint: See available pygments styles with `pygmentize -L styles`.\"\n            ) from e\n        except pygments.util.OptionError as e:\n            raise UsageError(\n                f\"PYTEST_THEME_MODE environment variable has an invalid value: '{theme_mode}'. \"\n                \"The allowed values are 'dark' (default) and 'light'.\"\n            ) from e\n\n    def _highlight(\n        self, source: str, lexer: Literal[\"diff\", \"python\"] = \"python\"\n    ) -> str:\n        \"\"\"Highlight the given source if we have markup support.\"\"\"\n        if not source or not self.hasmarkup or not self.code_highlight:\n            return source\n\n        pygments_lexer = self._get_pygments_lexer(lexer)\n        pygments_formatter = self._get_pygments_formatter()\n\n        highlighted: str = pygments.highlight(\n            source, pygments_lexer, pygments_formatter\n        )\n        # pygments terminal formatter may add a newline when there wasn't one.\n        # We don't want this, remove.\n        if highlighted[-1] == \"\\n\" and source[-1] != \"\\n\":\n            highlighted = highlighted[:-1]\n\n        # Some lexers will not set the initial color explicitly\n        # which may lead to the previous color being propagated to the\n        # start of the expression, so reset first.\n        highlighted = \"\\x1b[0m\" + highlighted\n\n        return highlighted\n"
  },
  {
    "path": "src/_pytest/_io/wcwidth.py",
    "content": "from __future__ import annotations\n\nfrom functools import lru_cache\nimport unicodedata\n\n\n@lru_cache(100)\ndef wcwidth(c: str) -> int:\n    \"\"\"Determine how many columns are needed to display a character in a terminal.\n\n    Returns -1 if the character is not printable.\n    Returns 0, 1 or 2 for other characters.\n    \"\"\"\n    o = ord(c)\n\n    # ASCII fast path.\n    if 0x20 <= o < 0x07F:\n        return 1\n\n    # Some Cf/Zp/Zl characters which should be zero-width.\n    if (\n        o == 0x0000\n        or 0x200B <= o <= 0x200F\n        or 0x2028 <= o <= 0x202E\n        or 0x2060 <= o <= 0x2063\n    ):\n        return 0\n\n    category = unicodedata.category(c)\n\n    # Control characters.\n    if category == \"Cc\":\n        return -1\n\n    # Combining characters with zero width.\n    if category in (\"Me\", \"Mn\"):\n        return 0\n\n    # Full/Wide east asian characters.\n    if unicodedata.east_asian_width(c) in (\"F\", \"W\"):\n        return 2\n\n    return 1\n\n\ndef wcswidth(s: str) -> int:\n    \"\"\"Determine how many columns are needed to display a string in a terminal.\n\n    Returns -1 if the string contains non-printable characters.\n    \"\"\"\n    width = 0\n    for c in unicodedata.normalize(\"NFC\", s):\n        wc = wcwidth(c)\n        if wc < 0:\n            return -1\n        width += wc\n    return width\n"
  },
  {
    "path": "src/_pytest/_py/__init__.py",
    "content": ""
  },
  {
    "path": "src/_pytest/_py/error.py",
    "content": "\"\"\"create errno-specific classes for IO or os calls.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nimport errno\nimport os\nimport sys\nfrom typing import TYPE_CHECKING\nfrom typing import TypeVar\n\n\nif TYPE_CHECKING:\n    from typing_extensions import ParamSpec\n\n    P = ParamSpec(\"P\")\n\nR = TypeVar(\"R\")\n\n\nclass Error(EnvironmentError):\n    def __repr__(self) -> str:\n        return \"{}.{} {!r}: {} \".format(\n            self.__class__.__module__,\n            self.__class__.__name__,\n            self.__class__.__doc__,\n            \" \".join(map(str, self.args)),\n            # repr(self.args)\n        )\n\n    def __str__(self) -> str:\n        s = \"[{}]: {}\".format(\n            self.__class__.__doc__,\n            \" \".join(map(str, self.args)),\n        )\n        return s\n\n\n_winerrnomap = {\n    2: errno.ENOENT,\n    3: errno.ENOENT,\n    17: errno.EEXIST,\n    18: errno.EXDEV,\n    13: errno.EBUSY,  # empty cd drive, but ENOMEDIUM seems unavailable\n    22: errno.ENOTDIR,\n    20: errno.ENOTDIR,\n    267: errno.ENOTDIR,\n    5: errno.EACCES,  # anything better?\n}\n\n\nclass ErrorMaker:\n    \"\"\"lazily provides Exception classes for each possible POSIX errno\n    (as defined per the 'errno' module).  All such instances\n    subclass EnvironmentError.\n    \"\"\"\n\n    _errno2class: dict[int, type[Error]] = {}\n\n    def __getattr__(self, name: str) -> type[Error]:\n        if name[0] == \"_\":\n            raise AttributeError(name)\n        eno = getattr(errno, name)\n        cls = self._geterrnoclass(eno)\n        setattr(self, name, cls)\n        return cls\n\n    def _geterrnoclass(self, eno: int) -> type[Error]:\n        try:\n            return self._errno2class[eno]\n        except KeyError:\n            clsname = errno.errorcode.get(eno, f\"UnknownErrno{eno}\")\n            errorcls = type(\n                clsname,\n                (Error,),\n                {\"__module__\": \"py.error\", \"__doc__\": os.strerror(eno)},\n            )\n            self._errno2class[eno] = errorcls\n            return errorcls\n\n    def checked_call(\n        self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs\n    ) -> R:\n        \"\"\"Call a function and raise an errno-exception if applicable.\"\"\"\n        __tracebackhide__ = True\n        try:\n            return func(*args, **kwargs)\n        except Error:\n            raise\n        except OSError as value:\n            if not hasattr(value, \"errno\"):\n                raise\n            if sys.platform == \"win32\":\n                try:\n                    # error: Invalid index type \"Optional[int]\" for \"dict[int, int]\"; expected type \"int\"  [index]\n                    # OK to ignore because we catch the KeyError below.\n                    cls = self._geterrnoclass(_winerrnomap[value.errno])  # type:ignore[index]\n                except KeyError:\n                    raise value\n            else:\n                # we are not on Windows, or we got a proper OSError\n                if value.errno is None:\n                    cls = type(\n                        \"UnknownErrnoNone\",\n                        (Error,),\n                        {\"__module__\": \"py.error\", \"__doc__\": None},\n                    )\n                else:\n                    cls = self._geterrnoclass(value.errno)\n\n            raise cls(f\"{func.__name__}{args!r}\")\n\n\n_error_maker = ErrorMaker()\nchecked_call = _error_maker.checked_call\n\n\ndef __getattr__(attr: str) -> type[Error]:\n    return getattr(_error_maker, attr)  # type: ignore[no-any-return]\n"
  },
  {
    "path": "src/_pytest/_py/path.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"local path implementation.\"\"\"\n\nfrom __future__ import annotations\n\nimport atexit\nfrom collections.abc import Callable\nfrom contextlib import contextmanager\nimport fnmatch\nimport importlib.util\nimport io\nimport os\nfrom os.path import abspath\nfrom os.path import dirname\nfrom os.path import exists\nfrom os.path import isabs\nfrom os.path import isdir\nfrom os.path import isfile\nfrom os.path import islink\nfrom os.path import normpath\nimport posixpath\nfrom stat import S_ISDIR\nfrom stat import S_ISLNK\nfrom stat import S_ISREG\nimport sys\nfrom typing import Any\nfrom typing import cast\nfrom typing import Literal\nfrom typing import overload\nfrom typing import TYPE_CHECKING\nimport uuid\nimport warnings\n\nfrom . import error\n\n\n# Moved from local.py.\niswin32 = sys.platform == \"win32\" or (getattr(os, \"_name\", False) == \"nt\")\n\n\nclass Checkers:\n    _depend_on_existence = \"exists\", \"link\", \"dir\", \"file\"\n\n    def __init__(self, path):\n        self.path = path\n\n    def dotfile(self):\n        return self.path.basename.startswith(\".\")\n\n    def ext(self, arg):\n        if not arg.startswith(\".\"):\n            arg = \".\" + arg\n        return self.path.ext == arg\n\n    def basename(self, arg):\n        return self.path.basename == arg\n\n    def basestarts(self, arg):\n        return self.path.basename.startswith(arg)\n\n    def relto(self, arg):\n        return self.path.relto(arg)\n\n    def fnmatch(self, arg):\n        return self.path.fnmatch(arg)\n\n    def endswith(self, arg):\n        return str(self.path).endswith(arg)\n\n    def _evaluate(self, kw):\n        from .._code.source import getrawcode\n\n        for name, value in kw.items():\n            invert = False\n            meth = None\n            try:\n                meth = getattr(self, name)\n            except AttributeError:\n                if name[:3] == \"not\":\n                    invert = True\n                    try:\n                        meth = getattr(self, name[3:])\n                    except AttributeError:\n                        pass\n            if meth is None:\n                raise TypeError(f\"no {name!r} checker available for {self.path!r}\")\n            try:\n                if getrawcode(meth).co_argcount > 1:\n                    if (not meth(value)) ^ invert:\n                        return False\n                else:\n                    if bool(value) ^ bool(meth()) ^ invert:\n                        return False\n            except (error.ENOENT, error.ENOTDIR, error.EBUSY):\n                # EBUSY feels not entirely correct,\n                # but its kind of necessary since ENOMEDIUM\n                # is not accessible in python\n                for name in self._depend_on_existence:\n                    if name in kw:\n                        if kw.get(name):\n                            return False\n                    name = \"not\" + name\n                    if name in kw:\n                        if not kw.get(name):\n                            return False\n        return True\n\n    _statcache: Stat\n\n    def _stat(self) -> Stat:\n        try:\n            return self._statcache\n        except AttributeError:\n            try:\n                self._statcache = self.path.stat()\n            except error.ELOOP:\n                self._statcache = self.path.lstat()\n            return self._statcache\n\n    def dir(self):\n        return S_ISDIR(self._stat().mode)\n\n    def file(self):\n        return S_ISREG(self._stat().mode)\n\n    def exists(self):\n        return self._stat()\n\n    def link(self):\n        st = self.path.lstat()\n        return S_ISLNK(st.mode)\n\n\nclass NeverRaised(Exception):\n    pass\n\n\nclass Visitor:\n    def __init__(self, fil, rec, ignore, bf, sort):\n        if isinstance(fil, (str, bytes)):\n            fil = FNMatcher(fil)\n        if isinstance(rec, str):\n            self.rec: Callable[[LocalPath], bool] = FNMatcher(rec)\n        elif not hasattr(rec, \"__call__\") and rec:\n            self.rec = lambda path: True\n        else:\n            self.rec = rec\n        self.fil = fil\n        self.ignore = ignore\n        self.breadthfirst = bf\n        self.optsort = cast(Callable[[Any], Any], sorted) if sort else (lambda x: x)\n\n    def gen(self, path):\n        try:\n            entries = path.listdir()\n        except self.ignore:\n            return\n        rec = self.rec\n        dirs = self.optsort(\n            [p for p in entries if p.check(dir=1) and (rec is None or rec(p))]\n        )\n        if not self.breadthfirst:\n            for subdir in dirs:\n                yield from self.gen(subdir)\n        for p in self.optsort(entries):\n            if self.fil is None or self.fil(p):\n                yield p\n        if self.breadthfirst:\n            for subdir in dirs:\n                yield from self.gen(subdir)\n\n\nclass FNMatcher:\n    def __init__(self, pattern):\n        self.pattern = pattern\n\n    def __call__(self, path):\n        pattern = self.pattern\n\n        if (\n            pattern.find(path.sep) == -1\n            and iswin32\n            and pattern.find(posixpath.sep) != -1\n        ):\n            # Running on Windows, the pattern has no Windows path separators,\n            # and the pattern has one or more Posix path separators. Replace\n            # the Posix path separators with the Windows path separator.\n            pattern = pattern.replace(posixpath.sep, path.sep)\n\n        if pattern.find(path.sep) == -1:\n            name = path.basename\n        else:\n            name = str(path)  # path.strpath # XXX svn?\n            if not os.path.isabs(pattern):\n                pattern = \"*\" + path.sep + pattern\n        return fnmatch.fnmatch(name, pattern)\n\n\ndef map_as_list(func, iter):\n    return list(map(func, iter))\n\n\nclass Stat:\n    if TYPE_CHECKING:\n\n        @property\n        def size(self) -> int: ...\n\n        @property\n        def mtime(self) -> float: ...\n\n    def __getattr__(self, name: str) -> Any:\n        return getattr(self._osstatresult, \"st_\" + name)\n\n    def __init__(self, path, osstatresult):\n        self.path = path\n        self._osstatresult = osstatresult\n\n    @property\n    def owner(self):\n        if iswin32:\n            raise NotImplementedError(\"XXX win32\")\n        import pwd\n\n        entry = error.checked_call(pwd.getpwuid, self.uid)  # type:ignore[attr-defined,unused-ignore]\n        return entry[0]\n\n    @property\n    def group(self):\n        \"\"\"Return group name of file.\"\"\"\n        if iswin32:\n            raise NotImplementedError(\"XXX win32\")\n        import grp\n\n        entry = error.checked_call(grp.getgrgid, self.gid)  # type:ignore[attr-defined,unused-ignore]\n        return entry[0]\n\n    def isdir(self):\n        return S_ISDIR(self._osstatresult.st_mode)\n\n    def isfile(self):\n        return S_ISREG(self._osstatresult.st_mode)\n\n    def islink(self):\n        self.path.lstat()\n        return S_ISLNK(self._osstatresult.st_mode)\n\n\ndef getuserid(user):\n    import pwd\n\n    if not isinstance(user, int):\n        user = pwd.getpwnam(user)[2]  # type:ignore[attr-defined,unused-ignore]\n    return user\n\n\ndef getgroupid(group):\n    import grp\n\n    if not isinstance(group, int):\n        group = grp.getgrnam(group)[2]  # type:ignore[attr-defined,unused-ignore]\n    return group\n\n\nclass LocalPath:\n    \"\"\"Object oriented interface to os.path and other local filesystem\n    related information.\n    \"\"\"\n\n    class ImportMismatchError(ImportError):\n        \"\"\"raised on pyimport() if there is a mismatch of __file__'s\"\"\"\n\n    sep = os.sep\n\n    def __init__(self, path=None, expanduser=False):\n        \"\"\"Initialize and return a local Path instance.\n\n        Path can be relative to the current directory.\n        If path is None it defaults to the current working directory.\n        If expanduser is True, tilde-expansion is performed.\n        Note that Path instances always carry an absolute path.\n        Note also that passing in a local path object will simply return\n        the exact same path object. Use new() to get a new copy.\n        \"\"\"\n        if path is None:\n            self.strpath = error.checked_call(os.getcwd)\n        else:\n            try:\n                path = os.fspath(path)\n            except TypeError:\n                raise ValueError(\n                    \"can only pass None, Path instances \"\n                    \"or non-empty strings to LocalPath\"\n                )\n            if expanduser:\n                path = os.path.expanduser(path)\n            self.strpath = abspath(path)\n\n    if sys.platform != \"win32\":\n\n        def chown(self, user, group, rec=0):\n            \"\"\"Change ownership to the given user and group.\n            user and group may be specified by a number or\n            by a name.  if rec is True change ownership\n            recursively.\n            \"\"\"\n            uid = getuserid(user)\n            gid = getgroupid(group)\n            if rec:\n                for x in self.visit(rec=lambda x: x.check(link=0)):\n                    if x.check(link=0):\n                        error.checked_call(os.chown, str(x), uid, gid)\n            error.checked_call(os.chown, str(self), uid, gid)\n\n        def readlink(self) -> str:\n            \"\"\"Return value of a symbolic link.\"\"\"\n            # https://github.com/python/mypy/issues/12278\n            return error.checked_call(os.readlink, self.strpath)  # type: ignore[arg-type,return-value,unused-ignore]\n\n        def mklinkto(self, oldname):\n            \"\"\"Posix style hard link to another name.\"\"\"\n            error.checked_call(os.link, str(oldname), str(self))\n\n        def mksymlinkto(self, value, absolute=1):\n            \"\"\"Create a symbolic link with the given value (pointing to another name).\"\"\"\n            if absolute:\n                error.checked_call(os.symlink, str(value), self.strpath)\n            else:\n                base = self.common(value)\n                # with posix local paths '/' is always a common base\n                relsource = self.__class__(value).relto(base)\n                reldest = self.relto(base)\n                n = reldest.count(self.sep)\n                target = self.sep.join((\"..\",) * n + (relsource,))\n                error.checked_call(os.symlink, target, self.strpath)\n\n    def __div__(self, other):\n        return self.join(os.fspath(other))\n\n    __truediv__ = __div__  # py3k\n\n    @property\n    def basename(self):\n        \"\"\"Basename part of path.\"\"\"\n        return self._getbyspec(\"basename\")[0]\n\n    @property\n    def dirname(self):\n        \"\"\"Dirname part of path.\"\"\"\n        return self._getbyspec(\"dirname\")[0]\n\n    @property\n    def purebasename(self):\n        \"\"\"Pure base name of the path.\"\"\"\n        return self._getbyspec(\"purebasename\")[0]\n\n    @property\n    def ext(self):\n        \"\"\"Extension of the path (including the '.').\"\"\"\n        return self._getbyspec(\"ext\")[0]\n\n    def read_binary(self):\n        \"\"\"Read and return a bytestring from reading the path.\"\"\"\n        with self.open(\"rb\") as f:\n            return f.read()\n\n    def read_text(self, encoding):\n        \"\"\"Read and return a Unicode string from reading the path.\"\"\"\n        with self.open(\"r\", encoding=encoding) as f:\n            return f.read()\n\n    def read(self, mode=\"r\"):\n        \"\"\"Read and return a bytestring from reading the path.\"\"\"\n        with self.open(mode) as f:\n            return f.read()\n\n    def readlines(self, cr=1):\n        \"\"\"Read and return a list of lines from the path. if cr is False, the\n        newline will be removed from the end of each line.\"\"\"\n        mode = \"r\"\n\n        if not cr:\n            content = self.read(mode)\n            return content.split(\"\\n\")\n        else:\n            f = self.open(mode)\n            try:\n                return f.readlines()\n            finally:\n                f.close()\n\n    def load(self):\n        \"\"\"(deprecated) return object unpickled from self.read()\"\"\"\n        f = self.open(\"rb\")\n        try:\n            import pickle\n\n            return error.checked_call(pickle.load, f)\n        finally:\n            f.close()\n\n    def move(self, target):\n        \"\"\"Move this path to target.\"\"\"\n        if target.relto(self):\n            raise error.EINVAL(target, \"cannot move path into a subdirectory of itself\")\n        try:\n            self.rename(target)\n        except error.EXDEV:  # invalid cross-device link\n            self.copy(target)\n            self.remove()\n\n    def fnmatch(self, pattern):\n        \"\"\"Return true if the basename/fullname matches the glob-'pattern'.\n\n        valid pattern characters::\n\n            *       matches everything\n            ?       matches any single character\n            [seq]   matches any character in seq\n            [!seq]  matches any char not in seq\n\n        If the pattern contains a path-separator then the full path\n        is used for pattern matching and a '*' is prepended to the\n        pattern.\n\n        if the pattern doesn't contain a path-separator the pattern\n        is only matched against the basename.\n        \"\"\"\n        return FNMatcher(pattern)(self)\n\n    def relto(self, relpath):\n        \"\"\"Return a string which is the relative part of the path\n        to the given 'relpath'.\n        \"\"\"\n        if not isinstance(relpath, str | LocalPath):\n            raise TypeError(f\"{relpath!r}: not a string or path object\")\n        strrelpath = str(relpath)\n        if strrelpath and strrelpath[-1] != self.sep:\n            strrelpath += self.sep\n        # assert strrelpath[-1] == self.sep\n        # assert strrelpath[-2] != self.sep\n        strself = self.strpath\n        if sys.platform == \"win32\" or getattr(os, \"_name\", None) == \"nt\":\n            if os.path.normcase(strself).startswith(os.path.normcase(strrelpath)):\n                return strself[len(strrelpath) :]\n        elif strself.startswith(strrelpath):\n            return strself[len(strrelpath) :]\n        return \"\"\n\n    def ensure_dir(self, *args):\n        \"\"\"Ensure the path joined with args is a directory.\"\"\"\n        return self.ensure(*args, dir=True)\n\n    def bestrelpath(self, dest):\n        \"\"\"Return a string which is a relative path from self\n        (assumed to be a directory) to dest such that\n        self.join(bestrelpath) == dest and if not such\n        path can be determined return dest.\n        \"\"\"\n        try:\n            if self == dest:\n                return os.curdir\n            base = self.common(dest)\n            if not base:  # can be the case on windows\n                return str(dest)\n            self2base = self.relto(base)\n            reldest = dest.relto(base)\n            if self2base:\n                n = self2base.count(self.sep) + 1\n            else:\n                n = 0\n            lst = [os.pardir] * n\n            if reldest:\n                lst.append(reldest)\n            target = dest.sep.join(lst)\n            return target\n        except AttributeError:\n            return str(dest)\n\n    def exists(self):\n        return self.check()\n\n    def isdir(self):\n        return self.check(dir=1)\n\n    def isfile(self):\n        return self.check(file=1)\n\n    def parts(self, reverse=False):\n        \"\"\"Return a root-first list of all ancestor directories\n        plus the path itself.\n        \"\"\"\n        current = self\n        lst = [self]\n        while 1:\n            last = current\n            current = current.dirpath()\n            if last == current:\n                break\n            lst.append(current)\n        if not reverse:\n            lst.reverse()\n        return lst\n\n    def common(self, other):\n        \"\"\"Return the common part shared with the other path\n        or None if there is no common part.\n        \"\"\"\n        last = None\n        for x, y in zip(self.parts(), other.parts()):\n            if x != y:\n                return last\n            last = x\n        return last\n\n    def __add__(self, other):\n        \"\"\"Return new path object with 'other' added to the basename\"\"\"\n        return self.new(basename=self.basename + str(other))\n\n    def visit(self, fil=None, rec=None, ignore=NeverRaised, bf=False, sort=False):\n        \"\"\"Yields all paths below the current one\n\n        fil is a filter (glob pattern or callable), if not matching the\n        path will not be yielded, defaulting to None (everything is\n        returned)\n\n        rec is a filter (glob pattern or callable) that controls whether\n        a node is descended, defaulting to None\n\n        ignore is an Exception class that is ignoredwhen calling dirlist()\n        on any of the paths (by default, all exceptions are reported)\n\n        bf if True will cause a breadthfirst search instead of the\n        default depthfirst. Default: False\n\n        sort if True will sort entries within each directory level.\n        \"\"\"\n        yield from Visitor(fil, rec, ignore, bf, sort).gen(self)\n\n    def _sortlist(self, res, sort):\n        if sort:\n            if hasattr(sort, \"__call__\"):\n                warnings.warn(\n                    DeprecationWarning(\n                        \"listdir(sort=callable) is deprecated and breaks on python3\"\n                    ),\n                    stacklevel=3,\n                )\n                res.sort(sort)\n            else:\n                res.sort()\n\n    def __fspath__(self):\n        return self.strpath\n\n    def __hash__(self):\n        s = self.strpath\n        if iswin32:\n            s = s.lower()\n        return hash(s)\n\n    def __eq__(self, other):\n        s1 = os.fspath(self)\n        try:\n            s2 = os.fspath(other)\n        except TypeError:\n            return False\n        if iswin32:\n            s1 = s1.lower()\n            try:\n                s2 = s2.lower()\n            except AttributeError:\n                return False\n        return s1 == s2\n\n    def __ne__(self, other):\n        return not (self == other)\n\n    def __lt__(self, other):\n        return os.fspath(self) < os.fspath(other)\n\n    def __gt__(self, other):\n        return os.fspath(self) > os.fspath(other)\n\n    def samefile(self, other):\n        \"\"\"Return True if 'other' references the same file as 'self'.\"\"\"\n        other = os.fspath(other)\n        if not isabs(other):\n            other = abspath(other)\n        if self == other:\n            return True\n        if not hasattr(os.path, \"samefile\"):\n            return False\n        return error.checked_call(os.path.samefile, self.strpath, other)\n\n    def remove(self, rec=1, ignore_errors=False):\n        \"\"\"Remove a file or directory (or a directory tree if rec=1).\n        if ignore_errors is True, errors while removing directories will\n        be ignored.\n        \"\"\"\n        if self.check(dir=1, link=0):\n            if rec:\n                # force remove of readonly files on windows\n                if iswin32:\n                    self.chmod(0o700, rec=1)\n                import shutil\n\n                error.checked_call(\n                    shutil.rmtree, self.strpath, ignore_errors=ignore_errors\n                )\n            else:\n                error.checked_call(os.rmdir, self.strpath)\n        else:\n            if iswin32:\n                self.chmod(0o700)\n            error.checked_call(os.remove, self.strpath)\n\n    def computehash(self, hashtype=\"md5\", chunksize=524288):\n        \"\"\"Return hexdigest of hashvalue for this file.\"\"\"\n        try:\n            try:\n                import hashlib as mod\n            except ImportError:\n                if hashtype == \"sha1\":\n                    hashtype = \"sha\"\n                mod = __import__(hashtype)\n            hash = getattr(mod, hashtype)()\n        except (AttributeError, ImportError):\n            raise ValueError(f\"Don't know how to compute {hashtype!r} hash\")\n        f = self.open(\"rb\")\n        try:\n            while 1:\n                buf = f.read(chunksize)\n                if not buf:\n                    return hash.hexdigest()\n                hash.update(buf)\n        finally:\n            f.close()\n\n    def new(self, **kw):\n        \"\"\"Create a modified version of this path.\n        the following keyword arguments modify various path parts::\n\n          a:/some/path/to/a/file.ext\n          xx                           drive\n          xxxxxxxxxxxxxxxxx            dirname\n                            xxxxxxxx   basename\n                            xxxx       purebasename\n                                 xxx   ext\n        \"\"\"\n        obj = object.__new__(self.__class__)\n        if not kw:\n            obj.strpath = self.strpath\n            return obj\n        drive, dirname, _basename, purebasename, ext = self._getbyspec(\n            \"drive,dirname,basename,purebasename,ext\"\n        )\n        if \"basename\" in kw:\n            if \"purebasename\" in kw or \"ext\" in kw:\n                raise ValueError(f\"invalid specification {kw!r}\")\n        else:\n            pb = kw.setdefault(\"purebasename\", purebasename)\n            try:\n                ext = kw[\"ext\"]\n            except KeyError:\n                pass\n            else:\n                if ext and not ext.startswith(\".\"):\n                    ext = \".\" + ext\n            kw[\"basename\"] = pb + ext\n\n        if \"dirname\" in kw and not kw[\"dirname\"]:\n            kw[\"dirname\"] = drive\n        else:\n            kw.setdefault(\"dirname\", dirname)\n        kw.setdefault(\"sep\", self.sep)\n        obj.strpath = normpath(\"{dirname}{sep}{basename}\".format(**kw))\n        return obj\n\n    def _getbyspec(self, spec: str) -> list[str]:\n        \"\"\"See new for what 'spec' can be.\"\"\"\n        res = []\n        parts = self.strpath.split(self.sep)\n\n        args = filter(None, spec.split(\",\"))\n        for name in args:\n            if name == \"drive\":\n                res.append(parts[0])\n            elif name == \"dirname\":\n                res.append(self.sep.join(parts[:-1]))\n            else:\n                basename = parts[-1]\n                if name == \"basename\":\n                    res.append(basename)\n                else:\n                    i = basename.rfind(\".\")\n                    if i == -1:\n                        purebasename, ext = basename, \"\"\n                    else:\n                        purebasename, ext = basename[:i], basename[i:]\n                    if name == \"purebasename\":\n                        res.append(purebasename)\n                    elif name == \"ext\":\n                        res.append(ext)\n                    else:\n                        raise ValueError(f\"invalid part specification {name!r}\")\n        return res\n\n    def dirpath(self, *args, **kwargs):\n        \"\"\"Return the directory path joined with any given path arguments.\"\"\"\n        if not kwargs:\n            path = object.__new__(self.__class__)\n            path.strpath = dirname(self.strpath)\n            if args:\n                path = path.join(*args)\n            return path\n        return self.new(basename=\"\").join(*args, **kwargs)\n\n    def join(self, *args: os.PathLike[str], abs: bool = False) -> LocalPath:\n        \"\"\"Return a new path by appending all 'args' as path\n        components.  if abs=1 is used restart from root if any\n        of the args is an absolute path.\n        \"\"\"\n        sep = self.sep\n        strargs = [os.fspath(arg) for arg in args]\n        strpath = self.strpath\n        if abs:\n            newargs: list[str] = []\n            for arg in reversed(strargs):\n                if isabs(arg):\n                    strpath = arg\n                    strargs = newargs\n                    break\n                newargs.insert(0, arg)\n        # special case for when we have e.g. strpath == \"/\"\n        actual_sep = \"\" if strpath.endswith(sep) else sep\n        for arg in strargs:\n            arg = arg.strip(sep)\n            if iswin32:\n                # allow unix style paths even on windows.\n                arg = arg.strip(\"/\")\n                arg = arg.replace(\"/\", sep)\n            strpath = strpath + actual_sep + arg\n            actual_sep = sep\n        obj = object.__new__(self.__class__)\n        obj.strpath = normpath(strpath)\n        return obj\n\n    def open(self, mode=\"r\", ensure=False, encoding=None):\n        \"\"\"Return an opened file with the given mode.\n\n        If ensure is True, create parent directories if needed.\n        \"\"\"\n        if ensure:\n            self.dirpath().ensure(dir=1)\n        if encoding:\n            return error.checked_call(\n                io.open,\n                self.strpath,\n                mode,\n                encoding=encoding,\n            )\n        return error.checked_call(open, self.strpath, mode)\n\n    def _fastjoin(self, name):\n        child = object.__new__(self.__class__)\n        child.strpath = self.strpath + self.sep + name\n        return child\n\n    def islink(self):\n        return islink(self.strpath)\n\n    def check(self, **kw):\n        \"\"\"Check a path for existence and properties.\n\n        Without arguments, return True if the path exists, otherwise False.\n\n        valid checkers::\n\n            file = 1  # is a file\n            file = 0  # is not a file (may not even exist)\n            dir = 1  # is a dir\n            link = 1  # is a link\n            exists = 1  # exists\n\n        You can specify multiple checker definitions, for example::\n\n            path.check(file=1, link=1)  # a link pointing to a file\n        \"\"\"\n        if not kw:\n            return exists(self.strpath)\n        if len(kw) == 1:\n            if \"dir\" in kw:\n                return not kw[\"dir\"] ^ isdir(self.strpath)\n            if \"file\" in kw:\n                return not kw[\"file\"] ^ isfile(self.strpath)\n        if not kw:\n            kw = {\"exists\": 1}\n        return Checkers(self)._evaluate(kw)\n\n    _patternchars = set(\"*?[\" + os.sep)\n\n    def listdir(self, fil=None, sort=None):\n        \"\"\"List directory contents, possibly filter by the given fil func\n        and possibly sorted.\n        \"\"\"\n        if fil is None and sort is None:\n            names = error.checked_call(os.listdir, self.strpath)\n            return map_as_list(self._fastjoin, names)\n        if isinstance(fil, str):\n            if not self._patternchars.intersection(fil):\n                child = self._fastjoin(fil)\n                if exists(child.strpath):\n                    return [child]\n                return []\n            fil = FNMatcher(fil)\n        names = error.checked_call(os.listdir, self.strpath)\n        res = []\n        for name in names:\n            child = self._fastjoin(name)\n            if fil is None or fil(child):\n                res.append(child)\n        self._sortlist(res, sort)\n        return res\n\n    def size(self) -> int:\n        \"\"\"Return size of the underlying file object\"\"\"\n        return self.stat().size\n\n    def mtime(self) -> float:\n        \"\"\"Return last modification time of the path.\"\"\"\n        return self.stat().mtime\n\n    def copy(self, target, mode=False, stat=False):\n        \"\"\"Copy path to target.\n\n        If mode is True, will copy permission from path to target.\n        If stat is True, copy permission, last modification\n        time, last access time, and flags from path to target.\n        \"\"\"\n        if self.check(file=1):\n            if target.check(dir=1):\n                target = target.join(self.basename)\n            assert self != target\n            copychunked(self, target)\n            if mode:\n                copymode(self.strpath, target.strpath)\n            if stat:\n                copystat(self, target)\n        else:\n\n            def rec(p):\n                return p.check(link=0)\n\n            for x in self.visit(rec=rec):\n                relpath = x.relto(self)\n                newx = target.join(relpath)\n                newx.dirpath().ensure(dir=1)\n                if x.check(link=1):\n                    newx.mksymlinkto(x.readlink())\n                    continue\n                elif x.check(file=1):\n                    copychunked(x, newx)\n                elif x.check(dir=1):\n                    newx.ensure(dir=1)\n                if mode:\n                    copymode(x.strpath, newx.strpath)\n                if stat:\n                    copystat(x, newx)\n\n    def rename(self, target):\n        \"\"\"Rename this path to target.\"\"\"\n        target = os.fspath(target)\n        return error.checked_call(os.rename, self.strpath, target)\n\n    def dump(self, obj, bin=1):\n        \"\"\"Pickle object into path location\"\"\"\n        f = self.open(\"wb\")\n        import pickle\n\n        try:\n            error.checked_call(pickle.dump, obj, f, bin)\n        finally:\n            f.close()\n\n    def mkdir(self, *args):\n        \"\"\"Create & return the directory joined with args.\"\"\"\n        p = self.join(*args)\n        error.checked_call(os.mkdir, os.fspath(p))\n        return p\n\n    def write_binary(self, data, ensure=False):\n        \"\"\"Write binary data into path.   If ensure is True create\n        missing parent directories.\n        \"\"\"\n        if ensure:\n            self.dirpath().ensure(dir=1)\n        with self.open(\"wb\") as f:\n            f.write(data)\n\n    def write_text(self, data, encoding, ensure=False):\n        \"\"\"Write text data into path using the specified encoding.\n        If ensure is True create missing parent directories.\n        \"\"\"\n        if ensure:\n            self.dirpath().ensure(dir=1)\n        with self.open(\"w\", encoding=encoding) as f:\n            f.write(data)\n\n    def write(self, data, mode=\"w\", ensure=False):\n        \"\"\"Write data into path.   If ensure is True create\n        missing parent directories.\n        \"\"\"\n        if ensure:\n            self.dirpath().ensure(dir=1)\n        if \"b\" in mode:\n            if not isinstance(data, bytes):\n                raise ValueError(\"can only process bytes\")\n        else:\n            if not isinstance(data, str):\n                if not isinstance(data, bytes):\n                    data = str(data)\n                else:\n                    data = data.decode(sys.getdefaultencoding())\n        f = self.open(mode)\n        try:\n            f.write(data)\n        finally:\n            f.close()\n\n    def _ensuredirs(self):\n        parent = self.dirpath()\n        if parent == self:\n            return self\n        if parent.check(dir=0):\n            parent._ensuredirs()\n        if self.check(dir=0):\n            try:\n                self.mkdir()\n            except error.EEXIST:\n                # race condition: file/dir created by another thread/process.\n                # complain if it is not a dir\n                if self.check(dir=0):\n                    raise\n        return self\n\n    def ensure(self, *args, **kwargs):\n        \"\"\"Ensure that an args-joined path exists (by default as\n        a file). if you specify a keyword argument 'dir=True'\n        then the path is forced to be a directory path.\n        \"\"\"\n        p = self.join(*args)\n        if kwargs.get(\"dir\", 0):\n            return p._ensuredirs()\n        else:\n            p.dirpath()._ensuredirs()\n            if not p.check(file=1):\n                p.open(\"wb\").close()\n            return p\n\n    @overload\n    def stat(self, raising: Literal[True] = ...) -> Stat: ...\n\n    @overload\n    def stat(self, raising: Literal[False]) -> Stat | None: ...\n\n    def stat(self, raising: bool = True) -> Stat | None:\n        \"\"\"Return an os.stat() tuple.\"\"\"\n        if raising:\n            return Stat(self, error.checked_call(os.stat, self.strpath))\n        try:\n            return Stat(self, os.stat(self.strpath))\n        except KeyboardInterrupt:\n            raise\n        except Exception:\n            return None\n\n    def lstat(self) -> Stat:\n        \"\"\"Return an os.lstat() tuple.\"\"\"\n        return Stat(self, error.checked_call(os.lstat, self.strpath))\n\n    def setmtime(self, mtime=None):\n        \"\"\"Set modification time for the given path.  if 'mtime' is None\n        (the default) then the file's mtime is set to current time.\n\n        Note that the resolution for 'mtime' is platform dependent.\n        \"\"\"\n        if mtime is None:\n            return error.checked_call(os.utime, self.strpath, mtime)\n        try:\n            return error.checked_call(os.utime, self.strpath, (-1, mtime))\n        except error.EINVAL:\n            return error.checked_call(os.utime, self.strpath, (self.atime(), mtime))\n\n    def chdir(self):\n        \"\"\"Change directory to self and return old current directory\"\"\"\n        try:\n            old = self.__class__()\n        except error.ENOENT:\n            old = None\n        error.checked_call(os.chdir, self.strpath)\n        return old\n\n    @contextmanager\n    def as_cwd(self):\n        \"\"\"\n        Return a context manager, which changes to the path's dir during the\n        managed \"with\" context.\n        On __enter__ it returns the old dir, which might be ``None``.\n        \"\"\"\n        old = self.chdir()\n        try:\n            yield old\n        finally:\n            if old is not None:\n                old.chdir()\n\n    def realpath(self):\n        \"\"\"Return a new path which contains no symbolic links.\"\"\"\n        return self.__class__(os.path.realpath(self.strpath))\n\n    def atime(self):\n        \"\"\"Return last access time of the path.\"\"\"\n        return self.stat().atime\n\n    def __repr__(self):\n        return f\"local({self.strpath!r})\"\n\n    def __str__(self):\n        \"\"\"Return string representation of the Path.\"\"\"\n        return self.strpath\n\n    def chmod(self, mode, rec=0):\n        \"\"\"Change permissions to the given mode. If mode is an\n        integer it directly encodes the os-specific modes.\n        if rec is True perform recursively.\n        \"\"\"\n        if not isinstance(mode, int):\n            raise TypeError(f\"mode {mode!r} must be an integer\")\n        if rec:\n            for x in self.visit(rec=rec):\n                error.checked_call(os.chmod, str(x), mode)\n        error.checked_call(os.chmod, self.strpath, mode)\n\n    def pypkgpath(self):\n        \"\"\"Return the Python package path by looking for the last\n        directory upwards which still contains an __init__.py.\n        Return None if a pkgpath cannot be determined.\n        \"\"\"\n        pkgpath = None\n        for parent in self.parts(reverse=True):\n            if parent.isdir():\n                if not parent.join(\"__init__.py\").exists():\n                    break\n                if not isimportable(parent.basename):\n                    break\n                pkgpath = parent\n        return pkgpath\n\n    def _ensuresyspath(self, ensuremode, path):\n        if ensuremode:\n            s = str(path)\n            if ensuremode == \"append\":\n                if s not in sys.path:\n                    sys.path.append(s)\n            else:\n                if s != sys.path[0]:\n                    sys.path.insert(0, s)\n\n    def pyimport(self, modname=None, ensuresyspath=True):\n        \"\"\"Return path as an imported python module.\n\n        If modname is None, look for the containing package\n        and construct an according module name.\n        The module will be put/looked up in sys.modules.\n        if ensuresyspath is True then the root dir for importing\n        the file (taking __init__.py files into account) will\n        be prepended to sys.path if it isn't there already.\n        If ensuresyspath==\"append\" the root dir will be appended\n        if it isn't already contained in sys.path.\n        if ensuresyspath is False no modification of syspath happens.\n\n        Special value of ensuresyspath==\"importlib\" is intended\n        purely for using in pytest, it is capable only of importing\n        separate .py files outside packages, e.g. for test suite\n        without any __init__.py file. It effectively allows having\n        same-named test modules in different places and offers\n        mild opt-in via this option. Note that it works only in\n        recent versions of python.\n        \"\"\"\n        if not self.check():\n            raise error.ENOENT(self)\n\n        if ensuresyspath == \"importlib\":\n            if modname is None:\n                modname = self.purebasename\n            spec = importlib.util.spec_from_file_location(modname, str(self))\n            if spec is None or spec.loader is None:\n                raise ImportError(f\"Can't find module {modname} at location {self!s}\")\n            mod = importlib.util.module_from_spec(spec)\n            spec.loader.exec_module(mod)\n            return mod\n\n        pkgpath = None\n        if modname is None:\n            pkgpath = self.pypkgpath()\n            if pkgpath is not None:\n                pkgroot = pkgpath.dirpath()\n                names = self.new(ext=\"\").relto(pkgroot).split(self.sep)\n                if names[-1] == \"__init__\":\n                    names.pop()\n                modname = \".\".join(names)\n            else:\n                pkgroot = self.dirpath()\n                modname = self.purebasename\n\n            self._ensuresyspath(ensuresyspath, pkgroot)\n            __import__(modname)\n            mod = sys.modules[modname]\n            if self.basename == \"__init__.py\":\n                return mod  # we don't check anything as we might\n                # be in a namespace package ... too icky to check\n            modfile = mod.__file__\n            assert modfile is not None\n            if modfile[-4:] in (\".pyc\", \".pyo\"):\n                modfile = modfile[:-1]\n            elif modfile.endswith(\"$py.class\"):\n                modfile = modfile[:-9] + \".py\"\n            if modfile.endswith(os.sep + \"__init__.py\"):\n                if self.basename != \"__init__.py\":\n                    modfile = modfile[:-12]\n            try:\n                issame = self.samefile(modfile)\n            except error.ENOENT:\n                issame = False\n            if not issame:\n                ignore = os.getenv(\"PY_IGNORE_IMPORTMISMATCH\")\n                if ignore != \"1\":\n                    raise self.ImportMismatchError(modname, modfile, self)\n            return mod\n        else:\n            try:\n                return sys.modules[modname]\n            except KeyError:\n                # we have a custom modname, do a pseudo-import\n                import types\n\n                mod = types.ModuleType(modname)\n                mod.__file__ = str(self)\n                sys.modules[modname] = mod\n                try:\n                    with open(str(self), \"rb\") as f:\n                        exec(f.read(), mod.__dict__)\n                except BaseException:\n                    del sys.modules[modname]\n                    raise\n                return mod\n\n    def sysexec(self, *argv: os.PathLike[str], **popen_opts: Any) -> str:\n        \"\"\"Return stdout text from executing a system child process,\n        where the 'self' path points to executable.\n        The process is directly invoked and not through a system shell.\n        \"\"\"\n        from subprocess import PIPE\n        from subprocess import Popen\n\n        popen_opts.pop(\"stdout\", None)\n        popen_opts.pop(\"stderr\", None)\n        proc = Popen(\n            [str(self)] + [str(arg) for arg in argv],\n            **popen_opts,\n            stdout=PIPE,\n            stderr=PIPE,\n        )\n        stdout: str | bytes\n        stdout, stderr = proc.communicate()\n        ret = proc.wait()\n        if isinstance(stdout, bytes):\n            stdout = stdout.decode(sys.getdefaultencoding())\n        if ret != 0:\n            if isinstance(stderr, bytes):\n                stderr = stderr.decode(sys.getdefaultencoding())\n            raise RuntimeError(\n                ret,\n                ret,\n                str(self),\n                stdout,\n                stderr,\n            )\n        return stdout\n\n    @classmethod\n    def sysfind(cls, name, checker=None, paths=None):\n        \"\"\"Return a path object found by looking at the systems\n        underlying PATH specification. If the checker is not None\n        it will be invoked to filter matching paths.  If a binary\n        cannot be found, None is returned\n        Note: This is probably not working on plain win32 systems\n        but may work on cygwin.\n        \"\"\"\n        if isabs(name):\n            p = local(name)\n            if p.check(file=1):\n                return p\n        else:\n            if paths is None:\n                if iswin32:\n                    paths = os.environ[\"Path\"].split(\";\")\n                    if \"\" not in paths and \".\" not in paths:\n                        paths.append(\".\")\n                    try:\n                        systemroot = os.environ[\"SYSTEMROOT\"]\n                    except KeyError:\n                        pass\n                    else:\n                        paths = [\n                            path.replace(\"%SystemRoot%\", systemroot) for path in paths\n                        ]\n                else:\n                    paths = os.environ[\"PATH\"].split(\":\")\n            tryadd = []\n            if iswin32:\n                tryadd += os.environ[\"PATHEXT\"].split(os.pathsep)\n            tryadd.append(\"\")\n\n            for x in paths:\n                for addext in tryadd:\n                    p = local(x).join(name, abs=True) + addext\n                    try:\n                        if p.check(file=1):\n                            if checker:\n                                if not checker(p):\n                                    continue\n                            return p\n                    except error.EACCES:\n                        pass\n        return None\n\n    @classmethod\n    def _gethomedir(cls):\n        try:\n            x = os.environ[\"HOME\"]\n        except KeyError:\n            try:\n                x = os.environ[\"HOMEDRIVE\"] + os.environ[\"HOMEPATH\"]\n            except KeyError:\n                return None\n        return cls(x)\n\n    # \"\"\"\n    # special class constructors for local filesystem paths\n    # \"\"\"\n    @classmethod\n    def get_temproot(cls):\n        \"\"\"Return the system's temporary directory\n        (where tempfiles are usually created in)\n        \"\"\"\n        import tempfile\n\n        return local(tempfile.gettempdir())\n\n    @classmethod\n    def mkdtemp(cls, rootdir=None):\n        \"\"\"Return a Path object pointing to a fresh new temporary directory\n        (which we created ourselves).\n        \"\"\"\n        import tempfile\n\n        if rootdir is None:\n            rootdir = cls.get_temproot()\n        path = error.checked_call(tempfile.mkdtemp, dir=str(rootdir))\n        return cls(path)\n\n    @classmethod\n    def make_numbered_dir(\n        cls, prefix=\"session-\", rootdir=None, keep=3, lock_timeout=172800\n    ):  # two days\n        \"\"\"Return unique directory with a number greater than the current\n        maximum one.  The number is assumed to start directly after prefix.\n        if keep is true directories with a number less than (maxnum-keep)\n        will be removed. If .lock files are used (lock_timeout non-zero),\n        algorithm is multi-process safe.\n        \"\"\"\n        if rootdir is None:\n            rootdir = cls.get_temproot()\n\n        nprefix = prefix.lower()\n\n        def parse_num(path):\n            \"\"\"Parse the number out of a path (if it matches the prefix)\"\"\"\n            nbasename = path.basename.lower()\n            if nbasename.startswith(nprefix):\n                try:\n                    return int(nbasename[len(nprefix) :])\n                except ValueError:\n                    pass\n\n        def create_lockfile(path):\n            \"\"\"Exclusively create lockfile. Throws when failed\"\"\"\n            mypid = os.getpid()\n            lockfile = path.join(\".lock\")\n            if hasattr(lockfile, \"mksymlinkto\"):\n                lockfile.mksymlinkto(str(mypid))\n            else:\n                fd = error.checked_call(\n                    os.open, str(lockfile), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644\n                )\n                with os.fdopen(fd, \"w\") as f:\n                    f.write(str(mypid))\n            return lockfile\n\n        def atexit_remove_lockfile(lockfile):\n            \"\"\"Ensure lockfile is removed at process exit\"\"\"\n            mypid = os.getpid()\n\n            def try_remove_lockfile():\n                # in a fork() situation, only the last process should\n                # remove the .lock, otherwise the other processes run the\n                # risk of seeing their temporary dir disappear.  For now\n                # we remove the .lock in the parent only (i.e. we assume\n                # that the children finish before the parent).\n                if os.getpid() != mypid:\n                    return\n                try:\n                    lockfile.remove()\n                except error.Error:\n                    pass\n\n            atexit.register(try_remove_lockfile)\n\n        # compute the maximum number currently in use with the prefix\n        lastmax = None\n        while True:\n            maxnum = -1\n            for path in rootdir.listdir():\n                num = parse_num(path)\n                if num is not None:\n                    maxnum = max(maxnum, num)\n\n            # make the new directory\n            try:\n                udir = rootdir.mkdir(prefix + str(maxnum + 1))\n                if lock_timeout:\n                    lockfile = create_lockfile(udir)\n                    atexit_remove_lockfile(lockfile)\n            except (error.EEXIST, error.ENOENT, error.EBUSY):\n                # race condition (1): another thread/process created the dir\n                #                     in the meantime - try again\n                # race condition (2): another thread/process spuriously acquired\n                #                     lock treating empty directory as candidate\n                #                     for removal - try again\n                # race condition (3): another thread/process tried to create the lock at\n                #                     the same time (happened in Python 3.3 on Windows)\n                # https://ci.appveyor.com/project/pytestbot/py/build/1.0.21/job/ffi85j4c0lqwsfwa\n                if lastmax == maxnum:\n                    raise\n                lastmax = maxnum\n                continue\n            break\n\n        def get_mtime(path):\n            \"\"\"Read file modification time\"\"\"\n            try:\n                return path.lstat().mtime\n            except error.Error:\n                pass\n\n        garbage_prefix = prefix + \"garbage-\"\n\n        def is_garbage(path):\n            \"\"\"Check if path denotes directory scheduled for removal\"\"\"\n            bn = path.basename\n            return bn.startswith(garbage_prefix)\n\n        # prune old directories\n        udir_time = get_mtime(udir)\n        if keep and udir_time:\n            for path in rootdir.listdir():\n                num = parse_num(path)\n                if num is not None and num <= (maxnum - keep):\n                    try:\n                        # try acquiring lock to remove directory as exclusive user\n                        if lock_timeout:\n                            create_lockfile(path)\n                    except (error.EEXIST, error.ENOENT, error.EBUSY):\n                        path_time = get_mtime(path)\n                        if not path_time:\n                            # assume directory doesn't exist now\n                            continue\n                        if abs(udir_time - path_time) < lock_timeout:\n                            # assume directory with lockfile exists\n                            # and lock timeout hasn't expired yet\n                            continue\n\n                    # path dir locked for exclusive use\n                    # and scheduled for removal to avoid another thread/process\n                    # treating it as a new directory or removal candidate\n                    garbage_path = rootdir.join(garbage_prefix + str(uuid.uuid4()))\n                    try:\n                        path.rename(garbage_path)\n                        garbage_path.remove(rec=1)\n                    except KeyboardInterrupt:\n                        raise\n                    except Exception:  # this might be error.Error, WindowsError ...\n                        pass\n                if is_garbage(path):\n                    try:\n                        path.remove(rec=1)\n                    except KeyboardInterrupt:\n                        raise\n                    except Exception:  # this might be error.Error, WindowsError ...\n                        pass\n\n        # make link...\n        try:\n            username = os.environ[\"USER\"]  # linux, et al\n        except KeyError:\n            try:\n                username = os.environ[\"USERNAME\"]  # windows\n            except KeyError:\n                username = \"current\"\n\n        src = str(udir)\n        dest = src[: src.rfind(\"-\")] + \"-\" + username\n        try:\n            os.unlink(dest)\n        except OSError:\n            pass\n        try:\n            os.symlink(src, dest)\n        except (OSError, AttributeError, NotImplementedError):\n            pass\n\n        return udir\n\n\ndef copymode(src, dest):\n    \"\"\"Copy permission from src to dst.\"\"\"\n    import shutil\n\n    shutil.copymode(src, dest)\n\n\ndef copystat(src, dest):\n    \"\"\"Copy permission,  last modification time,\n    last access time, and flags from src to dst.\"\"\"\n    import shutil\n\n    shutil.copystat(str(src), str(dest))\n\n\ndef copychunked(src, dest):\n    chunksize = 524288  # half a meg of bytes\n    fsrc = src.open(\"rb\")\n    try:\n        fdest = dest.open(\"wb\")\n        try:\n            while 1:\n                buf = fsrc.read(chunksize)\n                if not buf:\n                    break\n                fdest.write(buf)\n        finally:\n            fdest.close()\n    finally:\n        fsrc.close()\n\n\ndef isimportable(name):\n    if name and (name[0].isalpha() or name[0] == \"_\"):\n        name = name.replace(\"_\", \"\")\n        return not name or name.isalnum()\n\n\nlocal = LocalPath\n"
  },
  {
    "path": "src/_pytest/assertion/__init__.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Support for presenting detailed information in failing assertions.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nimport sys\nfrom typing import Any\nfrom typing import Protocol\nfrom typing import TYPE_CHECKING\n\nfrom _pytest.assertion import rewrite\nfrom _pytest.assertion import truncate\nfrom _pytest.assertion import util\nfrom _pytest.assertion.rewrite import assertstate_key\nfrom _pytest.config import Config\nfrom _pytest.config import hookimpl\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.nodes import Item\n\n\nif TYPE_CHECKING:\n    from _pytest.main import Session\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"debugconfig\")\n    group.addoption(\n        \"--assert\",\n        action=\"store\",\n        dest=\"assertmode\",\n        choices=(\"rewrite\", \"plain\"),\n        default=\"rewrite\",\n        metavar=\"MODE\",\n        help=(\n            \"Control assertion debugging tools.\\n\"\n            \"'plain' performs no assertion debugging.\\n\"\n            \"'rewrite' (the default) rewrites assert statements in test modules\"\n            \" on import to provide assert expression information.\"\n        ),\n    )\n    parser.addini(\n        \"enable_assertion_pass_hook\",\n        type=\"bool\",\n        default=False,\n        help=\"Enables the pytest_assertion_pass hook. \"\n        \"Make sure to delete any previously generated pyc cache files.\",\n    )\n\n    parser.addini(\n        \"truncation_limit_lines\",\n        default=None,\n        help=\"Set threshold of LINES after which truncation will take effect\",\n    )\n    parser.addini(\n        \"truncation_limit_chars\",\n        default=None,\n        help=(\"Set threshold of CHARS after which truncation will take effect\"),\n    )\n\n    Config._add_verbosity_ini(\n        parser,\n        Config.VERBOSITY_ASSERTIONS,\n        help=(\n            \"Specify a verbosity level for assertions, overriding the main level. \"\n            \"Higher levels will provide more detailed explanation when an assertion fails.\"\n        ),\n    )\n\n\ndef register_assert_rewrite(*names: str) -> None:\n    \"\"\"Register one or more module names to be rewritten on import.\n\n    This function will make sure that this module or all modules inside\n    the package will get their assert statements rewritten.\n    Thus you should make sure to call this before the module is\n    actually imported, usually in your __init__.py if you are a plugin\n    using a package.\n\n    :param names: The module names to register.\n    \"\"\"\n    for name in names:\n        if not isinstance(name, str):\n            msg = \"expected module names as *args, got {0} instead\"  # type: ignore[unreachable]\n            raise TypeError(msg.format(repr(names)))\n    rewrite_hook: RewriteHook\n    for hook in sys.meta_path:\n        if isinstance(hook, rewrite.AssertionRewritingHook):\n            rewrite_hook = hook\n            break\n    else:\n        rewrite_hook = DummyRewriteHook()\n    rewrite_hook.mark_rewrite(*names)\n\n\nclass RewriteHook(Protocol):\n    def mark_rewrite(self, *names: str) -> None: ...\n\n\nclass DummyRewriteHook:\n    \"\"\"A no-op import hook for when rewriting is disabled.\"\"\"\n\n    def mark_rewrite(self, *names: str) -> None:\n        pass\n\n\nclass AssertionState:\n    \"\"\"State for the assertion plugin.\"\"\"\n\n    def __init__(self, config: Config, mode) -> None:\n        self.mode = mode\n        self.trace = config.trace.root.get(\"assertion\")\n        self.hook: rewrite.AssertionRewritingHook | None = None\n\n\ndef install_importhook(config: Config) -> rewrite.AssertionRewritingHook:\n    \"\"\"Try to install the rewrite hook, raise SystemError if it fails.\"\"\"\n    config.stash[assertstate_key] = AssertionState(config, \"rewrite\")\n    config.stash[assertstate_key].hook = hook = rewrite.AssertionRewritingHook(config)\n    sys.meta_path.insert(0, hook)\n    config.stash[assertstate_key].trace(\"installed rewrite import hook\")\n\n    def undo() -> None:\n        hook = config.stash[assertstate_key].hook\n        if hook is not None and hook in sys.meta_path:\n            sys.meta_path.remove(hook)\n\n    config.add_cleanup(undo)\n    return hook\n\n\ndef pytest_collection(session: Session) -> None:\n    # This hook is only called when test modules are collected\n    # so for example not in the managing process of pytest-xdist\n    # (which does not collect test modules).\n    assertstate = session.config.stash.get(assertstate_key, None)\n    if assertstate:\n        if assertstate.hook is not None:\n            assertstate.hook.set_session(session)\n\n\n@hookimpl(wrapper=True, tryfirst=True)\ndef pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:\n    \"\"\"Setup the pytest_assertrepr_compare and pytest_assertion_pass hooks.\n\n    The rewrite module will use util._reprcompare if it exists to use custom\n    reporting via the pytest_assertrepr_compare hook.  This sets up this custom\n    comparison for the test.\n    \"\"\"\n    ihook = item.ihook\n\n    def callbinrepr(op, left: object, right: object) -> str | None:\n        \"\"\"Call the pytest_assertrepr_compare hook and prepare the result.\n\n        This uses the first result from the hook and then ensures the\n        following:\n        * Overly verbose explanations are truncated unless configured otherwise\n          (eg. if running in verbose mode).\n        * Embedded newlines are escaped to help util.format_explanation()\n          later.\n        * If the rewrite mode is used embedded %-characters are replaced\n          to protect later % formatting.\n\n        The result can be formatted by util.format_explanation() for\n        pretty printing.\n        \"\"\"\n        hook_result = ihook.pytest_assertrepr_compare(\n            config=item.config, op=op, left=left, right=right\n        )\n        for new_expl in hook_result:\n            if new_expl:\n                new_expl = truncate.truncate_if_required(new_expl, item)\n                new_expl = [line.replace(\"\\n\", \"\\\\n\") for line in new_expl]\n                res = \"\\n~\".join(new_expl)\n                if item.config.getvalue(\"assertmode\") == \"rewrite\":\n                    res = res.replace(\"%\", \"%%\")\n                return res\n        return None\n\n    saved_assert_hooks = util._reprcompare, util._assertion_pass\n    util._reprcompare = callbinrepr\n    util._config = item.config\n\n    if ihook.pytest_assertion_pass.get_hookimpls():\n\n        def call_assertion_pass_hook(lineno: int, orig: str, expl: str) -> None:\n            ihook.pytest_assertion_pass(item=item, lineno=lineno, orig=orig, expl=expl)\n\n        util._assertion_pass = call_assertion_pass_hook\n\n    try:\n        return (yield)\n    finally:\n        util._reprcompare, util._assertion_pass = saved_assert_hooks\n        util._config = None\n\n\ndef pytest_sessionfinish(session: Session) -> None:\n    assertstate = session.config.stash.get(assertstate_key, None)\n    if assertstate:\n        if assertstate.hook is not None:\n            assertstate.hook.set_session(None)\n\n\ndef pytest_assertrepr_compare(\n    config: Config, op: str, left: Any, right: Any\n) -> list[str] | None:\n    return util.assertrepr_compare(config=config, op=op, left=left, right=right)\n"
  },
  {
    "path": "src/_pytest/assertion/rewrite.py",
    "content": "\"\"\"Rewrite assertion AST to produce nice error messages.\"\"\"\n\nfrom __future__ import annotations\n\nimport ast\nfrom collections import defaultdict\nfrom collections.abc import Callable\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nfrom collections.abc import Sequence\nimport errno\nimport functools\nimport importlib.abc\nimport importlib.machinery\nimport importlib.util\nimport io\nimport itertools\nimport marshal\nimport os\nfrom pathlib import Path\nfrom pathlib import PurePath\nimport struct\nimport sys\nimport tokenize\nimport types\nfrom typing import IO\nfrom typing import TYPE_CHECKING\n\n\nif sys.version_info >= (3, 12):\n    from importlib.resources.abc import TraversableResources\nelse:\n    from importlib.abc import TraversableResources\nif sys.version_info < (3, 11):\n    from importlib.readers import FileReader\nelse:\n    from importlib.resources.readers import FileReader\n\n\nfrom _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest._io.saferepr import saferepr_unlimited\nfrom _pytest._version import version\nfrom _pytest.assertion import util\nfrom _pytest.config import Config\nfrom _pytest.fixtures import FixtureFunctionDefinition\nfrom _pytest.main import Session\nfrom _pytest.pathlib import absolutepath\nfrom _pytest.pathlib import fnmatch_ex\nfrom _pytest.stash import StashKey\n\n\n# fmt: off\nfrom _pytest.assertion.util import format_explanation as _format_explanation  # noqa:F401, isort:skip\n# fmt:on\n\nif TYPE_CHECKING:\n    from _pytest.assertion import AssertionState\n\n\nclass Sentinel:\n    pass\n\n\nassertstate_key = StashKey[\"AssertionState\"]()\n\n# pytest caches rewritten pycs in pycache dirs\nPYTEST_TAG = f\"{sys.implementation.cache_tag}-pytest-{version}\"\nPYC_EXT = \".py\" + ((__debug__ and \"c\") or \"o\")\nPYC_TAIL = \".\" + PYTEST_TAG + PYC_EXT\n\n# Special marker that denotes we have just left a scope definition\n_SCOPE_END_MARKER = Sentinel()\n\n\nclass AssertionRewritingHook(importlib.abc.MetaPathFinder, importlib.abc.Loader):\n    \"\"\"PEP302/PEP451 import hook which rewrites asserts.\"\"\"\n\n    def __init__(self, config: Config) -> None:\n        self.config = config\n        try:\n            self.fnpats = config.getini(\"python_files\")\n        except ValueError:\n            self.fnpats = [\"test_*.py\", \"*_test.py\"]\n        self.session: Session | None = None\n        self._rewritten_names: dict[str, Path] = {}\n        self._must_rewrite: set[str] = set()\n        # flag to guard against trying to rewrite a pyc file while we are already writing another pyc file,\n        # which might result in infinite recursion (#3506)\n        self._writing_pyc = False\n        self._basenames_to_check_rewrite = {\"conftest\"}\n        self._marked_for_rewrite_cache: dict[str, bool] = {}\n        self._session_paths_checked = False\n\n    def set_session(self, session: Session | None) -> None:\n        self.session = session\n        self._session_paths_checked = False\n\n    # Indirection so we can mock calls to find_spec originated from the hook during testing\n    _find_spec = importlib.machinery.PathFinder.find_spec\n\n    def find_spec(\n        self,\n        name: str,\n        path: Sequence[str | bytes] | None = None,\n        target: types.ModuleType | None = None,\n    ) -> importlib.machinery.ModuleSpec | None:\n        if self._writing_pyc:\n            return None\n        state = self.config.stash[assertstate_key]\n        if self._early_rewrite_bailout(name, state):\n            return None\n        state.trace(f\"find_module called for: {name}\")\n\n        # Type ignored because mypy is confused about the `self` binding here.\n        spec = self._find_spec(name, path)  # type: ignore\n\n        if spec is None and path is not None:\n            # With --import-mode=importlib, PathFinder cannot find spec without modifying `sys.path`,\n            # causing inability to assert rewriting (#12659).\n            # At this point, try using the file path to find the module spec.\n            for _path_str in path:\n                spec = importlib.util.spec_from_file_location(name, _path_str)\n                if spec is not None:\n                    break\n\n        if (\n            # the import machinery could not find a file to import\n            spec is None\n            # this is a namespace package (without `__init__.py`)\n            # there's nothing to rewrite there\n            or spec.origin is None\n            # we can only rewrite source files\n            or not isinstance(spec.loader, importlib.machinery.SourceFileLoader)\n            # if the file doesn't exist, we can't rewrite it\n            or not os.path.exists(spec.origin)\n        ):\n            return None\n        else:\n            fn = spec.origin\n\n        if not self._should_rewrite(name, fn, state):\n            return None\n\n        return importlib.util.spec_from_file_location(\n            name,\n            fn,\n            loader=self,\n            submodule_search_locations=spec.submodule_search_locations,\n        )\n\n    def create_module(\n        self, spec: importlib.machinery.ModuleSpec\n    ) -> types.ModuleType | None:\n        return None  # default behaviour is fine\n\n    def exec_module(self, module: types.ModuleType) -> None:\n        assert module.__spec__ is not None\n        assert module.__spec__.origin is not None\n        fn = Path(module.__spec__.origin)\n        state = self.config.stash[assertstate_key]\n\n        self._rewritten_names[module.__name__] = fn\n\n        # The requested module looks like a test file, so rewrite it. This is\n        # the most magical part of the process: load the source, rewrite the\n        # asserts, and load the rewritten source. We also cache the rewritten\n        # module code in a special pyc. We must be aware of the possibility of\n        # concurrent pytest processes rewriting and loading pycs. To avoid\n        # tricky race conditions, we maintain the following invariant: The\n        # cached pyc is always a complete, valid pyc. Operations on it must be\n        # atomic. POSIX's atomic rename comes in handy.\n        write = not sys.dont_write_bytecode\n        cache_dir = get_cache_dir(fn)\n        if write:\n            ok = try_makedirs(cache_dir)\n            if not ok:\n                write = False\n                state.trace(f\"read only directory: {cache_dir}\")\n\n        cache_name = fn.name[:-3] + PYC_TAIL\n        pyc = cache_dir / cache_name\n        # Notice that even if we're in a read-only directory, I'm going\n        # to check for a cached pyc. This may not be optimal...\n        co = _read_pyc(fn, pyc, state.trace)\n        if co is None:\n            state.trace(f\"rewriting {fn!r}\")\n            source_stat, co = _rewrite_test(fn, self.config)\n            if write:\n                self._writing_pyc = True\n                try:\n                    _write_pyc(state, co, source_stat, pyc)\n                finally:\n                    self._writing_pyc = False\n        else:\n            state.trace(f\"found cached rewritten pyc for {fn}\")\n        exec(co, module.__dict__)\n\n    def _early_rewrite_bailout(self, name: str, state: AssertionState) -> bool:\n        \"\"\"A fast way to get out of rewriting modules.\n\n        Profiling has shown that the call to PathFinder.find_spec (inside of\n        the find_spec from this class) is a major slowdown, so, this method\n        tries to filter what we're sure won't be rewritten before getting to\n        it.\n        \"\"\"\n        if self.session is not None and not self._session_paths_checked:\n            self._session_paths_checked = True\n            for initial_path in self.session._initialpaths:\n                # Make something as c:/projects/my_project/path.py ->\n                #     ['c:', 'projects', 'my_project', 'path.py']\n                parts = str(initial_path).split(os.sep)\n                # add 'path' to basenames to be checked.\n                self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0])\n\n        # Note: conftest already by default in _basenames_to_check_rewrite.\n        parts = name.split(\".\")\n        if parts[-1] in self._basenames_to_check_rewrite:\n            return False\n\n        # For matching the name it must be as if it was a filename.\n        path = PurePath(*parts).with_suffix(\".py\")\n\n        for pat in self.fnpats:\n            # if the pattern contains subdirectories (\"tests/**.py\" for example) we can't bail out based\n            # on the name alone because we need to match against the full path\n            if os.path.dirname(pat):\n                return False\n            if fnmatch_ex(pat, path):\n                return False\n\n        if self._is_marked_for_rewrite(name, state):\n            return False\n\n        state.trace(f\"early skip of rewriting module: {name}\")\n        return True\n\n    def _should_rewrite(self, name: str, fn: str, state: AssertionState) -> bool:\n        # always rewrite conftest files\n        if os.path.basename(fn) == \"conftest.py\":\n            state.trace(f\"rewriting conftest file: {fn!r}\")\n            return True\n\n        if self.session is not None:\n            if self.session.isinitpath(absolutepath(fn)):\n                state.trace(f\"matched test file (was specified on cmdline): {fn!r}\")\n                return True\n\n        # modules not passed explicitly on the command line are only\n        # rewritten if they match the naming convention for test files\n        fn_path = PurePath(fn)\n        for pat in self.fnpats:\n            if fnmatch_ex(pat, fn_path):\n                state.trace(f\"matched test file {fn!r}\")\n                return True\n\n        return self._is_marked_for_rewrite(name, state)\n\n    def _is_marked_for_rewrite(self, name: str, state: AssertionState) -> bool:\n        try:\n            return self._marked_for_rewrite_cache[name]\n        except KeyError:\n            for marked in self._must_rewrite:\n                if name == marked or name.startswith(marked + \".\"):\n                    state.trace(f\"matched marked file {name!r} (from {marked!r})\")\n                    self._marked_for_rewrite_cache[name] = True\n                    return True\n\n            self._marked_for_rewrite_cache[name] = False\n            return False\n\n    def mark_rewrite(self, *names: str) -> None:\n        \"\"\"Mark import names as needing to be rewritten.\n\n        The named module or package as well as any nested modules will\n        be rewritten on import.\n        \"\"\"\n        already_imported = (\n            set(names).intersection(sys.modules).difference(self._rewritten_names)\n        )\n        for name in already_imported:\n            mod = sys.modules[name]\n            if not AssertionRewriter.is_rewrite_disabled(\n                mod.__doc__ or \"\"\n            ) and not isinstance(mod.__loader__, type(self)):\n                self._warn_already_imported(name)\n        self._must_rewrite.update(names)\n        self._marked_for_rewrite_cache.clear()\n\n    def _warn_already_imported(self, name: str) -> None:\n        from _pytest.warning_types import PytestAssertRewriteWarning\n\n        self.config.issue_config_time_warning(\n            PytestAssertRewriteWarning(\n                f\"Module already imported so cannot be rewritten; {name}\"\n            ),\n            stacklevel=5,\n        )\n\n    def get_data(self, pathname: str | bytes) -> bytes:\n        \"\"\"Optional PEP302 get_data API.\"\"\"\n        with open(pathname, \"rb\") as f:\n            return f.read()\n\n    def get_resource_reader(self, name: str) -> TraversableResources:\n        return FileReader(types.SimpleNamespace(path=self._rewritten_names[name]))  # type: ignore[arg-type]\n\n\ndef _write_pyc_fp(\n    fp: IO[bytes], source_stat: os.stat_result, co: types.CodeType\n) -> None:\n    # Technically, we don't have to have the same pyc format as\n    # (C)Python, since these \"pycs\" should never be seen by builtin\n    # import. However, there's little reason to deviate.\n    fp.write(importlib.util.MAGIC_NUMBER)\n    # https://www.python.org/dev/peps/pep-0552/\n    flags = b\"\\x00\\x00\\x00\\x00\"\n    fp.write(flags)\n    # as of now, bytecode header expects 32-bit numbers for size and mtime (#4903)\n    mtime = int(source_stat.st_mtime) & 0xFFFFFFFF\n    size = source_stat.st_size & 0xFFFFFFFF\n    # \"<LL\" stands for 2 unsigned longs, little-endian.\n    fp.write(struct.pack(\"<LL\", mtime, size))\n    fp.write(marshal.dumps(co))\n\n\ndef _write_pyc(\n    state: AssertionState,\n    co: types.CodeType,\n    source_stat: os.stat_result,\n    pyc: Path,\n) -> bool:\n    proc_pyc = f\"{pyc}.{os.getpid()}\"\n    try:\n        with open(proc_pyc, \"wb\") as fp:\n            _write_pyc_fp(fp, source_stat, co)\n    except OSError as e:\n        state.trace(f\"error writing pyc file at {proc_pyc}: errno={e.errno}\")\n        return False\n\n    try:\n        os.replace(proc_pyc, pyc)\n    except OSError as e:\n        state.trace(f\"error writing pyc file at {pyc}: {e}\")\n        # we ignore any failure to write the cache file\n        # there are many reasons, permission-denied, pycache dir being a\n        # file etc.\n        return False\n    return True\n\n\ndef _rewrite_test(fn: Path, config: Config) -> tuple[os.stat_result, types.CodeType]:\n    \"\"\"Read and rewrite *fn* and return the code object.\"\"\"\n    stat = os.stat(fn)\n    source = fn.read_bytes()\n    strfn = str(fn)\n    tree = ast.parse(source, filename=strfn)\n    rewrite_asserts(tree, source, strfn, config)\n    co = compile(tree, strfn, \"exec\", dont_inherit=True)\n    return stat, co\n\n\ndef _read_pyc(\n    source: Path, pyc: Path, trace: Callable[[str], None] = lambda x: None\n) -> types.CodeType | None:\n    \"\"\"Possibly read a pytest pyc containing rewritten code.\n\n    Return rewritten code if successful or None if not.\n    \"\"\"\n    try:\n        fp = open(pyc, \"rb\")\n    except OSError:\n        return None\n    with fp:\n        try:\n            stat_result = os.stat(source)\n            mtime = int(stat_result.st_mtime)\n            size = stat_result.st_size\n            data = fp.read(16)\n        except OSError as e:\n            trace(f\"_read_pyc({source}): OSError {e}\")\n            return None\n        # Check for invalid or out of date pyc file.\n        if len(data) != (16):\n            trace(f\"_read_pyc({source}): invalid pyc (too short)\")\n            return None\n        if data[:4] != importlib.util.MAGIC_NUMBER:\n            trace(f\"_read_pyc({source}): invalid pyc (bad magic number)\")\n            return None\n        if data[4:8] != b\"\\x00\\x00\\x00\\x00\":\n            trace(f\"_read_pyc({source}): invalid pyc (unsupported flags)\")\n            return None\n        mtime_data = data[8:12]\n        if int.from_bytes(mtime_data, \"little\") != mtime & 0xFFFFFFFF:\n            trace(f\"_read_pyc({source}): out of date\")\n            return None\n        size_data = data[12:16]\n        if int.from_bytes(size_data, \"little\") != size & 0xFFFFFFFF:\n            trace(f\"_read_pyc({source}): invalid pyc (incorrect size)\")\n            return None\n        try:\n            co = marshal.load(fp)\n        except Exception as e:\n            trace(f\"_read_pyc({source}): marshal.load error {e}\")\n            return None\n        if not isinstance(co, types.CodeType):\n            trace(f\"_read_pyc({source}): not a code object\")\n            return None\n        return co\n\n\ndef rewrite_asserts(\n    mod: ast.Module,\n    source: bytes,\n    module_path: str | None = None,\n    config: Config | None = None,\n) -> None:\n    \"\"\"Rewrite the assert statements in mod.\"\"\"\n    AssertionRewriter(module_path, config, source).run(mod)\n\n\ndef _saferepr(obj: object) -> str:\n    r\"\"\"Get a safe repr of an object for assertion error messages.\n\n    The assertion formatting (util.format_explanation()) requires\n    newlines to be escaped since they are a special character for it.\n    Normally assertion.util.format_explanation() does this but for a\n    custom repr it is possible to contain one of the special escape\n    sequences, especially '\\n{' and '\\n}' are likely to be present in\n    JSON reprs.\n    \"\"\"\n    if isinstance(obj, types.MethodType):\n        # for bound methods, skip redundant <bound method ...> information\n        return obj.__name__\n\n    maxsize = _get_maxsize_for_saferepr(util._config)\n    if not maxsize:\n        return saferepr_unlimited(obj).replace(\"\\n\", \"\\\\n\")\n    return saferepr(obj, maxsize=maxsize).replace(\"\\n\", \"\\\\n\")\n\n\ndef _get_maxsize_for_saferepr(config: Config | None) -> int | None:\n    \"\"\"Get `maxsize` configuration for saferepr based on the given config object.\"\"\"\n    if config is None:\n        verbosity = 0\n    else:\n        verbosity = config.get_verbosity(Config.VERBOSITY_ASSERTIONS)\n    if verbosity >= 2:\n        return None\n    if verbosity >= 1:\n        return DEFAULT_REPR_MAX_SIZE * 10\n    return DEFAULT_REPR_MAX_SIZE\n\n\ndef _format_assertmsg(obj: object) -> str:\n    r\"\"\"Format the custom assertion message given.\n\n    For strings this simply replaces newlines with '\\n~' so that\n    util.format_explanation() will preserve them instead of escaping\n    newlines.  For other objects saferepr() is used first.\n    \"\"\"\n    # reprlib appears to have a bug which means that if a string\n    # contains a newline it gets escaped, however if an object has a\n    # .__repr__() which contains newlines it does not get escaped.\n    # However in either case we want to preserve the newline.\n    replaces = [(\"\\n\", \"\\n~\"), (\"%\", \"%%\")]\n    if not isinstance(obj, str):\n        obj = saferepr(obj, _get_maxsize_for_saferepr(util._config))\n        replaces.append((\"\\\\n\", \"\\n~\"))\n\n    for r1, r2 in replaces:\n        obj = obj.replace(r1, r2)\n\n    return obj\n\n\ndef _should_repr_global_name(obj: object) -> bool:\n    if callable(obj):\n        # For pytest fixtures the __repr__ method provides more information than the function name.\n        return isinstance(obj, FixtureFunctionDefinition)\n\n    try:\n        return not hasattr(obj, \"__name__\")\n    except Exception:\n        return True\n\n\ndef _format_boolop(explanations: Iterable[str], is_or: bool) -> str:\n    explanation = \"(\" + ((is_or and \" or \") or \" and \").join(explanations) + \")\"\n    return explanation.replace(\"%\", \"%%\")\n\n\ndef _call_reprcompare(\n    ops: Sequence[str],\n    results: Sequence[bool],\n    expls: Sequence[str],\n    each_obj: Sequence[object],\n) -> str:\n    for i, res, expl in zip(range(len(ops)), results, expls, strict=True):\n        try:\n            done = not res\n        except Exception:\n            done = True\n        if done:\n            break\n    if util._reprcompare is not None:\n        custom = util._reprcompare(ops[i], each_obj[i], each_obj[i + 1])\n        if custom is not None:\n            return custom\n    return expl\n\n\ndef _call_assertion_pass(lineno: int, orig: str, expl: str) -> None:\n    if util._assertion_pass is not None:\n        util._assertion_pass(lineno, orig, expl)\n\n\ndef _check_if_assertion_pass_impl() -> bool:\n    \"\"\"Check if any plugins implement the pytest_assertion_pass hook\n    in order not to generate explanation unnecessarily (might be expensive).\"\"\"\n    return True if util._assertion_pass else False\n\n\nUNARY_MAP = {ast.Not: \"not %s\", ast.Invert: \"~%s\", ast.USub: \"-%s\", ast.UAdd: \"+%s\"}\n\nBINOP_MAP = {\n    ast.BitOr: \"|\",\n    ast.BitXor: \"^\",\n    ast.BitAnd: \"&\",\n    ast.LShift: \"<<\",\n    ast.RShift: \">>\",\n    ast.Add: \"+\",\n    ast.Sub: \"-\",\n    ast.Mult: \"*\",\n    ast.Div: \"/\",\n    ast.FloorDiv: \"//\",\n    ast.Mod: \"%%\",  # escaped for string formatting\n    ast.Eq: \"==\",\n    ast.NotEq: \"!=\",\n    ast.Lt: \"<\",\n    ast.LtE: \"<=\",\n    ast.Gt: \">\",\n    ast.GtE: \">=\",\n    ast.Pow: \"**\",\n    ast.Is: \"is\",\n    ast.IsNot: \"is not\",\n    ast.In: \"in\",\n    ast.NotIn: \"not in\",\n    ast.MatMult: \"@\",\n}\n\n\ndef traverse_node(node: ast.AST) -> Iterator[ast.AST]:\n    \"\"\"Recursively yield node and all its children in depth-first order.\"\"\"\n    yield node\n    for child in ast.iter_child_nodes(node):\n        yield from traverse_node(child)\n\n\n@functools.lru_cache(maxsize=1)\ndef _get_assertion_exprs(src: bytes) -> dict[int, str]:\n    \"\"\"Return a mapping from {lineno: \"assertion test expression\"}.\"\"\"\n    ret: dict[int, str] = {}\n\n    depth = 0\n    lines: list[str] = []\n    assert_lineno: int | None = None\n    seen_lines: set[int] = set()\n\n    def _write_and_reset() -> None:\n        nonlocal depth, lines, assert_lineno, seen_lines\n        assert assert_lineno is not None\n        ret[assert_lineno] = \"\".join(lines).rstrip().rstrip(\"\\\\\")\n        depth = 0\n        lines = []\n        assert_lineno = None\n        seen_lines = set()\n\n    tokens = tokenize.tokenize(io.BytesIO(src).readline)\n    for tp, source, (lineno, offset), _, line in tokens:\n        if tp == tokenize.NAME and source == \"assert\":\n            assert_lineno = lineno\n        elif assert_lineno is not None:\n            # keep track of depth for the assert-message `,` lookup\n            if tp == tokenize.OP and source in \"([{\":\n                depth += 1\n            elif tp == tokenize.OP and source in \")]}\":\n                depth -= 1\n\n            if not lines:\n                lines.append(line[offset:])\n                seen_lines.add(lineno)\n            # a non-nested comma separates the expression from the message\n            elif depth == 0 and tp == tokenize.OP and source == \",\":\n                # one line assert with message\n                if lineno in seen_lines and len(lines) == 1:\n                    offset_in_trimmed = offset + len(lines[-1]) - len(line)\n                    lines[-1] = lines[-1][:offset_in_trimmed]\n                # multi-line assert with message\n                elif lineno in seen_lines:\n                    lines[-1] = lines[-1][:offset]\n                # multi line assert with escaped newline before message\n                else:\n                    lines.append(line[:offset])\n                _write_and_reset()\n            elif tp in {tokenize.NEWLINE, tokenize.ENDMARKER}:\n                _write_and_reset()\n            elif lines and lineno not in seen_lines:\n                lines.append(line)\n                seen_lines.add(lineno)\n\n    return ret\n\n\nclass AssertionRewriter(ast.NodeVisitor):\n    \"\"\"Assertion rewriting implementation.\n\n    The main entrypoint is to call .run() with an ast.Module instance,\n    this will then find all the assert statements and rewrite them to\n    provide intermediate values and a detailed assertion error.  See\n    http://pybites.blogspot.be/2011/07/behind-scenes-of-pytests-new-assertion.html\n    for an overview of how this works.\n\n    The entry point here is .run() which will iterate over all the\n    statements in an ast.Module and for each ast.Assert statement it\n    finds call .visit() with it.  Then .visit_Assert() takes over and\n    is responsible for creating new ast statements to replace the\n    original assert statement: it rewrites the test of an assertion\n    to provide intermediate values and replace it with an if statement\n    which raises an assertion error with a detailed explanation in\n    case the expression is false and calls pytest_assertion_pass hook\n    if expression is true.\n\n    For this .visit_Assert() uses the visitor pattern to visit all the\n    AST nodes of the ast.Assert.test field, each visit call returning\n    an AST node and the corresponding explanation string.  During this\n    state is kept in several instance attributes:\n\n    :statements: All the AST statements which will replace the assert\n       statement.\n\n    :variables: This is populated by .variable() with each variable\n       used by the statements so that they can all be set to None at\n       the end of the statements.\n\n    :variable_counter: Counter to create new unique variables needed\n       by statements.  Variables are created using .variable() and\n       have the form of \"@py_assert0\".\n\n    :expl_stmts: The AST statements which will be executed to get\n       data from the assertion.  This is the code which will construct\n       the detailed assertion message that is used in the AssertionError\n       or for the pytest_assertion_pass hook.\n\n    :explanation_specifiers: A dict filled by .explanation_param()\n       with %-formatting placeholders and their corresponding\n       expressions to use in the building of an assertion message.\n       This is used by .pop_format_context() to build a message.\n\n    :stack: A stack of the explanation_specifiers dicts maintained by\n       .push_format_context() and .pop_format_context() which allows\n       to build another %-formatted string while already building one.\n\n    :scope: A tuple containing the current scope used for variables_overwrite.\n\n    :variables_overwrite: A dict filled with references to variables\n       that change value within an assert. This happens when a variable is\n       reassigned with the walrus operator\n\n    This state, except the variables_overwrite,  is reset on every new assert\n    statement visited and used by the other visitors.\n    \"\"\"\n\n    def __init__(\n        self, module_path: str | None, config: Config | None, source: bytes\n    ) -> None:\n        super().__init__()\n        self.module_path = module_path\n        self.config = config\n        if config is not None:\n            self.enable_assertion_pass_hook = config.getini(\n                \"enable_assertion_pass_hook\"\n            )\n        else:\n            self.enable_assertion_pass_hook = False\n        self.source = source\n        self.scope: tuple[ast.AST, ...] = ()\n        self.variables_overwrite: defaultdict[tuple[ast.AST, ...], dict[str, str]] = (\n            defaultdict(dict)\n        )\n\n    def run(self, mod: ast.Module) -> None:\n        \"\"\"Find all assert statements in *mod* and rewrite them.\"\"\"\n        if not mod.body:\n            # Nothing to do.\n            return\n\n        # We'll insert some special imports at the top of the module, but after any\n        # docstrings and __future__ imports, so first figure out where that is.\n        doc = getattr(mod, \"docstring\", None)\n        expect_docstring = doc is None\n        if doc is not None and self.is_rewrite_disabled(doc):\n            return\n        pos = 0\n        for item in mod.body:\n            match item:\n                case ast.Expr(value=ast.Constant(value=str() as doc)) if (\n                    expect_docstring\n                ):\n                    if self.is_rewrite_disabled(doc):\n                        return\n                    expect_docstring = False\n                case ast.ImportFrom(level=0, module=\"__future__\"):\n                    pass\n                case _:\n                    break\n            pos += 1\n        # Special case: for a decorated function, set the lineno to that of the\n        # first decorator, not the `def`. Issue #4984.\n        if isinstance(item, ast.FunctionDef) and item.decorator_list:\n            lineno = item.decorator_list[0].lineno\n        else:\n            lineno = item.lineno\n        # Now actually insert the special imports.\n        aliases = [\n            ast.alias(\"builtins\", \"@py_builtins\", lineno=lineno, col_offset=0),\n            ast.alias(\n                \"_pytest.assertion.rewrite\",\n                \"@pytest_ar\",\n                lineno=lineno,\n                col_offset=0,\n            ),\n        ]\n        imports = [\n            ast.Import([alias], lineno=lineno, col_offset=0) for alias in aliases\n        ]\n        mod.body[pos:pos] = imports\n\n        # Collect asserts.\n        self.scope = (mod,)\n        nodes: list[ast.AST | Sentinel] = [mod]\n        while nodes:\n            node = nodes.pop()\n            if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):\n                self.scope = tuple((*self.scope, node))\n                nodes.append(_SCOPE_END_MARKER)\n            if node == _SCOPE_END_MARKER:\n                self.scope = self.scope[:-1]\n                continue\n            assert isinstance(node, ast.AST)\n            for name, field in ast.iter_fields(node):\n                if isinstance(field, list):\n                    new: list[ast.AST] = []\n                    for i, child in enumerate(field):\n                        if isinstance(child, ast.Assert):\n                            # Transform assert.\n                            new.extend(self.visit(child))\n                        else:\n                            new.append(child)\n                            if isinstance(child, ast.AST):\n                                nodes.append(child)\n                    setattr(node, name, new)\n                elif (\n                    isinstance(field, ast.AST)\n                    # Don't recurse into expressions as they can't contain\n                    # asserts.\n                    and not isinstance(field, ast.expr)\n                ):\n                    nodes.append(field)\n\n    @staticmethod\n    def is_rewrite_disabled(docstring: str) -> bool:\n        return \"PYTEST_DONT_REWRITE\" in docstring\n\n    def variable(self) -> str:\n        \"\"\"Get a new variable.\"\"\"\n        # Use a character invalid in python identifiers to avoid clashing.\n        name = \"@py_assert\" + str(next(self.variable_counter))\n        self.variables.append(name)\n        return name\n\n    def assign(self, expr: ast.expr) -> ast.Name:\n        \"\"\"Give *expr* a name.\"\"\"\n        name = self.variable()\n        self.statements.append(ast.Assign([ast.Name(name, ast.Store())], expr))\n        return ast.copy_location(ast.Name(name, ast.Load()), expr)\n\n    def display(self, expr: ast.expr) -> ast.expr:\n        \"\"\"Call saferepr on the expression.\"\"\"\n        return self.helper(\"_saferepr\", expr)\n\n    def helper(self, name: str, *args: ast.expr) -> ast.expr:\n        \"\"\"Call a helper in this module.\"\"\"\n        py_name = ast.Name(\"@pytest_ar\", ast.Load())\n        attr = ast.Attribute(py_name, name, ast.Load())\n        return ast.Call(attr, list(args), [])\n\n    def builtin(self, name: str) -> ast.Attribute:\n        \"\"\"Return the builtin called *name*.\"\"\"\n        builtin_name = ast.Name(\"@py_builtins\", ast.Load())\n        return ast.Attribute(builtin_name, name, ast.Load())\n\n    def explanation_param(self, expr: ast.expr) -> str:\n        \"\"\"Return a new named %-formatting placeholder for expr.\n\n        This creates a %-formatting placeholder for expr in the\n        current formatting context, e.g. ``%(py0)s``.  The placeholder\n        and expr are placed in the current format context so that it\n        can be used on the next call to .pop_format_context().\n        \"\"\"\n        specifier = \"py\" + str(next(self.variable_counter))\n        self.explanation_specifiers[specifier] = expr\n        return \"%(\" + specifier + \")s\"\n\n    def push_format_context(self) -> None:\n        \"\"\"Create a new formatting context.\n\n        The format context is used for when an explanation wants to\n        have a variable value formatted in the assertion message.  In\n        this case the value required can be added using\n        .explanation_param().  Finally .pop_format_context() is used\n        to format a string of %-formatted values as added by\n        .explanation_param().\n        \"\"\"\n        self.explanation_specifiers: dict[str, ast.expr] = {}\n        self.stack.append(self.explanation_specifiers)\n\n    def pop_format_context(self, expl_expr: ast.expr) -> ast.Name:\n        \"\"\"Format the %-formatted string with current format context.\n\n        The expl_expr should be an str ast.expr instance constructed from\n        the %-placeholders created by .explanation_param().  This will\n        add the required code to format said string to .expl_stmts and\n        return the ast.Name instance of the formatted string.\n        \"\"\"\n        current = self.stack.pop()\n        if self.stack:\n            self.explanation_specifiers = self.stack[-1]\n        keys: list[ast.expr | None] = [ast.Constant(key) for key in current.keys()]\n        format_dict = ast.Dict(keys, list(current.values()))\n        form = ast.BinOp(expl_expr, ast.Mod(), format_dict)\n        name = \"@py_format\" + str(next(self.variable_counter))\n        if self.enable_assertion_pass_hook:\n            self.format_variables.append(name)\n        self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))\n        return ast.Name(name, ast.Load())\n\n    def generic_visit(self, node: ast.AST) -> tuple[ast.Name, str]:\n        \"\"\"Handle expressions we don't have custom code for.\"\"\"\n        assert isinstance(node, ast.expr)\n        res = self.assign(node)\n        return res, self.explanation_param(self.display(res))\n\n    def visit_Assert(self, assert_: ast.Assert) -> list[ast.stmt]:\n        \"\"\"Return the AST statements to replace the ast.Assert instance.\n\n        This rewrites the test of an assertion to provide\n        intermediate values and replace it with an if statement which\n        raises an assertion error with a detailed explanation in case\n        the expression is false.\n        \"\"\"\n        if isinstance(assert_.test, ast.Tuple) and len(assert_.test.elts) >= 1:\n            import warnings\n\n            from _pytest.warning_types import PytestAssertRewriteWarning\n\n            # TODO: This assert should not be needed.\n            assert self.module_path is not None\n            warnings.warn_explicit(\n                PytestAssertRewriteWarning(\n                    \"assertion is always true, perhaps remove parentheses?\"\n                ),\n                category=None,\n                filename=self.module_path,\n                lineno=assert_.lineno,\n            )\n\n        self.statements: list[ast.stmt] = []\n        self.variables: list[str] = []\n        self.variable_counter = itertools.count()\n\n        if self.enable_assertion_pass_hook:\n            self.format_variables: list[str] = []\n\n        self.stack: list[dict[str, ast.expr]] = []\n        self.expl_stmts: list[ast.stmt] = []\n        self.push_format_context()\n        # Rewrite assert into a bunch of statements.\n        top_condition, explanation = self.visit(assert_.test)\n\n        negation = ast.UnaryOp(ast.Not(), top_condition)\n\n        if self.enable_assertion_pass_hook:  # Experimental pytest_assertion_pass hook\n            msg = self.pop_format_context(ast.Constant(explanation))\n\n            # Failed\n            if assert_.msg:\n                assertmsg = self.helper(\"_format_assertmsg\", assert_.msg)\n                gluestr = \"\\n>assert \"\n            else:\n                assertmsg = ast.Constant(\"\")\n                gluestr = \"assert \"\n            err_explanation = ast.BinOp(ast.Constant(gluestr), ast.Add(), msg)\n            err_msg = ast.BinOp(assertmsg, ast.Add(), err_explanation)\n            err_name = ast.Name(\"AssertionError\", ast.Load())\n            fmt = self.helper(\"_format_explanation\", err_msg)\n            exc = ast.Call(err_name, [fmt], [])\n            raise_ = ast.Raise(exc, None)\n            statements_fail = []\n            statements_fail.extend(self.expl_stmts)\n            statements_fail.append(raise_)\n\n            # Passed\n            fmt_pass = self.helper(\"_format_explanation\", msg)\n            orig = _get_assertion_exprs(self.source)[assert_.lineno]\n            hook_call_pass = ast.Expr(\n                self.helper(\n                    \"_call_assertion_pass\",\n                    ast.Constant(assert_.lineno),\n                    ast.Constant(orig),\n                    fmt_pass,\n                )\n            )\n            # If any hooks implement assert_pass hook\n            hook_impl_test = ast.If(\n                self.helper(\"_check_if_assertion_pass_impl\"),\n                [*self.expl_stmts, hook_call_pass],\n                [],\n            )\n            statements_pass: list[ast.stmt] = [hook_impl_test]\n\n            # Test for assertion condition\n            main_test = ast.If(negation, statements_fail, statements_pass)\n            self.statements.append(main_test)\n            if self.format_variables:\n                variables: list[ast.expr] = [\n                    ast.Name(name, ast.Store()) for name in self.format_variables\n                ]\n                clear_format = ast.Assign(variables, ast.Constant(None))\n                self.statements.append(clear_format)\n\n        else:  # Original assertion rewriting\n            # Create failure message.\n            body = self.expl_stmts\n            self.statements.append(ast.If(negation, body, []))\n            if assert_.msg:\n                assertmsg = self.helper(\"_format_assertmsg\", assert_.msg)\n                explanation = \"\\n>assert \" + explanation\n            else:\n                assertmsg = ast.Constant(\"\")\n                explanation = \"assert \" + explanation\n            template = ast.BinOp(assertmsg, ast.Add(), ast.Constant(explanation))\n            msg = self.pop_format_context(template)\n            fmt = self.helper(\"_format_explanation\", msg)\n            err_name = ast.Name(\"AssertionError\", ast.Load())\n            exc = ast.Call(err_name, [fmt], [])\n            raise_ = ast.Raise(exc, None)\n\n            body.append(raise_)\n\n        # Clear temporary variables by setting them to None.\n        if self.variables:\n            variables = [ast.Name(name, ast.Store()) for name in self.variables]\n            clear = ast.Assign(variables, ast.Constant(None))\n            self.statements.append(clear)\n        # Fix locations (line numbers/column offsets).\n        for stmt in self.statements:\n            for node in traverse_node(stmt):\n                if getattr(node, \"lineno\", None) is None:\n                    # apply the assertion location to all generated ast nodes without source location\n                    # and preserve the location of existing nodes or generated nodes with an correct location.\n                    ast.copy_location(node, assert_)\n        return self.statements\n\n    def visit_NamedExpr(self, name: ast.NamedExpr) -> tuple[ast.NamedExpr, str]:\n        # This method handles the 'walrus operator' repr of the target\n        # name if it's a local variable or _should_repr_global_name()\n        # thinks it's acceptable.\n        locs = ast.Call(self.builtin(\"locals\"), [], [])\n        target_id = name.target.id\n        inlocs = ast.Compare(ast.Constant(target_id), [ast.In()], [locs])\n        dorepr = self.helper(\"_should_repr_global_name\", name)\n        test = ast.BoolOp(ast.Or(), [inlocs, dorepr])\n        expr = ast.IfExp(test, self.display(name), ast.Constant(target_id))\n        return name, self.explanation_param(expr)\n\n    def visit_Name(self, name: ast.Name) -> tuple[ast.Name, str]:\n        # Display the repr of the name if it's a local variable or\n        # _should_repr_global_name() thinks it's acceptable.\n        locs = ast.Call(self.builtin(\"locals\"), [], [])\n        inlocs = ast.Compare(ast.Constant(name.id), [ast.In()], [locs])\n        dorepr = self.helper(\"_should_repr_global_name\", name)\n        test = ast.BoolOp(ast.Or(), [inlocs, dorepr])\n        expr = ast.IfExp(test, self.display(name), ast.Constant(name.id))\n        return name, self.explanation_param(expr)\n\n    def visit_BoolOp(self, boolop: ast.BoolOp) -> tuple[ast.Name, str]:\n        res_var = self.variable()\n        expl_list = self.assign(ast.List([], ast.Load()))\n        app = ast.Attribute(expl_list, \"append\", ast.Load())\n        is_or = int(isinstance(boolop.op, ast.Or))\n        body = save = self.statements\n        fail_save = self.expl_stmts\n        levels = len(boolop.values) - 1\n        self.push_format_context()\n        # Process each operand, short-circuiting if needed.\n        for i, v in enumerate(boolop.values):\n            if i:\n                fail_inner: list[ast.stmt] = []\n                # cond is set in a prior loop iteration below\n                self.expl_stmts.append(ast.If(cond, fail_inner, []))  # noqa: F821\n                self.expl_stmts = fail_inner\n                match v:\n                    # Check if the left operand is an ast.NamedExpr and the value has already been visited\n                    case ast.Compare(\n                        left=ast.NamedExpr(target=ast.Name(id=target_id))\n                    ) if target_id in [\n                        e.id for e in boolop.values[:i] if hasattr(e, \"id\")\n                    ]:\n                        pytest_temp = self.variable()\n                        self.variables_overwrite[self.scope][target_id] = v.left  # type:ignore[assignment]\n                        # mypy's false positive, we're checking that the 'target' attribute exists.\n                        v.left.target.id = pytest_temp  # type:ignore[attr-defined]\n            self.push_format_context()\n            res, expl = self.visit(v)\n            body.append(ast.Assign([ast.Name(res_var, ast.Store())], res))\n            expl_format = self.pop_format_context(ast.Constant(expl))\n            call = ast.Call(app, [expl_format], [])\n            self.expl_stmts.append(ast.Expr(call))\n            if i < levels:\n                cond: ast.expr = res\n                if is_or:\n                    cond = ast.UnaryOp(ast.Not(), cond)\n                inner: list[ast.stmt] = []\n                self.statements.append(ast.If(cond, inner, []))\n                self.statements = body = inner\n        self.statements = save\n        self.expl_stmts = fail_save\n        expl_template = self.helper(\"_format_boolop\", expl_list, ast.Constant(is_or))\n        expl = self.pop_format_context(expl_template)\n        return ast.Name(res_var, ast.Load()), self.explanation_param(expl)\n\n    def visit_UnaryOp(self, unary: ast.UnaryOp) -> tuple[ast.Name, str]:\n        pattern = UNARY_MAP[unary.op.__class__]\n        operand_res, operand_expl = self.visit(unary.operand)\n        res = self.assign(ast.copy_location(ast.UnaryOp(unary.op, operand_res), unary))\n        return res, pattern % (operand_expl,)\n\n    def visit_BinOp(self, binop: ast.BinOp) -> tuple[ast.Name, str]:\n        symbol = BINOP_MAP[binop.op.__class__]\n        left_expr, left_expl = self.visit(binop.left)\n        right_expr, right_expl = self.visit(binop.right)\n        explanation = f\"({left_expl} {symbol} {right_expl})\"\n        res = self.assign(\n            ast.copy_location(ast.BinOp(left_expr, binop.op, right_expr), binop)\n        )\n        return res, explanation\n\n    def visit_Call(self, call: ast.Call) -> tuple[ast.Name, str]:\n        new_func, func_expl = self.visit(call.func)\n        arg_expls = []\n        new_args = []\n        new_kwargs = []\n        for arg in call.args:\n            if isinstance(arg, ast.Name) and arg.id in self.variables_overwrite.get(\n                self.scope, {}\n            ):\n                arg = self.variables_overwrite[self.scope][arg.id]  # type:ignore[assignment]\n            res, expl = self.visit(arg)\n            arg_expls.append(expl)\n            new_args.append(res)\n        for keyword in call.keywords:\n            match keyword.value:\n                case ast.Name(id=id) if id in self.variables_overwrite.get(\n                    self.scope, {}\n                ):\n                    keyword.value = self.variables_overwrite[self.scope][id]  # type:ignore[assignment]\n            res, expl = self.visit(keyword.value)\n            new_kwargs.append(ast.keyword(keyword.arg, res))\n            if keyword.arg:\n                arg_expls.append(keyword.arg + \"=\" + expl)\n            else:  # **args have `arg` keywords with an .arg of None\n                arg_expls.append(\"**\" + expl)\n\n        expl = \"{}({})\".format(func_expl, \", \".join(arg_expls))\n        new_call = ast.copy_location(ast.Call(new_func, new_args, new_kwargs), call)\n        res = self.assign(new_call)\n        res_expl = self.explanation_param(self.display(res))\n        outer_expl = f\"{res_expl}\\n{{{res_expl} = {expl}\\n}}\"\n        return res, outer_expl\n\n    def visit_Starred(self, starred: ast.Starred) -> tuple[ast.Starred, str]:\n        # A Starred node can appear in a function call.\n        res, expl = self.visit(starred.value)\n        new_starred = ast.Starred(res, starred.ctx)\n        return new_starred, \"*\" + expl\n\n    def visit_Attribute(self, attr: ast.Attribute) -> tuple[ast.Name, str]:\n        if not isinstance(attr.ctx, ast.Load):\n            return self.generic_visit(attr)\n        value, value_expl = self.visit(attr.value)\n        res = self.assign(\n            ast.copy_location(ast.Attribute(value, attr.attr, ast.Load()), attr)\n        )\n        res_expl = self.explanation_param(self.display(res))\n        pat = \"%s\\n{%s = %s.%s\\n}\"\n        expl = pat % (res_expl, res_expl, value_expl, attr.attr)\n        return res, expl\n\n    def visit_Compare(self, comp: ast.Compare) -> tuple[ast.expr, str]:\n        self.push_format_context()\n        # We first check if we have overwritten a variable in the previous assert\n        match comp.left:\n            case ast.Name(id=name_id) if name_id in self.variables_overwrite.get(\n                self.scope, {}\n            ):\n                comp.left = self.variables_overwrite[self.scope][name_id]  # type: ignore[assignment]\n            case ast.NamedExpr(target=ast.Name(id=target_id)):\n                self.variables_overwrite[self.scope][target_id] = comp.left  # type: ignore[assignment]\n        left_res, left_expl = self.visit(comp.left)\n        if isinstance(comp.left, ast.Compare | ast.BoolOp):\n            left_expl = f\"({left_expl})\"\n        res_variables = [self.variable() for i in range(len(comp.ops))]\n        load_names: list[ast.expr] = [ast.Name(v, ast.Load()) for v in res_variables]\n        store_names = [ast.Name(v, ast.Store()) for v in res_variables]\n        it = zip(range(len(comp.ops)), comp.ops, comp.comparators, strict=True)\n        expls: list[ast.expr] = []\n        syms: list[ast.expr] = []\n        results = [left_res]\n        for i, op, next_operand in it:\n            match (next_operand, left_res):\n                case (\n                    ast.NamedExpr(target=ast.Name(id=target_id)),\n                    ast.Name(id=name_id),\n                ) if target_id == name_id:\n                    next_operand.target.id = self.variable()\n                    self.variables_overwrite[self.scope][name_id] = next_operand  # type: ignore[assignment]\n\n            next_res, next_expl = self.visit(next_operand)\n            if isinstance(next_operand, ast.Compare | ast.BoolOp):\n                next_expl = f\"({next_expl})\"\n            results.append(next_res)\n            sym = BINOP_MAP[op.__class__]\n            syms.append(ast.Constant(sym))\n            expl = f\"{left_expl} {sym} {next_expl}\"\n            expls.append(ast.Constant(expl))\n            res_expr = ast.copy_location(ast.Compare(left_res, [op], [next_res]), comp)\n            self.statements.append(ast.Assign([store_names[i]], res_expr))\n            left_res, left_expl = next_res, next_expl\n        # Use pytest.assertion.util._reprcompare if that's available.\n        expl_call = self.helper(\n            \"_call_reprcompare\",\n            ast.Tuple(syms, ast.Load()),\n            ast.Tuple(load_names, ast.Load()),\n            ast.Tuple(expls, ast.Load()),\n            ast.Tuple(results, ast.Load()),\n        )\n        if len(comp.ops) > 1:\n            res: ast.expr = ast.BoolOp(ast.And(), load_names)\n        else:\n            res = load_names[0]\n\n        return res, self.explanation_param(self.pop_format_context(expl_call))\n\n\ndef try_makedirs(cache_dir: Path) -> bool:\n    \"\"\"Attempt to create the given directory and sub-directories exist.\n\n    Returns True if successful or if it already exists.\n    \"\"\"\n    try:\n        os.makedirs(cache_dir, exist_ok=True)\n    except (FileNotFoundError, NotADirectoryError, FileExistsError):\n        # One of the path components was not a directory:\n        # - we're in a zip file\n        # - it is a file\n        return False\n    except PermissionError:\n        return False\n    except OSError as e:\n        # as of now, EROFS doesn't have an equivalent OSError-subclass\n        #\n        # squashfuse_ll returns ENOSYS \"OSError: [Errno 38] Function not\n        # implemented\" for a read-only error\n        if e.errno in {errno.EROFS, errno.ENOSYS}:\n            return False\n        raise\n    return True\n\n\ndef get_cache_dir(file_path: Path) -> Path:\n    \"\"\"Return the cache directory to write .pyc files for the given .py file path.\"\"\"\n    if sys.pycache_prefix:\n        # given:\n        #   prefix = '/tmp/pycs'\n        #   path = '/home/user/proj/test_app.py'\n        # we want:\n        #   '/tmp/pycs/home/user/proj'\n        return Path(sys.pycache_prefix) / Path(*file_path.parts[1:-1])\n    else:\n        # classic pycache directory\n        return file_path.parent / \"__pycache__\"\n"
  },
  {
    "path": "src/_pytest/assertion/truncate.py",
    "content": "\"\"\"Utilities for truncating assertion output.\n\nCurrent default behaviour is to truncate assertion explanations at\nterminal lines, unless running with an assertions verbosity level of at least 2 or running on CI.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom _pytest.compat import running_on_ci\nfrom _pytest.config import Config\nfrom _pytest.nodes import Item\n\n\nDEFAULT_MAX_LINES = 8\nDEFAULT_MAX_CHARS = DEFAULT_MAX_LINES * 80\nUSAGE_MSG = \"use '-vv' to show\"\n\n\ndef truncate_if_required(explanation: list[str], item: Item) -> list[str]:\n    \"\"\"Truncate this assertion explanation if the given test item is eligible.\"\"\"\n    should_truncate, max_lines, max_chars = _get_truncation_parameters(item)\n    if should_truncate:\n        return _truncate_explanation(\n            explanation,\n            max_lines=max_lines,\n            max_chars=max_chars,\n        )\n    return explanation\n\n\ndef _get_truncation_parameters(item: Item) -> tuple[bool, int, int]:\n    \"\"\"Return the truncation parameters related to the given item, as (should truncate, max lines, max chars).\"\"\"\n    # We do not need to truncate if one of conditions is met:\n    # 1. Verbosity level is 2 or more;\n    # 2. Test is being run in CI environment;\n    # 3. Both truncation_limit_lines and truncation_limit_chars\n    #    .ini parameters are set to 0 explicitly.\n    max_lines = item.config.getini(\"truncation_limit_lines\")\n    max_lines = int(max_lines if max_lines is not None else DEFAULT_MAX_LINES)\n\n    max_chars = item.config.getini(\"truncation_limit_chars\")\n    max_chars = int(max_chars if max_chars is not None else DEFAULT_MAX_CHARS)\n\n    verbose = item.config.get_verbosity(Config.VERBOSITY_ASSERTIONS)\n\n    should_truncate = verbose < 2 and not running_on_ci()\n    should_truncate = should_truncate and (max_lines > 0 or max_chars > 0)\n\n    return should_truncate, max_lines, max_chars\n\n\ndef _truncate_explanation(\n    input_lines: list[str],\n    max_lines: int,\n    max_chars: int,\n) -> list[str]:\n    \"\"\"Truncate given list of strings that makes up the assertion explanation.\n\n    Truncates to either max_lines, or max_chars - whichever the input reaches\n    first, taking the truncation explanation into account. The remaining lines\n    will be replaced by a usage message.\n\n    If max_chars=0, no truncation by character count is performed.\n    If max_lines=0, no truncation by line count is performed.\n\n    When this function is launched we know max_lines > 0 or max_chars > 0\n    because _get_truncation_parameters was called first.\n    \"\"\"\n    # The length of the truncation explanation depends on the number of lines\n    # removed but is at least 68 characters:\n    # The real value is\n    # 64 (for the base message:\n    # '...\\n...Full output truncated (1 line hidden), use '-vv' to show\")'\n    # )\n    # + 1 (for plural)\n    # + int(math.log10(len(input_lines) - max_lines)) (number of hidden line, at least 1)\n    # + 3 for the '...' added to the truncated line\n    # But if there's more than 100 lines it's very likely that we're going to\n    # truncate, so we don't need the exact value using log10.\n    tolerable_max_chars = (\n        max_chars + 70  # 64 + 1 (for plural) + 2 (for '99') + 3 for '...'\n    )\n    # The truncation explanation add two lines to the output\n    if max_lines == 0 or len(input_lines) <= max_lines + 2:\n        if max_chars == 0 or sum(len(s) for s in input_lines) <= tolerable_max_chars:\n            return input_lines\n        truncated_explanation = input_lines\n    else:\n        # Truncate first to max_lines, and then truncate to max_chars if necessary\n        truncated_explanation = input_lines[:max_lines]\n    # We reevaluate the need to truncate chars following removal of some lines\n    need_to_truncate_char = (\n        max_chars > 0\n        and sum(len(e) for e in truncated_explanation) > tolerable_max_chars\n    )\n    if need_to_truncate_char:\n        truncated_explanation = _truncate_by_char_count(\n            truncated_explanation, max_chars\n        )\n    # Something was truncated, adding '...' at the end to show that\n    truncated_explanation[-1] += \"...\"\n    truncated_line_count = (\n        len(input_lines) - len(truncated_explanation) + int(need_to_truncate_char)\n    )\n    return [\n        *truncated_explanation,\n        \"\",\n        f\"...Full output truncated ({truncated_line_count} line\"\n        f\"{'' if truncated_line_count == 1 else 's'} hidden), {USAGE_MSG}\",\n    ]\n\n\ndef _truncate_by_char_count(input_lines: list[str], max_chars: int) -> list[str]:\n    # Find point at which input length exceeds total allowed length\n    iterated_char_count = 0\n    for iterated_index, input_line in enumerate(input_lines):\n        if iterated_char_count + len(input_line) > max_chars:\n            break\n        iterated_char_count += len(input_line)\n\n    # Create truncated explanation with modified final line\n    truncated_result = input_lines[:iterated_index]\n    final_line = input_lines[iterated_index]\n    if final_line:\n        final_line_truncate_point = max_chars - iterated_char_count\n        final_line = final_line[:final_line_truncate_point]\n    truncated_result.append(final_line)\n    return truncated_result\n"
  },
  {
    "path": "src/_pytest/assertion/util.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Utilities for assertion debugging.\"\"\"\n\nfrom __future__ import annotations\n\nimport collections.abc\nfrom collections.abc import Callable\nfrom collections.abc import Iterable\nfrom collections.abc import Mapping\nfrom collections.abc import Sequence\nfrom collections.abc import Set as AbstractSet\nimport pprint\nfrom typing import Any\nfrom typing import Literal\nfrom typing import Protocol\nfrom unicodedata import normalize\n\nfrom _pytest import outcomes\nimport _pytest._code\nfrom _pytest._io.pprint import PrettyPrinter\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest._io.saferepr import saferepr_unlimited\nfrom _pytest.compat import running_on_ci\nfrom _pytest.config import Config\n\n\n# The _reprcompare attribute on the util module is used by the new assertion\n# interpretation code and assertion rewriter to detect this plugin was\n# loaded and in turn call the hooks defined here as part of the\n# DebugInterpreter.\n_reprcompare: Callable[[str, object, object], str | None] | None = None\n\n# Works similarly as _reprcompare attribute. Is populated with the hook call\n# when pytest_runtest_setup is called.\n_assertion_pass: Callable[[int, str, str], None] | None = None\n\n# Config object which is assigned during pytest_runtest_protocol.\n_config: Config | None = None\n\n\nclass _HighlightFunc(Protocol):\n    def __call__(self, source: str, lexer: Literal[\"diff\", \"python\"] = \"python\") -> str:\n        \"\"\"Apply highlighting to the given source.\"\"\"\n\n\ndef dummy_highlighter(source: str, lexer: Literal[\"diff\", \"python\"] = \"python\") -> str:\n    \"\"\"Dummy highlighter that returns the text unprocessed.\n\n    Needed for _notin_text, as the diff gets post-processed to only show the \"+\" part.\n    \"\"\"\n    return source\n\n\ndef format_explanation(explanation: str) -> str:\n    r\"\"\"Format an explanation.\n\n    Normally all embedded newlines are escaped, however there are\n    three exceptions: \\n{, \\n} and \\n~.  The first two are intended\n    cover nested explanations, see function and attribute explanations\n    for examples (.visit_Call(), visit_Attribute()).  The last one is\n    for when one explanation needs to span multiple lines, e.g. when\n    displaying diffs.\n    \"\"\"\n    lines = _split_explanation(explanation)\n    result = _format_lines(lines)\n    return \"\\n\".join(result)\n\n\ndef _split_explanation(explanation: str) -> list[str]:\n    r\"\"\"Return a list of individual lines in the explanation.\n\n    This will return a list of lines split on '\\n{', '\\n}' and '\\n~'.\n    Any other newlines will be escaped and appear in the line as the\n    literal '\\n' characters.\n    \"\"\"\n    raw_lines = (explanation or \"\").split(\"\\n\")\n    lines = [raw_lines[0]]\n    for values in raw_lines[1:]:\n        if values and values[0] in [\"{\", \"}\", \"~\", \">\"]:\n            lines.append(values)\n        else:\n            lines[-1] += \"\\\\n\" + values\n    return lines\n\n\ndef _format_lines(lines: Sequence[str]) -> list[str]:\n    \"\"\"Format the individual lines.\n\n    This will replace the '{', '}' and '~' characters of our mini formatting\n    language with the proper 'where ...', 'and ...' and ' + ...' text, taking\n    care of indentation along the way.\n\n    Return a list of formatted lines.\n    \"\"\"\n    result = list(lines[:1])\n    stack = [0]\n    stackcnt = [0]\n    for line in lines[1:]:\n        if line.startswith(\"{\"):\n            if stackcnt[-1]:\n                s = \"and   \"\n            else:\n                s = \"where \"\n            stack.append(len(result))\n            stackcnt[-1] += 1\n            stackcnt.append(0)\n            result.append(\" +\" + \"  \" * (len(stack) - 1) + s + line[1:])\n        elif line.startswith(\"}\"):\n            stack.pop()\n            stackcnt.pop()\n            result[stack[-1]] += line[1:]\n        else:\n            assert line[0] in [\"~\", \">\"]\n            stack[-1] += 1\n            indent = len(stack) if line.startswith(\"~\") else len(stack) - 1\n            result.append(\"  \" * indent + line[1:])\n    assert len(stack) == 1\n    return result\n\n\ndef issequence(x: Any) -> bool:\n    return isinstance(x, collections.abc.Sequence) and not isinstance(x, str)\n\n\ndef istext(x: Any) -> bool:\n    return isinstance(x, str)\n\n\ndef isdict(x: Any) -> bool:\n    return isinstance(x, dict)\n\n\ndef isset(x: Any) -> bool:\n    return isinstance(x, set | frozenset)\n\n\ndef isnamedtuple(obj: Any) -> bool:\n    return isinstance(obj, tuple) and getattr(obj, \"_fields\", None) is not None\n\n\ndef isdatacls(obj: Any) -> bool:\n    return getattr(obj, \"__dataclass_fields__\", None) is not None\n\n\ndef isattrs(obj: Any) -> bool:\n    return getattr(obj, \"__attrs_attrs__\", None) is not None\n\n\ndef isiterable(obj: Any) -> bool:\n    try:\n        iter(obj)\n        return not istext(obj)\n    except Exception:\n        return False\n\n\ndef has_default_eq(\n    obj: object,\n) -> bool:\n    \"\"\"Check if an instance of an object contains the default eq\n\n    First, we check if the object's __eq__ attribute has __code__,\n    if so, we check the equally of the method code filename (__code__.co_filename)\n    to the default one generated by the dataclass and attr module\n    for dataclasses the default co_filename is <string>, for attrs class, the __eq__ should contain \"attrs eq generated\"\n    \"\"\"\n    # inspired from https://github.com/willmcgugan/rich/blob/07d51ffc1aee6f16bd2e5a25b4e82850fb9ed778/rich/pretty.py#L68\n    if hasattr(obj.__eq__, \"__code__\") and hasattr(obj.__eq__.__code__, \"co_filename\"):\n        code_filename = obj.__eq__.__code__.co_filename\n\n        if isattrs(obj):\n            return \"attrs generated \" in code_filename\n\n        return code_filename == \"<string>\"  # data class\n    return True\n\n\ndef assertrepr_compare(\n    config, op: str, left: Any, right: Any, use_ascii: bool = False\n) -> list[str] | None:\n    \"\"\"Return specialised explanations for some operators/operands.\"\"\"\n    verbose = config.get_verbosity(Config.VERBOSITY_ASSERTIONS)\n\n    # Strings which normalize equal are often hard to distinguish when printed; use ascii() to make this easier.\n    # See issue #3246.\n    use_ascii = (\n        isinstance(left, str)\n        and isinstance(right, str)\n        and normalize(\"NFD\", left) == normalize(\"NFD\", right)\n    )\n\n    if verbose > 1:\n        left_repr = saferepr_unlimited(left, use_ascii=use_ascii)\n        right_repr = saferepr_unlimited(right, use_ascii=use_ascii)\n    else:\n        # XXX: \"15 chars indentation\" is wrong\n        #      (\"E       AssertionError: assert \"); should use term width.\n        maxsize = (\n            80 - 15 - len(op) - 2\n        ) // 2  # 15 chars indentation, 1 space around op\n\n        left_repr = saferepr(left, maxsize=maxsize, use_ascii=use_ascii)\n        right_repr = saferepr(right, maxsize=maxsize, use_ascii=use_ascii)\n\n    summary = f\"{left_repr} {op} {right_repr}\"\n    highlighter = config.get_terminal_writer()._highlight\n\n    explanation = None\n    try:\n        if op == \"==\":\n            explanation = _compare_eq_any(left, right, highlighter, verbose)\n        elif op == \"not in\":\n            if istext(left) and istext(right):\n                explanation = _notin_text(left, right, verbose)\n        elif op == \"!=\":\n            if isset(left) and isset(right):\n                explanation = [\"Both sets are equal\"]\n        elif op == \">=\":\n            if isset(left) and isset(right):\n                explanation = _compare_gte_set(left, right, highlighter, verbose)\n        elif op == \"<=\":\n            if isset(left) and isset(right):\n                explanation = _compare_lte_set(left, right, highlighter, verbose)\n        elif op == \">\":\n            if isset(left) and isset(right):\n                explanation = _compare_gt_set(left, right, highlighter, verbose)\n        elif op == \"<\":\n            if isset(left) and isset(right):\n                explanation = _compare_lt_set(left, right, highlighter, verbose)\n\n    except outcomes.Exit:\n        raise\n    except Exception:\n        repr_crash = _pytest._code.ExceptionInfo.from_current()._getreprcrash()\n        explanation = [\n            f\"(pytest_assertion plugin: representation of details failed: {repr_crash}.\",\n            \" Probably an object has a faulty __repr__.)\",\n        ]\n\n    if not explanation:\n        return None\n\n    if explanation[0] != \"\":\n        explanation = [\"\", *explanation]\n    return [summary, *explanation]\n\n\ndef _compare_eq_any(\n    left: Any, right: Any, highlighter: _HighlightFunc, verbose: int = 0\n) -> list[str]:\n    explanation = []\n    if istext(left) and istext(right):\n        explanation = _diff_text(left, right, highlighter, verbose)\n    else:\n        from _pytest.python_api import ApproxBase\n\n        if isinstance(left, ApproxBase) or isinstance(right, ApproxBase):\n            # Although the common order should be obtained == expected, this ensures both ways\n            approx_side = left if isinstance(left, ApproxBase) else right\n            other_side = right if isinstance(left, ApproxBase) else left\n\n            explanation = approx_side._repr_compare(other_side)\n        elif type(left) is type(right) and (\n            isdatacls(left) or isattrs(left) or isnamedtuple(left)\n        ):\n            # Note: unlike dataclasses/attrs, namedtuples compare only the\n            # field values, not the type or field names. But this branch\n            # intentionally only handles the same-type case, which was often\n            # used in older code bases before dataclasses/attrs were available.\n            explanation = _compare_eq_cls(left, right, highlighter, verbose)\n        elif issequence(left) and issequence(right):\n            explanation = _compare_eq_sequence(left, right, highlighter, verbose)\n        elif isset(left) and isset(right):\n            explanation = _compare_eq_set(left, right, highlighter, verbose)\n        elif isdict(left) and isdict(right):\n            explanation = _compare_eq_dict(left, right, highlighter, verbose)\n\n        if isiterable(left) and isiterable(right):\n            expl = _compare_eq_iterable(left, right, highlighter, verbose)\n            explanation.extend(expl)\n\n    return explanation\n\n\ndef _diff_text(\n    left: str, right: str, highlighter: _HighlightFunc, verbose: int = 0\n) -> list[str]:\n    \"\"\"Return the explanation for the diff between text.\n\n    Unless --verbose is used this will skip leading and trailing\n    characters which are identical to keep the diff minimal.\n    \"\"\"\n    from difflib import ndiff\n\n    explanation: list[str] = []\n\n    if verbose < 1:\n        i = 0  # just in case left or right has zero length\n        for i in range(min(len(left), len(right))):\n            if left[i] != right[i]:\n                break\n        if i > 42:\n            i -= 10  # Provide some context\n            explanation = [\n                f\"Skipping {i} identical leading characters in diff, use -v to show\"\n            ]\n            left = left[i:]\n            right = right[i:]\n        if len(left) == len(right):\n            for i in range(len(left)):\n                if left[-i] != right[-i]:\n                    break\n            if i > 42:\n                i -= 10  # Provide some context\n                explanation += [\n                    f\"Skipping {i} identical trailing \"\n                    \"characters in diff, use -v to show\"\n                ]\n                left = left[:-i]\n                right = right[:-i]\n    keepends = True\n    if left.isspace() or right.isspace():\n        left = repr(str(left))\n        right = repr(str(right))\n        explanation += [\"Strings contain only whitespace, escaping them using repr()\"]\n    # \"right\" is the expected base against which we compare \"left\",\n    # see https://github.com/pytest-dev/pytest/issues/3333\n    explanation.extend(\n        highlighter(\n            \"\\n\".join(\n                line.strip(\"\\n\")\n                for line in ndiff(right.splitlines(keepends), left.splitlines(keepends))\n            ),\n            lexer=\"diff\",\n        ).splitlines()\n    )\n    return explanation\n\n\ndef _compare_eq_iterable(\n    left: Iterable[Any],\n    right: Iterable[Any],\n    highlighter: _HighlightFunc,\n    verbose: int = 0,\n) -> list[str]:\n    if verbose <= 0 and not running_on_ci():\n        return [\"Use -v to get more diff\"]\n    # dynamic import to speedup pytest\n    import difflib\n\n    left_formatting = PrettyPrinter().pformat(left).splitlines()\n    right_formatting = PrettyPrinter().pformat(right).splitlines()\n\n    explanation = [\"\", \"Full diff:\"]\n    # \"right\" is the expected base against which we compare \"left\",\n    # see https://github.com/pytest-dev/pytest/issues/3333\n    explanation.extend(\n        highlighter(\n            \"\\n\".join(\n                line.rstrip()\n                for line in difflib.ndiff(right_formatting, left_formatting)\n            ),\n            lexer=\"diff\",\n        ).splitlines()\n    )\n    return explanation\n\n\ndef _compare_eq_sequence(\n    left: Sequence[Any],\n    right: Sequence[Any],\n    highlighter: _HighlightFunc,\n    verbose: int = 0,\n) -> list[str]:\n    comparing_bytes = isinstance(left, bytes) and isinstance(right, bytes)\n    explanation: list[str] = []\n    len_left = len(left)\n    len_right = len(right)\n    for i in range(min(len_left, len_right)):\n        if left[i] != right[i]:\n            if comparing_bytes:\n                # when comparing bytes, we want to see their ascii representation\n                # instead of their numeric values (#5260)\n                # using a slice gives us the ascii representation:\n                # >>> s = b'foo'\n                # >>> s[0]\n                # 102\n                # >>> s[0:1]\n                # b'f'\n                left_value = left[i : i + 1]\n                right_value = right[i : i + 1]\n            else:\n                left_value = left[i]\n                right_value = right[i]\n\n            explanation.append(\n                f\"At index {i} diff:\"\n                f\" {highlighter(repr(left_value))} != {highlighter(repr(right_value))}\"\n            )\n            break\n\n    if comparing_bytes:\n        # when comparing bytes, it doesn't help to show the \"sides contain one or more\n        # items\" longer explanation, so skip it\n\n        return explanation\n\n    len_diff = len_left - len_right\n    if len_diff:\n        if len_diff > 0:\n            dir_with_more = \"Left\"\n            extra = saferepr(left[len_right])\n        else:\n            len_diff = 0 - len_diff\n            dir_with_more = \"Right\"\n            extra = saferepr(right[len_left])\n\n        if len_diff == 1:\n            explanation += [\n                f\"{dir_with_more} contains one more item: {highlighter(extra)}\"\n            ]\n        else:\n            explanation += [\n                f\"{dir_with_more} contains {len_diff} more items, first extra item: {highlighter(extra)}\"\n            ]\n    return explanation\n\n\ndef _compare_eq_set(\n    left: AbstractSet[Any],\n    right: AbstractSet[Any],\n    highlighter: _HighlightFunc,\n    verbose: int = 0,\n) -> list[str]:\n    explanation = []\n    explanation.extend(_set_one_sided_diff(\"left\", left, right, highlighter))\n    explanation.extend(_set_one_sided_diff(\"right\", right, left, highlighter))\n    return explanation\n\n\ndef _compare_gt_set(\n    left: AbstractSet[Any],\n    right: AbstractSet[Any],\n    highlighter: _HighlightFunc,\n    verbose: int = 0,\n) -> list[str]:\n    explanation = _compare_gte_set(left, right, highlighter)\n    if not explanation:\n        return [\"Both sets are equal\"]\n    return explanation\n\n\ndef _compare_lt_set(\n    left: AbstractSet[Any],\n    right: AbstractSet[Any],\n    highlighter: _HighlightFunc,\n    verbose: int = 0,\n) -> list[str]:\n    explanation = _compare_lte_set(left, right, highlighter)\n    if not explanation:\n        return [\"Both sets are equal\"]\n    return explanation\n\n\ndef _compare_gte_set(\n    left: AbstractSet[Any],\n    right: AbstractSet[Any],\n    highlighter: _HighlightFunc,\n    verbose: int = 0,\n) -> list[str]:\n    return _set_one_sided_diff(\"right\", right, left, highlighter)\n\n\ndef _compare_lte_set(\n    left: AbstractSet[Any],\n    right: AbstractSet[Any],\n    highlighter: _HighlightFunc,\n    verbose: int = 0,\n) -> list[str]:\n    return _set_one_sided_diff(\"left\", left, right, highlighter)\n\n\ndef _set_one_sided_diff(\n    posn: str,\n    set1: AbstractSet[Any],\n    set2: AbstractSet[Any],\n    highlighter: _HighlightFunc,\n) -> list[str]:\n    explanation = []\n    diff = set1 - set2\n    if diff:\n        explanation.append(f\"Extra items in the {posn} set:\")\n        for item in diff:\n            explanation.append(highlighter(saferepr(item)))\n    return explanation\n\n\ndef _compare_eq_dict(\n    left: Mapping[Any, Any],\n    right: Mapping[Any, Any],\n    highlighter: _HighlightFunc,\n    verbose: int = 0,\n) -> list[str]:\n    explanation: list[str] = []\n    set_left = set(left)\n    set_right = set(right)\n    common = set_left.intersection(set_right)\n    same = {k: left[k] for k in common if left[k] == right[k]}\n    if same and verbose < 2:\n        explanation += [f\"Omitting {len(same)} identical items, use -vv to show\"]\n    elif same:\n        explanation += [\"Common items:\"]\n        explanation += highlighter(pprint.pformat(same)).splitlines()\n    diff = {k for k in common if left[k] != right[k]}\n    if diff:\n        explanation += [\"Differing items:\"]\n        for k in diff:\n            explanation += [\n                highlighter(saferepr({k: left[k]}))\n                + \" != \"\n                + highlighter(saferepr({k: right[k]}))\n            ]\n    extra_left = set_left - set_right\n    len_extra_left = len(extra_left)\n    if len_extra_left:\n        explanation.append(\n            f\"Left contains {len_extra_left} more item{'' if len_extra_left == 1 else 's'}:\"\n        )\n        explanation.extend(\n            highlighter(pprint.pformat({k: left[k] for k in extra_left})).splitlines()\n        )\n    extra_right = set_right - set_left\n    len_extra_right = len(extra_right)\n    if len_extra_right:\n        explanation.append(\n            f\"Right contains {len_extra_right} more item{'' if len_extra_right == 1 else 's'}:\"\n        )\n        explanation.extend(\n            highlighter(pprint.pformat({k: right[k] for k in extra_right})).splitlines()\n        )\n    return explanation\n\n\ndef _compare_eq_cls(\n    left: Any, right: Any, highlighter: _HighlightFunc, verbose: int\n) -> list[str]:\n    if not has_default_eq(left):\n        return []\n    if isdatacls(left):\n        import dataclasses\n\n        all_fields = dataclasses.fields(left)\n        fields_to_check = [info.name for info in all_fields if info.compare]\n    elif isattrs(left):\n        all_fields = left.__attrs_attrs__\n        fields_to_check = [field.name for field in all_fields if getattr(field, \"eq\")]\n    elif isnamedtuple(left):\n        fields_to_check = left._fields\n    else:\n        assert False\n\n    indent = \"  \"\n    same = []\n    diff = []\n    for field in fields_to_check:\n        if getattr(left, field) == getattr(right, field):\n            same.append(field)\n        else:\n            diff.append(field)\n\n    explanation = []\n    if same or diff:\n        explanation += [\"\"]\n    if same and verbose < 2:\n        explanation.append(f\"Omitting {len(same)} identical items, use -vv to show\")\n    elif same:\n        explanation += [\"Matching attributes:\"]\n        explanation += highlighter(pprint.pformat(same)).splitlines()\n    if diff:\n        explanation += [\"Differing attributes:\"]\n        explanation += highlighter(pprint.pformat(diff)).splitlines()\n        for field in diff:\n            field_left = getattr(left, field)\n            field_right = getattr(right, field)\n            explanation += [\n                \"\",\n                f\"Drill down into differing attribute {field}:\",\n                f\"{indent}{field}: {highlighter(repr(field_left))} != {highlighter(repr(field_right))}\",\n            ]\n            explanation += [\n                indent + line\n                for line in _compare_eq_any(\n                    field_left, field_right, highlighter, verbose\n                )\n            ]\n    return explanation\n\n\ndef _notin_text(term: str, text: str, verbose: int = 0) -> list[str]:\n    index = text.find(term)\n    head = text[:index]\n    tail = text[index + len(term) :]\n    correct_text = head + tail\n    diff = _diff_text(text, correct_text, dummy_highlighter, verbose)\n    newdiff = [f\"{saferepr(term, maxsize=42)} is contained here:\"]\n    for line in diff:\n        if line.startswith(\"Skipping\"):\n            continue\n        if line.startswith(\"- \"):\n            continue\n        if line.startswith(\"+ \"):\n            newdiff.append(\"  \" + line[2:])\n        else:\n            newdiff.append(line)\n    return newdiff\n"
  },
  {
    "path": "src/_pytest/cacheprovider.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Implementation of the cache provider.\"\"\"\n\n# This plugin was not named \"cache\" to avoid conflicts with the external\n# pytest-cache version.\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nfrom collections.abc import Iterable\nimport dataclasses\nimport errno\nimport json\nimport os\nfrom pathlib import Path\nimport shutil\nimport tempfile\nfrom typing import final\n\nfrom .pathlib import resolve_from_str\nfrom .pathlib import rm_rf\nfrom .reports import CollectReport\nfrom _pytest import nodes\nfrom _pytest._io import TerminalWriter\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.config import hookimpl\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.fixtures import fixture\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.main import Session\nfrom _pytest.nodes import Directory\nfrom _pytest.nodes import File\nfrom _pytest.reports import TestReport\n\n\nCACHEDIR_FILES: dict[str, bytes] = {\n    \"README.md\": b\"\"\"\\\n# pytest cache directory #\n\nThis directory contains data from the pytest's cache plugin,\nwhich provides the `--lf` and `--ff` options, as well as the `cache` fixture.\n\n**Do not** commit this to version control.\n\nSee [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.\n\"\"\",\n    \".gitignore\": b\"# Created by pytest automatically.\\n*\\n\",\n    \"CACHEDIR.TAG\": b\"\"\"\\\nSignature: 8a477f597d28d172789f06886806bc55\n# This file is a cache directory tag created by pytest.\n# For information about cache directory tags, see:\n#\thttps://bford.info/cachedir/spec.html\n\"\"\",\n}\n\n\ndef _make_cachedir(target: Path) -> None:\n    \"\"\"Create the pytest cache directory atomically with supporting files.\n\n    Creates a temporary directory with README.md, .gitignore, and CACHEDIR.TAG,\n    then atomically renames it to the target location. If another process wins\n    the race, the temporary directory is cleaned up.\n    \"\"\"\n    target.parent.mkdir(parents=True, exist_ok=True)\n    path = Path(tempfile.mkdtemp(prefix=\"pytest-cache-files-\", dir=target.parent))\n    try:\n        # Reset permissions to the default, see #12308.\n        # Note: there's no way to get the current umask atomically, eek.\n        umask = os.umask(0o022)\n        os.umask(umask)\n        path.chmod(0o777 - umask)\n\n        for name, content in CACHEDIR_FILES.items():\n            path.joinpath(name).write_bytes(content)\n\n        path.rename(target)\n    except OSError as e:\n        # If 2 concurrent pytests both race to the rename, the loser\n        # gets \"Directory not empty\" from the rename. In this case,\n        # everything is handled so just continue after cleanup.\n        # On Windows, the error is a FileExistsError which translates to EEXIST.\n        if e.errno not in (errno.ENOTEMPTY, errno.EEXIST):\n            raise\n    finally:\n        shutil.rmtree(path, ignore_errors=True)\n\n\n@final\n@dataclasses.dataclass\nclass Cache:\n    \"\"\"Instance of the `cache` fixture.\"\"\"\n\n    _cachedir: Path = dataclasses.field(repr=False)\n    _config: Config = dataclasses.field(repr=False)\n\n    # Sub-directory under cache-dir for directories created by `mkdir()`.\n    _CACHE_PREFIX_DIRS = \"d\"\n\n    # Sub-directory under cache-dir for values created by `set()`.\n    _CACHE_PREFIX_VALUES = \"v\"\n\n    def __init__(\n        self, cachedir: Path, config: Config, *, _ispytest: bool = False\n    ) -> None:\n        check_ispytest(_ispytest)\n        self._cachedir = cachedir\n        self._config = config\n\n    @classmethod\n    def for_config(cls, config: Config, *, _ispytest: bool = False) -> Cache:\n        \"\"\"Create the Cache instance for a Config.\n\n        :meta private:\n        \"\"\"\n        check_ispytest(_ispytest)\n        cachedir = cls.cache_dir_from_config(config, _ispytest=True)\n        if config.getoption(\"cacheclear\") and cachedir.is_dir():\n            cls.clear_cache(cachedir, _ispytest=True)\n        return cls(cachedir, config, _ispytest=True)\n\n    @classmethod\n    def clear_cache(cls, cachedir: Path, _ispytest: bool = False) -> None:\n        \"\"\"Clear the sub-directories used to hold cached directories and values.\n\n        :meta private:\n        \"\"\"\n        check_ispytest(_ispytest)\n        for prefix in (cls._CACHE_PREFIX_DIRS, cls._CACHE_PREFIX_VALUES):\n            d = cachedir / prefix\n            if d.is_dir():\n                rm_rf(d)\n\n    @staticmethod\n    def cache_dir_from_config(config: Config, *, _ispytest: bool = False) -> Path:\n        \"\"\"Get the path to the cache directory for a Config.\n\n        :meta private:\n        \"\"\"\n        check_ispytest(_ispytest)\n        return resolve_from_str(config.getini(\"cache_dir\"), config.rootpath)\n\n    def warn(self, fmt: str, *, _ispytest: bool = False, **args: object) -> None:\n        \"\"\"Issue a cache warning.\n\n        :meta private:\n        \"\"\"\n        check_ispytest(_ispytest)\n        import warnings\n\n        from _pytest.warning_types import PytestCacheWarning\n\n        warnings.warn(\n            PytestCacheWarning(fmt.format(**args) if args else fmt),\n            self._config.hook,\n            stacklevel=3,\n        )\n\n    def _mkdir(self, path: Path) -> None:\n        self._ensure_cache_dir_and_supporting_files()\n        path.mkdir(exist_ok=True, parents=True)\n\n    def mkdir(self, name: str) -> Path:\n        \"\"\"Return a directory path object with the given name.\n\n        If the directory does not yet exist, it will be created. You can use\n        it to manage files to e.g. store/retrieve database dumps across test\n        sessions.\n\n        .. versionadded:: 7.0\n\n        :param name:\n            Must be a string not containing a ``/`` separator.\n            Make sure the name contains your plugin or application\n            identifiers to prevent clashes with other cache users.\n        \"\"\"\n        path = Path(name)\n        if len(path.parts) > 1:\n            raise ValueError(\"name is not allowed to contain path separators\")\n        res = self._cachedir.joinpath(self._CACHE_PREFIX_DIRS, path)\n        self._mkdir(res)\n        return res\n\n    def _getvaluepath(self, key: str) -> Path:\n        return self._cachedir.joinpath(self._CACHE_PREFIX_VALUES, Path(key))\n\n    def get(self, key: str, default):\n        \"\"\"Return the cached value for the given key.\n\n        If no value was yet cached or the value cannot be read, the specified\n        default is returned.\n\n        :param key:\n            Must be a ``/`` separated value. Usually the first\n            name is the name of your plugin or your application.\n        :param default:\n            The value to return in case of a cache-miss or invalid cache value.\n        \"\"\"\n        path = self._getvaluepath(key)\n        try:\n            with path.open(\"r\", encoding=\"UTF-8\") as f:\n                return json.load(f)\n        except (ValueError, OSError):\n            return default\n\n    def set(self, key: str, value: object) -> None:\n        \"\"\"Save value for the given key.\n\n        :param key:\n            Must be a ``/`` separated value. Usually the first\n            name is the name of your plugin or your application.\n        :param value:\n            Must be of any combination of basic python types,\n            including nested types like lists of dictionaries.\n        \"\"\"\n        path = self._getvaluepath(key)\n        try:\n            self._mkdir(path.parent)\n        except OSError as exc:\n            self.warn(\n                f\"could not create cache path {path}: {exc}\",\n                _ispytest=True,\n            )\n            return\n        data = json.dumps(value, ensure_ascii=False, indent=2)\n        try:\n            f = path.open(\"w\", encoding=\"UTF-8\")\n        except OSError as exc:\n            self.warn(\n                f\"cache could not write path {path}: {exc}\",\n                _ispytest=True,\n            )\n        else:\n            with f:\n                f.write(data)\n\n    def _ensure_cache_dir_and_supporting_files(self) -> None:\n        \"\"\"Create the cache dir and its supporting files.\"\"\"\n        if not self._cachedir.is_dir():\n            _make_cachedir(self._cachedir)\n\n\nclass LFPluginCollWrapper:\n    def __init__(self, lfplugin: LFPlugin) -> None:\n        self.lfplugin = lfplugin\n        self._collected_at_least_one_failure = False\n\n    @hookimpl(wrapper=True)\n    def pytest_make_collect_report(\n        self, collector: nodes.Collector\n    ) -> Generator[None, CollectReport, CollectReport]:\n        res = yield\n        if isinstance(collector, Session | Directory):\n            # Sort any lf-paths to the beginning.\n            lf_paths = self.lfplugin._last_failed_paths\n\n            # Use stable sort to prioritize last failed.\n            def sort_key(node: nodes.Item | nodes.Collector) -> bool:\n                return node.path in lf_paths\n\n            res.result = sorted(\n                res.result,\n                key=sort_key,\n                reverse=True,\n            )\n\n        elif isinstance(collector, File):\n            if collector.path in self.lfplugin._last_failed_paths:\n                result = res.result\n                lastfailed = self.lfplugin.lastfailed\n\n                # Only filter with known failures.\n                if not self._collected_at_least_one_failure:\n                    if not any(x.nodeid in lastfailed for x in result):\n                        return res\n                    self.lfplugin.config.pluginmanager.register(\n                        LFPluginCollSkipfiles(self.lfplugin), \"lfplugin-collskip\"\n                    )\n                    self._collected_at_least_one_failure = True\n\n                session = collector.session\n                result[:] = [\n                    x\n                    for x in result\n                    if x.nodeid in lastfailed\n                    # Include any passed arguments (not trivial to filter).\n                    or session.isinitpath(x.path)\n                    # Keep all sub-collectors.\n                    or isinstance(x, nodes.Collector)\n                ]\n\n        return res\n\n\nclass LFPluginCollSkipfiles:\n    def __init__(self, lfplugin: LFPlugin) -> None:\n        self.lfplugin = lfplugin\n\n    @hookimpl\n    def pytest_make_collect_report(\n        self, collector: nodes.Collector\n    ) -> CollectReport | None:\n        if isinstance(collector, File):\n            if collector.path not in self.lfplugin._last_failed_paths:\n                self.lfplugin._skipped_files += 1\n\n                return CollectReport(\n                    collector.nodeid, \"passed\", longrepr=None, result=[]\n                )\n        return None\n\n\nclass LFPlugin:\n    \"\"\"Plugin which implements the --lf (run last-failing) option.\"\"\"\n\n    def __init__(self, config: Config) -> None:\n        self.config = config\n        active_keys = \"lf\", \"failedfirst\"\n        self.active = any(config.getoption(key) for key in active_keys)\n        assert config.cache\n        self.lastfailed: dict[str, bool] = config.cache.get(\"cache/lastfailed\", {})\n        self._previously_failed_count: int | None = None\n        self._report_status: str | None = None\n        self._skipped_files = 0  # count skipped files during collection due to --lf\n\n        if config.getoption(\"lf\"):\n            self._last_failed_paths = self.get_last_failed_paths()\n            config.pluginmanager.register(\n                LFPluginCollWrapper(self), \"lfplugin-collwrapper\"\n            )\n\n    def get_last_failed_paths(self) -> set[Path]:\n        \"\"\"Return a set with all Paths of the previously failed nodeids and\n        their parents.\"\"\"\n        rootpath = self.config.rootpath\n        result = set()\n        for nodeid in self.lastfailed:\n            path = rootpath / nodeid.split(\"::\")[0]\n            result.add(path)\n            result.update(path.parents)\n        return {x for x in result if x.exists()}\n\n    def pytest_report_collectionfinish(self) -> str | None:\n        if self.active and self.config.get_verbosity() >= 0:\n            return f\"run-last-failure: {self._report_status}\"\n        return None\n\n    def pytest_runtest_logreport(self, report: TestReport) -> None:\n        if (report.when == \"call\" and report.passed) or report.skipped:\n            self.lastfailed.pop(report.nodeid, None)\n        elif report.failed:\n            self.lastfailed[report.nodeid] = True\n\n    def pytest_collectreport(self, report: CollectReport) -> None:\n        passed = report.outcome in (\"passed\", \"skipped\")\n        if passed:\n            if report.nodeid in self.lastfailed:\n                self.lastfailed.pop(report.nodeid)\n                self.lastfailed.update((item.nodeid, True) for item in report.result)\n        else:\n            self.lastfailed[report.nodeid] = True\n\n    @hookimpl(wrapper=True, tryfirst=True)\n    def pytest_collection_modifyitems(\n        self, config: Config, items: list[nodes.Item]\n    ) -> Generator[None]:\n        res = yield\n\n        if not self.active:\n            return res\n\n        if self.lastfailed:\n            previously_failed = []\n            previously_passed = []\n            for item in items:\n                if item.nodeid in self.lastfailed:\n                    previously_failed.append(item)\n                else:\n                    previously_passed.append(item)\n            self._previously_failed_count = len(previously_failed)\n\n            if not previously_failed:\n                # Running a subset of all tests with recorded failures\n                # only outside of it.\n                self._report_status = (\n                    f\"{len(self.lastfailed)} known failures not in selected tests\"\n                )\n            else:\n                if self.config.getoption(\"lf\"):\n                    items[:] = previously_failed\n                    config.hook.pytest_deselected(items=previously_passed)\n                else:  # --failedfirst\n                    items[:] = previously_failed + previously_passed\n\n                noun = \"failure\" if self._previously_failed_count == 1 else \"failures\"\n                suffix = \" first\" if self.config.getoption(\"failedfirst\") else \"\"\n                self._report_status = (\n                    f\"rerun previous {self._previously_failed_count} {noun}{suffix}\"\n                )\n\n            if self._skipped_files > 0:\n                files_noun = \"file\" if self._skipped_files == 1 else \"files\"\n                self._report_status += f\" (skipped {self._skipped_files} {files_noun})\"\n        else:\n            self._report_status = \"no previously failed tests, \"\n            if self.config.getoption(\"last_failed_no_failures\") == \"none\":\n                self._report_status += \"deselecting all items.\"\n                config.hook.pytest_deselected(items=items[:])\n                items[:] = []\n            else:\n                self._report_status += \"not deselecting items.\"\n\n        return res\n\n    def pytest_sessionfinish(self, session: Session) -> None:\n        config = self.config\n        if config.getoption(\"cacheshow\") or hasattr(config, \"workerinput\"):\n            return\n\n        assert config.cache is not None\n        saved_lastfailed = config.cache.get(\"cache/lastfailed\", {})\n        if saved_lastfailed != self.lastfailed:\n            config.cache.set(\"cache/lastfailed\", self.lastfailed)\n\n\nclass NFPlugin:\n    \"\"\"Plugin which implements the --nf (run new-first) option.\"\"\"\n\n    def __init__(self, config: Config) -> None:\n        self.config = config\n        self.active = config.option.newfirst\n        assert config.cache is not None\n        self.cached_nodeids = set(config.cache.get(\"cache/nodeids\", []))\n\n    @hookimpl(wrapper=True, tryfirst=True)\n    def pytest_collection_modifyitems(self, items: list[nodes.Item]) -> Generator[None]:\n        res = yield\n\n        if self.active:\n            new_items: dict[str, nodes.Item] = {}\n            other_items: dict[str, nodes.Item] = {}\n            for item in items:\n                if item.nodeid not in self.cached_nodeids:\n                    new_items[item.nodeid] = item\n                else:\n                    other_items[item.nodeid] = item\n\n            items[:] = self._get_increasing_order(\n                new_items.values()\n            ) + self._get_increasing_order(other_items.values())\n            self.cached_nodeids.update(new_items)\n        else:\n            self.cached_nodeids.update(item.nodeid for item in items)\n\n        return res\n\n    def _get_increasing_order(self, items: Iterable[nodes.Item]) -> list[nodes.Item]:\n        return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True)\n\n    def pytest_sessionfinish(self) -> None:\n        config = self.config\n        if config.getoption(\"cacheshow\") or hasattr(config, \"workerinput\"):\n            return\n\n        if config.getoption(\"collectonly\"):\n            return\n\n        assert config.cache is not None\n        config.cache.set(\"cache/nodeids\", sorted(self.cached_nodeids))\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    \"\"\"Add command-line options for cache functionality.\n\n    :param parser: Parser object to add command-line options to.\n    \"\"\"\n    group = parser.getgroup(\"general\")\n    group.addoption(\n        \"--lf\",\n        \"--last-failed\",\n        action=\"store_true\",\n        dest=\"lf\",\n        help=\"Rerun only the tests that failed at the last run (or all if none failed)\",\n    )\n    group.addoption(\n        \"--ff\",\n        \"--failed-first\",\n        action=\"store_true\",\n        dest=\"failedfirst\",\n        help=\"Run all tests, but run the last failures first. \"\n        \"This may re-order tests and thus lead to \"\n        \"repeated fixture setup/teardown.\",\n    )\n    group.addoption(\n        \"--nf\",\n        \"--new-first\",\n        action=\"store_true\",\n        dest=\"newfirst\",\n        help=\"Run tests from new files first, then the rest of the tests \"\n        \"sorted by file mtime\",\n    )\n    group.addoption(\n        \"--cache-show\",\n        action=\"append\",\n        nargs=\"?\",\n        dest=\"cacheshow\",\n        help=(\n            \"Show cache contents, don't perform collection or tests. \"\n            \"Optional argument: glob (default: '*').\"\n        ),\n    )\n    group.addoption(\n        \"--cache-clear\",\n        action=\"store_true\",\n        dest=\"cacheclear\",\n        help=\"Remove all cache contents at start of test run\",\n    )\n    cache_dir_default = \".pytest_cache\"\n    if \"TOX_ENV_DIR\" in os.environ:\n        cache_dir_default = os.path.join(os.environ[\"TOX_ENV_DIR\"], cache_dir_default)\n    parser.addini(\"cache_dir\", default=cache_dir_default, help=\"Cache directory path\")\n    group.addoption(\n        \"--lfnf\",\n        \"--last-failed-no-failures\",\n        action=\"store\",\n        dest=\"last_failed_no_failures\",\n        choices=(\"all\", \"none\"),\n        default=\"all\",\n        help=\"With ``--lf``, determines whether to execute tests when there \"\n        \"are no previously (known) failures or when no \"\n        \"cached ``lastfailed`` data was found. \"\n        \"``all`` (the default) runs the full test suite again. \"\n        \"``none`` just emits a message about no known failures and exits successfully.\",\n    )\n\n\ndef pytest_cmdline_main(config: Config) -> int | ExitCode | None:\n    if config.option.cacheshow and not config.option.help:\n        from _pytest.main import wrap_session\n\n        return wrap_session(config, cacheshow)\n    return None\n\n\n@hookimpl(tryfirst=True)\ndef pytest_configure(config: Config) -> None:\n    \"\"\"Configure cache system and register related plugins.\n\n    Creates the Cache instance and registers the last-failed (LFPlugin)\n    and new-first (NFPlugin) plugins with the plugin manager.\n\n    :param config: pytest configuration object.\n    \"\"\"\n    config.cache = Cache.for_config(config, _ispytest=True)\n    config.pluginmanager.register(LFPlugin(config), \"lfplugin\")\n    config.pluginmanager.register(NFPlugin(config), \"nfplugin\")\n\n\n@fixture\ndef cache(request: FixtureRequest) -> Cache:\n    \"\"\"Return a cache object that can persist state between testing sessions.\n\n    cache.get(key, default)\n    cache.set(key, value)\n\n    Keys must be ``/`` separated strings, where the first part is usually the\n    name of your plugin or application to avoid clashes with other cache users.\n\n    Values can be any object handled by the json stdlib module.\n    \"\"\"\n    assert request.config.cache is not None\n    return request.config.cache\n\n\ndef pytest_report_header(config: Config) -> str | None:\n    \"\"\"Display cachedir with --cache-show and if non-default.\"\"\"\n    if config.option.verbose > 0 or config.getini(\"cache_dir\") != \".pytest_cache\":\n        assert config.cache is not None\n        cachedir = config.cache._cachedir\n        # TODO: evaluate generating upward relative paths\n        # starting with .., ../.. if sensible\n\n        try:\n            displaypath = cachedir.relative_to(config.rootpath)\n        except ValueError:\n            displaypath = cachedir\n        return f\"cachedir: {displaypath}\"\n    return None\n\n\ndef cacheshow(config: Config, session: Session) -> int:\n    \"\"\"Display cache contents when --cache-show is used.\n\n    Shows cached values and directories matching the specified glob pattern\n    (default: '*'). Displays cache location, cached test results, and\n    any cached directories created by plugins.\n\n    :param config: pytest configuration object.\n    :param session: pytest session object.\n    :returns: Exit code (0 for success).\n    \"\"\"\n    from pprint import pformat\n\n    assert config.cache is not None\n\n    tw = TerminalWriter()\n    tw.line(\"cachedir: \" + str(config.cache._cachedir))\n    if not config.cache._cachedir.is_dir():\n        tw.line(\"cache is empty\")\n        return 0\n\n    glob = config.option.cacheshow[0]\n    if glob is None:\n        glob = \"*\"\n\n    dummy = object()\n    basedir = config.cache._cachedir\n    vdir = basedir / Cache._CACHE_PREFIX_VALUES\n    tw.sep(\"-\", f\"cache values for {glob!r}\")\n    for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):\n        key = str(valpath.relative_to(vdir))\n        val = config.cache.get(key, dummy)\n        if val is dummy:\n            tw.line(f\"{key} contains unreadable content, will be ignored\")\n        else:\n            tw.line(f\"{key} contains:\")\n            for line in pformat(val).splitlines():\n                tw.line(\"  \" + line)\n\n    ddir = basedir / Cache._CACHE_PREFIX_DIRS\n    if ddir.is_dir():\n        contents = sorted(ddir.rglob(glob))\n        tw.sep(\"-\", f\"cache directories for {glob!r}\")\n        for p in contents:\n            # if p.is_dir():\n            #    print(\"%s/\" % p.relative_to(basedir))\n            if p.is_file():\n                key = str(p.relative_to(basedir))\n                tw.line(f\"{key} is a file of length {p.stat().st_size}\")\n    return 0\n"
  },
  {
    "path": "src/_pytest/capture.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Per-test stdout/stderr capturing mechanism.\"\"\"\n\nfrom __future__ import annotations\n\nimport abc\nimport collections\nfrom collections.abc import Generator\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nimport contextlib\nimport io\nfrom io import UnsupportedOperation\nimport os\nimport sys\nfrom tempfile import TemporaryFile\nfrom types import TracebackType\nfrom typing import Any\nfrom typing import AnyStr\nfrom typing import BinaryIO\nfrom typing import cast\nfrom typing import Final\nfrom typing import final\nfrom typing import Generic\nfrom typing import Literal\nfrom typing import NamedTuple\nfrom typing import TextIO\nfrom typing import TYPE_CHECKING\n\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\nfrom _pytest.config import Config\nfrom _pytest.config import hookimpl\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.fixtures import fixture\nfrom _pytest.fixtures import SubRequest\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import File\nfrom _pytest.nodes import Item\nfrom _pytest.reports import CollectReport\n\n\n_CaptureMethod = Literal[\"fd\", \"sys\", \"no\", \"tee-sys\"]\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"general\")\n    group.addoption(\n        \"--capture\",\n        action=\"store\",\n        default=\"fd\",\n        metavar=\"method\",\n        choices=[\"fd\", \"sys\", \"no\", \"tee-sys\"],\n        help=\"Per-test capturing method: one of fd|sys|no|tee-sys\",\n    )\n    group._addoption(  # private to use reserved lower-case short option\n        \"-s\",\n        action=\"store_const\",\n        const=\"no\",\n        dest=\"capture\",\n        help=\"Shortcut for --capture=no\",\n    )\n\n\ndef _colorama_workaround() -> None:\n    \"\"\"Ensure colorama is imported so that it attaches to the correct stdio\n    handles on Windows.\n\n    colorama uses the terminal on import time. So if something does the\n    first import of colorama while I/O capture is active, colorama will\n    fail in various ways.\n    \"\"\"\n    if sys.platform.startswith(\"win32\"):\n        try:\n            import colorama  # noqa: F401\n        except ImportError:\n            pass\n\n\ndef _readline_workaround() -> None:\n    \"\"\"Ensure readline is imported early so it attaches to the correct stdio handles.\n\n    This isn't a problem with the default GNU readline implementation, but in\n    some configurations, Python uses libedit instead (on macOS, and for prebuilt\n    binaries such as used by uv).\n\n    In theory this is only needed if readline.backend == \"libedit\", but the\n    workaround consists of importing readline here, so we already worked around\n    the issue by the time we could check if we need to.\n    \"\"\"\n    try:\n        import readline  # noqa: F401\n    except ImportError:\n        pass\n\n\ndef _windowsconsoleio_workaround(stream: TextIO) -> None:\n    \"\"\"Workaround for Windows Unicode console handling.\n\n    Python 3.6 implemented Unicode console handling for Windows. This works\n    by reading/writing to the raw console handle using\n    ``{Read,Write}ConsoleW``.\n\n    The problem is that we are going to ``dup2`` over the stdio file\n    descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the\n    handles used by Python to write to the console. Though there is still some\n    weirdness and the console handle seems to only be closed randomly and not\n    on the first call to ``CloseHandle``, or maybe it gets reopened with the\n    same handle value when we suspend capturing.\n\n    The workaround in this case will reopen stdio with a different fd which\n    also means a different handle by replicating the logic in\n    \"Py_lifecycle.c:initstdio/create_stdio\".\n\n    :param stream:\n        In practice ``sys.stdout`` or ``sys.stderr``, but given\n        here as parameter for unittesting purposes.\n\n    See https://github.com/pytest-dev/py/issues/103.\n    \"\"\"\n    if not sys.platform.startswith(\"win32\") or hasattr(sys, \"pypy_version_info\"):\n        return\n\n    # Bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666).\n    if not hasattr(stream, \"buffer\"):  # type: ignore[unreachable,unused-ignore]\n        return\n\n    raw_stdout = stream.buffer.raw if hasattr(stream.buffer, \"raw\") else stream.buffer\n\n    if not isinstance(raw_stdout, io._WindowsConsoleIO):  # type: ignore[attr-defined,unused-ignore]\n        return\n\n    def _reopen_stdio(f, mode):\n        if not hasattr(stream.buffer, \"raw\") and mode[0] == \"w\":\n            buffering = 0\n        else:\n            buffering = -1\n\n        return io.TextIOWrapper(\n            open(os.dup(f.fileno()), mode, buffering),\n            f.encoding,\n            f.errors,\n            f.newlines,\n            f.line_buffering,\n        )\n\n    sys.stdin = _reopen_stdio(sys.stdin, \"rb\")\n    sys.stdout = _reopen_stdio(sys.stdout, \"wb\")\n    sys.stderr = _reopen_stdio(sys.stderr, \"wb\")\n\n\n@hookimpl(wrapper=True)\ndef pytest_load_initial_conftests(early_config: Config) -> Generator[None]:\n    ns = early_config.known_args_namespace\n    if ns.capture == \"fd\":\n        _windowsconsoleio_workaround(sys.stdout)\n    _colorama_workaround()\n    _readline_workaround()\n    pluginmanager = early_config.pluginmanager\n    capman = CaptureManager(ns.capture)\n    pluginmanager.register(capman, \"capturemanager\")\n\n    # Make sure that capturemanager is properly reset at final shutdown.\n    early_config.add_cleanup(capman.stop_global_capturing)\n\n    # Finally trigger conftest loading but while capturing (issue #93).\n    capman.start_global_capturing()\n    try:\n        try:\n            yield\n        finally:\n            capman.suspend_global_capture()\n    except BaseException:\n        out, err = capman.read_global_capture()\n        sys.stdout.write(out)\n        sys.stderr.write(err)\n        raise\n\n\n# IO Helpers.\n\n\nclass EncodedFile(io.TextIOWrapper):\n    __slots__ = ()\n\n    @property\n    def name(self) -> str:\n        # Ensure that file.name is a string. Workaround for a Python bug\n        # fixed in >=3.7.4: https://bugs.python.org/issue36015\n        return repr(self.buffer)\n\n    @property\n    def mode(self) -> str:\n        # TextIOWrapper doesn't expose a mode, but at least some of our\n        # tests check it.\n        assert hasattr(self.buffer, \"mode\")\n        return cast(str, self.buffer.mode.replace(\"b\", \"\"))\n\n\nclass CaptureIO(io.TextIOWrapper):\n    def __init__(self) -> None:\n        super().__init__(io.BytesIO(), encoding=\"UTF-8\", newline=\"\", write_through=True)\n\n    def getvalue(self) -> str:\n        assert isinstance(self.buffer, io.BytesIO)\n        return self.buffer.getvalue().decode(\"UTF-8\")\n\n\nclass TeeCaptureIO(CaptureIO):\n    def __init__(self, other: TextIO) -> None:\n        self._other = other\n        super().__init__()\n\n    def write(self, s: str) -> int:\n        super().write(s)\n        return self._other.write(s)\n\n\nclass DontReadFromInput(TextIO):\n    @property\n    def encoding(self) -> str:\n        assert sys.__stdin__ is not None\n        return sys.__stdin__.encoding\n\n    def read(self, size: int = -1) -> str:\n        raise OSError(\n            \"pytest: reading from stdin while output is captured!  Consider using `-s`.\"\n        )\n\n    readline = read\n\n    def __next__(self) -> str:\n        return self.readline()\n\n    def readlines(self, hint: int | None = -1) -> list[str]:\n        raise OSError(\n            \"pytest: reading from stdin while output is captured!  Consider using `-s`.\"\n        )\n\n    def __iter__(self) -> Iterator[str]:\n        return self\n\n    def fileno(self) -> int:\n        raise UnsupportedOperation(\"redirected stdin is pseudofile, has no fileno()\")\n\n    def flush(self) -> None:\n        raise UnsupportedOperation(\"redirected stdin is pseudofile, has no flush()\")\n\n    def isatty(self) -> bool:\n        return False\n\n    def close(self) -> None:\n        pass\n\n    def readable(self) -> bool:\n        return False\n\n    def seek(self, offset: int, whence: int = 0) -> int:\n        raise UnsupportedOperation(\"redirected stdin is pseudofile, has no seek(int)\")\n\n    def seekable(self) -> bool:\n        return False\n\n    def tell(self) -> int:\n        raise UnsupportedOperation(\"redirected stdin is pseudofile, has no tell()\")\n\n    def truncate(self, size: int | None = None) -> int:\n        raise UnsupportedOperation(\"cannot truncate stdin\")\n\n    def write(self, data: str) -> int:\n        raise UnsupportedOperation(\"cannot write to stdin\")\n\n    def writelines(self, lines: Iterable[str]) -> None:\n        raise UnsupportedOperation(\"Cannot write to stdin\")\n\n    def writable(self) -> bool:\n        return False\n\n    def __enter__(self) -> Self:\n        return self\n\n    def __exit__(\n        self,\n        type: type[BaseException] | None,\n        value: BaseException | None,\n        traceback: TracebackType | None,\n    ) -> None:\n        pass\n\n    @property\n    def buffer(self) -> BinaryIO:\n        # The str/bytes doesn't actually matter in this type, so OK to fake.\n        return self  # type: ignore[return-value]\n\n\n# Capture classes.\n\n\nclass CaptureBase(abc.ABC, Generic[AnyStr]):\n    EMPTY_BUFFER: AnyStr\n\n    @abc.abstractmethod\n    def __init__(self, fd: int) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def start(self) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def done(self) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def suspend(self) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def resume(self) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def writeorg(self, data: AnyStr) -> None:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def snap(self) -> AnyStr:\n        raise NotImplementedError()\n\n\npatchsysdict = {0: \"stdin\", 1: \"stdout\", 2: \"stderr\"}\n\n\nclass NoCapture(CaptureBase[str]):\n    EMPTY_BUFFER = \"\"\n\n    def __init__(self, fd: int) -> None:\n        pass\n\n    def start(self) -> None:\n        pass\n\n    def done(self) -> None:\n        pass\n\n    def suspend(self) -> None:\n        pass\n\n    def resume(self) -> None:\n        pass\n\n    def snap(self) -> str:\n        return \"\"\n\n    def writeorg(self, data: str) -> None:\n        pass\n\n\nclass SysCaptureBase(CaptureBase[AnyStr]):\n    def __init__(\n        self, fd: int, tmpfile: TextIO | None = None, *, tee: bool = False\n    ) -> None:\n        name = patchsysdict[fd]\n        self._old: TextIO = getattr(sys, name)\n        self.name = name\n        if tmpfile is None:\n            if name == \"stdin\":\n                tmpfile = DontReadFromInput()\n            else:\n                tmpfile = CaptureIO() if not tee else TeeCaptureIO(self._old)\n        self.tmpfile = tmpfile\n        self._state = \"initialized\"\n\n    def repr(self, class_name: str) -> str:\n        return \"<{} {} _old={} _state={!r} tmpfile={!r}>\".format(\n            class_name,\n            self.name,\n            (hasattr(self, \"_old\") and repr(self._old)) or \"<UNSET>\",\n            self._state,\n            self.tmpfile,\n        )\n\n    def __repr__(self) -> str:\n        return \"<{} {} _old={} _state={!r} tmpfile={!r}>\".format(\n            self.__class__.__name__,\n            self.name,\n            (hasattr(self, \"_old\") and repr(self._old)) or \"<UNSET>\",\n            self._state,\n            self.tmpfile,\n        )\n\n    def _assert_state(self, op: str, states: tuple[str, ...]) -> None:\n        assert self._state in states, (\n            \"cannot {} in state {!r}: expected one of {}\".format(\n                op, self._state, \", \".join(states)\n            )\n        )\n\n    def start(self) -> None:\n        self._assert_state(\"start\", (\"initialized\",))\n        setattr(sys, self.name, self.tmpfile)\n        self._state = \"started\"\n\n    def done(self) -> None:\n        self._assert_state(\"done\", (\"initialized\", \"started\", \"suspended\", \"done\"))\n        if self._state == \"done\":\n            return\n        setattr(sys, self.name, self._old)\n        del self._old\n        self.tmpfile.close()\n        self._state = \"done\"\n\n    def suspend(self) -> None:\n        self._assert_state(\"suspend\", (\"started\", \"suspended\"))\n        setattr(sys, self.name, self._old)\n        self._state = \"suspended\"\n\n    def resume(self) -> None:\n        self._assert_state(\"resume\", (\"started\", \"suspended\"))\n        if self._state == \"started\":\n            return\n        setattr(sys, self.name, self.tmpfile)\n        self._state = \"started\"\n\n\nclass SysCaptureBinary(SysCaptureBase[bytes]):\n    EMPTY_BUFFER = b\"\"\n\n    def snap(self) -> bytes:\n        self._assert_state(\"snap\", (\"started\", \"suspended\"))\n        self.tmpfile.seek(0)\n        res = self.tmpfile.buffer.read()\n        self.tmpfile.seek(0)\n        self.tmpfile.truncate()\n        return res\n\n    def writeorg(self, data: bytes) -> None:\n        self._assert_state(\"writeorg\", (\"started\", \"suspended\"))\n        self._old.flush()\n        self._old.buffer.write(data)\n        self._old.buffer.flush()\n\n\nclass SysCapture(SysCaptureBase[str]):\n    EMPTY_BUFFER = \"\"\n\n    def snap(self) -> str:\n        self._assert_state(\"snap\", (\"started\", \"suspended\"))\n        assert isinstance(self.tmpfile, CaptureIO)\n        res = self.tmpfile.getvalue()\n        self.tmpfile.seek(0)\n        self.tmpfile.truncate()\n        return res\n\n    def writeorg(self, data: str) -> None:\n        self._assert_state(\"writeorg\", (\"started\", \"suspended\"))\n        self._old.write(data)\n        self._old.flush()\n\n\nclass FDCaptureBase(CaptureBase[AnyStr]):\n    def __init__(self, targetfd: int) -> None:\n        self.targetfd = targetfd\n\n        try:\n            os.fstat(targetfd)\n        except OSError:\n            # FD capturing is conceptually simple -- create a temporary file,\n            # redirect the FD to it, redirect back when done. But when the\n            # target FD is invalid it throws a wrench into this lovely scheme.\n            #\n            # Tests themselves shouldn't care if the FD is valid, FD capturing\n            # should work regardless of external circumstances. So falling back\n            # to just sys capturing is not a good option.\n            #\n            # Further complications are the need to support suspend() and the\n            # possibility of FD reuse (e.g. the tmpfile getting the very same\n            # target FD). The following approach is robust, I believe.\n            self.targetfd_invalid: int | None = os.open(os.devnull, os.O_RDWR)\n            os.dup2(self.targetfd_invalid, targetfd)\n        else:\n            self.targetfd_invalid = None\n        self.targetfd_save = os.dup(targetfd)\n\n        if targetfd == 0:\n            self.tmpfile = open(os.devnull, encoding=\"utf-8\")\n            self.syscapture: CaptureBase[str] = SysCapture(targetfd)\n        else:\n            self.tmpfile = EncodedFile(\n                TemporaryFile(buffering=0),\n                encoding=\"utf-8\",\n                errors=\"replace\",\n                newline=\"\",\n                write_through=True,\n            )\n            if targetfd in patchsysdict:\n                self.syscapture = SysCapture(targetfd, self.tmpfile)\n            else:\n                self.syscapture = NoCapture(targetfd)\n\n        self._state = \"initialized\"\n\n    def __repr__(self) -> str:\n        return (\n            f\"<{self.__class__.__name__} {self.targetfd} oldfd={self.targetfd_save} \"\n            f\"_state={self._state!r} tmpfile={self.tmpfile!r}>\"\n        )\n\n    def _assert_state(self, op: str, states: tuple[str, ...]) -> None:\n        assert self._state in states, (\n            \"cannot {} in state {!r}: expected one of {}\".format(\n                op, self._state, \", \".join(states)\n            )\n        )\n\n    def start(self) -> None:\n        \"\"\"Start capturing on targetfd using memorized tmpfile.\"\"\"\n        self._assert_state(\"start\", (\"initialized\",))\n        os.dup2(self.tmpfile.fileno(), self.targetfd)\n        self.syscapture.start()\n        self._state = \"started\"\n\n    def done(self) -> None:\n        \"\"\"Stop capturing, restore streams, return original capture file,\n        seeked to position zero.\"\"\"\n        self._assert_state(\"done\", (\"initialized\", \"started\", \"suspended\", \"done\"))\n        if self._state == \"done\":\n            return\n        os.dup2(self.targetfd_save, self.targetfd)\n        os.close(self.targetfd_save)\n        if self.targetfd_invalid is not None:\n            if self.targetfd_invalid != self.targetfd:\n                os.close(self.targetfd)\n            os.close(self.targetfd_invalid)\n        self.syscapture.done()\n        self.tmpfile.close()\n        self._state = \"done\"\n\n    def suspend(self) -> None:\n        self._assert_state(\"suspend\", (\"started\", \"suspended\"))\n        if self._state == \"suspended\":\n            return\n        self.syscapture.suspend()\n        os.dup2(self.targetfd_save, self.targetfd)\n        self._state = \"suspended\"\n\n    def resume(self) -> None:\n        self._assert_state(\"resume\", (\"started\", \"suspended\"))\n        if self._state == \"started\":\n            return\n        self.syscapture.resume()\n        os.dup2(self.tmpfile.fileno(), self.targetfd)\n        self._state = \"started\"\n\n\nclass FDCaptureBinary(FDCaptureBase[bytes]):\n    \"\"\"Capture IO to/from a given OS-level file descriptor.\n\n    snap() produces `bytes`.\n    \"\"\"\n\n    EMPTY_BUFFER = b\"\"\n\n    def snap(self) -> bytes:\n        self._assert_state(\"snap\", (\"started\", \"suspended\"))\n        self.tmpfile.seek(0)\n        res = self.tmpfile.buffer.read()\n        self.tmpfile.seek(0)\n        self.tmpfile.truncate()\n        return res  # type: ignore[return-value]\n\n    def writeorg(self, data: bytes) -> None:\n        \"\"\"Write to original file descriptor.\"\"\"\n        self._assert_state(\"writeorg\", (\"started\", \"suspended\"))\n        os.write(self.targetfd_save, data)\n\n\nclass FDCapture(FDCaptureBase[str]):\n    \"\"\"Capture IO to/from a given OS-level file descriptor.\n\n    snap() produces text.\n    \"\"\"\n\n    EMPTY_BUFFER = \"\"\n\n    def snap(self) -> str:\n        self._assert_state(\"snap\", (\"started\", \"suspended\"))\n        self.tmpfile.seek(0)\n        res = self.tmpfile.read()\n        self.tmpfile.seek(0)\n        self.tmpfile.truncate()\n        return res\n\n    def writeorg(self, data: str) -> None:\n        \"\"\"Write to original file descriptor.\"\"\"\n        self._assert_state(\"writeorg\", (\"started\", \"suspended\"))\n        # XXX use encoding of original stream\n        os.write(self.targetfd_save, data.encode(\"utf-8\"))\n\n\n# MultiCapture\n\n\n# Generic NamedTuple only supported since Python 3.11.\nif sys.version_info >= (3, 11) or TYPE_CHECKING:\n\n    @final\n    class CaptureResult(NamedTuple, Generic[AnyStr]):\n        \"\"\"The result of :method:`caplog.readouterr() <pytest.CaptureFixture.readouterr>`.\"\"\"\n\n        out: AnyStr\n        err: AnyStr\n\nelse:\n\n    class CaptureResult(\n        collections.namedtuple(\"CaptureResult\", [\"out\", \"err\"]),  # noqa: PYI024\n        Generic[AnyStr],\n    ):\n        \"\"\"The result of :method:`caplog.readouterr() <pytest.CaptureFixture.readouterr>`.\"\"\"\n\n        __slots__ = ()\n\n\nclass MultiCapture(Generic[AnyStr]):\n    _state = None\n    _in_suspended = False\n\n    def __init__(\n        self,\n        in_: CaptureBase[AnyStr] | None,\n        out: CaptureBase[AnyStr] | None,\n        err: CaptureBase[AnyStr] | None,\n    ) -> None:\n        self.in_: CaptureBase[AnyStr] | None = in_\n        self.out: CaptureBase[AnyStr] | None = out\n        self.err: CaptureBase[AnyStr] | None = err\n\n    def __repr__(self) -> str:\n        return (\n            f\"<MultiCapture out={self.out!r} err={self.err!r} in_={self.in_!r} \"\n            f\"_state={self._state!r} _in_suspended={self._in_suspended!r}>\"\n        )\n\n    def start_capturing(self) -> None:\n        self._state = \"started\"\n        if self.in_:\n            self.in_.start()\n        if self.out:\n            self.out.start()\n        if self.err:\n            self.err.start()\n\n    def pop_outerr_to_orig(self) -> tuple[AnyStr, AnyStr]:\n        \"\"\"Pop current snapshot out/err capture and flush to orig streams.\"\"\"\n        out, err = self.readouterr()\n        if out:\n            assert self.out is not None\n            self.out.writeorg(out)\n        if err:\n            assert self.err is not None\n            self.err.writeorg(err)\n        return out, err\n\n    def suspend_capturing(self, in_: bool = False) -> None:\n        self._state = \"suspended\"\n        if self.out:\n            self.out.suspend()\n        if self.err:\n            self.err.suspend()\n        if in_ and self.in_:\n            self.in_.suspend()\n            self._in_suspended = True\n\n    def resume_capturing(self) -> None:\n        self._state = \"started\"\n        if self.out:\n            self.out.resume()\n        if self.err:\n            self.err.resume()\n        if self._in_suspended:\n            assert self.in_ is not None\n            self.in_.resume()\n            self._in_suspended = False\n\n    def stop_capturing(self) -> None:\n        \"\"\"Stop capturing and reset capturing streams.\"\"\"\n        if self._state == \"stopped\":\n            raise ValueError(\"was already stopped\")\n        self._state = \"stopped\"\n        if self.out:\n            self.out.done()\n        if self.err:\n            self.err.done()\n        if self.in_:\n            self.in_.done()\n\n    def is_started(self) -> bool:\n        \"\"\"Whether actively capturing -- not suspended or stopped.\"\"\"\n        return self._state == \"started\"\n\n    def readouterr(self) -> CaptureResult[AnyStr]:\n        out = self.out.snap() if self.out else \"\"\n        err = self.err.snap() if self.err else \"\"\n        # TODO: This type error is real, need to fix.\n        return CaptureResult(out, err)  # type: ignore[arg-type]\n\n\ndef _get_multicapture(method: _CaptureMethod) -> MultiCapture[str]:\n    if method == \"fd\":\n        return MultiCapture(in_=FDCapture(0), out=FDCapture(1), err=FDCapture(2))\n    elif method == \"sys\":\n        return MultiCapture(in_=SysCapture(0), out=SysCapture(1), err=SysCapture(2))\n    elif method == \"no\":\n        return MultiCapture(in_=None, out=None, err=None)\n    elif method == \"tee-sys\":\n        return MultiCapture(\n            in_=None, out=SysCapture(1, tee=True), err=SysCapture(2, tee=True)\n        )\n    raise ValueError(f\"unknown capturing method: {method!r}\")\n\n\n# CaptureManager and CaptureFixture\n\n\nclass CaptureManager:\n    \"\"\"The capture plugin.\n\n    Manages that the appropriate capture method is enabled/disabled during\n    collection and each test phase (setup, call, teardown). After each of\n    those points, the captured output is obtained and attached to the\n    collection/runtest report.\n\n    There are two levels of capture:\n\n    * global: enabled by default and can be suppressed by the ``-s``\n      option. This is always enabled/disabled during collection and each test\n      phase.\n\n    * fixture: when a test function or one of its fixture depend on the\n      ``capsys`` or ``capfd`` fixtures. In this case special handling is\n      needed to ensure the fixtures take precedence over the global capture.\n    \"\"\"\n\n    def __init__(self, method: _CaptureMethod) -> None:\n        self._method: Final = method\n        self._global_capturing: MultiCapture[str] | None = None\n        self._capture_fixture: CaptureFixture[Any] | None = None\n\n    def __repr__(self) -> str:\n        return (\n            f\"<CaptureManager _method={self._method!r} _global_capturing={self._global_capturing!r} \"\n            f\"_capture_fixture={self._capture_fixture!r}>\"\n        )\n\n    def is_capturing(self) -> str | bool:\n        if self.is_globally_capturing():\n            return \"global\"\n        if self._capture_fixture:\n            return f\"fixture {self._capture_fixture.request.fixturename}\"\n        return False\n\n    # Global capturing control\n\n    def is_globally_capturing(self) -> bool:\n        return self._method != \"no\"\n\n    def start_global_capturing(self) -> None:\n        assert self._global_capturing is None\n        self._global_capturing = _get_multicapture(self._method)\n        self._global_capturing.start_capturing()\n\n    def stop_global_capturing(self) -> None:\n        if self._global_capturing is not None:\n            self._global_capturing.pop_outerr_to_orig()\n            self._global_capturing.stop_capturing()\n            self._global_capturing = None\n\n    def resume_global_capture(self) -> None:\n        # During teardown of the python process, and on rare occasions, capture\n        # attributes can be `None` while trying to resume global capture.\n        if self._global_capturing is not None:\n            self._global_capturing.resume_capturing()\n\n    def suspend_global_capture(self, in_: bool = False) -> None:\n        if self._global_capturing is not None:\n            self._global_capturing.suspend_capturing(in_=in_)\n\n    def suspend(self, in_: bool = False) -> None:\n        # Need to undo local capsys-et-al if it exists before disabling global capture.\n        self.suspend_fixture()\n        self.suspend_global_capture(in_)\n\n    def resume(self) -> None:\n        self.resume_global_capture()\n        self.resume_fixture()\n\n    def read_global_capture(self) -> CaptureResult[str]:\n        assert self._global_capturing is not None\n        return self._global_capturing.readouterr()\n\n    # Fixture Control\n\n    def set_fixture(self, capture_fixture: CaptureFixture[Any]) -> None:\n        if self._capture_fixture:\n            current_fixture = self._capture_fixture.request.fixturename\n            requested_fixture = capture_fixture.request.fixturename\n            capture_fixture.request.raiseerror(\n                f\"cannot use {requested_fixture} and {current_fixture} at the same time\"\n            )\n        self._capture_fixture = capture_fixture\n\n    def unset_fixture(self) -> None:\n        self._capture_fixture = None\n\n    def activate_fixture(self) -> None:\n        \"\"\"If the current item is using ``capsys`` or ``capfd``, activate\n        them so they take precedence over the global capture.\"\"\"\n        if self._capture_fixture:\n            self._capture_fixture._start()\n\n    def deactivate_fixture(self) -> None:\n        \"\"\"Deactivate the ``capsys`` or ``capfd`` fixture of this item, if any.\"\"\"\n        if self._capture_fixture:\n            self._capture_fixture.close()\n\n    def suspend_fixture(self) -> None:\n        if self._capture_fixture:\n            self._capture_fixture._suspend()\n\n    def resume_fixture(self) -> None:\n        if self._capture_fixture:\n            self._capture_fixture._resume()\n\n    # Helper context managers\n\n    @contextlib.contextmanager\n    def global_and_fixture_disabled(self) -> Generator[None]:\n        \"\"\"Context manager to temporarily disable global and current fixture capturing.\"\"\"\n        do_fixture = self._capture_fixture and self._capture_fixture._is_started()\n        if do_fixture:\n            self.suspend_fixture()\n        do_global = self._global_capturing and self._global_capturing.is_started()\n        if do_global:\n            self.suspend_global_capture()\n        try:\n            yield\n        finally:\n            if do_global:\n                self.resume_global_capture()\n            if do_fixture:\n                self.resume_fixture()\n\n    @contextlib.contextmanager\n    def item_capture(self, when: str, item: Item) -> Generator[None]:\n        self.resume_global_capture()\n        self.activate_fixture()\n        try:\n            yield\n        finally:\n            self.deactivate_fixture()\n            self.suspend_global_capture(in_=False)\n\n            out, err = self.read_global_capture()\n            item.add_report_section(when, \"stdout\", out)\n            item.add_report_section(when, \"stderr\", err)\n\n    # Hooks\n\n    @hookimpl(wrapper=True)\n    def pytest_make_collect_report(\n        self, collector: Collector\n    ) -> Generator[None, CollectReport, CollectReport]:\n        if isinstance(collector, File):\n            self.resume_global_capture()\n            try:\n                rep = yield\n            finally:\n                self.suspend_global_capture()\n            out, err = self.read_global_capture()\n            if out:\n                rep.sections.append((\"Captured stdout\", out))\n            if err:\n                rep.sections.append((\"Captured stderr\", err))\n        else:\n            rep = yield\n        return rep\n\n    @hookimpl(wrapper=True)\n    def pytest_runtest_setup(self, item: Item) -> Generator[None]:\n        with self.item_capture(\"setup\", item):\n            return (yield)\n\n    @hookimpl(wrapper=True)\n    def pytest_runtest_call(self, item: Item) -> Generator[None]:\n        with self.item_capture(\"call\", item):\n            return (yield)\n\n    @hookimpl(wrapper=True)\n    def pytest_runtest_teardown(self, item: Item) -> Generator[None]:\n        with self.item_capture(\"teardown\", item):\n            return (yield)\n\n    @hookimpl(tryfirst=True)\n    def pytest_keyboard_interrupt(self) -> None:\n        self.stop_global_capturing()\n\n    @hookimpl(tryfirst=True)\n    def pytest_internalerror(self) -> None:\n        self.stop_global_capturing()\n\n\nclass CaptureFixture(Generic[AnyStr]):\n    \"\"\"Object returned by the :fixture:`capsys`, :fixture:`capsysbinary`,\n    :fixture:`capfd` and :fixture:`capfdbinary` fixtures.\"\"\"\n\n    def __init__(\n        self,\n        captureclass: type[CaptureBase[AnyStr]],\n        request: SubRequest,\n        *,\n        config: dict[str, Any] | None = None,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        self.captureclass: type[CaptureBase[AnyStr]] = captureclass\n        self.request = request\n        self._config = config if config else {}\n        self._capture: MultiCapture[AnyStr] | None = None\n        self._captured_out: AnyStr = self.captureclass.EMPTY_BUFFER\n        self._captured_err: AnyStr = self.captureclass.EMPTY_BUFFER\n\n    def _start(self) -> None:\n        if self._capture is None:\n            self._capture = MultiCapture(\n                in_=None,\n                out=self.captureclass(1, **self._config),\n                err=self.captureclass(2, **self._config),\n            )\n            self._capture.start_capturing()\n\n    def close(self) -> None:\n        if self._capture is not None:\n            out, err = self._capture.pop_outerr_to_orig()\n            self._captured_out += out\n            self._captured_err += err\n            self._capture.stop_capturing()\n            self._capture = None\n\n    def readouterr(self) -> CaptureResult[AnyStr]:\n        \"\"\"Read and return the captured output so far, resetting the internal\n        buffer.\n\n        :returns:\n            The captured content as a namedtuple with ``out`` and ``err``\n            string attributes.\n        \"\"\"\n        captured_out, captured_err = self._captured_out, self._captured_err\n        if self._capture is not None:\n            out, err = self._capture.readouterr()\n            captured_out += out\n            captured_err += err\n        self._captured_out = self.captureclass.EMPTY_BUFFER\n        self._captured_err = self.captureclass.EMPTY_BUFFER\n        return CaptureResult(captured_out, captured_err)\n\n    def _suspend(self) -> None:\n        \"\"\"Suspend this fixture's own capturing temporarily.\"\"\"\n        if self._capture is not None:\n            self._capture.suspend_capturing()\n\n    def _resume(self) -> None:\n        \"\"\"Resume this fixture's own capturing temporarily.\"\"\"\n        if self._capture is not None:\n            self._capture.resume_capturing()\n\n    def _is_started(self) -> bool:\n        \"\"\"Whether actively capturing -- not disabled or closed.\"\"\"\n        if self._capture is not None:\n            return self._capture.is_started()\n        return False\n\n    @contextlib.contextmanager\n    def disabled(self) -> Generator[None]:\n        \"\"\"Temporarily disable capturing while inside the ``with`` block.\"\"\"\n        capmanager: CaptureManager = self.request.config.pluginmanager.getplugin(\n            \"capturemanager\"\n        )\n        with capmanager.global_and_fixture_disabled():\n            yield\n\n\n# The fixtures.\n\n\n@fixture\ndef capsys(request: SubRequest) -> Generator[CaptureFixture[str]]:\n    r\"\"\"Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n    The captured output is made available via ``capsys.readouterr()`` method\n    calls, which return a ``(out, err)`` namedtuple.\n    ``out`` and ``err`` will be ``text`` objects.\n\n    Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.\n\n    Example:\n\n    .. code-block:: python\n\n        def test_output(capsys):\n            print(\"hello\")\n            captured = capsys.readouterr()\n            assert captured.out == \"hello\\n\"\n    \"\"\"\n    capman: CaptureManager = request.config.pluginmanager.getplugin(\"capturemanager\")\n    capture_fixture = CaptureFixture(SysCapture, request, _ispytest=True)\n    capman.set_fixture(capture_fixture)\n    capture_fixture._start()\n    yield capture_fixture\n    capture_fixture.close()\n    capman.unset_fixture()\n\n\n@fixture\ndef capteesys(request: SubRequest) -> Generator[CaptureFixture[str]]:\n    r\"\"\"Enable simultaneous text capturing and pass-through of writes\n    to ``sys.stdout`` and ``sys.stderr`` as defined by ``--capture=``.\n\n\n    The captured output is made available via ``capteesys.readouterr()`` method\n    calls, which return a ``(out, err)`` namedtuple.\n    ``out`` and ``err`` will be ``text`` objects.\n\n    The output is also passed-through, allowing it to be \"live-printed\",\n    reported, or both as defined by ``--capture=``.\n\n    Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.\n\n    Example:\n\n    .. code-block:: python\n\n        def test_output(capteesys):\n            print(\"hello\")\n            captured = capteesys.readouterr()\n            assert captured.out == \"hello\\n\"\n    \"\"\"\n    capman: CaptureManager = request.config.pluginmanager.getplugin(\"capturemanager\")\n    capture_fixture = CaptureFixture(\n        SysCapture, request, config=dict(tee=True), _ispytest=True\n    )\n    capman.set_fixture(capture_fixture)\n    capture_fixture._start()\n    yield capture_fixture\n    capture_fixture.close()\n    capman.unset_fixture()\n\n\n@fixture\ndef capsysbinary(request: SubRequest) -> Generator[CaptureFixture[bytes]]:\n    r\"\"\"Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.\n\n    The captured output is made available via ``capsysbinary.readouterr()``\n    method calls, which return a ``(out, err)`` namedtuple.\n    ``out`` and ``err`` will be ``bytes`` objects.\n\n    Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.\n\n    Example:\n\n    .. code-block:: python\n\n        def test_output(capsysbinary):\n            print(\"hello\")\n            captured = capsysbinary.readouterr()\n            assert captured.out == b\"hello\\n\"\n    \"\"\"\n    capman: CaptureManager = request.config.pluginmanager.getplugin(\"capturemanager\")\n    capture_fixture = CaptureFixture(SysCaptureBinary, request, _ispytest=True)\n    capman.set_fixture(capture_fixture)\n    capture_fixture._start()\n    yield capture_fixture\n    capture_fixture.close()\n    capman.unset_fixture()\n\n\n@fixture\ndef capfd(request: SubRequest) -> Generator[CaptureFixture[str]]:\n    r\"\"\"Enable text capturing of writes to file descriptors ``1`` and ``2``.\n\n    The captured output is made available via ``capfd.readouterr()`` method\n    calls, which return a ``(out, err)`` namedtuple.\n    ``out`` and ``err`` will be ``text`` objects.\n\n    Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`.\n\n    Example:\n\n    .. code-block:: python\n\n        def test_system_echo(capfd):\n            os.system('echo \"hello\"')\n            captured = capfd.readouterr()\n            assert captured.out == \"hello\\n\"\n    \"\"\"\n    capman: CaptureManager = request.config.pluginmanager.getplugin(\"capturemanager\")\n    capture_fixture = CaptureFixture(FDCapture, request, _ispytest=True)\n    capman.set_fixture(capture_fixture)\n    capture_fixture._start()\n    yield capture_fixture\n    capture_fixture.close()\n    capman.unset_fixture()\n\n\n@fixture\ndef capfdbinary(request: SubRequest) -> Generator[CaptureFixture[bytes]]:\n    r\"\"\"Enable bytes capturing of writes to file descriptors ``1`` and ``2``.\n\n    The captured output is made available via ``capfd.readouterr()`` method\n    calls, which return a ``(out, err)`` namedtuple.\n    ``out`` and ``err`` will be ``byte`` objects.\n\n    Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`.\n\n    Example:\n\n    .. code-block:: python\n\n        def test_system_echo(capfdbinary):\n            os.system('echo \"hello\"')\n            captured = capfdbinary.readouterr()\n            assert captured.out == b\"hello\\n\"\n\n    \"\"\"\n    capman: CaptureManager = request.config.pluginmanager.getplugin(\"capturemanager\")\n    capture_fixture = CaptureFixture(FDCaptureBinary, request, _ispytest=True)\n    capman.set_fixture(capture_fixture)\n    capture_fixture._start()\n    yield capture_fixture\n    capture_fixture.close()\n    capman.unset_fixture()\n"
  },
  {
    "path": "src/_pytest/compat.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Python version compatibility code and random general utilities.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nimport enum\nimport functools\nimport inspect\nfrom inspect import Parameter\nfrom inspect import Signature\nimport os\nfrom pathlib import Path\nimport sys\nfrom typing import Any\nfrom typing import Final\nfrom typing import NoReturn\nfrom typing import TYPE_CHECKING\n\nimport py\n\n\nif sys.version_info >= (3, 14):\n    from annotationlib import Format\n\n\n#: constant to prepare valuing pylib path replacements/lazy proxies later on\n#  intended for removal in pytest 8.0 or 9.0\n\n# fmt: off\n# intentional space to create a fake difference for the verification\nLEGACY_PATH = py.path. local\n# fmt: on\n\n\ndef legacy_path(path: str | os.PathLike[str]) -> LEGACY_PATH:\n    \"\"\"Internal wrapper to prepare lazy proxies for legacy_path instances\"\"\"\n    return LEGACY_PATH(path)\n\n\n# fmt: off\n# Singleton type for NOTSET, as described in:\n# https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions\nclass NotSetType(enum.Enum):\n    token = 0\nNOTSET: Final = NotSetType.token\n# fmt: on\n\n\ndef iscoroutinefunction(func: object) -> bool:\n    \"\"\"Return True if func is a coroutine function (a function defined with async\n    def syntax, and doesn't contain yield), or a function decorated with\n    @asyncio.coroutine.\n\n    Note: copied and modified from Python 3.5's builtin coroutines.py to avoid\n    importing asyncio directly, which in turns also initializes the \"logging\"\n    module as a side-effect (see issue #8).\n    \"\"\"\n    return inspect.iscoroutinefunction(func) or getattr(func, \"_is_coroutine\", False)\n\n\ndef is_async_function(func: object) -> bool:\n    \"\"\"Return True if the given function seems to be an async function or\n    an async generator.\"\"\"\n    return iscoroutinefunction(func) or inspect.isasyncgenfunction(func)\n\n\ndef signature(obj: Callable[..., Any]) -> Signature:\n    \"\"\"Return signature without evaluating annotations.\"\"\"\n    if sys.version_info >= (3, 14):\n        return inspect.signature(obj, annotation_format=Format.STRING)\n    return inspect.signature(obj)\n\n\ndef getlocation(function, curdir: str | os.PathLike[str] | None = None) -> str:\n    function = get_real_func(function)\n    fn = Path(inspect.getfile(function))\n    lineno = function.__code__.co_firstlineno\n    if curdir is not None:\n        try:\n            relfn = fn.relative_to(curdir)\n        except ValueError:\n            pass\n        else:\n            return f\"{relfn}:{lineno + 1}\"\n    return f\"{fn}:{lineno + 1}\"\n\n\ndef num_mock_patch_args(function) -> int:\n    \"\"\"Return number of arguments used up by mock arguments (if any).\"\"\"\n    patchings = getattr(function, \"patchings\", None)\n    if not patchings:\n        return 0\n\n    mock_sentinel = getattr(sys.modules.get(\"mock\"), \"DEFAULT\", object())\n    ut_mock_sentinel = getattr(sys.modules.get(\"unittest.mock\"), \"DEFAULT\", object())\n\n    return len(\n        [\n            p\n            for p in patchings\n            if not p.attribute_name\n            and (p.new is mock_sentinel or p.new is ut_mock_sentinel)\n        ]\n    )\n\n\ndef getfuncargnames(\n    function: Callable[..., object],\n    *,\n    name: str = \"\",\n    cls: type | None = None,\n) -> tuple[str, ...]:\n    \"\"\"Return the names of a function's mandatory arguments.\n\n    Should return the names of all function arguments that:\n    * Aren't bound to an instance or type as in instance or class methods.\n    * Don't have default values.\n    * Aren't bound with functools.partial.\n    * Aren't replaced with mocks.\n\n    The cls arguments indicate that the function should be treated as a bound\n    method even though it's not unless the function is a static method.\n\n    The name parameter should be the original name in which the function was collected.\n    \"\"\"\n    # TODO(RonnyPfannschmidt): This function should be refactored when we\n    # revisit fixtures. The fixture mechanism should ask the node for\n    # the fixture names, and not try to obtain directly from the\n    # function object well after collection has occurred.\n\n    # The parameters attribute of a Signature object contains an\n    # ordered mapping of parameter names to Parameter instances.  This\n    # creates a tuple of the names of the parameters that don't have\n    # defaults.\n    try:\n        parameters = signature(function).parameters.values()\n    except (ValueError, TypeError) as e:\n        from _pytest.outcomes import fail\n\n        fail(\n            f\"Could not determine arguments of {function!r}: {e}\",\n            pytrace=False,\n        )\n\n    arg_names = tuple(\n        p.name\n        for p in parameters\n        if (\n            p.kind is Parameter.POSITIONAL_OR_KEYWORD\n            or p.kind is Parameter.KEYWORD_ONLY\n        )\n        and p.default is Parameter.empty\n    )\n    if not name:\n        name = function.__name__\n\n    # If this function should be treated as a bound method even though\n    # it's passed as an unbound method or function, and its first parameter\n    # wasn't defined as positional only, remove the first parameter name.\n    if not any(p.kind is Parameter.POSITIONAL_ONLY for p in parameters) and (\n        # Not using `getattr` because we don't want to resolve the staticmethod.\n        # Not using `cls.__dict__` because we want to check the entire MRO.\n        cls\n        and not isinstance(\n            inspect.getattr_static(cls, name, default=None), staticmethod\n        )\n    ):\n        arg_names = arg_names[1:]\n    # Remove any names that will be replaced with mocks.\n    if hasattr(function, \"__wrapped__\"):\n        arg_names = arg_names[num_mock_patch_args(function) :]\n    return arg_names\n\n\ndef get_default_arg_names(function: Callable[..., Any]) -> tuple[str, ...]:\n    # Note: this code intentionally mirrors the code at the beginning of\n    # getfuncargnames, to get the arguments which were excluded from its result\n    # because they had default values.\n    return tuple(\n        p.name\n        for p in signature(function).parameters.values()\n        if p.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY)\n        and p.default is not Parameter.empty\n    )\n\n\n_non_printable_ascii_translate_table = {\n    i: f\"\\\\x{i:02x}\" for i in range(128) if i not in range(32, 127)\n}\n_non_printable_ascii_translate_table.update(\n    {ord(\"\\t\"): \"\\\\t\", ord(\"\\r\"): \"\\\\r\", ord(\"\\n\"): \"\\\\n\"}\n)\n\n\ndef ascii_escaped(val: bytes | str) -> str:\n    r\"\"\"If val is pure ASCII, return it as an str, otherwise, escape\n    bytes objects into a sequence of escaped bytes:\n\n    b'\\xc3\\xb4\\xc5\\xd6' -> r'\\xc3\\xb4\\xc5\\xd6'\n\n    and escapes strings into a sequence of escaped unicode ids, e.g.:\n\n    r'4\\nV\\U00043efa\\x0eMXWB\\x1e\\u3028\\u15fd\\xcd\\U0007d944'\n\n    Note:\n       The obvious \"v.decode('unicode-escape')\" will return\n       valid UTF-8 unicode if it finds them in bytes, but we\n       want to return escaped bytes for any byte, even if they match\n       a UTF-8 string.\n    \"\"\"\n    if isinstance(val, bytes):\n        ret = val.decode(\"ascii\", \"backslashreplace\")\n    else:\n        ret = val.encode(\"unicode_escape\").decode(\"ascii\")\n    return ret.translate(_non_printable_ascii_translate_table)\n\n\ndef get_real_func(obj):\n    \"\"\"Get the real function object of the (possibly) wrapped object by\n    :func:`functools.wraps`, or :func:`functools.partial`.\"\"\"\n    obj = inspect.unwrap(obj)\n\n    if isinstance(obj, functools.partial):\n        obj = obj.func\n    return obj\n\n\ndef getimfunc(func):\n    try:\n        return func.__func__\n    except AttributeError:\n        return func\n\n\ndef safe_getattr(object: Any, name: str, default: Any) -> Any:\n    \"\"\"Like getattr but return default upon any Exception or any OutcomeException.\n\n    Attribute access can potentially fail for 'evil' Python objects.\n    See issue #214.\n    It catches OutcomeException because of #2490 (issue #580), new outcomes\n    are derived from BaseException instead of Exception (for more details\n    check #2707).\n    \"\"\"\n    from _pytest.outcomes import TEST_OUTCOME\n\n    try:\n        return getattr(object, name, default)\n    except TEST_OUTCOME:\n        return default\n\n\ndef safe_isclass(obj: object) -> bool:\n    \"\"\"Ignore any exception via isinstance on Python 3.\"\"\"\n    try:\n        return inspect.isclass(obj)\n    except Exception:\n        return False\n\n\ndef get_user_id() -> int | None:\n    \"\"\"Return the current process's real user id or None if it could not be\n    determined.\n\n    :return: The user id or None if it could not be determined.\n    \"\"\"\n    # mypy follows the version and platform checking expectation of PEP 484:\n    # https://mypy.readthedocs.io/en/stable/common_issues.html?highlight=platform#python-version-and-system-platform-checks\n    # Containment checks are too complex for mypy v1.5.0 and cause failure.\n    if sys.platform == \"win32\" or sys.platform == \"emscripten\":\n        # win32 does not have a getuid() function.\n        # Emscripten has a return 0 stub.\n        return None\n    else:\n        # On other platforms, a return value of -1 is assumed to indicate that\n        # the current process's real user id could not be determined.\n        ERROR = -1\n        uid = os.getuid()\n        return uid if uid != ERROR else None\n\n\nif sys.version_info >= (3, 11):\n    from typing import assert_never\nelse:\n\n    def assert_never(value: NoReturn) -> NoReturn:\n        assert False, f\"Unhandled value: {value} ({type(value).__name__})\"\n\n\nclass CallableBool:\n    \"\"\"\n    A bool-like object that can also be called, returning its true/false value.\n\n    Used for backwards compatibility in cases where something was supposed to be a method\n    but was implemented as a simple attribute by mistake (see `TerminalReporter.isatty`).\n\n    Do not use in new code.\n    \"\"\"\n\n    def __init__(self, value: bool) -> None:\n        self._value = value\n\n    def __bool__(self) -> bool:\n        return self._value\n\n    def __call__(self) -> bool:\n        return self._value\n\n\ndef running_on_ci() -> bool:\n    \"\"\"Check if we're currently running on a CI system.\"\"\"\n    # Only enable CI mode if one of these env variables is defined and non-empty.\n    # Note: review `regendoc` tox env in case this list is changed.\n    env_vars = [\"CI\", \"BUILD_NUMBER\"]\n    return any(os.environ.get(var) for var in env_vars)\n\n\nif sys.version_info >= (3, 13):\n    from warnings import deprecated as deprecated\nelse:\n    if TYPE_CHECKING:\n        from typing_extensions import deprecated as deprecated\n    else:\n\n        def deprecated(msg, /, *, category=None, stacklevel=1):\n            def decorator(func):\n                return func\n\n            return decorator\n"
  },
  {
    "path": "src/_pytest/config/__init__.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Command line options, config-file and conftest.py processing.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport builtins\nimport collections.abc\nfrom collections.abc import Callable\nfrom collections.abc import Generator\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nfrom collections.abc import Mapping\nfrom collections.abc import MutableMapping\nfrom collections.abc import Sequence\nimport contextlib\nimport copy\nimport dataclasses\nimport enum\nfrom functools import lru_cache\nimport glob\nimport importlib\nimport importlib.metadata\nimport inspect\nimport os\nimport pathlib\nimport re\nimport shlex\nimport sys\nfrom textwrap import dedent\nimport types\nfrom types import FunctionType\nfrom typing import Any\nfrom typing import cast\nfrom typing import Final\nfrom typing import final\nfrom typing import IO\nfrom typing import TextIO\nfrom typing import TYPE_CHECKING\nimport warnings\n\nfrom pluggy import HookimplMarker\nfrom pluggy import HookimplOpts\nfrom pluggy import HookspecMarker\nfrom pluggy import HookspecOpts\nfrom pluggy import PluginManager\n\nfrom .exceptions import PrintHelp as PrintHelp\nfrom .exceptions import UsageError as UsageError\nfrom .findpaths import ConfigDict\nfrom .findpaths import ConfigValue\nfrom .findpaths import determine_setup\nfrom _pytest import __version__\nimport _pytest._code\nfrom _pytest._code import ExceptionInfo\nfrom _pytest._code import filter_traceback\nfrom _pytest._code.code import TracebackStyle\nfrom _pytest._io import TerminalWriter\nfrom _pytest.compat import assert_never\nfrom _pytest.compat import deprecated\nfrom _pytest.compat import NOTSET\nfrom _pytest.config.argparsing import Argument\nfrom _pytest.config.argparsing import FILE_OR_DIR\nfrom _pytest.config.argparsing import Parser\nimport _pytest.deprecated\nimport _pytest.hookspec\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import Skipped\nfrom _pytest.pathlib import absolutepath\nfrom _pytest.pathlib import bestrelpath\nfrom _pytest.pathlib import import_path\nfrom _pytest.pathlib import ImportMode\nfrom _pytest.pathlib import resolve_package_path\nfrom _pytest.pathlib import safe_exists\nfrom _pytest.stash import Stash\nfrom _pytest.warning_types import PytestConfigWarning\nfrom _pytest.warning_types import warn_explicit_for\n\n\nif TYPE_CHECKING:\n    from _pytest.assertion.rewrite import AssertionRewritingHook\n    from _pytest.cacheprovider import Cache\n    from _pytest.terminal import TerminalReporter\n\n_PluggyPlugin = object\n\"\"\"A type to represent plugin objects.\n\nPlugins can be any namespace, so we can't narrow it down much, but we use an\nalias to make the intent clear.\n\nIdeally this type would be provided by pluggy itself.\n\"\"\"\n\n\nhookimpl = HookimplMarker(\"pytest\")\nhookspec = HookspecMarker(\"pytest\")\n\n\n@final\nclass ExitCode(enum.IntEnum):\n    \"\"\"Encodes the valid exit codes by pytest.\n\n    Currently users and plugins may supply other exit codes as well.\n\n    .. versionadded:: 5.0\n    \"\"\"\n\n    #: Tests passed.\n    OK = 0\n    #: Tests failed.\n    TESTS_FAILED = 1\n    #: pytest was interrupted.\n    INTERRUPTED = 2\n    #: An internal error got in the way.\n    INTERNAL_ERROR = 3\n    #: pytest was misused.\n    USAGE_ERROR = 4\n    #: pytest couldn't find tests.\n    NO_TESTS_COLLECTED = 5\n\n    __module__ = \"pytest\"\n\n\nclass ConftestImportFailure(Exception):\n    def __init__(\n        self,\n        path: pathlib.Path,\n        *,\n        cause: Exception,\n    ) -> None:\n        self.path = path\n        self.cause = cause\n\n    def __str__(self) -> str:\n        return f\"{type(self.cause).__name__}: {self.cause} (from {self.path})\"\n\n\ndef filter_traceback_for_conftest_import_failure(\n    entry: _pytest._code.TracebackEntry,\n) -> bool:\n    \"\"\"Filter tracebacks entries which point to pytest internals or importlib.\n\n    Make a special case for importlib because we use it to import test modules and conftest files\n    in _pytest.pathlib.import_path.\n    \"\"\"\n    return filter_traceback(entry) and \"importlib\" not in str(entry.path).split(os.sep)\n\n\ndef print_conftest_import_error(e: ConftestImportFailure, file: TextIO) -> None:\n    exc_info = ExceptionInfo.from_exception(e.cause)\n    tw = TerminalWriter(file)\n    tw.line(f\"ImportError while loading conftest '{e.path}'.\", red=True)\n    exc_info.traceback = exc_info.traceback.filter(\n        filter_traceback_for_conftest_import_failure\n    )\n    exc_repr = (\n        exc_info.getrepr(style=\"short\", chain=False)\n        if exc_info.traceback\n        else exc_info.exconly()\n    )\n    formatted_tb = str(exc_repr)\n    for line in formatted_tb.splitlines():\n        tw.line(line.rstrip(), red=True)\n\n\ndef print_usage_error(e: UsageError, file: TextIO) -> None:\n    tw = TerminalWriter(file)\n    for msg in e.args:\n        tw.line(f\"ERROR: {msg}\\n\", red=True)\n\n\ndef main(\n    args: list[str] | os.PathLike[str] | None = None,\n    plugins: Sequence[str | _PluggyPlugin] | None = None,\n) -> int | ExitCode:\n    \"\"\"Perform an in-process test run.\n\n    :param args:\n        List of command line arguments. If `None` or not given, defaults to reading\n        arguments directly from the process command line (:data:`sys.argv`).\n    :param plugins: List of plugin objects to be auto-registered during initialization.\n\n    :returns: An exit code.\n    \"\"\"\n    # Handle a single `--version` argument early to avoid starting up the entire pytest infrastructure.\n    new_args = sys.argv[1:] if args is None else args\n    if isinstance(new_args, Sequence) and new_args.count(\"--version\") == 1:\n        sys.stdout.write(f\"pytest {__version__}\\n\")\n        return ExitCode.OK\n\n    old_pytest_version = os.environ.get(\"PYTEST_VERSION\")\n    try:\n        os.environ[\"PYTEST_VERSION\"] = __version__\n        try:\n            config = _prepareconfig(new_args, plugins)\n        except ConftestImportFailure as e:\n            print_conftest_import_error(e, file=sys.stderr)\n            return ExitCode.USAGE_ERROR\n\n        try:\n            ret: ExitCode | int = config.hook.pytest_cmdline_main(config=config)\n            try:\n                return ExitCode(ret)\n            except ValueError:\n                return ret\n        finally:\n            config._ensure_unconfigure()\n    except UsageError as e:\n        print_usage_error(e, file=sys.stderr)\n        return ExitCode.USAGE_ERROR\n    finally:\n        if old_pytest_version is None:\n            os.environ.pop(\"PYTEST_VERSION\", None)\n        else:\n            os.environ[\"PYTEST_VERSION\"] = old_pytest_version\n\n\ndef console_main() -> int:\n    \"\"\"The CLI entry point of pytest.\n\n    This function is not meant for programmable use; use `main()` instead.\n    \"\"\"\n    # https://docs.python.org/3/library/signal.html#note-on-sigpipe\n    try:\n        code = main()\n        sys.stdout.flush()\n        return code\n    except BrokenPipeError:\n        # Python flushes standard streams on exit; redirect remaining output\n        # to devnull to avoid another BrokenPipeError at shutdown\n        devnull = os.open(os.devnull, os.O_WRONLY)\n        os.dup2(devnull, sys.stdout.fileno())\n        return 1  # Python exits with error code 1 on EPIPE\n\n\nclass cmdline:  # compatibility namespace\n    main = staticmethod(main)\n\n\ndef filename_arg(path: str, optname: str) -> str:\n    \"\"\"Argparse type validator for filename arguments.\n\n    :path: Path of filename.\n    :optname: Name of the option.\n    \"\"\"\n    if os.path.isdir(path):\n        raise UsageError(f\"{optname} must be a filename, given: {path}\")\n    return path\n\n\ndef directory_arg(path: str, optname: str) -> str:\n    \"\"\"Argparse type validator for directory arguments.\n\n    :path: Path of directory.\n    :optname: Name of the option.\n    \"\"\"\n    if not os.path.isdir(path):\n        raise UsageError(f\"{optname} must be a directory, given: {path}\")\n    return path\n\n\n# Plugins that cannot be disabled via \"-p no:X\" currently.\nessential_plugins = (\n    \"mark\",\n    \"main\",\n    \"runner\",\n    \"fixtures\",\n    \"helpconfig\",  # Provides -p.\n)\n\ndefault_plugins = (\n    *essential_plugins,\n    \"python\",\n    \"terminal\",\n    \"debugging\",\n    \"unittest\",\n    \"capture\",\n    \"skipping\",\n    \"legacypath\",\n    \"tmpdir\",\n    \"monkeypatch\",\n    \"recwarn\",\n    \"pastebin\",\n    \"assertion\",\n    \"junitxml\",\n    \"doctest\",\n    \"cacheprovider\",\n    \"setuponly\",\n    \"setupplan\",\n    \"stepwise\",\n    \"unraisableexception\",\n    \"threadexception\",\n    \"warnings\",\n    \"logging\",\n    \"reports\",\n    \"faulthandler\",\n    \"subtests\",\n)\n\nbuiltin_plugins = {\n    *default_plugins,\n    \"pytester\",\n    \"pytester_assertions\",\n    \"terminalprogress\",\n}\n\n\ndef get_config(\n    args: Iterable[str] | None = None,\n    plugins: Sequence[str | _PluggyPlugin] | None = None,\n) -> Config:\n    # Subsequent calls to main will create a fresh instance.\n    pluginmanager = PytestPluginManager()\n    invocation_params = Config.InvocationParams(\n        args=args or (),\n        plugins=plugins,\n        dir=pathlib.Path.cwd(),\n    )\n    config = Config(pluginmanager, invocation_params=invocation_params)\n\n    if invocation_params.args:\n        # Handle any \"-p no:plugin\" args.\n        pluginmanager.consider_preparse(invocation_params.args, exclude_only=True)\n\n    for spec in default_plugins:\n        pluginmanager.import_plugin(spec)\n\n    return config\n\n\ndef get_plugin_manager() -> PytestPluginManager:\n    \"\"\"Obtain a new instance of the\n    :py:class:`pytest.PytestPluginManager`, with default plugins\n    already loaded.\n\n    This function can be used by integration with other tools, like hooking\n    into pytest to run tests into an IDE.\n    \"\"\"\n    return get_config().pluginmanager\n\n\ndef _prepareconfig(\n    args: list[str] | os.PathLike[str],\n    plugins: Sequence[str | _PluggyPlugin] | None = None,\n) -> Config:\n    if isinstance(args, os.PathLike):\n        args = [os.fspath(args)]\n    elif not isinstance(args, list):\n        msg = (  # type:ignore[unreachable]\n            \"`args` parameter expected to be a list of strings, got: {!r} (type: {})\"\n        )\n        raise TypeError(msg.format(args, type(args)))\n\n    initial_config = get_config(args, plugins)\n    pluginmanager = initial_config.pluginmanager\n    try:\n        if plugins:\n            for plugin in plugins:\n                if isinstance(plugin, str):\n                    pluginmanager.consider_pluginarg(plugin)\n                else:\n                    pluginmanager.register(plugin)\n        config: Config = pluginmanager.hook.pytest_cmdline_parse(\n            pluginmanager=pluginmanager, args=args\n        )\n        return config\n    except BaseException:\n        initial_config._ensure_unconfigure()\n        raise\n\n\ndef _get_directory(path: pathlib.Path) -> pathlib.Path:\n    \"\"\"Get the directory of a path - itself if already a directory.\"\"\"\n    if path.is_file():\n        return path.parent\n    else:\n        return path\n\n\ndef _get_legacy_hook_marks(\n    method: Any,\n    hook_type: str,\n    opt_names: tuple[str, ...],\n) -> dict[str, bool]:\n    if TYPE_CHECKING:\n        # abuse typeguard from importlib to avoid massive method type union that's lacking an alias\n        assert inspect.isroutine(method)\n    known_marks: set[str] = {m.name for m in getattr(method, \"pytestmark\", [])}\n    must_warn: list[str] = []\n    opts: dict[str, bool] = {}\n    for opt_name in opt_names:\n        opt_attr = getattr(method, opt_name, AttributeError)\n        if opt_attr is not AttributeError:\n            must_warn.append(f\"{opt_name}={opt_attr}\")\n            opts[opt_name] = True\n        elif opt_name in known_marks:\n            must_warn.append(f\"{opt_name}=True\")\n            opts[opt_name] = True\n        else:\n            opts[opt_name] = False\n    if must_warn:\n        hook_opts = \", \".join(must_warn)\n        message = _pytest.deprecated.HOOK_LEGACY_MARKING.format(\n            type=hook_type,\n            fullname=method.__qualname__,\n            hook_opts=hook_opts,\n        )\n        warn_explicit_for(cast(FunctionType, method), message)\n    return opts\n\n\n@final\nclass PytestPluginManager(PluginManager):\n    \"\"\"A :py:class:`pluggy.PluginManager <pluggy.PluginManager>` with\n    additional pytest-specific functionality:\n\n    * Loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and\n      ``pytest_plugins`` global variables found in plugins being loaded.\n    * ``conftest.py`` loading during start-up.\n    \"\"\"\n\n    def __init__(self) -> None:\n        from _pytest.assertion import DummyRewriteHook\n        from _pytest.assertion import RewriteHook\n\n        super().__init__(\"pytest\")\n\n        # -- State related to local conftest plugins.\n        # All loaded conftest modules.\n        self._conftest_plugins: set[types.ModuleType] = set()\n        # All conftest modules applicable for a directory.\n        # This includes the directory's own conftest modules as well\n        # as those of its parent directories.\n        self._dirpath2confmods: dict[pathlib.Path, list[types.ModuleType]] = {}\n        # Cutoff directory above which conftests are no longer discovered.\n        self._confcutdir: pathlib.Path | None = None\n        # If set, conftest loading is skipped.\n        self._noconftest = False\n\n        # _getconftestmodules()'s call to _get_directory() causes a stat\n        # storm when it's called potentially thousands of times in a test\n        # session (#9478), often with the same path, so cache it.\n        self._get_directory = lru_cache(256)(_get_directory)\n\n        # plugins that were explicitly skipped with pytest.skip\n        # list of (module name, skip reason)\n        # previously we would issue a warning when a plugin was skipped, but\n        # since we refactored warnings as first citizens of Config, they are\n        # just stored here to be used later.\n        self.skipped_plugins: list[tuple[str, str]] = []\n\n        self.add_hookspecs(_pytest.hookspec)\n        self.register(self)\n        if os.environ.get(\"PYTEST_DEBUG\"):\n            err: IO[str] = sys.stderr\n            encoding: str = getattr(err, \"encoding\", \"utf8\")\n            try:\n                err = open(\n                    os.dup(err.fileno()),\n                    mode=err.mode,\n                    buffering=1,\n                    encoding=encoding,\n                )\n            except Exception:\n                pass\n            self.trace.root.setwriter(err.write)\n            self.enable_tracing()\n\n        # Config._consider_importhook will set a real object if required.\n        self.rewrite_hook: RewriteHook = DummyRewriteHook()\n        # Used to know when we are importing conftests after the pytest_configure stage.\n        self._configured = False\n\n    def parse_hookimpl_opts(\n        self, plugin: _PluggyPlugin, name: str\n    ) -> HookimplOpts | None:\n        \"\"\":meta private:\"\"\"\n        # pytest hooks are always prefixed with \"pytest_\",\n        # so we avoid accessing possibly non-readable attributes\n        # (see issue #1073).\n        if not name.startswith(\"pytest_\"):\n            return None\n        # Ignore names which cannot be hooks.\n        if name == \"pytest_plugins\":\n            return None\n\n        opts = super().parse_hookimpl_opts(plugin, name)\n        if opts is not None:\n            return opts\n\n        method = getattr(plugin, name)\n        # Consider only actual functions for hooks (#3775).\n        if not inspect.isroutine(method):\n            return None\n        # Collect unmarked hooks as long as they have the `pytest_' prefix.\n        legacy = _get_legacy_hook_marks(\n            method, \"impl\", (\"tryfirst\", \"trylast\", \"optionalhook\", \"hookwrapper\")\n        )\n        return cast(HookimplOpts, legacy)\n\n    def parse_hookspec_opts(self, module_or_class, name: str) -> HookspecOpts | None:\n        \"\"\":meta private:\"\"\"\n        opts = super().parse_hookspec_opts(module_or_class, name)\n        if opts is None:\n            method = getattr(module_or_class, name)\n            if name.startswith(\"pytest_\"):\n                legacy = _get_legacy_hook_marks(\n                    method, \"spec\", (\"firstresult\", \"historic\")\n                )\n                opts = cast(HookspecOpts, legacy)\n        return opts\n\n    def register(self, plugin: _PluggyPlugin, name: str | None = None) -> str | None:\n        if name in _pytest.deprecated.DEPRECATED_EXTERNAL_PLUGINS:\n            warnings.warn(\n                PytestConfigWarning(\n                    \"{} plugin has been merged into the core, \"\n                    \"please remove it from your requirements.\".format(\n                        name.replace(\"_\", \"-\")\n                    )\n                )\n            )\n            return None\n        plugin_name = super().register(plugin, name)\n        if plugin_name is not None:\n            self.hook.pytest_plugin_registered.call_historic(\n                kwargs=dict(\n                    plugin=plugin,\n                    plugin_name=plugin_name,\n                    manager=self,\n                )\n            )\n\n            if isinstance(plugin, types.ModuleType):\n                self.consider_module(plugin)\n        return plugin_name\n\n    def getplugin(self, name: str):\n        # Support deprecated naming because plugins (xdist e.g.) use it.\n        plugin: _PluggyPlugin | None = self.get_plugin(name)\n        return plugin\n\n    def hasplugin(self, name: str) -> bool:\n        \"\"\"Return whether a plugin with the given name is registered.\"\"\"\n        return bool(self.get_plugin(name))\n\n    def pytest_configure(self, config: Config) -> None:\n        \"\"\":meta private:\"\"\"\n        # XXX now that the pluginmanager exposes hookimpl(tryfirst...)\n        # we should remove tryfirst/trylast as markers.\n        config.addinivalue_line(\n            \"markers\",\n            \"tryfirst: mark a hook implementation function such that the \"\n            \"plugin machinery will try to call it first/as early as possible. \"\n            \"DEPRECATED, use @pytest.hookimpl(tryfirst=True) instead.\",\n        )\n        config.addinivalue_line(\n            \"markers\",\n            \"trylast: mark a hook implementation function such that the \"\n            \"plugin machinery will try to call it last/as late as possible. \"\n            \"DEPRECATED, use @pytest.hookimpl(trylast=True) instead.\",\n        )\n        self._configured = True\n\n    #\n    # Internal API for local conftest plugin handling.\n    #\n    def _set_initial_conftests(\n        self,\n        args: Sequence[str | pathlib.Path],\n        pyargs: bool,\n        noconftest: bool,\n        rootpath: pathlib.Path,\n        confcutdir: pathlib.Path | None,\n        invocation_dir: pathlib.Path,\n        importmode: ImportMode | str,\n        *,\n        consider_namespace_packages: bool,\n    ) -> None:\n        \"\"\"Load initial conftest files given a preparsed \"namespace\".\n\n        As conftest files may add their own command line options which have\n        arguments ('--my-opt somepath') we might get some false positives.\n        All builtin and 3rd party plugins will have been loaded, however, so\n        common options will not confuse our logic here.\n        \"\"\"\n        self._confcutdir = (\n            absolutepath(invocation_dir / confcutdir) if confcutdir else None\n        )\n        self._noconftest = noconftest\n        self._using_pyargs = pyargs\n        foundanchor = False\n        for initial_path in args:\n            path = str(initial_path)\n            # remove node-id syntax\n            i = path.find(\"::\")\n            if i != -1:\n                path = path[:i]\n            anchor = absolutepath(invocation_dir / path)\n\n            # Ensure we do not break if what appears to be an anchor\n            # is in fact a very long option (#10169, #11394).\n            if safe_exists(anchor):\n                self._try_load_conftest(\n                    anchor,\n                    importmode,\n                    rootpath,\n                    consider_namespace_packages=consider_namespace_packages,\n                )\n                foundanchor = True\n        if not foundanchor:\n            self._try_load_conftest(\n                invocation_dir,\n                importmode,\n                rootpath,\n                consider_namespace_packages=consider_namespace_packages,\n            )\n\n    def _is_in_confcutdir(self, path: pathlib.Path) -> bool:\n        \"\"\"Whether to consider the given path to load conftests from.\"\"\"\n        if self._confcutdir is None:\n            return True\n        # The semantics here are literally:\n        #   Do not load a conftest if it is found upwards from confcut dir.\n        # But this is *not* the same as:\n        #   Load only conftests from confcutdir or below.\n        # At first glance they might seem the same thing, however we do support use cases where\n        # we want to load conftests that are not found in confcutdir or below, but are found\n        # in completely different directory hierarchies like packages installed\n        # in out-of-source trees.\n        # (see #9767 for a regression where the logic was inverted).\n        return path not in self._confcutdir.parents\n\n    def _try_load_conftest(\n        self,\n        anchor: pathlib.Path,\n        importmode: str | ImportMode,\n        rootpath: pathlib.Path,\n        *,\n        consider_namespace_packages: bool,\n    ) -> None:\n        self._loadconftestmodules(\n            anchor,\n            importmode,\n            rootpath,\n            consider_namespace_packages=consider_namespace_packages,\n        )\n        # let's also consider test* subdirs\n        if anchor.is_dir():\n            for x in anchor.glob(\"test*\"):\n                if x.is_dir():\n                    self._loadconftestmodules(\n                        x,\n                        importmode,\n                        rootpath,\n                        consider_namespace_packages=consider_namespace_packages,\n                    )\n\n    def _loadconftestmodules(\n        self,\n        path: pathlib.Path,\n        importmode: str | ImportMode,\n        rootpath: pathlib.Path,\n        *,\n        consider_namespace_packages: bool,\n    ) -> None:\n        if self._noconftest:\n            return\n\n        directory = self._get_directory(path)\n\n        # Optimization: avoid repeated searches in the same directory.\n        # Assumes always called with same importmode and rootpath.\n        if directory in self._dirpath2confmods:\n            return\n\n        clist = []\n        for parent in reversed((directory, *directory.parents)):\n            if self._is_in_confcutdir(parent):\n                conftestpath = parent / \"conftest.py\"\n                if conftestpath.is_file():\n                    mod = self._importconftest(\n                        conftestpath,\n                        importmode,\n                        rootpath,\n                        consider_namespace_packages=consider_namespace_packages,\n                    )\n                    clist.append(mod)\n        self._dirpath2confmods[directory] = clist\n\n    def _getconftestmodules(self, path: pathlib.Path) -> Sequence[types.ModuleType]:\n        directory = self._get_directory(path)\n        return self._dirpath2confmods.get(directory, ())\n\n    def _rget_with_confmod(\n        self,\n        name: str,\n        path: pathlib.Path,\n    ) -> tuple[types.ModuleType, Any]:\n        modules = self._getconftestmodules(path)\n        for mod in reversed(modules):\n            try:\n                return mod, getattr(mod, name)\n            except AttributeError:\n                continue\n        raise KeyError(name)\n\n    def _importconftest(\n        self,\n        conftestpath: pathlib.Path,\n        importmode: str | ImportMode,\n        rootpath: pathlib.Path,\n        *,\n        consider_namespace_packages: bool,\n    ) -> types.ModuleType:\n        conftestpath_plugin_name = str(conftestpath)\n        existing = self.get_plugin(conftestpath_plugin_name)\n        if existing is not None:\n            return cast(types.ModuleType, existing)\n\n        # conftest.py files there are not in a Python package all have module\n        # name \"conftest\", and thus conflict with each other. Clear the existing\n        # before loading the new one, otherwise the existing one will be\n        # returned from the module cache.\n        pkgpath = resolve_package_path(conftestpath)\n        if pkgpath is None:\n            try:\n                del sys.modules[conftestpath.stem]\n            except KeyError:\n                pass\n\n        try:\n            mod = import_path(\n                conftestpath,\n                mode=importmode,\n                root=rootpath,\n                consider_namespace_packages=consider_namespace_packages,\n            )\n        except Exception as e:\n            assert e.__traceback__ is not None\n            raise ConftestImportFailure(conftestpath, cause=e) from e\n\n        self._check_non_top_pytest_plugins(mod, conftestpath)\n\n        self._conftest_plugins.add(mod)\n        dirpath = conftestpath.parent\n        if dirpath in self._dirpath2confmods:\n            for path, mods in self._dirpath2confmods.items():\n                if dirpath in path.parents or path == dirpath:\n                    if mod in mods:\n                        raise AssertionError(\n                            f\"While trying to load conftest path {conftestpath!s}, \"\n                            f\"found that the module {mod} is already loaded with path {mod.__file__}. \"\n                            \"This is not supposed to happen. Please report this issue to pytest.\"\n                        )\n                    mods.append(mod)\n        self.trace(f\"loading conftestmodule {mod!r}\")\n        self.consider_conftest(mod, registration_name=conftestpath_plugin_name)\n        return mod\n\n    def _check_non_top_pytest_plugins(\n        self,\n        mod: types.ModuleType,\n        conftestpath: pathlib.Path,\n    ) -> None:\n        if (\n            hasattr(mod, \"pytest_plugins\")\n            and self._configured\n            and not self._using_pyargs\n        ):\n            msg = (\n                \"Defining 'pytest_plugins' in a non-top-level conftest is no longer supported:\\n\"\n                \"It affects the entire test suite instead of just below the conftest as expected.\\n\"\n                \"  {}\\n\"\n                \"Please move it to a top level conftest file at the rootdir:\\n\"\n                \"  {}\\n\"\n                \"For more information, visit:\\n\"\n                \"  https://docs.pytest.org/en/stable/deprecations.html#pytest-plugins-in-non-top-level-conftest-files\"\n            )\n            fail(msg.format(conftestpath, self._confcutdir), pytrace=False)\n\n    #\n    # API for bootstrapping plugin loading\n    #\n    #\n\n    def consider_preparse(\n        self, args: Sequence[str], *, exclude_only: bool = False\n    ) -> None:\n        \"\"\":meta private:\"\"\"\n        i = 0\n        n = len(args)\n        while i < n:\n            opt = args[i]\n            i += 1\n            if isinstance(opt, str):\n                if opt == \"-p\":\n                    try:\n                        parg = args[i]\n                    except IndexError:\n                        return\n                    i += 1\n                elif opt.startswith(\"-p\"):\n                    parg = opt[2:]\n                else:\n                    continue\n                parg = parg.strip()\n                if exclude_only and not parg.startswith(\"no:\"):\n                    continue\n                self.consider_pluginarg(parg)\n\n    def consider_pluginarg(self, arg: str) -> None:\n        \"\"\":meta private:\"\"\"\n        if arg.startswith(\"no:\"):\n            name = arg[3:]\n            if name in essential_plugins:\n                raise UsageError(f\"plugin {name} cannot be disabled\")\n\n            if name.endswith(\"conftest.py\"):\n                raise UsageError(\n                    f\"Blocking conftest files using -p is not supported: -p no:{name}\\n\"\n                    \"conftest.py files are not plugins and cannot be disabled via -p.\\n\"\n                )\n\n            # PR #4304: remove stepwise if cacheprovider is blocked.\n            if name == \"cacheprovider\":\n                self.set_blocked(\"stepwise\")\n                self.set_blocked(\"pytest_stepwise\")\n\n            self.set_blocked(name)\n            if not name.startswith(\"pytest_\"):\n                self.set_blocked(\"pytest_\" + name)\n        else:\n            name = arg\n            # Unblock the plugin.\n            self.unblock(name)\n            if not name.startswith(\"pytest_\"):\n                self.unblock(\"pytest_\" + name)\n            self.import_plugin(arg, consider_entry_points=True)\n\n    def consider_conftest(\n        self, conftestmodule: types.ModuleType, registration_name: str\n    ) -> None:\n        \"\"\":meta private:\"\"\"\n        self.register(conftestmodule, name=registration_name)\n\n    def consider_env(self) -> None:\n        \"\"\":meta private:\"\"\"\n        self._import_plugin_specs(os.environ.get(\"PYTEST_PLUGINS\"))\n\n    def consider_module(self, mod: types.ModuleType) -> None:\n        \"\"\":meta private:\"\"\"\n        self._import_plugin_specs(getattr(mod, \"pytest_plugins\", []))\n\n    def _import_plugin_specs(\n        self, spec: None | types.ModuleType | str | Sequence[str]\n    ) -> None:\n        plugins = _get_plugin_specs_as_list(spec)\n        for import_spec in plugins:\n            self.import_plugin(import_spec)\n\n    def import_plugin(self, modname: str, consider_entry_points: bool = False) -> None:\n        \"\"\"Import a plugin with ``modname``.\n\n        If ``consider_entry_points`` is True, entry point names are also\n        considered to find a plugin.\n        \"\"\"\n        # Most often modname refers to builtin modules, e.g. \"pytester\",\n        # \"terminal\" or \"capture\".  Those plugins are registered under their\n        # basename for historic purposes but must be imported with the\n        # _pytest prefix.\n        assert isinstance(modname, str), (\n            f\"module name as text required, got {modname!r}\"\n        )\n        if self.is_blocked(modname) or self.get_plugin(modname) is not None:\n            return\n\n        importspec = \"_pytest.\" + modname if modname in builtin_plugins else modname\n        self.rewrite_hook.mark_rewrite(importspec)\n\n        if consider_entry_points:\n            loaded = self.load_setuptools_entrypoints(\"pytest11\", name=modname)\n            if loaded:\n                return\n\n        try:\n            if sys.version_info >= (3, 11):\n                mod = importlib.import_module(importspec)\n            else:\n                # On Python 3.10, import_module breaks\n                # testing/test_config.py::test_disable_plugin_autoload.\n                __import__(importspec)\n                mod = sys.modules[importspec]\n        except ImportError as e:\n            raise ImportError(\n                f'Error importing plugin \"{modname}\": {e.args[0]}'\n            ).with_traceback(e.__traceback__) from e\n\n        except Skipped as e:\n            self.skipped_plugins.append((modname, e.msg or \"\"))\n        else:\n            self.register(mod, modname)\n\n\ndef _get_plugin_specs_as_list(\n    specs: None | types.ModuleType | str | Sequence[str],\n) -> list[str]:\n    \"\"\"Parse a plugins specification into a list of plugin names.\"\"\"\n    # None means empty.\n    if specs is None:\n        return []\n    # Workaround for #3899 - a submodule which happens to be called \"pytest_plugins\".\n    if isinstance(specs, types.ModuleType):\n        return []\n    # Comma-separated list.\n    if isinstance(specs, str):\n        return specs.split(\",\") if specs else []\n    # Direct specification.\n    if isinstance(specs, collections.abc.Sequence):\n        return list(specs)\n    raise UsageError(\n        f\"Plugins may be specified as a sequence or a ','-separated string of plugin names. Got: {specs!r}\"\n    )\n\n\ndef _iter_rewritable_modules(package_files: Iterable[str]) -> Iterator[str]:\n    \"\"\"Given an iterable of file names in a source distribution, return the \"names\" that should\n    be marked for assertion rewrite.\n\n    For example the package \"pytest_mock/__init__.py\" should be added as \"pytest_mock\" in\n    the assertion rewrite mechanism.\n\n    This function has to deal with dist-info based distributions and egg based distributions\n    (which are still very much in use for \"editable\" installs).\n\n    Here are the file names as seen in a dist-info based distribution:\n\n        pytest_mock/__init__.py\n        pytest_mock/_version.py\n        pytest_mock/plugin.py\n        pytest_mock.egg-info/PKG-INFO\n\n    Here are the file names as seen in an egg based distribution:\n\n        src/pytest_mock/__init__.py\n        src/pytest_mock/_version.py\n        src/pytest_mock/plugin.py\n        src/pytest_mock.egg-info/PKG-INFO\n        LICENSE\n        setup.py\n\n    We have to take in account those two distribution flavors in order to determine which\n    names should be considered for assertion rewriting.\n\n    More information:\n        https://github.com/pytest-dev/pytest-mock/issues/167\n    \"\"\"\n    package_files = list(package_files)\n    seen_some = False\n    for fn in package_files:\n        is_simple_module = \"/\" not in fn and fn.endswith(\".py\")\n        is_package = fn.count(\"/\") == 1 and fn.endswith(\"__init__.py\")\n        if is_simple_module:\n            module_name, _ = os.path.splitext(fn)\n            # we ignore \"setup.py\" at the root of the distribution\n            # as well as editable installation finder modules made by setuptools\n            if module_name != \"setup\" and not module_name.startswith(\"__editable__\"):\n                seen_some = True\n                yield module_name\n        elif is_package:\n            package_name = os.path.dirname(fn)\n            seen_some = True\n            yield package_name\n\n    if not seen_some:\n        # At this point we did not find any packages or modules suitable for assertion\n        # rewriting, so we try again by stripping the first path component (to account for\n        # \"src\" based source trees for example).\n        # This approach lets us have the common case continue to be fast, as egg-distributions\n        # are rarer.\n        new_package_files = []\n        for fn in package_files:\n            parts = fn.split(\"/\")\n            new_fn = \"/\".join(parts[1:])\n            if new_fn:\n                new_package_files.append(new_fn)\n        if new_package_files:\n            yield from _iter_rewritable_modules(new_package_files)\n\n\nclass _DeprecatedInicfgProxy(MutableMapping[str, Any]):\n    \"\"\"Compatibility proxy for the deprecated Config.inicfg.\"\"\"\n\n    __slots__ = (\"_config\",)\n\n    def __init__(self, config: Config) -> None:\n        self._config = config\n\n    def __getitem__(self, key: str) -> Any:\n        return self._config._inicfg[key].value\n\n    def __setitem__(self, key: str, value: Any) -> None:\n        self._config._inicfg[key] = ConfigValue(value, origin=\"override\", mode=\"toml\")\n\n    def __delitem__(self, key: str) -> None:\n        del self._config._inicfg[key]\n\n    def __iter__(self) -> Iterator[str]:\n        return iter(self._config._inicfg)\n\n    def __len__(self) -> int:\n        return len(self._config._inicfg)\n\n\n@final\nclass Config:\n    \"\"\"Access to configuration values, pluginmanager and plugin hooks.\n\n    :param PytestPluginManager pluginmanager:\n        A pytest PluginManager.\n\n    :param InvocationParams invocation_params:\n        Object containing parameters regarding the :func:`pytest.main`\n        invocation.\n    \"\"\"\n\n    @final\n    @dataclasses.dataclass(frozen=True)\n    class InvocationParams:\n        \"\"\"Holds parameters passed during :func:`pytest.main`.\n\n        The object attributes are read-only.\n\n        .. versionadded:: 5.1\n\n        .. note::\n\n            Note that the environment variable ``PYTEST_ADDOPTS`` and the ``addopts``\n            configuration option are handled by pytest, not being included in the ``args`` attribute.\n\n            Plugins accessing ``InvocationParams`` must be aware of that.\n        \"\"\"\n\n        args: tuple[str, ...]\n        \"\"\"The command-line arguments as passed to :func:`pytest.main`.\"\"\"\n        plugins: Sequence[str | _PluggyPlugin] | None\n        \"\"\"Extra plugins, might be `None`.\"\"\"\n        dir: pathlib.Path\n        \"\"\"The directory from which :func:`pytest.main` was invoked.\"\"\"\n\n        def __init__(\n            self,\n            *,\n            args: Iterable[str],\n            plugins: Sequence[str | _PluggyPlugin] | None,\n            dir: pathlib.Path,\n        ) -> None:\n            object.__setattr__(self, \"args\", tuple(args))\n            object.__setattr__(self, \"plugins\", plugins)\n            object.__setattr__(self, \"dir\", dir)\n\n    class ArgsSource(enum.Enum):\n        \"\"\"Indicates the source of the test arguments.\n\n        .. versionadded:: 7.2\n        \"\"\"\n\n        #: Command line arguments.\n        ARGS = enum.auto()\n        #: Invocation directory.\n        INVOCATION_DIR = enum.auto()\n        INCOVATION_DIR = INVOCATION_DIR  # backwards compatibility alias\n        #: 'testpaths' configuration value.\n        TESTPATHS = enum.auto()\n\n    # Set by cacheprovider plugin.\n    cache: Cache\n\n    def __init__(\n        self,\n        pluginmanager: PytestPluginManager,\n        *,\n        invocation_params: InvocationParams | None = None,\n    ) -> None:\n        if invocation_params is None:\n            invocation_params = self.InvocationParams(\n                args=(), plugins=None, dir=pathlib.Path.cwd()\n            )\n\n        self.option = argparse.Namespace()\n        \"\"\"Access to command line option as attributes.\n\n        :type: argparse.Namespace\n        \"\"\"\n\n        self.invocation_params = invocation_params\n        \"\"\"The parameters with which pytest was invoked.\n\n        :type: InvocationParams\n        \"\"\"\n\n        self._parser = Parser(\n            usage=f\"%(prog)s [options] [{FILE_OR_DIR}] [{FILE_OR_DIR}] [...]\",\n            processopt=self._processopt,\n            _ispytest=True,\n        )\n        self.pluginmanager = pluginmanager\n        \"\"\"The plugin manager handles plugin registration and hook invocation.\n\n        :type: PytestPluginManager\n        \"\"\"\n\n        self.stash = Stash()\n        \"\"\"A place where plugins can store information on the config for their\n        own use.\n\n        :type: Stash\n        \"\"\"\n        # Deprecated alias. Was never public. Can be removed in a few releases.\n        self._store = self.stash\n\n        self.trace = self.pluginmanager.trace.root.get(\"config\")\n        self.hook = self.pluginmanager.hook\n        self._inicache: dict[str, Any] = {}\n        self._inicfg: ConfigDict = {}\n        self._cleanup_stack = contextlib.ExitStack()\n        self.pluginmanager.register(self, \"pytestconfig\")\n        self._configured = False\n        self.hook.pytest_addoption.call_historic(\n            kwargs=dict(parser=self._parser, pluginmanager=self.pluginmanager)\n        )\n        self.args_source = Config.ArgsSource.ARGS\n        self.args: list[str] = []\n\n    if TYPE_CHECKING:\n\n        @deprecated(\n            \"config.inicfg is deprecated, use config.getini() to access configuration values instead.\",\n        )\n        @property\n        def inicfg(self) -> _DeprecatedInicfgProxy:\n            raise NotImplementedError()\n    else:\n\n        @property\n        def inicfg(self) -> _DeprecatedInicfgProxy:\n            warnings.warn(\n                _pytest.deprecated.CONFIG_INICFG,\n                stacklevel=2,\n            )\n            return _DeprecatedInicfgProxy(self)\n\n    @property\n    def rootpath(self) -> pathlib.Path:\n        \"\"\"The path to the :ref:`rootdir <rootdir>`.\n\n        .. versionadded:: 6.1\n        \"\"\"\n        return self._rootpath\n\n    @property\n    def inipath(self) -> pathlib.Path | None:\n        \"\"\"The path to the :ref:`configfile <configfiles>`.\n\n        .. versionadded:: 6.1\n        \"\"\"\n        return self._inipath\n\n    def add_cleanup(self, func: Callable[[], None]) -> None:\n        \"\"\"Add a function to be called when the config object gets out of\n        use (usually coinciding with pytest_unconfigure).\n        \"\"\"\n        self._cleanup_stack.callback(func)\n\n    def _do_configure(self) -> None:\n        assert not self._configured\n        self._configured = True\n        self.hook.pytest_configure.call_historic(kwargs=dict(config=self))\n\n    def _ensure_unconfigure(self) -> None:\n        try:\n            if self._configured:\n                self._configured = False\n                try:\n                    self.hook.pytest_unconfigure(config=self)\n                finally:\n                    self.hook.pytest_configure._call_history = []\n        finally:\n            try:\n                self._cleanup_stack.close()\n            finally:\n                self._cleanup_stack = contextlib.ExitStack()\n\n    def get_terminal_writer(self) -> TerminalWriter:\n        terminalreporter: TerminalReporter | None = self.pluginmanager.get_plugin(\n            \"terminalreporter\"\n        )\n        assert terminalreporter is not None\n        return terminalreporter._tw\n\n    def pytest_cmdline_parse(\n        self, pluginmanager: PytestPluginManager, args: list[str]\n    ) -> Config:\n        try:\n            self.parse(args)\n        except UsageError:\n            # Handle `--version --version` and `--help` here in a minimal fashion.\n            # This gets done via helpconfig normally, but its\n            # pytest_cmdline_main is not called in case of errors.\n            if getattr(self.option, \"version\", False) or \"--version\" in args:\n                from _pytest.helpconfig import show_version_verbose\n\n                # Note that `--version` (single argument) is handled early by `Config.main()`, so the only\n                # way we are reaching this point is via `--version --version`.\n                show_version_verbose(self)\n            elif (\n                getattr(self.option, \"help\", False) or \"--help\" in args or \"-h\" in args\n            ):\n                self._parser.optparser.print_help()\n                sys.stdout.write(\n                    \"\\nNOTE: displaying only minimal help due to UsageError.\\n\\n\"\n                )\n\n            raise\n\n        return self\n\n    def notify_exception(\n        self,\n        excinfo: ExceptionInfo[BaseException],\n        option: argparse.Namespace | None = None,\n    ) -> None:\n        if option and getattr(option, \"fulltrace\", False):\n            style: TracebackStyle = \"long\"\n        else:\n            style = \"native\"\n        excrepr = excinfo.getrepr(\n            funcargs=True, showlocals=getattr(option, \"showlocals\", False), style=style\n        )\n        res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)\n        if not any(res):\n            for line in str(excrepr).split(\"\\n\"):\n                sys.stderr.write(f\"INTERNALERROR> {line}\\n\")\n                sys.stderr.flush()\n\n    def cwd_relative_nodeid(self, nodeid: str) -> str:\n        # nodeid's are relative to the rootpath, compute relative to cwd.\n        if self.invocation_params.dir != self.rootpath:\n            base_path_part, *nodeid_part = nodeid.split(\"::\")\n            # Only process path part\n            fullpath = self.rootpath / base_path_part\n            relative_path = bestrelpath(self.invocation_params.dir, fullpath)\n\n            nodeid = \"::\".join([relative_path, *nodeid_part])\n        return nodeid\n\n    @classmethod\n    def fromdictargs(cls, option_dict: Mapping[str, Any], args: list[str]) -> Config:\n        \"\"\"Constructor usable for subprocesses.\"\"\"\n        config = get_config(args)\n        config.option.__dict__.update(option_dict)\n        config.parse(args, addopts=False)\n        for x in config.option.plugins:\n            config.pluginmanager.consider_pluginarg(x)\n        return config\n\n    def _processopt(self, opt: Argument) -> None:\n        if not hasattr(self.option, opt.dest):\n            setattr(self.option, opt.dest, opt.default)\n\n    @hookimpl(trylast=True)\n    def pytest_load_initial_conftests(self, early_config: Config) -> None:\n        # We haven't fully parsed the command line arguments yet, so\n        # early_config.args it not set yet. But we need it for\n        # discovering the initial conftests. So \"pre-run\" the logic here.\n        # It will be done for real in `parse()`.\n        args, _args_source = early_config._decide_args(\n            args=early_config.known_args_namespace.file_or_dir,\n            pyargs=early_config.known_args_namespace.pyargs,\n            testpaths=early_config.getini(\"testpaths\"),\n            invocation_dir=early_config.invocation_params.dir,\n            rootpath=early_config.rootpath,\n            warn=False,\n        )\n        self.pluginmanager._set_initial_conftests(\n            args=args,\n            pyargs=early_config.known_args_namespace.pyargs,\n            noconftest=early_config.known_args_namespace.noconftest,\n            rootpath=early_config.rootpath,\n            confcutdir=early_config.known_args_namespace.confcutdir,\n            invocation_dir=early_config.invocation_params.dir,\n            importmode=early_config.known_args_namespace.importmode,\n            consider_namespace_packages=early_config.getini(\n                \"consider_namespace_packages\"\n            ),\n        )\n\n    def _consider_importhook(self) -> None:\n        \"\"\"Install the PEP 302 import hook if using assertion rewriting.\n\n        Needs to parse the --assert=<mode> option from the commandline\n        and find all the installed plugins to mark them for rewriting\n        by the importhook.\n        \"\"\"\n        mode = getattr(self.known_args_namespace, \"assertmode\", \"plain\")\n\n        disable_autoload = getattr(\n            self.known_args_namespace, \"disable_plugin_autoload\", False\n        ) or bool(os.environ.get(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\"))\n        if mode == \"rewrite\":\n            import _pytest.assertion\n\n            try:\n                hook = _pytest.assertion.install_importhook(self)\n            except SystemError:\n                mode = \"plain\"\n            else:\n                self._mark_plugins_for_rewrite(hook, disable_autoload)\n        self._warn_about_missing_assertion(mode)\n\n    def _mark_plugins_for_rewrite(\n        self, hook: AssertionRewritingHook, disable_autoload: bool\n    ) -> None:\n        \"\"\"Given an importhook, mark for rewrite any top-level\n        modules or packages in the distribution package for\n        all pytest plugins.\"\"\"\n        self.pluginmanager.rewrite_hook = hook\n\n        if disable_autoload:\n            # We don't autoload from distribution package entry points,\n            # no need to continue.\n            return\n\n        package_files = (\n            str(file)\n            for dist in importlib.metadata.distributions()\n            if any(ep.group == \"pytest11\" for ep in dist.entry_points)\n            for file in dist.files or []\n        )\n\n        for name in _iter_rewritable_modules(package_files):\n            hook.mark_rewrite(name)\n\n    def _configure_python_path(self) -> None:\n        # `pythonpath = a b` will set `sys.path` to `[a, b, x, y, z, ...]`\n        for path in reversed(self.getini(\"pythonpath\")):\n            sys.path.insert(0, str(path))\n        self.add_cleanup(self._unconfigure_python_path)\n\n    def _unconfigure_python_path(self) -> None:\n        for path in self.getini(\"pythonpath\"):\n            path_str = str(path)\n            if path_str in sys.path:\n                sys.path.remove(path_str)\n\n    def _validate_args(self, args: list[str], via: str) -> list[str]:\n        \"\"\"Validate known args.\"\"\"\n        self._parser.extra_info[\"config source\"] = via\n        try:\n            self._parser.parse_known_and_unknown_args(\n                args, namespace=copy.copy(self.option)\n            )\n        finally:\n            self._parser.extra_info.pop(\"config source\", None)\n\n        return args\n\n    def _decide_args(\n        self,\n        *,\n        args: list[str],\n        pyargs: bool,\n        testpaths: list[str],\n        invocation_dir: pathlib.Path,\n        rootpath: pathlib.Path,\n        warn: bool,\n    ) -> tuple[list[str], ArgsSource]:\n        \"\"\"Decide the args (initial paths/nodeids) to use given the relevant inputs.\n\n        :param warn: Whether can issue warnings.\n\n        :returns: The args and the args source. Guaranteed to be non-empty.\n        \"\"\"\n        if args:\n            source = Config.ArgsSource.ARGS\n            result = args\n        else:\n            if invocation_dir == rootpath:\n                source = Config.ArgsSource.TESTPATHS\n                if pyargs:\n                    result = testpaths\n                else:\n                    result = []\n                    for path in testpaths:\n                        result.extend(sorted(glob.iglob(path, recursive=True)))\n                    if testpaths and not result:\n                        if warn:\n                            warning_text = (\n                                \"No files were found in testpaths; \"\n                                \"consider removing or adjusting your testpaths configuration. \"\n                                \"Searching recursively from the current directory instead.\"\n                            )\n                            self.issue_config_time_warning(\n                                PytestConfigWarning(warning_text), stacklevel=3\n                            )\n            else:\n                result = []\n            if not result:\n                source = Config.ArgsSource.INVOCATION_DIR\n                result = [str(invocation_dir)]\n        return result, source\n\n    @hookimpl(wrapper=True)\n    def pytest_collection(self) -> Generator[None, object, object]:\n        # Validate invalid configuration keys after collection is done so we\n        # take in account options added by late-loading conftest files.\n        try:\n            return (yield)\n        finally:\n            self._validate_config_options()\n\n    def _checkversion(self) -> None:\n        import pytest\n\n        minver = self.getini(\"minversion\")\n        if minver:\n            # Imported lazily to improve start-up time.\n            from packaging.version import Version\n\n            if Version(minver) > Version(pytest.__version__):\n                raise pytest.UsageError(\n                    f\"{self.inipath}: 'minversion' requires pytest-{minver}, actual pytest-{pytest.__version__}'\"\n                )\n\n    def _validate_config_options(self) -> None:\n        for key in sorted(self._get_unknown_ini_keys()):\n            self._warn_or_fail_if_strict(f\"Unknown config option: {key}\\n\")\n\n    def _validate_plugins(self) -> None:\n        required_plugins = sorted(self.getini(\"required_plugins\"))\n        if not required_plugins:\n            return\n\n        # Imported lazily to improve start-up time.\n        from packaging.requirements import InvalidRequirement\n        from packaging.requirements import Requirement\n        from packaging.version import Version\n\n        plugin_info = self.pluginmanager.list_plugin_distinfo()\n        plugin_dist_info = {dist.project_name: dist.version for _, dist in plugin_info}\n\n        missing_plugins = []\n        for required_plugin in required_plugins:\n            try:\n                req = Requirement(required_plugin)\n            except InvalidRequirement:\n                missing_plugins.append(required_plugin)\n                continue\n\n            if req.name not in plugin_dist_info:\n                missing_plugins.append(required_plugin)\n            elif not req.specifier.contains(\n                Version(plugin_dist_info[req.name]), prereleases=True\n            ):\n                missing_plugins.append(required_plugin)\n\n        if missing_plugins:\n            raise UsageError(\n                \"Missing required plugins: {}\".format(\", \".join(missing_plugins)),\n            )\n\n    def _warn_or_fail_if_strict(self, message: str) -> None:\n        strict_config = self.getini(\"strict_config\")\n        if strict_config is None:\n            strict_config = self.getini(\"strict\")\n        if strict_config:\n            raise UsageError(message)\n\n        self.issue_config_time_warning(PytestConfigWarning(message), stacklevel=3)\n\n    def _get_unknown_ini_keys(self) -> set[str]:\n        known_keys = self._parser._inidict.keys() | self._parser._ini_aliases.keys()\n        return self._inicfg.keys() - known_keys\n\n    def parse(self, args: list[str], addopts: bool = True) -> None:\n        # Parse given cmdline arguments into this config object.\n        assert self.args == [], (\n            \"can only parse cmdline args at most once per Config object\"\n        )\n\n        self.hook.pytest_addhooks.call_historic(\n            kwargs=dict(pluginmanager=self.pluginmanager)\n        )\n\n        if addopts:\n            env_addopts = os.environ.get(\"PYTEST_ADDOPTS\", \"\")\n            if len(env_addopts):\n                args[:] = (\n                    self._validate_args(shlex.split(env_addopts), \"via PYTEST_ADDOPTS\")\n                    + args\n                )\n\n        ns = self._parser.parse_known_args(args, namespace=copy.copy(self.option))\n        rootpath, inipath, inicfg, ignored_config_files = determine_setup(\n            inifile=ns.inifilename,\n            override_ini=ns.override_ini,\n            args=ns.file_or_dir,\n            rootdir_cmd_arg=ns.rootdir or None,\n            invocation_dir=self.invocation_params.dir,\n        )\n        self._rootpath = rootpath\n        self._inipath = inipath\n        self._ignored_config_files = ignored_config_files\n        self._inicfg = inicfg\n        self._parser.extra_info[\"rootdir\"] = str(self.rootpath)\n        self._parser.extra_info[\"inifile\"] = str(self.inipath)\n\n        self._parser.addini(\"addopts\", \"Extra command line options\", \"args\")\n        self._parser.addini(\"minversion\", \"Minimally required pytest version\")\n        self._parser.addini(\n            \"pythonpath\", type=\"paths\", help=\"Add paths to sys.path\", default=[]\n        )\n        self._parser.addini(\n            \"required_plugins\",\n            \"Plugins that must be present for pytest to run\",\n            type=\"args\",\n            default=[],\n        )\n\n        if addopts:\n            args[:] = (\n                self._validate_args(self.getini(\"addopts\"), \"via addopts config\") + args\n            )\n\n        self.known_args_namespace = self._parser.parse_known_args(\n            args, namespace=copy.copy(self.option)\n        )\n        self._checkversion()\n        self._consider_importhook()\n        self._configure_python_path()\n        self.pluginmanager.consider_preparse(args, exclude_only=False)\n        if (\n            not os.environ.get(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\")\n            and not self.known_args_namespace.disable_plugin_autoload\n        ):\n            # Autoloading from distribution package entry point has\n            # not been disabled.\n            self.pluginmanager.load_setuptools_entrypoints(\"pytest11\")\n        # Otherwise only plugins explicitly specified in PYTEST_PLUGINS\n        # are going to be loaded.\n        self.pluginmanager.consider_env()\n\n        self._parser.parse_known_args(args, namespace=self.known_args_namespace)\n\n        self._validate_plugins()\n        self._warn_about_skipped_plugins()\n\n        if self.known_args_namespace.confcutdir is None:\n            if self.inipath is not None:\n                confcutdir = str(self.inipath.parent)\n            else:\n                confcutdir = str(self.rootpath)\n            self.known_args_namespace.confcutdir = confcutdir\n        try:\n            self.hook.pytest_load_initial_conftests(\n                early_config=self, args=args, parser=self._parser\n            )\n        except ConftestImportFailure as e:\n            if self.known_args_namespace.help or self.known_args_namespace.version:\n                # we don't want to prevent --help/--version to work\n                # so just let it pass and print a warning at the end\n                self.issue_config_time_warning(\n                    PytestConfigWarning(f\"could not load initial conftests: {e.path}\"),\n                    stacklevel=2,\n                )\n            else:\n                raise\n\n        try:\n            self._parser.parse(args, namespace=self.option)\n        except PrintHelp:\n            return\n\n        self.args, self.args_source = self._decide_args(\n            args=getattr(self.option, FILE_OR_DIR),\n            pyargs=self.option.pyargs,\n            testpaths=self.getini(\"testpaths\"),\n            invocation_dir=self.invocation_params.dir,\n            rootpath=self.rootpath,\n            warn=True,\n        )\n\n    def issue_config_time_warning(self, warning: Warning, stacklevel: int) -> None:\n        \"\"\"Issue and handle a warning during the \"configure\" stage.\n\n        During ``pytest_configure`` we can't capture warnings using the ``catch_warnings_for_item``\n        function because it is not possible to have hook wrappers around ``pytest_configure``.\n\n        This function is mainly intended for plugins that need to issue warnings during\n        ``pytest_configure`` (or similar stages).\n\n        :param warning: The warning instance.\n        :param stacklevel: stacklevel forwarded to warnings.warn.\n        \"\"\"\n        if self.pluginmanager.is_blocked(\"warnings\"):\n            return\n\n        cmdline_filters = self.known_args_namespace.pythonwarnings or []\n        config_filters = self.getini(\"filterwarnings\")\n\n        with warnings.catch_warnings(record=True) as records:\n            warnings.simplefilter(\"always\", type(warning))\n            apply_warning_filters(config_filters, cmdline_filters)\n            warnings.warn(warning, stacklevel=stacklevel)\n\n        if records:\n            frame = sys._getframe(stacklevel - 1)\n            location = frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name\n            self.hook.pytest_warning_recorded.call_historic(\n                kwargs=dict(\n                    warning_message=records[0],\n                    when=\"config\",\n                    nodeid=\"\",\n                    location=location,\n                )\n            )\n\n    def addinivalue_line(self, name: str, line: str) -> None:\n        \"\"\"Add a line to a configuration option. The option must have been\n        declared but might not yet be set in which case the line becomes\n        the first line in its value.\"\"\"\n        x = self.getini(name)\n        assert isinstance(x, list)\n        x.append(line)  # modifies the cached list inline\n\n    def getini(self, name: str) -> Any:\n        \"\"\"Return configuration value the an :ref:`configuration file <configfiles>`.\n\n        If a configuration value is not defined in a\n        :ref:`configuration file <configfiles>`, then the ``default`` value\n        provided while registering the configuration through\n        :func:`parser.addini <pytest.Parser.addini>` will be returned.\n        Please note that you can even provide ``None`` as a valid\n        default value.\n\n        If ``default`` is not provided while registering using\n        :func:`parser.addini <pytest.Parser.addini>`, then a default value\n        based on the ``type`` parameter passed to\n        :func:`parser.addini <pytest.Parser.addini>` will be returned.\n        The default values based on ``type`` are:\n        ``paths``, ``pathlist``, ``args`` and ``linelist`` : empty list ``[]``\n        ``bool`` : ``False``\n        ``string`` : empty string ``\"\"``\n        ``int`` : ``0``\n        ``float`` : ``0.0``\n\n        If neither the ``default`` nor the ``type`` parameter is passed\n        while registering the configuration through\n        :func:`parser.addini <pytest.Parser.addini>`, then the configuration\n        is treated as a string and a default empty string '' is returned.\n\n        If the specified name hasn't been registered through a prior\n        :func:`parser.addini <pytest.Parser.addini>` call (usually from a\n        plugin), a ValueError is raised.\n        \"\"\"\n        canonical_name = self._parser._ini_aliases.get(name, name)\n        try:\n            return self._inicache[canonical_name]\n        except KeyError:\n            pass\n        self._inicache[canonical_name] = val = self._getini(canonical_name)\n        return val\n\n    # Meant for easy monkeypatching by legacypath plugin.\n    # Can be inlined back (with no cover removed) once legacypath is gone.\n    def _getini_unknown_type(self, name: str, type: str, value: object):\n        msg = (\n            f\"Option {name} has unknown configuration type {type} with value {value!r}\"\n        )\n        raise ValueError(msg)  # pragma: no cover\n\n    def _getini(self, name: str):\n        # If this is an alias, resolve to canonical name.\n        canonical_name = self._parser._ini_aliases.get(name, name)\n\n        try:\n            _description, type, default = self._parser._inidict[canonical_name]\n        except KeyError as e:\n            raise ValueError(f\"unknown configuration value: {name!r}\") from e\n\n        # Collect all possible values (canonical name + aliases) from _inicfg.\n        # Each candidate is (ConfigValue, is_canonical).\n        candidates = []\n        if canonical_name in self._inicfg:\n            candidates.append((self._inicfg[canonical_name], True))\n        for alias, target in self._parser._ini_aliases.items():\n            if target == canonical_name and alias in self._inicfg:\n                candidates.append((self._inicfg[alias], False))\n\n        if not candidates:\n            return default\n\n        # Pick the best candidate based on precedence:\n        # 1. CLI override takes precedence over file, then\n        # 2. Canonical name takes precedence over alias.\n        selected = max(candidates, key=lambda x: (x[0].origin == \"override\", x[1]))[0]\n        value = selected.value\n        mode = selected.mode\n\n        if mode == \"ini\":\n            # In ini mode, values are always str | list[str].\n            assert isinstance(value, (str, list))\n            return self._getini_ini(name, canonical_name, type, value, default)\n        elif mode == \"toml\":\n            return self._getini_toml(name, canonical_name, type, value, default)\n        else:\n            assert_never(mode)\n\n    def _getini_ini(\n        self,\n        name: str,\n        canonical_name: str,\n        type: str,\n        value: str | list[str],\n        default: Any,\n    ):\n        \"\"\"Handle config values read in INI mode.\n\n        In INI mode, values are stored as str or list[str] only, and coerced\n        from string based on the registered type.\n        \"\"\"\n        # Note: some coercions are only required if we are reading from .ini\n        # files, because the file format doesn't contain type information, but\n        # when reading from toml (in ini mode) we will get either str or list of\n        # str values (see load_config_dict_from_file). For example:\n        #\n        #   ini:\n        #     a_line_list = \"tests acceptance\"\n        #\n        # in this case, we need to split the string to obtain a list of strings.\n        #\n        #   toml (ini mode):\n        #     a_line_list = [\"tests\", \"acceptance\"]\n        #\n        # in this case, we already have a list ready to use.\n        if type == \"paths\":\n            dp = (\n                self.inipath.parent\n                if self.inipath is not None\n                else self.invocation_params.dir\n            )\n            input_values = shlex.split(value) if isinstance(value, str) else value\n            return [dp / x for x in input_values]\n        elif type == \"args\":\n            return shlex.split(value) if isinstance(value, str) else value\n        elif type == \"linelist\":\n            if isinstance(value, str):\n                return [t for t in map(lambda x: x.strip(), value.split(\"\\n\")) if t]\n            else:\n                return value\n        elif type == \"bool\":\n            return _strtobool(str(value).strip())\n        elif type == \"string\":\n            return value\n        elif type == \"int\":\n            if not isinstance(value, str):\n                raise TypeError(\n                    f\"Expected an int string for option {name} of type integer, but got: {value!r}\"\n                ) from None\n            return int(value)\n        elif type == \"float\":\n            if not isinstance(value, str):\n                raise TypeError(\n                    f\"Expected a float string for option {name} of type float, but got: {value!r}\"\n                ) from None\n            return float(value)\n        else:\n            return self._getini_unknown_type(name, type, value)\n\n    def _getini_toml(\n        self,\n        name: str,\n        canonical_name: str,\n        type: str,\n        value: object,\n        default: Any,\n    ):\n        \"\"\"Handle TOML config values with strict type validation and no coercion.\n\n        In TOML mode, values already have native types from TOML parsing.\n        We validate types match expectations exactly, including list items.\n        \"\"\"\n        value_type = builtins.type(value).__name__\n        if type == \"paths\":\n            # Expect a list of strings.\n            if not isinstance(value, list):\n                raise TypeError(\n                    f\"{self.inipath}: config option '{name}' expects a list for type 'paths', \"\n                    f\"got {value_type}: {value!r}\"\n                )\n            for i, item in enumerate(value):\n                if not isinstance(item, str):\n                    item_type = builtins.type(item).__name__\n                    raise TypeError(\n                        f\"{self.inipath}: config option '{name}' expects a list of strings, \"\n                        f\"but item at index {i} is {item_type}: {item!r}\"\n                    )\n            dp = (\n                self.inipath.parent\n                if self.inipath is not None\n                else self.invocation_params.dir\n            )\n            return [dp / x for x in value]\n        elif type in {\"args\", \"linelist\"}:\n            # Expect a list of strings.\n            if not isinstance(value, list):\n                raise TypeError(\n                    f\"{self.inipath}: config option '{name}' expects a list for type '{type}', \"\n                    f\"got {value_type}: {value!r}\"\n                )\n            for i, item in enumerate(value):\n                if not isinstance(item, str):\n                    item_type = builtins.type(item).__name__\n                    raise TypeError(\n                        f\"{self.inipath}: config option '{name}' expects a list of strings, \"\n                        f\"but item at index {i} is {item_type}: {item!r}\"\n                    )\n            return list(value)\n        elif type == \"bool\":\n            # Expect a boolean.\n            if not isinstance(value, bool):\n                raise TypeError(\n                    f\"{self.inipath}: config option '{name}' expects a bool, \"\n                    f\"got {value_type}: {value!r}\"\n                )\n            return value\n        elif type == \"int\":\n            # Expect an integer (but not bool, which is a subclass of int).\n            if not isinstance(value, int) or isinstance(value, bool):\n                raise TypeError(\n                    f\"{self.inipath}: config option '{name}' expects an int, \"\n                    f\"got {value_type}: {value!r}\"\n                )\n            return value\n        elif type == \"float\":\n            # Expect a float or integer only.\n            if not isinstance(value, (float, int)) or isinstance(value, bool):\n                raise TypeError(\n                    f\"{self.inipath}: config option '{name}' expects a float, \"\n                    f\"got {value_type}: {value!r}\"\n                )\n            return value\n        elif type == \"string\":\n            # Expect a string.\n            if not isinstance(value, str):\n                raise TypeError(\n                    f\"{self.inipath}: config option '{name}' expects a string, \"\n                    f\"got {value_type}: {value!r}\"\n                )\n            return value\n        else:\n            return self._getini_unknown_type(name, type, value)\n\n    def _getconftest_pathlist(\n        self, name: str, path: pathlib.Path\n    ) -> list[pathlib.Path] | None:\n        try:\n            mod, relroots = self.pluginmanager._rget_with_confmod(name, path)\n        except KeyError:\n            return None\n        assert mod.__file__ is not None\n        modpath = pathlib.Path(mod.__file__).parent\n        values: list[pathlib.Path] = []\n        for relroot in relroots:\n            if isinstance(relroot, os.PathLike):\n                relroot = pathlib.Path(relroot)\n            else:\n                relroot = relroot.replace(\"/\", os.sep)\n                relroot = absolutepath(modpath / relroot)\n            values.append(relroot)\n        return values\n\n    def getoption(self, name: str, default: Any = NOTSET, skip: bool = False):\n        \"\"\"Return command line option value.\n\n        :param name: Name of the option. You may also specify\n            the literal ``--OPT`` option instead of the \"dest\" option name.\n        :param default: Fallback value if no option of that name is **declared** via :hook:`pytest_addoption`.\n            Note this parameter will be ignored when the option is **declared** even if the option's value is ``None``.\n        :param skip: If ``True``, raise :func:`pytest.skip` if option is undeclared or has a ``None`` value.\n            Note that even if ``True``, if a default was specified it will be returned instead of a skip.\n        \"\"\"\n        name = self._parser._opt2dest.get(name, name)\n        try:\n            val = getattr(self.option, name)\n            if val is None and skip:\n                raise AttributeError(name)\n            return val\n        except AttributeError as e:\n            if default is not NOTSET:\n                return default\n            if skip:\n                import pytest\n\n                pytest.skip(f\"no {name!r} option found\")\n            raise ValueError(f\"no option named {name!r}\") from e\n\n    def getvalue(self, name: str, path=None):\n        \"\"\"Deprecated, use getoption() instead.\"\"\"\n        return self.getoption(name)\n\n    def getvalueorskip(self, name: str, path=None):\n        \"\"\"Deprecated, use getoption(skip=True) instead.\"\"\"\n        return self.getoption(name, skip=True)\n\n    #: Verbosity type for failed assertions (see :confval:`verbosity_assertions`).\n    VERBOSITY_ASSERTIONS: Final = \"assertions\"\n    #: Verbosity type for test case execution (see :confval:`verbosity_test_cases`).\n    VERBOSITY_TEST_CASES: Final = \"test_cases\"\n    #: Verbosity type for failed subtests (see :confval:`verbosity_subtests`).\n    VERBOSITY_SUBTESTS: Final = \"subtests\"\n\n    _VERBOSITY_INI_DEFAULT: Final = \"auto\"\n\n    def get_verbosity(self, verbosity_type: str | None = None) -> int:\n        r\"\"\"Retrieve the verbosity level for a fine-grained verbosity type.\n\n        :param verbosity_type: Verbosity type to get level for. If a level is\n            configured for the given type, that value will be returned. If the\n            given type is not a known verbosity type, the global verbosity\n            level will be returned. If the given type is None (default), the\n            global verbosity level will be returned.\n\n        To configure a level for a fine-grained verbosity type, the\n        configuration file should have a setting for the configuration name\n        and a numeric value for the verbosity level. A special value of \"auto\"\n        can be used to explicitly use the global verbosity level.\n\n        Example:\n\n        .. tab:: toml\n\n            .. code-block:: toml\n\n                [tool.pytest]\n                verbosity_assertions = 2\n\n        .. tab:: ini\n\n            .. code-block:: ini\n\n                [pytest]\n                verbosity_assertions = 2\n\n        .. code-block:: console\n\n            pytest -v\n\n        .. code-block:: python\n\n            print(config.get_verbosity())  # 1\n            print(config.get_verbosity(Config.VERBOSITY_ASSERTIONS))  # 2\n        \"\"\"\n        global_level = self.getoption(\"verbose\", default=0)\n        assert isinstance(global_level, int)\n        if verbosity_type is None:\n            return global_level\n\n        ini_name = Config._verbosity_ini_name(verbosity_type)\n        if ini_name not in self._parser._inidict:\n            return global_level\n\n        level = self.getini(ini_name)\n        if level == Config._VERBOSITY_INI_DEFAULT:\n            return global_level\n\n        return int(level)\n\n    @staticmethod\n    def _verbosity_ini_name(verbosity_type: str) -> str:\n        return f\"verbosity_{verbosity_type}\"\n\n    @staticmethod\n    def _add_verbosity_ini(parser: Parser, verbosity_type: str, help: str) -> None:\n        \"\"\"Add a output verbosity configuration option for the given output type.\n\n        :param parser: Parser for command line arguments and config-file values.\n        :param verbosity_type: Fine-grained verbosity category.\n        :param help: Description of the output this type controls.\n\n        The value should be retrieved via a call to\n        :py:func:`config.get_verbosity(type) <pytest.Config.get_verbosity>`.\n        \"\"\"\n        parser.addini(\n            Config._verbosity_ini_name(verbosity_type),\n            help=help,\n            type=\"string\",\n            default=Config._VERBOSITY_INI_DEFAULT,\n        )\n\n    def _warn_about_missing_assertion(self, mode: str) -> None:\n        if not _assertion_supported():\n            if mode == \"plain\":\n                warning_text = (\n                    \"ASSERTIONS ARE NOT EXECUTED\"\n                    \" and FAILING TESTS WILL PASS.  Are you\"\n                    \" using python -O?\"\n                )\n            else:\n                warning_text = (\n                    \"assertions not in test modules or\"\n                    \" plugins will be ignored\"\n                    \" because assert statements are not executed \"\n                    \"by the underlying Python interpreter \"\n                    \"(are you using python -O?)\\n\"\n                )\n            self.issue_config_time_warning(\n                PytestConfigWarning(warning_text),\n                stacklevel=3,\n            )\n\n    def _warn_about_skipped_plugins(self) -> None:\n        for module_name, msg in self.pluginmanager.skipped_plugins:\n            self.issue_config_time_warning(\n                PytestConfigWarning(f\"skipped plugin {module_name!r}: {msg}\"),\n                stacklevel=2,\n            )\n\n\ndef _assertion_supported() -> bool:\n    try:\n        assert False\n    except AssertionError:\n        return True\n    else:\n        return False  # type: ignore[unreachable]\n\n\ndef create_terminal_writer(\n    config: Config, file: TextIO | None = None\n) -> TerminalWriter:\n    \"\"\"Create a TerminalWriter instance configured according to the options\n    in the config object.\n\n    Every code which requires a TerminalWriter object and has access to a\n    config object should use this function.\n    \"\"\"\n    tw = TerminalWriter(file=file)\n\n    if config.option.color == \"yes\":\n        tw.hasmarkup = True\n    elif config.option.color == \"no\":\n        tw.hasmarkup = False\n\n    if config.option.code_highlight == \"yes\":\n        tw.code_highlight = True\n    elif config.option.code_highlight == \"no\":\n        tw.code_highlight = False\n\n    return tw\n\n\ndef _strtobool(val: str) -> bool:\n    \"\"\"Convert a string representation of truth to True or False.\n\n    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values\n    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if\n    'val' is anything else.\n\n    .. note:: Copied from distutils.util.\n    \"\"\"\n    val = val.lower()\n    if val in (\"y\", \"yes\", \"t\", \"true\", \"on\", \"1\"):\n        return True\n    elif val in (\"n\", \"no\", \"f\", \"false\", \"off\", \"0\"):\n        return False\n    else:\n        raise ValueError(f\"invalid truth value {val!r}\")\n\n\n@lru_cache(maxsize=50)\ndef parse_warning_filter(\n    arg: str, *, escape: bool\n) -> tuple[warnings._ActionKind, str, type[Warning], str, int]:\n    \"\"\"Parse a warnings filter string.\n\n    This is copied from warnings._setoption with the following changes:\n\n    * Does not apply the filter.\n    * Escaping is optional.\n    * Raises UsageError so we get nice error messages on failure.\n    \"\"\"\n    __tracebackhide__ = True\n    error_template = dedent(\n        f\"\"\"\\\n        while parsing the following warning configuration:\n\n          {arg}\n\n        This error occurred:\n\n        {{error}}\n        \"\"\"\n    )\n\n    parts = arg.split(\":\")\n    if len(parts) > 5:\n        doc_url = (\n            \"https://docs.python.org/3/library/warnings.html#describing-warning-filters\"\n        )\n        error = dedent(\n            f\"\"\"\\\n            Too many fields ({len(parts)}), expected at most 5 separated by colons:\n\n              action:message:category:module:line\n\n            For more information please consult: {doc_url}\n            \"\"\"\n        )\n        raise UsageError(error_template.format(error=error))\n\n    while len(parts) < 5:\n        parts.append(\"\")\n    action_, message, category_, module, lineno_ = (s.strip() for s in parts)\n    try:\n        action: warnings._ActionKind = warnings._getaction(action_)  # type: ignore[attr-defined]\n    except warnings._OptionError as e:\n        raise UsageError(error_template.format(error=str(e))) from None\n    try:\n        category: type[Warning] = _resolve_warning_category(category_)\n    except ImportError:\n        raise\n    except Exception:\n        exc_info = ExceptionInfo.from_current()\n        exception_text = exc_info.getrepr(style=\"native\")\n        raise UsageError(error_template.format(error=exception_text)) from None\n    if message and escape:\n        message = re.escape(message)\n    if module and escape:\n        module = re.escape(module) + r\"\\Z\"\n    if lineno_:\n        try:\n            lineno = int(lineno_)\n            if lineno < 0:\n                raise ValueError(\"number is negative\")\n        except ValueError as e:\n            raise UsageError(\n                error_template.format(error=f\"invalid lineno {lineno_!r}: {e}\")\n            ) from None\n    else:\n        lineno = 0\n    try:\n        re.compile(message)\n        re.compile(module)\n    except re.error as e:\n        raise UsageError(\n            error_template.format(error=f\"Invalid regex {e.pattern!r}: {e}\")\n        ) from None\n    return action, message, category, module, lineno\n\n\ndef _resolve_warning_category(category: str) -> type[Warning]:\n    \"\"\"\n    Copied from warnings._getcategory, but changed so it lets exceptions (specially ImportErrors)\n    propagate so we can get access to their tracebacks (#9218).\n    \"\"\"\n    __tracebackhide__ = True\n    if not category:\n        return Warning\n\n    if \".\" not in category:\n        import builtins as m\n\n        klass = category\n    else:\n        module, _, klass = category.rpartition(\".\")\n        m = importlib.import_module(module)\n    cat = getattr(m, klass)\n    if not issubclass(cat, Warning):\n        raise UsageError(f\"{cat} is not a Warning subclass\")\n    return cast(type[Warning], cat)\n\n\ndef apply_warning_filters(\n    config_filters: Iterable[str], cmdline_filters: Iterable[str]\n) -> None:\n    \"\"\"Applies pytest-configured filters to the warnings module\"\"\"\n    # Filters should have this precedence: cmdline options, config.\n    # Filters should be applied in the inverse order of precedence.\n    for arg in config_filters:\n        try:\n            warnings.filterwarnings(*parse_warning_filter(arg, escape=False))\n        except ImportError as e:\n            warnings.warn(\n                f\"Failed to import filter module '{e.name}': {arg}\", PytestConfigWarning\n            )\n            continue\n\n    for arg in cmdline_filters:\n        try:\n            warnings.filterwarnings(*parse_warning_filter(arg, escape=True))\n        except ImportError as e:\n            warnings.warn(\n                f\"Failed to import filter module '{e.name}': {arg}\", PytestConfigWarning\n            )\n            continue\n"
  },
  {
    "path": "src/_pytest/config/argparsing.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport argparse\nfrom collections.abc import Callable\nfrom collections.abc import Sequence\nimport os\nimport sys\nimport textwrap\nfrom typing import Any\nfrom typing import final\nfrom typing import Literal\nfrom typing import NoReturn\n\nfrom .exceptions import UsageError\nimport _pytest._io\nfrom _pytest.compat import NOTSET\nfrom _pytest.deprecated import check_ispytest\n\n\nFILE_OR_DIR = \"file_or_dir\"\n\n\n@final\nclass Parser:\n    \"\"\"Parser for command line arguments and config-file values.\n\n    :ivar extra_info: Dict of generic param -> value to display in case\n        there's an error processing the command line arguments.\n    \"\"\"\n\n    def __init__(\n        self,\n        usage: str | None = None,\n        processopt: Callable[[Argument], None] | None = None,\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n\n        from _pytest._argcomplete import filescompleter\n\n        self._processopt = processopt\n        self.extra_info: dict[str, Any] = {}\n        self.optparser = PytestArgumentParser(usage, self.extra_info)\n        anonymous_arggroup = self.optparser.add_argument_group(\"Custom options\")\n        self._anonymous = OptionGroup(\n            anonymous_arggroup, \"_anonymous\", self, _ispytest=True\n        )\n        self._groups = [self._anonymous]\n        # Maps option strings -> dest, e.g. \"-V\" and \"--version\" to \"version\".\n        self._opt2dest: dict[str, str] = {}\n        file_or_dir_arg = self.optparser.add_argument(FILE_OR_DIR, nargs=\"*\")\n        file_or_dir_arg.completer = filescompleter  # type: ignore\n\n        self._inidict: dict[str, tuple[str, str, Any]] = {}\n        # Maps alias -> canonical name.\n        self._ini_aliases: dict[str, str] = {}\n\n    @property\n    def prog(self) -> str:\n        return self.optparser.prog\n\n    @prog.setter\n    def prog(self, value: str) -> None:\n        self.optparser.prog = value\n\n    def processoption(self, option: Argument) -> None:\n        if self._processopt:\n            if option.dest:\n                self._processopt(option)\n\n    def getgroup(\n        self, name: str, description: str = \"\", after: str | None = None\n    ) -> OptionGroup:\n        \"\"\"Get (or create) a named option Group.\n\n        :param name: Name of the option group.\n        :param description: Long description for --help output.\n        :param after: Name of another group, used for ordering --help output.\n        :returns: The option group.\n\n        The returned group object has an ``addoption`` method with the same\n        signature as :func:`parser.addoption <pytest.Parser.addoption>` but\n        will be shown in the respective group in the output of\n        ``pytest --help``.\n        \"\"\"\n        for group in self._groups:\n            if group.name == name:\n                return group\n\n        arggroup = self.optparser.add_argument_group(description or name)\n        group = OptionGroup(arggroup, name, self, _ispytest=True)\n        i = 0\n        for i, grp in enumerate(self._groups):\n            if grp.name == after:\n                break\n        self._groups.insert(i + 1, group)\n        # argparse doesn't provide a way to control `--help` order, so must\n        # access its internals ☹.\n        self.optparser._action_groups.insert(i + 1, self.optparser._action_groups.pop())\n        return group\n\n    def addoption(self, *opts: str, **attrs: Any) -> None:\n        \"\"\"Register a command line option.\n\n        :param opts:\n            Option names, can be short or long options.\n        :param attrs:\n            Same attributes as the argparse library's :meth:`add_argument()\n            <argparse.ArgumentParser.add_argument>` function accepts.\n\n        After command line parsing, options are available on the pytest config\n        object via ``config.option.NAME`` where ``NAME`` is usually set\n        by passing a ``dest`` attribute, for example\n        ``addoption(\"--long\", dest=\"NAME\", ...)``.\n        \"\"\"\n        self._anonymous.addoption(*opts, **attrs)\n\n    def parse(\n        self,\n        args: Sequence[str | os.PathLike[str]],\n        namespace: argparse.Namespace | None = None,\n    ) -> argparse.Namespace:\n        \"\"\"Parse the arguments.\n\n        Unlike ``parse_known_args`` and ``parse_known_and_unknown_args``,\n        raises PrintHelp on `--help` and UsageError on unknown flags\n\n        :meta private:\n        \"\"\"\n        from _pytest._argcomplete import try_argcomplete\n\n        try_argcomplete(self.optparser)\n        strargs = [os.fspath(x) for x in args]\n        if namespace is None:\n            namespace = argparse.Namespace()\n        try:\n            namespace._raise_print_help = True\n            return self.optparser.parse_intermixed_args(strargs, namespace=namespace)\n        finally:\n            del namespace._raise_print_help\n\n    def parse_known_args(\n        self,\n        args: Sequence[str | os.PathLike[str]],\n        namespace: argparse.Namespace | None = None,\n    ) -> argparse.Namespace:\n        \"\"\"Parse the known arguments at this point.\n\n        :returns: An argparse namespace object.\n        \"\"\"\n        return self.parse_known_and_unknown_args(args, namespace=namespace)[0]\n\n    def parse_known_and_unknown_args(\n        self,\n        args: Sequence[str | os.PathLike[str]],\n        namespace: argparse.Namespace | None = None,\n    ) -> tuple[argparse.Namespace, list[str]]:\n        \"\"\"Parse the known arguments at this point, and also return the\n        remaining unknown flag arguments.\n\n        :returns:\n            A tuple containing an argparse namespace object for the known\n            arguments, and a list of unknown flag arguments.\n        \"\"\"\n        strargs = [os.fspath(x) for x in args]\n        if sys.version_info < (3, 12, 8) or (3, 13) <= sys.version_info < (3, 13, 1):\n            # Older argparse have a bugged parse_known_intermixed_args.\n            namespace, unknown = self.optparser.parse_known_args(strargs, namespace)\n            assert namespace is not None\n            file_or_dir = getattr(namespace, FILE_OR_DIR)\n            unknown_flags: list[str] = []\n            for arg in unknown:\n                (unknown_flags if arg.startswith(\"-\") else file_or_dir).append(arg)\n            return namespace, unknown_flags\n        else:\n            return self.optparser.parse_known_intermixed_args(strargs, namespace)\n\n    def addini(\n        self,\n        name: str,\n        help: str,\n        type: Literal[\n            \"string\", \"paths\", \"pathlist\", \"args\", \"linelist\", \"bool\", \"int\", \"float\"\n        ]\n        | None = None,\n        default: Any = NOTSET,\n        *,\n        aliases: Sequence[str] = (),\n    ) -> None:\n        \"\"\"Register a configuration file option.\n\n        :param name:\n            Name of the configuration.\n        :param type:\n            Type of the configuration. Can be:\n\n                * ``string``: a string\n                * ``bool``: a boolean\n                * ``args``: a list of strings, separated as in a shell\n                * ``linelist``: a list of strings, separated by line breaks\n                * ``paths``: a list of :class:`pathlib.Path`, separated as in a shell\n                * ``pathlist``: a list of ``py.path``, separated as in a shell\n                * ``int``: an integer\n                * ``float``: a floating-point number\n\n                .. versionadded:: 8.4\n\n                    The ``float`` and ``int`` types.\n\n            For ``paths`` and ``pathlist`` types, they are considered relative to the config-file.\n            In case the execution is happening without a config-file defined,\n            they will be considered relative to the current working directory (for example with ``--override-ini``).\n\n            .. versionadded:: 7.0\n                The ``paths`` variable type.\n\n            .. versionadded:: 8.1\n                Use the current working directory to resolve ``paths`` and ``pathlist`` in the absence of a config-file.\n\n            Defaults to ``string`` if ``None`` or not passed.\n        :param default:\n            Default value if no config-file option exists but is queried.\n        :param aliases:\n            Additional names by which this option can be referenced.\n            Aliases resolve to the canonical name.\n\n            .. versionadded:: 9.0\n                The ``aliases`` parameter.\n\n        The value of configuration keys can be retrieved via a call to\n        :py:func:`config.getini(name) <pytest.Config.getini>`.\n        \"\"\"\n        assert type in (\n            None,\n            \"string\",\n            \"paths\",\n            \"pathlist\",\n            \"args\",\n            \"linelist\",\n            \"bool\",\n            \"int\",\n            \"float\",\n        )\n        if type is None:\n            type = \"string\"\n        if default is NOTSET:\n            default = get_ini_default_for_type(type)\n\n        self._inidict[name] = (help, type, default)\n\n        for alias in aliases:\n            if alias in self._inidict:\n                raise ValueError(\n                    f\"alias {alias!r} conflicts with existing configuration option\"\n                )\n            if (already := self._ini_aliases.get(alias)) is not None:\n                raise ValueError(f\"{alias!r} is already an alias of {already!r}\")\n            self._ini_aliases[alias] = name\n\n\ndef get_ini_default_for_type(\n    type: Literal[\n        \"string\", \"paths\", \"pathlist\", \"args\", \"linelist\", \"bool\", \"int\", \"float\"\n    ],\n) -> Any:\n    \"\"\"\n    Used by addini to get the default value for a given config option type, when\n    default is not supplied.\n    \"\"\"\n    if type in (\"paths\", \"pathlist\", \"args\", \"linelist\"):\n        return []\n    elif type == \"bool\":\n        return False\n    elif type == \"int\":\n        return 0\n    elif type == \"float\":\n        return 0.0\n    else:\n        return \"\"\n\n\nclass Argument:\n    \"\"\"An option defined in an OptionGroup.\"\"\"\n\n    def __init__(self, action: argparse.Action) -> None:\n        self._action = action\n\n    def attrs(self) -> dict[str, Any]:\n        return self._action.__dict__\n\n    def names(self) -> Sequence[str]:\n        return self._action.option_strings\n\n    @property\n    def dest(self) -> str:\n        return self._action.dest\n\n    @property\n    def default(self) -> Any:\n        return self._action.default\n\n    @property\n    def type(self) -> Any | None:\n        return self._action.type\n\n    def __repr__(self) -> str:\n        args: list[str] = []\n        args += [\"opts: \" + repr(self.names())]\n        args += [\"dest: \" + repr(self.dest)]\n        if self._action.type:\n            args += [\"type: \" + repr(self.type)]\n        args += [\"default: \" + repr(self.default)]\n        return \"Argument({})\".format(\", \".join(args))\n\n\nclass OptionGroup:\n    \"\"\"A group of options shown in its own section.\"\"\"\n\n    def __init__(\n        self,\n        arggroup: argparse._ArgumentGroup,\n        name: str,\n        parser: Parser | None,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        self._arggroup = arggroup\n        self.name = name\n        self.options: list[Argument] = []\n        self.parser = parser\n\n    def addoption(self, *opts: str, **attrs: Any) -> None:\n        \"\"\"Add an option to this group.\n\n        If a shortened version of a long option is specified, it will\n        be suppressed in the help. ``addoption('--twowords', '--two-words')``\n        results in help showing ``--two-words`` only, but ``--twowords`` gets\n        accepted **and** the automatic destination is in ``args.twowords``.\n\n        :param opts:\n            Option names, can be short or long options.\n            Note that lower-case short options (e.g. `-x`) are reserved.\n        :param attrs:\n            Same attributes as the argparse library's :meth:`add_argument()\n            <argparse.ArgumentParser.add_argument>` function accepts.\n        \"\"\"\n        conflict = set(opts).intersection(\n            name for opt in self.options for name in opt.names()\n        )\n        if conflict:\n            raise ValueError(f\"option names {conflict} already added\")\n        self._addoption_inner(opts, attrs, allow_reserved=False)\n\n    def _addoption(self, *opts: str, **attrs: Any) -> None:\n        \"\"\"Like addoption(), but also allows registering short lower case options (e.g. -x),\n        which are reserved for pytest core.\"\"\"\n        self._addoption_inner(opts, attrs, allow_reserved=True)\n\n    def _addoption_inner(\n        self, opts: tuple[str, ...], attrs: dict[str, Any], allow_reserved: bool\n    ) -> None:\n        if not allow_reserved:\n            for opt in opts:\n                if len(opt) >= 2 and opt[0] == \"-\" and opt[1].islower():\n                    raise ValueError(\"lowercase short options are reserved\")\n\n        action = self._arggroup.add_argument(*opts, **attrs)\n        option = Argument(action)\n        self.options.append(option)\n        if self.parser:\n            for name in option.names():\n                self.parser._opt2dest[name] = option.dest\n            self.parser.processoption(option)\n\n\nclass PytestArgumentParser(argparse.ArgumentParser):\n    def __init__(\n        self,\n        usage: str | None,\n        extra_info: dict[str, str],\n    ) -> None:\n        super().__init__(\n            usage=usage,\n            add_help=False,\n            formatter_class=DropShorterLongHelpFormatter,\n            allow_abbrev=False,\n            fromfile_prefix_chars=\"@\",\n        )\n        # extra_info is a dict of (param -> value) to display if there's\n        # an usage error to provide more contextual information to the user.\n        self.extra_info = extra_info\n\n    def error(self, message: str) -> NoReturn:\n        \"\"\"Transform argparse error message into UsageError.\"\"\"\n        # TODO(py313): Replace with `exit_on_error=False`. Note that while it\n        # was added in Python 3.9, it was broken until 3.13 (cpython#121018).\n        msg = f\"{self.prog}: error: {message}\"\n        if self.extra_info:\n            msg += \"\\n\" + \"\\n\".join(\n                f\"  {k}: {v}\" for k, v in sorted(self.extra_info.items())\n            )\n        raise UsageError(self.format_usage() + msg)\n\n\nclass DropShorterLongHelpFormatter(argparse.HelpFormatter):\n    \"\"\"Shorten help for long options that differ only in extra hyphens.\n\n    - Collapse **long** options that are the same except for extra hyphens.\n    - Shortcut if there are only two options and one of them is a short one.\n    \"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        # Use more accurate terminal width.\n        if \"width\" not in kwargs:\n            kwargs[\"width\"] = _pytest._io.get_terminal_width()\n        super().__init__(*args, **kwargs)\n\n    def _format_action_invocation(self, action: argparse.Action) -> str:\n        orgstr = super()._format_action_invocation(action)\n        if orgstr and orgstr[0] != \"-\":  # only optional arguments\n            return orgstr\n        options = orgstr.split(\", \")\n        if len(options) == 2 and (len(options[0]) == 2 or len(options[1]) == 2):\n            # a shortcut for '-h, --help' or '--abc', '-a'\n            return orgstr\n        return_list = []\n        short_long: dict[str, str] = {}\n        for option in options:\n            if len(option) == 2 or option[2] == \" \":\n                continue\n            assert option.startswith(\"--\"), (\n                f'long optional argument without \"--\": [{option}]'\n            )\n            xxoption = option[2:]\n            shortened = xxoption.replace(\"-\", \"\")\n            if shortened not in short_long or len(short_long[shortened]) < len(\n                xxoption\n            ):\n                short_long[shortened] = xxoption\n        # now short_long has been filled out to the longest with dashes\n        # **and** we keep the right option ordering from add_argument\n        for option in options:\n            if len(option) == 2 or option[2] == \" \":\n                return_list.append(option)\n            if option[2:] == short_long.get(option.replace(\"-\", \"\")):\n                return_list.append(option.replace(\" \", \"=\", 1))\n        return \", \".join(return_list)\n\n    def _split_lines(self, text: str, width: int) -> list[str]:\n        \"\"\"Wrap lines after splitting on original newlines.\n\n        This allows to have explicit line breaks in the help text.\n        \"\"\"\n        lines = []\n        for line in text.splitlines():\n            lines.extend(textwrap.wrap(line.strip(), width))\n        return lines\n\n\nclass OverrideIniAction(argparse.Action):\n    \"\"\"Custom argparse action that makes a CLI flag equivalent to overriding an\n    option, in addition to behaving like `store_true`.\n\n    This can simplify things since code only needs to inspect the config option\n    and not consider the CLI flag.\n    \"\"\"\n\n    def __init__(\n        self,\n        option_strings: Sequence[str],\n        dest: str,\n        nargs: int | str | None = None,\n        *args,\n        ini_option: str,\n        ini_value: str,\n        **kwargs,\n    ) -> None:\n        super().__init__(option_strings, dest, 0, *args, **kwargs)\n        self.ini_option = ini_option\n        self.ini_value = ini_value\n\n    def __call__(\n        self,\n        parser: argparse.ArgumentParser,\n        namespace: argparse.Namespace,\n        *args,\n        **kwargs,\n    ) -> None:\n        setattr(namespace, self.dest, True)\n        current_overrides = getattr(namespace, \"override_ini\", None)\n        if current_overrides is None:\n            current_overrides = []\n        current_overrides.append(f\"{self.ini_option}={self.ini_value}\")\n        setattr(namespace, \"override_ini\", current_overrides)\n"
  },
  {
    "path": "src/_pytest/config/exceptions.py",
    "content": "from __future__ import annotations\n\nfrom typing import final\n\n\n@final\nclass UsageError(Exception):\n    \"\"\"Error in pytest usage or invocation.\"\"\"\n\n    __module__ = \"pytest\"\n\n\nclass PrintHelp(Exception):\n    \"\"\"Raised when pytest should print its help to skip the rest of the\n    argument parsing and validation.\"\"\"\n"
  },
  {
    "path": "src/_pytest/config/findpaths.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Iterable\nfrom collections.abc import Sequence\nfrom dataclasses import dataclass\nfrom dataclasses import KW_ONLY\nimport os\nfrom pathlib import Path\nimport sys\nfrom typing import Literal\nfrom typing import TypeAlias\n\nimport iniconfig\n\nfrom .exceptions import UsageError\nfrom _pytest.outcomes import fail\nfrom _pytest.pathlib import absolutepath\nfrom _pytest.pathlib import commonpath\nfrom _pytest.pathlib import safe_exists\n\n\n@dataclass(frozen=True)\nclass ConfigValue:\n    \"\"\"Represents a configuration value with its origin and parsing mode.\n\n    This allows tracking whether a value came from a configuration file\n    or from a CLI override (--override-ini), which is important for\n    determining precedence when dealing with ini option aliases.\n\n    The mode tracks the parsing mode/data model used for the value:\n    - \"ini\": from INI files or [tool.pytest.ini_options], where the only\n      supported value types are `str` or `list[str]`.\n    - \"toml\": from TOML files (not in INI mode), where native TOML types\n       are preserved.\n    \"\"\"\n\n    value: object\n    _: KW_ONLY\n    origin: Literal[\"file\", \"override\"]\n    mode: Literal[\"ini\", \"toml\"]\n\n\nConfigDict: TypeAlias = dict[str, ConfigValue]\n\n\ndef _parse_ini_config(path: Path) -> iniconfig.IniConfig:\n    \"\"\"Parse the given generic '.ini' file using legacy IniConfig parser, returning\n    the parsed object.\n\n    Raise UsageError if the file cannot be parsed.\n    \"\"\"\n    try:\n        return iniconfig.IniConfig(str(path))\n    except iniconfig.ParseError as exc:\n        raise UsageError(str(exc)) from exc\n\n\ndef load_config_dict_from_file(\n    filepath: Path,\n) -> ConfigDict | None:\n    \"\"\"Load pytest configuration from the given file path, if supported.\n\n    Return None if the file does not contain valid pytest configuration.\n    \"\"\"\n    # Configuration from ini files are obtained from the [pytest] section, if present.\n    if filepath.suffix == \".ini\":\n        iniconfig = _parse_ini_config(filepath)\n\n        if \"pytest\" in iniconfig:\n            return {\n                k: ConfigValue(v, origin=\"file\", mode=\"ini\")\n                for k, v in iniconfig[\"pytest\"].items()\n            }\n        else:\n            # \"pytest.ini\" files are always the source of configuration, even if empty.\n            if filepath.name in {\"pytest.ini\", \".pytest.ini\"}:\n                return {}\n\n    # '.cfg' files are considered if they contain a \"[tool:pytest]\" section.\n    elif filepath.suffix == \".cfg\":\n        iniconfig = _parse_ini_config(filepath)\n\n        if \"tool:pytest\" in iniconfig.sections:\n            return {\n                k: ConfigValue(v, origin=\"file\", mode=\"ini\")\n                for k, v in iniconfig[\"tool:pytest\"].items()\n            }\n        elif \"pytest\" in iniconfig.sections:\n            # If a setup.cfg contains a \"[pytest]\" section, we raise a failure to indicate users that\n            # plain \"[pytest]\" sections in setup.cfg files is no longer supported (#3086).\n            fail(CFG_PYTEST_SECTION.format(filename=\"setup.cfg\"), pytrace=False)\n\n    # '.toml' files are considered if they contain a [tool.pytest] table (toml mode)\n    # or [tool.pytest.ini_options] table (ini mode) for pyproject.toml,\n    # or [pytest] table (toml mode) for pytest.toml/.pytest.toml.\n    elif filepath.suffix == \".toml\":\n        if sys.version_info >= (3, 11):\n            import tomllib\n        else:\n            import tomli as tomllib\n\n        toml_text = filepath.read_text(encoding=\"utf-8\")\n        try:\n            config = tomllib.loads(toml_text)\n        except tomllib.TOMLDecodeError as exc:\n            raise UsageError(f\"{filepath}: {exc}\") from exc\n\n        # pytest.toml and .pytest.toml use [pytest] table directly.\n        if filepath.name in (\"pytest.toml\", \".pytest.toml\"):\n            pytest_config = config.get(\"pytest\", {})\n            if pytest_config:\n                # TOML mode - preserve native TOML types.\n                return {\n                    k: ConfigValue(v, origin=\"file\", mode=\"toml\")\n                    for k, v in pytest_config.items()\n                }\n            # \"pytest.toml\" files are always the source of configuration, even if empty.\n            return {}\n\n        # pyproject.toml uses [tool.pytest] or [tool.pytest.ini_options].\n        else:\n            tool_pytest = config.get(\"tool\", {}).get(\"pytest\", {})\n\n            # Check for toml mode config: [tool.pytest] with content outside of ini_options.\n            toml_config = {k: v for k, v in tool_pytest.items() if k != \"ini_options\"}\n            # Check for ini mode config: [tool.pytest.ini_options].\n            ini_config = tool_pytest.get(\"ini_options\", None)\n\n            if toml_config and ini_config:\n                raise UsageError(\n                    f\"{filepath}: Cannot use both [tool.pytest] (native TOML types) and \"\n                    \"[tool.pytest.ini_options] (string-based INI format) simultaneously. \"\n                    \"Please use [tool.pytest] with native TOML types (recommended) \"\n                    \"or [tool.pytest.ini_options] for backwards compatibility.\"\n                )\n\n            if toml_config:\n                # TOML mode - preserve native TOML types.\n                return {\n                    k: ConfigValue(v, origin=\"file\", mode=\"toml\")\n                    for k, v in toml_config.items()\n                }\n\n            elif ini_config is not None:\n                # INI mode - TOML supports richer data types than INI files, but we need to\n                # convert all scalar values to str for compatibility with the INI system.\n                def make_scalar(v: object) -> str | list[str]:\n                    return v if isinstance(v, list) else str(v)\n\n                return {\n                    k: ConfigValue(make_scalar(v), origin=\"file\", mode=\"ini\")\n                    for k, v in ini_config.items()\n                }\n\n    return None\n\n\ndef locate_config(\n    invocation_dir: Path,\n    args: Iterable[Path],\n) -> tuple[Path | None, Path | None, ConfigDict, Sequence[str]]:\n    \"\"\"Search in the list of arguments for a valid ini-file for pytest,\n    and return a tuple of (rootdir, inifile, cfg-dict, ignored-config-files), where\n    ignored-config-files is a list of config basenames found that contain\n    pytest configuration but were ignored.\"\"\"\n    config_names = [\n        \"pytest.toml\",\n        \".pytest.toml\",\n        \"pytest.ini\",\n        \".pytest.ini\",\n        \"pyproject.toml\",\n        \"tox.ini\",\n        \"setup.cfg\",\n    ]\n    args = [x for x in args if not str(x).startswith(\"-\")]\n    if not args:\n        args = [invocation_dir]\n    found_pyproject_toml: Path | None = None\n    ignored_config_files: list[str] = []\n\n    for arg in args:\n        argpath = absolutepath(arg)\n        for base in (argpath, *argpath.parents):\n            for config_name in config_names:\n                p = base / config_name\n                if p.is_file():\n                    if p.name == \"pyproject.toml\" and found_pyproject_toml is None:\n                        found_pyproject_toml = p\n                    ini_config = load_config_dict_from_file(p)\n                    if ini_config is not None:\n                        index = config_names.index(config_name)\n                        for remainder in config_names[index + 1 :]:\n                            p2 = base / remainder\n                            if (\n                                p2.is_file()\n                                and load_config_dict_from_file(p2) is not None\n                            ):\n                                ignored_config_files.append(remainder)\n                        return base, p, ini_config, ignored_config_files\n    if found_pyproject_toml is not None:\n        return found_pyproject_toml.parent, found_pyproject_toml, {}, []\n    return None, None, {}, []\n\n\ndef get_common_ancestor(\n    invocation_dir: Path,\n    paths: Iterable[Path],\n) -> Path:\n    common_ancestor: Path | None = None\n    for path in paths:\n        if not path.exists():\n            continue\n        if common_ancestor is None:\n            common_ancestor = path\n        else:\n            if common_ancestor in path.parents or path == common_ancestor:\n                continue\n            elif path in common_ancestor.parents:\n                common_ancestor = path\n            else:\n                shared = commonpath(path, common_ancestor)\n                if shared is not None:\n                    common_ancestor = shared\n    if common_ancestor is None:\n        common_ancestor = invocation_dir\n    elif common_ancestor.is_file():\n        common_ancestor = common_ancestor.parent\n    return common_ancestor\n\n\ndef get_dirs_from_args(args: Iterable[str]) -> list[Path]:\n    def is_option(x: str) -> bool:\n        return x.startswith(\"-\")\n\n    def get_file_part_from_node_id(x: str) -> str:\n        return x.split(\"::\")[0]\n\n    def get_dir_from_path(path: Path) -> Path:\n        if path.is_dir():\n            return path\n        return path.parent\n\n    # These look like paths but may not exist\n    possible_paths = (\n        absolutepath(get_file_part_from_node_id(arg))\n        for arg in args\n        if not is_option(arg)\n    )\n\n    return [get_dir_from_path(path) for path in possible_paths if safe_exists(path)]\n\n\ndef parse_override_ini(override_ini: Sequence[str] | None) -> ConfigDict:\n    \"\"\"Parse the -o/--override-ini command line arguments and return the overrides.\n\n    :raises UsageError:\n        If one of the values is malformed.\n    \"\"\"\n    overrides = {}\n    # override_ini is a list of \"ini=value\" options.\n    # Always use the last item if multiple values are set for same ini-name,\n    # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2.\n    for ini_config in override_ini or ():\n        try:\n            key, user_ini_value = ini_config.split(\"=\", 1)\n        except ValueError as e:\n            raise UsageError(\n                f\"-o/--override-ini expects option=value style (got: {ini_config!r}).\"\n            ) from e\n        else:\n            overrides[key] = ConfigValue(user_ini_value, origin=\"override\", mode=\"ini\")\n    return overrides\n\n\nCFG_PYTEST_SECTION = \"[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead.\"\n\n\ndef determine_setup(\n    *,\n    inifile: str | None,\n    override_ini: Sequence[str] | None,\n    args: Sequence[str],\n    rootdir_cmd_arg: str | None,\n    invocation_dir: Path,\n) -> tuple[Path, Path | None, ConfigDict, Sequence[str]]:\n    \"\"\"Determine the rootdir, inifile and ini configuration values from the\n    command line arguments.\n\n    :param inifile:\n        The `--inifile` command line argument, if given.\n    :param override_ini:\n        The -o/--override-ini command line arguments, if given.\n    :param args:\n        The free command line arguments.\n    :param rootdir_cmd_arg:\n        The `--rootdir` command line argument, if given.\n    :param invocation_dir:\n        The working directory when pytest was invoked.\n\n    :raises UsageError:\n    \"\"\"\n    rootdir = None\n    dirs = get_dirs_from_args(args)\n    ignored_config_files: Sequence[str] = []\n\n    if inifile:\n        inipath_ = absolutepath(inifile)\n        inipath: Path | None = inipath_\n        inicfg = load_config_dict_from_file(inipath_) or {}\n        if rootdir_cmd_arg is None:\n            rootdir = inipath_.parent\n    else:\n        ancestor = get_common_ancestor(invocation_dir, dirs)\n        rootdir, inipath, inicfg, ignored_config_files = locate_config(\n            invocation_dir, [ancestor]\n        )\n        if rootdir is None and rootdir_cmd_arg is None:\n            for possible_rootdir in (ancestor, *ancestor.parents):\n                if (possible_rootdir / \"setup.py\").is_file():\n                    rootdir = possible_rootdir\n                    break\n            else:\n                if dirs != [ancestor]:\n                    rootdir, inipath, inicfg, _ = locate_config(invocation_dir, dirs)\n                if rootdir is None:\n                    rootdir = get_common_ancestor(\n                        invocation_dir, [invocation_dir, ancestor]\n                    )\n                    if is_fs_root(rootdir):\n                        rootdir = ancestor\n    if rootdir_cmd_arg:\n        rootdir = absolutepath(os.path.expandvars(rootdir_cmd_arg))\n        if not rootdir.is_dir():\n            raise UsageError(\n                f\"Directory '{rootdir}' not found. Check your '--rootdir' option.\"\n            )\n\n    ini_overrides = parse_override_ini(override_ini)\n    inicfg.update(ini_overrides)\n\n    assert rootdir is not None\n    return rootdir, inipath, inicfg, ignored_config_files\n\n\ndef is_fs_root(p: Path) -> bool:\n    r\"\"\"\n    Return True if the given path is pointing to the root of the\n    file system (\"/\" on Unix and \"C:\\\\\" on Windows for example).\n    \"\"\"\n    return os.path.splitdrive(str(p))[1] == os.sep\n"
  },
  {
    "path": "src/_pytest/debugging.py",
    "content": "# mypy: allow-untyped-defs\n# ruff: noqa: T100\n\"\"\"Interactive debugging with PDB, the Python Debugger.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nfrom collections.abc import Callable\nfrom collections.abc import Generator\nimport functools\nimport importlib\nimport sys\nimport types\nfrom typing import Any\n\nfrom _pytest import outcomes\nfrom _pytest._code import ExceptionInfo\nfrom _pytest.capture import CaptureManager\nfrom _pytest.config import Config\nfrom _pytest.config import ConftestImportFailure\nfrom _pytest.config import hookimpl\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.config.exceptions import UsageError\nfrom _pytest.nodes import Node\nfrom _pytest.reports import BaseReport\nfrom _pytest.runner import CallInfo\n\n\ndef _validate_usepdb_cls(value: str) -> tuple[str, str]:\n    \"\"\"Validate syntax of --pdbcls option.\"\"\"\n    try:\n        modname, classname = value.split(\":\")\n    except ValueError as e:\n        raise argparse.ArgumentTypeError(\n            f\"{value!r} is not in the format 'modname:classname'\"\n        ) from e\n    return (modname, classname)\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"general\")\n    group.addoption(\n        \"--pdb\",\n        dest=\"usepdb\",\n        action=\"store_true\",\n        help=\"Start the interactive Python debugger on errors or KeyboardInterrupt\",\n    )\n    group.addoption(\n        \"--pdbcls\",\n        dest=\"usepdb_cls\",\n        metavar=\"modulename:classname\",\n        type=_validate_usepdb_cls,\n        help=\"Specify a custom interactive Python debugger for use with --pdb.\"\n        \"For example: --pdbcls=IPython.terminal.debugger:TerminalPdb\",\n    )\n    group.addoption(\n        \"--trace\",\n        dest=\"trace\",\n        action=\"store_true\",\n        help=\"Immediately break when running each test\",\n    )\n\n\ndef pytest_configure(config: Config) -> None:\n    import pdb\n\n    if config.getvalue(\"trace\"):\n        config.pluginmanager.register(PdbTrace(), \"pdbtrace\")\n    if config.getvalue(\"usepdb\"):\n        config.pluginmanager.register(PdbInvoke(), \"pdbinvoke\")\n\n    pytestPDB._saved.append(\n        (pdb.set_trace, pytestPDB._pluginmanager, pytestPDB._config)\n    )\n    pdb.set_trace = pytestPDB.set_trace\n    pytestPDB._pluginmanager = config.pluginmanager\n    pytestPDB._config = config\n\n    # NOTE: not using pytest_unconfigure, since it might get called although\n    #       pytest_configure was not (if another plugin raises UsageError).\n    def fin() -> None:\n        (\n            pdb.set_trace,\n            pytestPDB._pluginmanager,\n            pytestPDB._config,\n        ) = pytestPDB._saved.pop()\n\n    config.add_cleanup(fin)\n\n\nclass pytestPDB:\n    \"\"\"Pseudo PDB that defers to the real pdb.\"\"\"\n\n    _pluginmanager: PytestPluginManager | None = None\n    _config: Config | None = None\n    _saved: list[\n        tuple[Callable[..., None], PytestPluginManager | None, Config | None]\n    ] = []\n    _recursive_debug = 0\n    _wrapped_pdb_cls: tuple[type[Any], type[Any]] | None = None\n\n    @classmethod\n    def _is_capturing(cls, capman: CaptureManager | None) -> str | bool:\n        if capman:\n            return capman.is_capturing()\n        return False\n\n    @classmethod\n    def _import_pdb_cls(cls, capman: CaptureManager | None):\n        if not cls._config:\n            import pdb\n\n            # Happens when using pytest.set_trace outside of a test.\n            return pdb.Pdb\n\n        usepdb_cls = cls._config.getvalue(\"usepdb_cls\")\n\n        if cls._wrapped_pdb_cls and cls._wrapped_pdb_cls[0] == usepdb_cls:\n            return cls._wrapped_pdb_cls[1]\n\n        if usepdb_cls:\n            modname, classname = usepdb_cls\n\n            try:\n                mod = importlib.import_module(modname)\n\n                # Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp).\n                parts = classname.split(\".\")\n                pdb_cls = getattr(mod, parts[0])\n                for part in parts[1:]:\n                    pdb_cls = getattr(pdb_cls, part)\n            except Exception as exc:\n                value = \":\".join((modname, classname))\n                raise UsageError(\n                    f\"--pdbcls: could not import {value!r}: {exc}\"\n                ) from exc\n        else:\n            import pdb\n\n            pdb_cls = pdb.Pdb\n\n        wrapped_cls = cls._get_pdb_wrapper_class(pdb_cls, capman)\n        cls._wrapped_pdb_cls = (usepdb_cls, wrapped_cls)\n        return wrapped_cls\n\n    @classmethod\n    def _get_pdb_wrapper_class(cls, pdb_cls, capman: CaptureManager | None):\n        import _pytest.config\n\n        class PytestPdbWrapper(pdb_cls):\n            _pytest_capman = capman\n            _continued = False\n\n            def do_debug(self, arg):\n                cls._recursive_debug += 1\n                ret = super().do_debug(arg)\n                cls._recursive_debug -= 1\n                return ret\n\n            if hasattr(pdb_cls, \"do_debug\"):\n                do_debug.__doc__ = pdb_cls.do_debug.__doc__\n\n            def do_continue(self, arg):\n                ret = super().do_continue(arg)\n                if cls._recursive_debug == 0:\n                    assert cls._config is not None\n                    tw = _pytest.config.create_terminal_writer(cls._config)\n                    tw.line()\n\n                    capman = self._pytest_capman\n                    capturing = pytestPDB._is_capturing(capman)\n                    if capturing:\n                        if capturing == \"global\":\n                            tw.sep(\">\", \"PDB continue (IO-capturing resumed)\")\n                        else:\n                            tw.sep(\n                                \">\",\n                                f\"PDB continue (IO-capturing resumed for {capturing})\",\n                            )\n                        assert capman is not None\n                        capman.resume()\n                    else:\n                        tw.sep(\">\", \"PDB continue\")\n                assert cls._pluginmanager is not None\n                cls._pluginmanager.hook.pytest_leave_pdb(config=cls._config, pdb=self)\n                self._continued = True\n                return ret\n\n            if hasattr(pdb_cls, \"do_continue\"):\n                do_continue.__doc__ = pdb_cls.do_continue.__doc__\n\n            do_c = do_cont = do_continue\n\n            def do_quit(self, arg):\n                # Raise Exit outcome when quit command is used in pdb.\n                #\n                # This is a bit of a hack - it would be better if BdbQuit\n                # could be handled, but this would require to wrap the\n                # whole pytest run, and adjust the report etc.\n                ret = super().do_quit(arg)\n\n                if cls._recursive_debug == 0:\n                    outcomes.exit(\"Quitting debugger\")\n\n                return ret\n\n            if hasattr(pdb_cls, \"do_quit\"):\n                do_quit.__doc__ = pdb_cls.do_quit.__doc__\n\n            do_q = do_quit\n            do_exit = do_quit\n\n            def setup(self, f, tb):\n                \"\"\"Suspend on setup().\n\n                Needed after do_continue resumed, and entering another\n                breakpoint again.\n                \"\"\"\n                ret = super().setup(f, tb)\n                if not ret and self._continued:\n                    # pdb.setup() returns True if the command wants to exit\n                    # from the interaction: do not suspend capturing then.\n                    if self._pytest_capman:\n                        self._pytest_capman.suspend_global_capture(in_=True)\n                return ret\n\n            def get_stack(self, f, t):\n                stack, i = super().get_stack(f, t)\n                if f is None:\n                    # Find last non-hidden frame.\n                    i = max(0, len(stack) - 1)\n                    while i and stack[i][0].f_locals.get(\"__tracebackhide__\", False):\n                        i -= 1\n                return stack, i\n\n        return PytestPdbWrapper\n\n    @classmethod\n    def _init_pdb(cls, method, *args, **kwargs):\n        \"\"\"Initialize PDB debugging, dropping any IO capturing.\"\"\"\n        import _pytest.config\n\n        if cls._pluginmanager is None:\n            capman: CaptureManager | None = None\n        else:\n            capman = cls._pluginmanager.getplugin(\"capturemanager\")\n        if capman:\n            capman.suspend(in_=True)\n\n        if cls._config:\n            tw = _pytest.config.create_terminal_writer(cls._config)\n            tw.line()\n\n            if cls._recursive_debug == 0:\n                # Handle header similar to pdb.set_trace in py37+.\n                header = kwargs.pop(\"header\", None)\n                if header is not None:\n                    tw.sep(\">\", header)\n                else:\n                    capturing = cls._is_capturing(capman)\n                    if capturing == \"global\":\n                        tw.sep(\">\", f\"PDB {method} (IO-capturing turned off)\")\n                    elif capturing:\n                        tw.sep(\n                            \">\",\n                            f\"PDB {method} (IO-capturing turned off for {capturing})\",\n                        )\n                    else:\n                        tw.sep(\">\", f\"PDB {method}\")\n\n        _pdb = cls._import_pdb_cls(capman)(**kwargs)\n\n        if cls._pluginmanager:\n            cls._pluginmanager.hook.pytest_enter_pdb(config=cls._config, pdb=_pdb)\n        return _pdb\n\n    @classmethod\n    def set_trace(cls, *args, **kwargs) -> None:\n        \"\"\"Invoke debugging via ``Pdb.set_trace``, dropping any IO capturing.\"\"\"\n        frame = sys._getframe().f_back\n        _pdb = cls._init_pdb(\"set_trace\", *args, **kwargs)\n        _pdb.set_trace(frame)\n\n\nclass PdbInvoke:\n    def pytest_exception_interact(\n        self, node: Node, call: CallInfo[Any], report: BaseReport\n    ) -> None:\n        capman = node.config.pluginmanager.getplugin(\"capturemanager\")\n        if capman:\n            capman.suspend_global_capture(in_=True)\n            out, err = capman.read_global_capture()\n            sys.stdout.write(out)\n            sys.stdout.write(err)\n        assert call.excinfo is not None\n        _enter_pdb(node, call.excinfo, report)\n\n    def pytest_internalerror(self, excinfo: ExceptionInfo[BaseException]) -> None:\n        exc_or_tb = _postmortem_exc_or_tb(excinfo)\n        post_mortem(exc_or_tb)\n\n\nclass PdbTrace:\n    @hookimpl(wrapper=True)\n    def pytest_pyfunc_call(self, pyfuncitem) -> Generator[None, object, object]:\n        wrap_pytest_function_for_tracing(pyfuncitem)\n        return (yield)\n\n\ndef wrap_pytest_function_for_tracing(pyfuncitem) -> None:\n    \"\"\"Change the Python function object of the given Function item by a\n    wrapper which actually enters pdb before calling the python function\n    itself, effectively leaving the user in the pdb prompt in the first\n    statement of the function.\"\"\"\n    _pdb = pytestPDB._init_pdb(\"runcall\")\n    testfunction = pyfuncitem.obj\n\n    # we can't just return `partial(pdb.runcall, testfunction)` because (on\n    # python < 3.7.4) runcall's first param is `func`, which means we'd get\n    # an exception if one of the kwargs to testfunction was called `func`.\n    @functools.wraps(testfunction)\n    def wrapper(*args, **kwargs) -> None:\n        func = functools.partial(testfunction, *args, **kwargs)\n        _pdb.runcall(func)\n\n    pyfuncitem.obj = wrapper\n\n\ndef maybe_wrap_pytest_function_for_tracing(pyfuncitem) -> None:\n    \"\"\"Wrap the given pytestfunct item for tracing support if --trace was given in\n    the command line.\"\"\"\n    if pyfuncitem.config.getvalue(\"trace\"):\n        wrap_pytest_function_for_tracing(pyfuncitem)\n\n\ndef _enter_pdb(\n    node: Node, excinfo: ExceptionInfo[BaseException], rep: BaseReport\n) -> BaseReport:\n    # XXX we reuse the TerminalReporter's terminalwriter\n    # because this seems to avoid some encoding related troubles\n    # for not completely clear reasons.\n    tw = node.config.pluginmanager.getplugin(\"terminalreporter\")._tw\n    tw.line()\n\n    showcapture = node.config.option.showcapture\n\n    for sectionname, content in (\n        (\"stdout\", rep.capstdout),\n        (\"stderr\", rep.capstderr),\n        (\"log\", rep.caplog),\n    ):\n        if showcapture in (sectionname, \"all\") and content:\n            tw.sep(\">\", \"captured \" + sectionname)\n            if content[-1:] == \"\\n\":\n                content = content[:-1]\n            tw.line(content)\n\n    tw.sep(\">\", \"traceback\")\n    rep.toterminal(tw)\n    tw.sep(\">\", \"entering PDB\")\n    tb_or_exc = _postmortem_exc_or_tb(excinfo)\n    rep._pdbshown = True  # type: ignore[attr-defined]\n    post_mortem(tb_or_exc)\n    return rep\n\n\ndef _postmortem_exc_or_tb(\n    excinfo: ExceptionInfo[BaseException],\n) -> types.TracebackType | BaseException:\n    from doctest import UnexpectedException\n\n    get_exc = sys.version_info >= (3, 13)\n    if isinstance(excinfo.value, UnexpectedException):\n        # A doctest.UnexpectedException is not useful for post_mortem.\n        # Use the underlying exception instead:\n        underlying_exc = excinfo.value\n        if get_exc:\n            return underlying_exc.exc_info[1]\n\n        return underlying_exc.exc_info[2]\n    elif isinstance(excinfo.value, ConftestImportFailure):\n        # A config.ConftestImportFailure is not useful for post_mortem.\n        # Use the underlying exception instead:\n        cause = excinfo.value.cause\n        if get_exc:\n            return cause\n\n        assert cause.__traceback__ is not None\n        return cause.__traceback__\n    else:\n        assert excinfo._excinfo is not None\n        if get_exc:\n            return excinfo._excinfo[1]\n\n        return excinfo._excinfo[2]\n\n\ndef post_mortem(tb_or_exc: types.TracebackType | BaseException) -> None:\n    p = pytestPDB._init_pdb(\"post_mortem\")\n    p.reset()\n    p.interaction(None, tb_or_exc)\n    if p.quitting:\n        outcomes.exit(\"Quitting debugger\")\n"
  },
  {
    "path": "src/_pytest/deprecated.py",
    "content": "\"\"\"Deprecation messages and bits of code used elsewhere in the codebase that\nis planned to be removed in the next pytest release.\n\nKeeping it in a central location makes it easy to track what is deprecated and should\nbe removed when the time comes.\n\nAll constants defined in this module should be either instances of\n:class:`PytestWarning`, or :class:`UnformattedWarning`\nin case of warnings which need to format their messages.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom warnings import warn\n\nfrom _pytest.warning_types import PytestDeprecationWarning\nfrom _pytest.warning_types import PytestRemovedIn10Warning\nfrom _pytest.warning_types import UnformattedWarning\n\n\n# set of plugins which have been integrated into the core; we use this list to ignore\n# them during registration to avoid conflicts\nDEPRECATED_EXTERNAL_PLUGINS = {\n    \"pytest_catchlog\",\n    \"pytest_capturelog\",\n    \"pytest_faulthandler\",\n    \"pytest_subtests\",\n}\n\n\n# This could have been removed pytest 8, but it's harmless and common, so no rush to remove.\nYIELD_FIXTURE = PytestDeprecationWarning(\n    \"@pytest.yield_fixture is deprecated.\\n\"\n    \"Use @pytest.fixture instead; they are the same.\"\n)\n\n# This deprecation is never really meant to be removed.\nPRIVATE = PytestDeprecationWarning(\"A private pytest class or function was used.\")\n\n\nHOOK_LEGACY_MARKING = UnformattedWarning(\n    PytestDeprecationWarning,\n    \"The hook{type} {fullname} uses old-style configuration options (marks or attributes).\\n\"\n    \"Please use the pytest.hook{type}({hook_opts}) decorator instead\\n\"\n    \" to configure the hooks.\\n\"\n    \" See https://docs.pytest.org/en/latest/deprecations.html\"\n    \"#configuring-hook-specs-impls-using-markers\",\n)\n\nMONKEYPATCH_LEGACY_NAMESPACE_PACKAGES = PytestRemovedIn10Warning(\n    \"monkeypatch.syspath_prepend() called with pkg_resources legacy namespace packages detected.\\n\"\n    \"Legacy namespace packages (using pkg_resources.declare_namespace) are deprecated.\\n\"\n    \"Please use native namespace packages (PEP 420) instead.\\n\"\n    \"See https://docs.pytest.org/en/stable/deprecations.html#monkeypatch-fixup-namespace-packages\"\n)\n\nPARAMETRIZE_NON_COLLECTION_ITERABLE = UnformattedWarning(\n    PytestRemovedIn10Warning,\n    \"Passing a non-Collection iterable to parametrize is deprecated.\\n\"\n    \"Test: {nodeid}, argvalues type: {type_name}\\n\"\n    \"Please convert to a list or tuple.\\n\"\n    \"See https://docs.pytest.org/en/stable/deprecations.html#parametrize-iterators\",\n)\n\nCONFIG_INICFG = PytestRemovedIn10Warning(\n    \"config.inicfg is deprecated, use config.getini() to access configuration values instead.\\n\"\n    \"See https://docs.pytest.org/en/stable/deprecations.html#config-inicfg\"\n)\n\nFIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN = UnformattedWarning(\n    PytestRemovedIn10Warning,\n    'Calling request.getfixturevalue(\"{argname}\") during teardown is deprecated.\\n'\n    \"Please request the fixture before teardown begins, either by declaring it in the fixture signature \"\n    \"or by calling request.getfixturevalue() before the fixture yields.\\n\"\n    \"See https://docs.pytest.org/en/stable/deprecations.html#dynamic-fixture-request-during-teardown\",\n)\n\n# You want to make some `__init__` or function \"private\".\n#\n#   def my_private_function(some, args):\n#       ...\n#\n# Do this:\n#\n#   def my_private_function(some, args, *, _ispytest: bool = False):\n#       check_ispytest(_ispytest)\n#       ...\n#\n# Change all internal/allowed calls to\n#\n#   my_private_function(some, args, _ispytest=True)\n#\n# All other calls will get the default _ispytest=False and trigger\n# the warning (possibly error in the future).\n\n\ndef check_ispytest(ispytest: bool) -> None:\n    if not ispytest:\n        warn(PRIVATE, stacklevel=3)\n"
  },
  {
    "path": "src/_pytest/doctest.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Discover and run doctests in modules and test files.\"\"\"\n\nfrom __future__ import annotations\n\nimport bdb\nfrom collections.abc import Callable\nfrom collections.abc import Generator\nfrom collections.abc import Iterable\nfrom collections.abc import Sequence\nfrom contextlib import contextmanager\nimport functools\nimport inspect\nimport os\nfrom pathlib import Path\nimport platform\nimport re\nimport sys\nimport traceback\nimport types\nfrom typing import Any\nfrom typing import TYPE_CHECKING\nimport warnings\n\nfrom _pytest import outcomes\nfrom _pytest._code.code import ExceptionInfo\nfrom _pytest._code.code import ReprFileLocation\nfrom _pytest._code.code import TerminalRepr\nfrom _pytest._io import TerminalWriter\nfrom _pytest.compat import safe_getattr\nfrom _pytest.config import Config\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.fixtures import fixture\nfrom _pytest.fixtures import TopRequest\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import Item\nfrom _pytest.outcomes import OutcomeException\nfrom _pytest.outcomes import skip\nfrom _pytest.pathlib import fnmatch_ex\nfrom _pytest.python import Module\nfrom _pytest.python_api import approx\nfrom _pytest.warning_types import PytestWarning\n\n\nif TYPE_CHECKING:\n    import doctest\n\n    from typing_extensions import Self\n\nDOCTEST_REPORT_CHOICE_NONE = \"none\"\nDOCTEST_REPORT_CHOICE_CDIFF = \"cdiff\"\nDOCTEST_REPORT_CHOICE_NDIFF = \"ndiff\"\nDOCTEST_REPORT_CHOICE_UDIFF = \"udiff\"\nDOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = \"only_first_failure\"\n\nDOCTEST_REPORT_CHOICES = (\n    DOCTEST_REPORT_CHOICE_NONE,\n    DOCTEST_REPORT_CHOICE_CDIFF,\n    DOCTEST_REPORT_CHOICE_NDIFF,\n    DOCTEST_REPORT_CHOICE_UDIFF,\n    DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,\n)\n\n# Lazy definition of runner class\nRUNNER_CLASS = None\n# Lazy definition of output checker class\nCHECKER_CLASS: type[doctest.OutputChecker] | None = None\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    parser.addini(\n        \"doctest_optionflags\",\n        \"Option flags for doctests\",\n        type=\"args\",\n        default=[\"ELLIPSIS\"],\n    )\n    parser.addini(\n        \"doctest_encoding\", \"Encoding used for doctest files\", default=\"utf-8\"\n    )\n    group = parser.getgroup(\"collect\")\n    group.addoption(\n        \"--doctest-modules\",\n        action=\"store_true\",\n        default=False,\n        help=\"Run doctests in all .py modules\",\n        dest=\"doctestmodules\",\n    )\n    group.addoption(\n        \"--doctest-report\",\n        type=str.lower,\n        default=\"udiff\",\n        help=\"Choose another output format for diffs on doctest failure\",\n        choices=DOCTEST_REPORT_CHOICES,\n        dest=\"doctestreport\",\n    )\n    group.addoption(\n        \"--doctest-glob\",\n        action=\"append\",\n        default=[],\n        metavar=\"pat\",\n        help=\"Doctests file matching pattern, default: test*.txt\",\n        dest=\"doctestglob\",\n    )\n    group.addoption(\n        \"--doctest-ignore-import-errors\",\n        action=\"store_true\",\n        default=False,\n        help=\"Ignore doctest collection errors\",\n        dest=\"doctest_ignore_import_errors\",\n    )\n    group.addoption(\n        \"--doctest-continue-on-failure\",\n        action=\"store_true\",\n        default=False,\n        help=\"For a given doctest, continue to run after the first failure\",\n        dest=\"doctest_continue_on_failure\",\n    )\n\n\ndef pytest_unconfigure() -> None:\n    global RUNNER_CLASS\n\n    RUNNER_CLASS = None\n\n\ndef pytest_collect_file(\n    file_path: Path,\n    parent: Collector,\n) -> DoctestModule | DoctestTextfile | None:\n    config = parent.config\n    if file_path.suffix == \".py\":\n        if config.option.doctestmodules and not any(\n            (_is_setup_py(file_path), _is_main_py(file_path))\n        ):\n            return DoctestModule.from_parent(parent, path=file_path)\n    elif _is_doctest(config, file_path, parent):\n        return DoctestTextfile.from_parent(parent, path=file_path)\n    return None\n\n\ndef _is_setup_py(path: Path) -> bool:\n    if path.name != \"setup.py\":\n        return False\n    contents = path.read_bytes()\n    return b\"setuptools\" in contents or b\"distutils\" in contents\n\n\ndef _is_doctest(config: Config, path: Path, parent: Collector) -> bool:\n    if path.suffix in (\".txt\", \".rst\") and parent.session.isinitpath(path):\n        return True\n    globs = config.getoption(\"doctestglob\") or [\"test*.txt\"]\n    return any(fnmatch_ex(glob, path) for glob in globs)\n\n\ndef _is_main_py(path: Path) -> bool:\n    return path.name == \"__main__.py\"\n\n\nclass ReprFailDoctest(TerminalRepr):\n    def __init__(\n        self, reprlocation_lines: Sequence[tuple[ReprFileLocation, Sequence[str]]]\n    ) -> None:\n        self.reprlocation_lines = reprlocation_lines\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        for reprlocation, lines in self.reprlocation_lines:\n            for line in lines:\n                tw.line(line)\n            reprlocation.toterminal(tw)\n\n\nclass MultipleDoctestFailures(Exception):\n    def __init__(self, failures: Sequence[doctest.DocTestFailure]) -> None:\n        super().__init__()\n        self.failures = failures\n\n\ndef _init_runner_class() -> type[doctest.DocTestRunner]:\n    import doctest\n\n    class PytestDoctestRunner(doctest.DebugRunner):\n        \"\"\"Runner to collect failures.\n\n        Note that the out variable in this case is a list instead of a\n        stdout-like object.\n        \"\"\"\n\n        def __init__(\n            self,\n            checker: doctest.OutputChecker | None = None,\n            verbose: bool | None = None,\n            optionflags: int = 0,\n            continue_on_failure: bool = True,\n        ) -> None:\n            super().__init__(checker=checker, verbose=verbose, optionflags=optionflags)\n            self.continue_on_failure = continue_on_failure\n\n        def report_failure(\n            self,\n            out,\n            test: doctest.DocTest,\n            example: doctest.Example,\n            got: str,\n        ) -> None:\n            failure = doctest.DocTestFailure(test, example, got)\n            if self.continue_on_failure:\n                out.append(failure)\n            else:\n                raise failure\n\n        def report_unexpected_exception(\n            self,\n            out,\n            test: doctest.DocTest,\n            example: doctest.Example,\n            exc_info: tuple[type[BaseException], BaseException, types.TracebackType],\n        ) -> None:\n            if isinstance(exc_info[1], OutcomeException):\n                raise exc_info[1]\n            if isinstance(exc_info[1], bdb.BdbQuit):\n                outcomes.exit(\"Quitting debugger\")\n            failure = doctest.UnexpectedException(test, example, exc_info)\n            if self.continue_on_failure:\n                out.append(failure)\n            else:\n                raise failure\n\n    return PytestDoctestRunner\n\n\ndef _get_runner(\n    checker: doctest.OutputChecker | None = None,\n    verbose: bool | None = None,\n    optionflags: int = 0,\n    continue_on_failure: bool = True,\n) -> doctest.DocTestRunner:\n    # We need this in order to do a lazy import on doctest\n    global RUNNER_CLASS\n    if RUNNER_CLASS is None:\n        RUNNER_CLASS = _init_runner_class()\n    # Type ignored because the continue_on_failure argument is only defined on\n    # PytestDoctestRunner, which is lazily defined so can't be used as a type.\n    return RUNNER_CLASS(  # type: ignore\n        checker=checker,\n        verbose=verbose,\n        optionflags=optionflags,\n        continue_on_failure=continue_on_failure,\n    )\n\n\nclass DoctestItem(Item):\n    def __init__(\n        self,\n        name: str,\n        parent: DoctestTextfile | DoctestModule,\n        runner: doctest.DocTestRunner,\n        dtest: doctest.DocTest,\n    ) -> None:\n        super().__init__(name, parent)\n        self.runner = runner\n        self.dtest = dtest\n\n        # Stuff needed for fixture support.\n        self.obj = None\n        fm = self.session._fixturemanager\n        fixtureinfo = fm.getfixtureinfo(node=self, func=None, cls=None)\n        self._fixtureinfo = fixtureinfo\n        self.fixturenames = fixtureinfo.names_closure\n        self._initrequest()\n\n    @classmethod\n    def from_parent(  # type: ignore[override]\n        cls,\n        parent: DoctestTextfile | DoctestModule,\n        *,\n        name: str,\n        runner: doctest.DocTestRunner,\n        dtest: doctest.DocTest,\n    ) -> Self:\n        # incompatible signature due to imposed limits on subclass\n        \"\"\"The public named constructor.\"\"\"\n        return super().from_parent(name=name, parent=parent, runner=runner, dtest=dtest)\n\n    def _initrequest(self) -> None:\n        self.funcargs: dict[str, object] = {}\n        self._request = TopRequest(self, _ispytest=True)  # type: ignore[arg-type]\n\n    def setup(self) -> None:\n        self._request._fillfixtures()\n        globs = dict(getfixture=self._request.getfixturevalue)\n        for name, value in self._request.getfixturevalue(\"doctest_namespace\").items():\n            globs[name] = value\n        self.dtest.globs.update(globs)\n\n    def runtest(self) -> None:\n        _check_all_skipped(self.dtest)\n        self._disable_output_capturing_for_darwin()\n        failures: list[doctest.DocTestFailure] = []\n        # Type ignored because we change the type of `out` from what\n        # doctest expects.\n        self.runner.run(self.dtest, out=failures)  # type: ignore[arg-type]\n        if failures:\n            raise MultipleDoctestFailures(failures)\n\n    def _disable_output_capturing_for_darwin(self) -> None:\n        \"\"\"Disable output capturing. Otherwise, stdout is lost to doctest (#985).\"\"\"\n        if platform.system() != \"Darwin\":\n            return\n        capman = self.config.pluginmanager.getplugin(\"capturemanager\")\n        if capman:\n            capman.suspend_global_capture(in_=True)\n            out, err = capman.read_global_capture()\n            sys.stdout.write(out)\n            sys.stderr.write(err)\n\n    # TODO: Type ignored -- breaks Liskov Substitution.\n    def repr_failure(  # type: ignore[override]\n        self,\n        excinfo: ExceptionInfo[BaseException],\n    ) -> str | TerminalRepr:\n        import doctest\n\n        failures: (\n            Sequence[doctest.DocTestFailure | doctest.UnexpectedException] | None\n        ) = None\n        if isinstance(\n            excinfo.value, doctest.DocTestFailure | doctest.UnexpectedException\n        ):\n            failures = [excinfo.value]\n        elif isinstance(excinfo.value, MultipleDoctestFailures):\n            failures = excinfo.value.failures\n\n        if failures is None:\n            return super().repr_failure(excinfo)\n\n        reprlocation_lines = []\n        for failure in failures:\n            example = failure.example\n            test = failure.test\n            filename = test.filename\n            if test.lineno is None:\n                lineno = None\n            else:\n                lineno = test.lineno + example.lineno + 1\n            message = type(failure).__name__\n            # TODO: ReprFileLocation doesn't expect a None lineno.\n            reprlocation = ReprFileLocation(filename, lineno, message)  # type: ignore[arg-type]\n            checker = _get_checker()\n            report_choice = _get_report_choice(self.config.getoption(\"doctestreport\"))\n            if lineno is not None:\n                assert failure.test.docstring is not None\n                lines = failure.test.docstring.splitlines(False)\n                # add line numbers to the left of the error message\n                assert test.lineno is not None\n                lines = [\n                    f\"{i + test.lineno + 1:03d} {x}\" for (i, x) in enumerate(lines)\n                ]\n                # trim docstring error lines to 10\n                lines = lines[max(example.lineno - 9, 0) : example.lineno + 1]\n            else:\n                lines = [\n                    \"EXAMPLE LOCATION UNKNOWN, not showing all tests of that example\"\n                ]\n                indent = \">>>\"\n                for line in example.source.splitlines():\n                    lines.append(f\"??? {indent} {line}\")\n                    indent = \"...\"\n            if isinstance(failure, doctest.DocTestFailure):\n                lines += checker.output_difference(\n                    example, failure.got, report_choice\n                ).split(\"\\n\")\n            else:\n                inner_excinfo = ExceptionInfo.from_exc_info(failure.exc_info)\n                lines += [f\"UNEXPECTED EXCEPTION: {inner_excinfo.value!r}\"]\n                lines += [\n                    x.strip(\"\\n\") for x in traceback.format_exception(*failure.exc_info)\n                ]\n            reprlocation_lines.append((reprlocation, lines))\n        return ReprFailDoctest(reprlocation_lines)\n\n    def reportinfo(self) -> tuple[os.PathLike[str] | str, int | None, str]:\n        return self.path, self.dtest.lineno, f\"[doctest] {self.name}\"\n\n\ndef _get_flag_lookup() -> dict[str, int]:\n    import doctest\n\n    return dict(\n        DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,\n        DONT_ACCEPT_BLANKLINE=doctest.DONT_ACCEPT_BLANKLINE,\n        NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,\n        ELLIPSIS=doctest.ELLIPSIS,\n        IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,\n        COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,\n        ALLOW_UNICODE=_get_allow_unicode_flag(),\n        ALLOW_BYTES=_get_allow_bytes_flag(),\n        NUMBER=_get_number_flag(),\n    )\n\n\ndef get_optionflags(config: Config) -> int:\n    optionflags_str = config.getini(\"doctest_optionflags\")\n    flag_lookup_table = _get_flag_lookup()\n    flag_acc = 0\n    for flag in optionflags_str:\n        flag_acc |= flag_lookup_table[flag]\n    return flag_acc\n\n\ndef _get_continue_on_failure(config: Config) -> bool:\n    continue_on_failure: bool = config.getvalue(\"doctest_continue_on_failure\")\n    if continue_on_failure:\n        # We need to turn off this if we use pdb since we should stop at\n        # the first failure.\n        if config.getvalue(\"usepdb\"):\n            continue_on_failure = False\n    return continue_on_failure\n\n\nclass DoctestTextfile(Module):\n    obj = None\n\n    def collect(self) -> Iterable[DoctestItem]:\n        import doctest\n\n        # Inspired by doctest.testfile; ideally we would use it directly,\n        # but it doesn't support passing a custom checker.\n        encoding = self.config.getini(\"doctest_encoding\")\n        text = self.path.read_text(encoding)\n        filename = str(self.path)\n        name = self.path.name\n        globs = {\"__name__\": \"__main__\"}\n\n        optionflags = get_optionflags(self.config)\n\n        runner = _get_runner(\n            verbose=False,\n            optionflags=optionflags,\n            checker=_get_checker(),\n            continue_on_failure=_get_continue_on_failure(self.config),\n        )\n\n        parser = doctest.DocTestParser()\n        test = parser.get_doctest(text, globs, name, filename, 0)\n        if test.examples:\n            yield DoctestItem.from_parent(\n                self, name=test.name, runner=runner, dtest=test\n            )\n\n\ndef _check_all_skipped(test: doctest.DocTest) -> None:\n    \"\"\"Raise pytest.skip() if all examples in the given DocTest have the SKIP\n    option set.\"\"\"\n    import doctest\n\n    all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)\n    if all_skipped:\n        skip(\"all tests skipped by +SKIP option\")\n\n\ndef _is_mocked(obj: object) -> bool:\n    \"\"\"Return if an object is possibly a mock object by checking the\n    existence of a highly improbable attribute.\"\"\"\n    return (\n        safe_getattr(obj, \"pytest_mock_example_attribute_that_shouldnt_exist\", None)\n        is not None\n    )\n\n\n@contextmanager\ndef _patch_unwrap_mock_aware() -> Generator[None]:\n    \"\"\"Context manager which replaces ``inspect.unwrap`` with a version\n    that's aware of mock objects and doesn't recurse into them.\"\"\"\n    real_unwrap = inspect.unwrap\n\n    def _mock_aware_unwrap(\n        func: Callable[..., Any], *, stop: Callable[[Any], Any] | None = None\n    ) -> Any:\n        try:\n            if stop is None or stop is _is_mocked:\n                return real_unwrap(func, stop=_is_mocked)\n            _stop = stop\n            return real_unwrap(func, stop=lambda obj: _is_mocked(obj) or _stop(func))\n        except Exception as e:\n            warnings.warn(\n                f\"Got {e!r} when unwrapping {func!r}.  This is usually caused \"\n                \"by a violation of Python's object protocol; see e.g. \"\n                \"https://github.com/pytest-dev/pytest/issues/5080\",\n                PytestWarning,\n            )\n            raise\n\n    inspect.unwrap = _mock_aware_unwrap\n    try:\n        yield\n    finally:\n        inspect.unwrap = real_unwrap\n\n\nclass DoctestModule(Module):\n    def collect(self) -> Iterable[DoctestItem]:\n        import doctest\n\n        class MockAwareDocTestFinder(doctest.DocTestFinder):\n            py_ver_info_minor = sys.version_info[:2]\n            is_find_lineno_broken = (\n                py_ver_info_minor < (3, 11)\n                or (py_ver_info_minor == (3, 11) and sys.version_info.micro < 9)\n                or (py_ver_info_minor == (3, 12) and sys.version_info.micro < 3)\n            )\n            if is_find_lineno_broken:\n\n                def _find_lineno(self, obj, source_lines):\n                    \"\"\"On older Pythons, doctest code does not take into account\n                    `@property`. https://github.com/python/cpython/issues/61648\n\n                    Moreover, wrapped Doctests need to be unwrapped so the correct\n                    line number is returned. #8796\n                    \"\"\"\n                    if isinstance(obj, property):\n                        obj = getattr(obj, \"fget\", obj)\n\n                    if hasattr(obj, \"__wrapped__\"):\n                        # Get the main obj in case of it being wrapped\n                        obj = inspect.unwrap(obj)\n\n                    # Type ignored because this is a private function.\n                    return super()._find_lineno(  # type:ignore[misc]\n                        obj,\n                        source_lines,\n                    )\n\n            if sys.version_info < (3, 13):\n\n                def _from_module(self, module, object):\n                    \"\"\"`cached_property` objects are never considered a part\n                    of the 'current module'. As such they are skipped by doctest.\n                    Here we override `_from_module` to check the underlying\n                    function instead. https://github.com/python/cpython/issues/107995\n                    \"\"\"\n                    if isinstance(object, functools.cached_property):\n                        object = object.func\n\n                    # Type ignored because this is a private function.\n                    return super()._from_module(module, object)  # type: ignore[misc]\n\n        try:\n            module = self.obj\n        except Collector.CollectError:\n            if self.config.getvalue(\"doctest_ignore_import_errors\"):\n                skip(f\"unable to import module {self.path!r}\")\n            else:\n                raise\n\n        # While doctests currently don't support fixtures directly, we still\n        # need to pick up autouse fixtures.\n        self.session._fixturemanager.parsefactories(self)\n\n        # Uses internal doctest module parsing mechanism.\n        finder = MockAwareDocTestFinder()\n        optionflags = get_optionflags(self.config)\n        runner = _get_runner(\n            verbose=False,\n            optionflags=optionflags,\n            checker=_get_checker(),\n            continue_on_failure=_get_continue_on_failure(self.config),\n        )\n\n        for test in finder.find(module, module.__name__):\n            if test.examples:  # skip empty doctests\n                yield DoctestItem.from_parent(\n                    self, name=test.name, runner=runner, dtest=test\n                )\n\n\ndef _init_checker_class() -> type[doctest.OutputChecker]:\n    import doctest\n\n    class LiteralsOutputChecker(doctest.OutputChecker):\n        # Based on doctest_nose_plugin.py from the nltk project\n        # (https://github.com/nltk/nltk) and on the \"numtest\" doctest extension\n        # by Sebastien Boisgerault (https://github.com/boisgera/numtest).\n\n        _unicode_literal_re = re.compile(r\"(\\W|^)[uU]([rR]?[\\'\\\"])\", re.UNICODE)\n        _bytes_literal_re = re.compile(r\"(\\W|^)[bB]([rR]?[\\'\\\"])\", re.UNICODE)\n        _number_re = re.compile(\n            r\"\"\"\n            (?P<number>\n              (?P<mantissa>\n                (?P<integer1> [+-]?\\d*)\\.(?P<fraction>\\d+)\n                |\n                (?P<integer2> [+-]?\\d+)\\.\n              )\n              (?:\n                [Ee]\n                (?P<exponent1> [+-]?\\d+)\n              )?\n              |\n              (?P<integer3> [+-]?\\d+)\n              (?:\n                [Ee]\n                (?P<exponent2> [+-]?\\d+)\n              )\n            )\n            \"\"\",\n            re.VERBOSE,\n        )\n\n        def check_output(self, want: str, got: str, optionflags: int) -> bool:\n            if super().check_output(want, got, optionflags):\n                return True\n\n            allow_unicode = optionflags & _get_allow_unicode_flag()\n            allow_bytes = optionflags & _get_allow_bytes_flag()\n            allow_number = optionflags & _get_number_flag()\n\n            if not allow_unicode and not allow_bytes and not allow_number:\n                return False\n\n            def remove_prefixes(regex: re.Pattern[str], txt: str) -> str:\n                return re.sub(regex, r\"\\1\\2\", txt)\n\n            if allow_unicode:\n                want = remove_prefixes(self._unicode_literal_re, want)\n                got = remove_prefixes(self._unicode_literal_re, got)\n\n            if allow_bytes:\n                want = remove_prefixes(self._bytes_literal_re, want)\n                got = remove_prefixes(self._bytes_literal_re, got)\n\n            if allow_number:\n                got = self._remove_unwanted_precision(want, got)\n\n            return super().check_output(want, got, optionflags)\n\n        def _remove_unwanted_precision(self, want: str, got: str) -> str:\n            wants = list(self._number_re.finditer(want))\n            gots = list(self._number_re.finditer(got))\n            if len(wants) != len(gots):\n                return got\n            offset = 0\n            for w, g in zip(wants, gots, strict=True):\n                fraction: str | None = w.group(\"fraction\")\n                exponent: str | None = w.group(\"exponent1\")\n                if exponent is None:\n                    exponent = w.group(\"exponent2\")\n                precision = 0 if fraction is None else len(fraction)\n                if exponent is not None:\n                    precision -= int(exponent)\n                if float(w.group()) == approx(float(g.group()), abs=10**-precision):\n                    # They're close enough. Replace the text we actually\n                    # got with the text we want, so that it will match when we\n                    # check the string literally.\n                    got = (\n                        got[: g.start() + offset] + w.group() + got[g.end() + offset :]\n                    )\n                    offset += w.end() - w.start() - (g.end() - g.start())\n            return got\n\n    return LiteralsOutputChecker\n\n\ndef _get_checker() -> doctest.OutputChecker:\n    \"\"\"Return a doctest.OutputChecker subclass that supports some\n    additional options:\n\n    * ALLOW_UNICODE and ALLOW_BYTES options to ignore u'' and b''\n      prefixes (respectively) in string literals. Useful when the same\n      doctest should run in Python 2 and Python 3.\n\n    * NUMBER to ignore floating-point differences smaller than the\n      precision of the literal number in the doctest.\n\n    An inner class is used to avoid importing \"doctest\" at the module\n    level.\n    \"\"\"\n    global CHECKER_CLASS\n    if CHECKER_CLASS is None:\n        CHECKER_CLASS = _init_checker_class()\n    return CHECKER_CLASS()\n\n\ndef _get_allow_unicode_flag() -> int:\n    \"\"\"Register and return the ALLOW_UNICODE flag.\"\"\"\n    import doctest\n\n    return doctest.register_optionflag(\"ALLOW_UNICODE\")\n\n\ndef _get_allow_bytes_flag() -> int:\n    \"\"\"Register and return the ALLOW_BYTES flag.\"\"\"\n    import doctest\n\n    return doctest.register_optionflag(\"ALLOW_BYTES\")\n\n\ndef _get_number_flag() -> int:\n    \"\"\"Register and return the NUMBER flag.\"\"\"\n    import doctest\n\n    return doctest.register_optionflag(\"NUMBER\")\n\n\ndef _get_report_choice(key: str) -> int:\n    \"\"\"Return the actual `doctest` module flag value.\n\n    We want to do it as late as possible to avoid importing `doctest` and all\n    its dependencies when parsing options, as it adds overhead and breaks tests.\n    \"\"\"\n    import doctest\n\n    return {\n        DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,\n        DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,\n        DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,\n        DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,\n        DOCTEST_REPORT_CHOICE_NONE: 0,\n    }[key]\n\n\n@fixture(scope=\"session\")\ndef doctest_namespace() -> dict[str, Any]:\n    \"\"\"Fixture that returns a :py:class:`dict` that will be injected into the\n    namespace of doctests.\n\n    Usually this fixture is used in conjunction with another ``autouse`` fixture:\n\n    .. code-block:: python\n\n        @pytest.fixture(autouse=True)\n        def add_np(doctest_namespace):\n            doctest_namespace[\"np\"] = numpy\n\n    For more details: :ref:`doctest_namespace`.\n    \"\"\"\n    return dict()\n"
  },
  {
    "path": "src/_pytest/faulthandler.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Generator\nimport os\nimport sys\n\nfrom _pytest.config import Config\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.nodes import Item\nfrom _pytest.stash import StashKey\nimport pytest\n\n\nfault_handler_original_stderr_fd_key = StashKey[int]()\nfault_handler_stderr_fd_key = StashKey[int]()\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    help_timeout = (\n        \"Dump the traceback of all threads if a test takes \"\n        \"more than TIMEOUT seconds to finish\"\n    )\n    help_exit_on_timeout = (\n        \"Exit the test process if a test takes more than \"\n        \"faulthandler_timeout seconds to finish\"\n    )\n    parser.addini(\"faulthandler_timeout\", help_timeout, default=0.0)\n    parser.addini(\n        \"faulthandler_exit_on_timeout\", help_exit_on_timeout, type=\"bool\", default=False\n    )\n\n\ndef pytest_configure(config: Config) -> None:\n    import faulthandler\n\n    # at teardown we want to restore the original faulthandler fileno\n    # but faulthandler has no api to return the original fileno\n    # so here we stash the stderr fileno to be used at teardown\n    # sys.stderr and sys.__stderr__ may be closed or patched during the session\n    # so we can't rely on their values being good at that point (#11572).\n    stderr_fileno = get_stderr_fileno()\n    if faulthandler.is_enabled():\n        config.stash[fault_handler_original_stderr_fd_key] = stderr_fileno\n    config.stash[fault_handler_stderr_fd_key] = os.dup(stderr_fileno)\n    faulthandler.enable(file=config.stash[fault_handler_stderr_fd_key])\n\n\ndef pytest_unconfigure(config: Config) -> None:\n    import faulthandler\n\n    faulthandler.disable()\n    # Close the dup file installed during pytest_configure.\n    if fault_handler_stderr_fd_key in config.stash:\n        os.close(config.stash[fault_handler_stderr_fd_key])\n        del config.stash[fault_handler_stderr_fd_key]\n    # Re-enable the faulthandler if it was originally enabled.\n    if fault_handler_original_stderr_fd_key in config.stash:\n        faulthandler.enable(config.stash[fault_handler_original_stderr_fd_key])\n        del config.stash[fault_handler_original_stderr_fd_key]\n\n\ndef get_stderr_fileno() -> int:\n    try:\n        fileno = sys.stderr.fileno()\n        # The Twisted Logger will return an invalid file descriptor since it is not backed\n        # by an FD. So, let's also forward this to the same code path as with pytest-xdist.\n        if fileno == -1:\n            raise AttributeError()\n        return fileno\n    except (AttributeError, ValueError):\n        # pytest-xdist monkeypatches sys.stderr with an object that is not an actual file.\n        # https://docs.python.org/3/library/faulthandler.html#issue-with-file-descriptors\n        # This is potentially dangerous, but the best we can do.\n        assert sys.__stderr__ is not None\n        return sys.__stderr__.fileno()\n\n\ndef get_timeout_config_value(config: Config) -> float:\n    return float(config.getini(\"faulthandler_timeout\") or 0.0)\n\n\ndef get_exit_on_timeout_config_value(config: Config) -> bool:\n    exit_on_timeout = config.getini(\"faulthandler_exit_on_timeout\")\n    assert isinstance(exit_on_timeout, bool)\n    return exit_on_timeout\n\n\n@pytest.hookimpl(wrapper=True, trylast=True)\ndef pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:\n    timeout = get_timeout_config_value(item.config)\n    exit_on_timeout = get_exit_on_timeout_config_value(item.config)\n    if timeout > 0:\n        import faulthandler\n\n        stderr = item.config.stash[fault_handler_stderr_fd_key]\n        faulthandler.dump_traceback_later(timeout, file=stderr, exit=exit_on_timeout)\n        try:\n            return (yield)\n        finally:\n            faulthandler.cancel_dump_traceback_later()\n    else:\n        return (yield)\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_enter_pdb() -> None:\n    \"\"\"Cancel any traceback dumping due to timeout before entering pdb.\"\"\"\n    import faulthandler\n\n    faulthandler.cancel_dump_traceback_later()\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_exception_interact() -> None:\n    \"\"\"Cancel any traceback dumping due to an interactive exception being\n    raised.\"\"\"\n    import faulthandler\n\n    faulthandler.cancel_dump_traceback_later()\n"
  },
  {
    "path": "src/_pytest/fixtures.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport abc\nfrom collections import defaultdict\nfrom collections import deque\nfrom collections import OrderedDict\nfrom collections.abc import Callable\nfrom collections.abc import Generator\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nfrom collections.abc import Mapping\nfrom collections.abc import MutableMapping\nfrom collections.abc import Sequence\nfrom collections.abc import Set as AbstractSet\nimport dataclasses\nimport functools\nimport inspect\nimport os\nfrom pathlib import Path\nimport sys\nimport types\nfrom typing import Any\nfrom typing import cast\nfrom typing import Final\nfrom typing import final\nfrom typing import Generic\nfrom typing import Literal\nfrom typing import NoReturn\nfrom typing import overload\nfrom typing import TYPE_CHECKING\nfrom typing import TypeVar\nimport warnings\n\nimport _pytest\nfrom _pytest import nodes\nfrom _pytest._code import getfslineno\nfrom _pytest._code import Source\nfrom _pytest._code.code import FormattedExcinfo\nfrom _pytest._code.code import TerminalRepr\nfrom _pytest._io import TerminalWriter\nfrom _pytest.compat import assert_never\nfrom _pytest.compat import get_real_func\nfrom _pytest.compat import getfuncargnames\nfrom _pytest.compat import getimfunc\nfrom _pytest.compat import getlocation\nfrom _pytest.compat import NOTSET\nfrom _pytest.compat import NotSetType\nfrom _pytest.compat import safe_getattr\nfrom _pytest.compat import safe_isclass\nfrom _pytest.compat import signature\nfrom _pytest.config import _PluggyPlugin\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.deprecated import FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN\nfrom _pytest.deprecated import YIELD_FIXTURE\nfrom _pytest.main import Session\nfrom _pytest.mark import ParameterSet\nfrom _pytest.mark.structures import MarkDecorator\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import skip\nfrom _pytest.outcomes import TEST_OUTCOME\nfrom _pytest.pathlib import absolutepath\nfrom _pytest.pathlib import bestrelpath\nfrom _pytest.scope import _ScopeName\nfrom _pytest.scope import HIGH_SCOPES\nfrom _pytest.scope import Scope\nfrom _pytest.warning_types import PytestWarning\n\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import BaseExceptionGroup\n\n\nif TYPE_CHECKING:\n    from _pytest.python import CallSpec2\n    from _pytest.python import Function\n    from _pytest.python import Metafunc\n\n\n# The value of the fixture -- return/yield of the fixture function (type variable).\nFixtureValue = TypeVar(\"FixtureValue\", covariant=True)\n# The type of the fixture function (type variable).\nFixtureFunction = TypeVar(\"FixtureFunction\", bound=Callable[..., object])\n# The type of a fixture function (type alias generic in fixture value).\n_FixtureFunc = Callable[..., FixtureValue] | Callable[..., Generator[FixtureValue]]\n# The type of FixtureDef.cached_result (type alias generic in fixture value).\n_FixtureCachedResult = (\n    tuple[\n        # The result.\n        FixtureValue,\n        # Cache key.\n        object,\n        None,\n    ]\n    | tuple[\n        None,\n        # Cache key.\n        object,\n        # The exception and the original traceback.\n        tuple[BaseException, types.TracebackType | None],\n    ]\n)\n\n\ndef pytest_sessionstart(session: Session) -> None:\n    session._fixturemanager = FixtureManager(session)\n\n\ndef get_scope_package(\n    node: nodes.Item,\n    fixturedef: FixtureDef[object],\n) -> nodes.Node | None:\n    from _pytest.python import Package\n\n    for parent in node.iter_parents():\n        if isinstance(parent, Package) and parent.nodeid == fixturedef.baseid:\n            return parent\n    return node.session\n\n\ndef get_scope_node(node: nodes.Node, scope: Scope) -> nodes.Node | None:\n    \"\"\"Get the closest parent node (including self) which matches the given\n    scope.\n\n    If there is no parent node for the scope (e.g. asking for class scope on a\n    Module, or on a Function when not defined in a class), returns None.\n    \"\"\"\n    import _pytest.python\n\n    if scope is Scope.Function:\n        # Type ignored because this is actually safe, see:\n        # https://github.com/python/mypy/issues/4717\n        return node.getparent(nodes.Item)  # type: ignore[type-abstract]\n    elif scope is Scope.Class:\n        return node.getparent(_pytest.python.Class)\n    elif scope is Scope.Module:\n        return node.getparent(_pytest.python.Module)\n    elif scope is Scope.Package:\n        return node.getparent(_pytest.python.Package)\n    elif scope is Scope.Session:\n        return node.getparent(_pytest.main.Session)\n    else:\n        assert_never(scope)\n\n\n# TODO: Try to use FixtureFunctionDefinition instead of the marker\ndef getfixturemarker(obj: object) -> FixtureFunctionMarker | None:\n    \"\"\"Return fixturemarker or None if it doesn't exist\"\"\"\n    if isinstance(obj, FixtureFunctionDefinition):\n        return obj._fixture_function_marker\n    return None\n\n\n# Algorithm for sorting on a per-parametrized resource setup basis.\n# It is called for Session scope first and performs sorting\n# down to the lower scopes such as to minimize number of \"high scope\"\n# setups and teardowns.\n\n\n@dataclasses.dataclass(frozen=True)\nclass ParamArgKey:\n    \"\"\"A key for a high-scoped parameter used by an item.\n\n    For use as a hashable key in `reorder_items`. The combination of fields\n    is meant to uniquely identify a particular \"instance\" of a param,\n    potentially shared by multiple items in a scope.\n    \"\"\"\n\n    #: The param name.\n    argname: str\n    param_index: int\n    #: For scopes Package, Module, Class, the path to the file (directory in\n    #: Package's case) of the package/module/class where the item is defined.\n    scoped_item_path: Path | None\n    #: For Class scope, the class where the item is defined.\n    item_cls: type | None\n\n\n_V = TypeVar(\"_V\")\nOrderedSet = dict[_V, None]\n\n\ndef get_param_argkeys(item: nodes.Item, scope: Scope) -> Iterator[ParamArgKey]:\n    \"\"\"Return all ParamArgKeys for item matching the specified high scope.\"\"\"\n    assert scope is not Scope.Function\n\n    try:\n        callspec: CallSpec2 = item.callspec  # type: ignore[attr-defined]\n    except AttributeError:\n        return\n\n    item_cls = None\n    if scope is Scope.Session:\n        scoped_item_path = None\n    elif scope is Scope.Package:\n        # Package key = module's directory.\n        scoped_item_path = item.path.parent\n    elif scope is Scope.Module:\n        scoped_item_path = item.path\n    elif scope is Scope.Class:\n        scoped_item_path = item.path\n        item_cls = item.cls  # type: ignore[attr-defined]\n    else:\n        assert_never(scope)\n\n    for argname in callspec.indices:\n        if callspec._arg2scope[argname] != scope:\n            continue\n        param_index = callspec.indices[argname]\n        yield ParamArgKey(argname, param_index, scoped_item_path, item_cls)\n\n\ndef reorder_items(items: Sequence[nodes.Item]) -> list[nodes.Item]:\n    argkeys_by_item: dict[Scope, dict[nodes.Item, OrderedSet[ParamArgKey]]] = {}\n    items_by_argkey: dict[Scope, dict[ParamArgKey, OrderedDict[nodes.Item, None]]] = {}\n    for scope in HIGH_SCOPES:\n        scoped_argkeys_by_item = argkeys_by_item[scope] = {}\n        scoped_items_by_argkey = items_by_argkey[scope] = defaultdict(OrderedDict)\n        for item in items:\n            argkeys = dict.fromkeys(get_param_argkeys(item, scope))\n            if argkeys:\n                scoped_argkeys_by_item[item] = argkeys\n                for argkey in argkeys:\n                    scoped_items_by_argkey[argkey][item] = None\n\n    items_set = dict.fromkeys(items)\n    return list(\n        reorder_items_atscope(\n            items_set, argkeys_by_item, items_by_argkey, Scope.Session\n        )\n    )\n\n\ndef reorder_items_atscope(\n    items: OrderedSet[nodes.Item],\n    argkeys_by_item: Mapping[Scope, Mapping[nodes.Item, OrderedSet[ParamArgKey]]],\n    items_by_argkey: Mapping[\n        Scope, Mapping[ParamArgKey, OrderedDict[nodes.Item, None]]\n    ],\n    scope: Scope,\n) -> OrderedSet[nodes.Item]:\n    if scope is Scope.Function or len(items) < 3:\n        return items\n\n    scoped_items_by_argkey = items_by_argkey[scope]\n    scoped_argkeys_by_item = argkeys_by_item[scope]\n\n    ignore: set[ParamArgKey] = set()\n    items_deque = deque(items)\n    items_done: OrderedSet[nodes.Item] = {}\n    while items_deque:\n        no_argkey_items: OrderedSet[nodes.Item] = {}\n        slicing_argkey = None\n        while items_deque:\n            item = items_deque.popleft()\n            if item in items_done or item in no_argkey_items:\n                continue\n            argkeys = dict.fromkeys(\n                k for k in scoped_argkeys_by_item.get(item, ()) if k not in ignore\n            )\n            if not argkeys:\n                no_argkey_items[item] = None\n            else:\n                slicing_argkey, _ = argkeys.popitem()\n                # We don't have to remove relevant items from later in the\n                # deque because they'll just be ignored.\n                matching_items = [\n                    i for i in scoped_items_by_argkey[slicing_argkey] if i in items\n                ]\n                for i in reversed(matching_items):\n                    items_deque.appendleft(i)\n                    # Fix items_by_argkey order.\n                    for other_scope in HIGH_SCOPES:\n                        other_scoped_items_by_argkey = items_by_argkey[other_scope]\n                        for argkey in argkeys_by_item[other_scope].get(i, ()):\n                            argkey_dict = other_scoped_items_by_argkey[argkey]\n                            if not hasattr(sys, \"pypy_version_info\"):\n                                argkey_dict[i] = None\n                                argkey_dict.move_to_end(i, last=False)\n                            else:\n                                # Work around a bug in PyPy:\n                                # https://github.com/pypy/pypy/issues/5257\n                                # https://github.com/pytest-dev/pytest/issues/13312\n                                bkp = argkey_dict.copy()\n                                argkey_dict.clear()\n                                argkey_dict[i] = None\n                                argkey_dict.update(bkp)\n                break\n        if no_argkey_items:\n            reordered_no_argkey_items = reorder_items_atscope(\n                no_argkey_items, argkeys_by_item, items_by_argkey, scope.next_lower()\n            )\n            items_done.update(reordered_no_argkey_items)\n        if slicing_argkey is not None:\n            ignore.add(slicing_argkey)\n    return items_done\n\n\n@dataclasses.dataclass(frozen=True)\nclass FuncFixtureInfo:\n    \"\"\"Fixture-related information for a fixture-requesting item (e.g. test\n    function).\n\n    This is used to examine the fixtures which an item requests statically\n    (known during collection). This includes autouse fixtures, fixtures\n    requested by the `usefixtures` marker, fixtures requested in the function\n    parameters, and the transitive closure of these.\n\n    An item may also request fixtures dynamically (using `request.getfixturevalue`);\n    these are not reflected here.\n    \"\"\"\n\n    __slots__ = (\"argnames\", \"initialnames\", \"name2fixturedefs\", \"names_closure\")\n\n    # Fixture names that the item requests directly by function parameters.\n    argnames: tuple[str, ...]\n    # Fixture names that the item immediately requires. These include\n    # argnames + fixture names specified via usefixtures and via autouse=True in\n    # fixture definitions.\n    initialnames: tuple[str, ...]\n    # The transitive closure of the fixture names that the item requires.\n    # Note: can't include dynamic dependencies (`request.getfixturevalue` calls).\n    names_closure: list[str]\n    # A map from a fixture name in the transitive closure to the FixtureDefs\n    # matching the name which are applicable to this function.\n    # There may be multiple overriding fixtures with the same name. The\n    # sequence is ordered from furthest to closes to the function.\n    name2fixturedefs: dict[str, Sequence[FixtureDef[Any]]]\n\n    def prune_dependency_tree(self) -> None:\n        \"\"\"Recompute names_closure from initialnames and name2fixturedefs.\n\n        Can only reduce names_closure, which means that the new closure will\n        always be a subset of the old one. The order is preserved.\n\n        This method is needed because direct parametrization may shadow some\n        of the fixtures that were included in the originally built dependency\n        tree. In this way the dependency tree can get pruned, and the closure\n        of argnames may get reduced.\n        \"\"\"\n        closure: set[str] = set()\n        working_set = set(self.initialnames)\n        while working_set:\n            argname = working_set.pop()\n            if argname not in closure and argname in self.names_closure:\n                closure.add(argname)\n                if argname in self.name2fixturedefs:\n                    working_set.update(self.name2fixturedefs[argname][-1].argnames)\n\n        self.names_closure[:] = sorted(closure, key=self.names_closure.index)\n\n\nclass FixtureRequest(abc.ABC):\n    \"\"\"The type of the ``request`` fixture.\n\n    A request object gives access to the requesting test context and has a\n    ``param`` attribute in case the fixture is parametrized.\n    \"\"\"\n\n    def __init__(\n        self,\n        pyfuncitem: Function,\n        fixturename: str | None,\n        arg2fixturedefs: Mapping[str, Sequence[FixtureDef[Any]]],\n        fixture_defs: dict[str, FixtureDef[Any]],\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        #: Fixture for which this request is being performed.\n        self.fixturename: Final = fixturename\n        self._pyfuncitem: Final = pyfuncitem\n        # The FixtureDefs for each fixture name statically requested by this\n        # item (computed during collection). Dynamically requested fixtures\n        # (using `request.getfixturevalue(\"foo\")`) are not included here.\n        self._arg2fixturedefs: Final = arg2fixturedefs\n        # The evaluated argnames so far, mapping to the FixtureDef they resolved\n        # to.\n        self._fixture_defs: Final = fixture_defs\n        # Notes on the type of `param`:\n        # -`request.param` is only defined in parametrized fixtures, and will raise\n        #   AttributeError otherwise. Python typing has no notion of \"undefined\", so\n        #   this cannot be reflected in the type.\n        # - Technically `param` is only (possibly) defined on SubRequest, not\n        #   FixtureRequest, but the typing of that is still in flux so this cheats.\n        # - In the future we might consider using a generic for the param type, but\n        #   for now just using Any.\n        self.param: Any\n\n    @property\n    def _fixturemanager(self) -> FixtureManager:\n        return self._pyfuncitem.session._fixturemanager\n\n    @property\n    @abc.abstractmethod\n    def _scope(self) -> Scope:\n        raise NotImplementedError()\n\n    @property\n    def scope(self) -> _ScopeName:\n        \"\"\"Scope string, one of \"function\", \"class\", \"module\", \"package\", \"session\".\"\"\"\n        return self._scope.value\n\n    @abc.abstractmethod\n    def _check_scope(\n        self,\n        requested_fixturedef: FixtureDef[object],\n        requested_scope: Scope,\n    ) -> None:\n        raise NotImplementedError()\n\n    @property\n    def fixturenames(self) -> list[str]:\n        \"\"\"Names of all active fixtures in this request.\"\"\"\n        result = list(self._pyfuncitem.fixturenames)\n        result.extend(set(self._fixture_defs).difference(result))\n        return result\n\n    @property\n    @abc.abstractmethod\n    def node(self):\n        \"\"\"Underlying collection node (depends on current request scope).\"\"\"\n        raise NotImplementedError()\n\n    @property\n    def config(self) -> Config:\n        \"\"\"The pytest config object associated with this request.\"\"\"\n        return self._pyfuncitem.config\n\n    @property\n    def function(self):\n        \"\"\"Test function object if the request has a per-function scope.\"\"\"\n        if self.scope != \"function\":\n            raise AttributeError(\n                f\"function not available in {self.scope}-scoped context\"\n            )\n        return self._pyfuncitem.obj\n\n    @property\n    def cls(self):\n        \"\"\"Class (can be None) where the test function was collected.\"\"\"\n        if self.scope not in (\"class\", \"function\"):\n            raise AttributeError(f\"cls not available in {self.scope}-scoped context\")\n        clscol = self._pyfuncitem.getparent(_pytest.python.Class)\n        if clscol:\n            return clscol.obj\n\n    @property\n    def instance(self):\n        \"\"\"Instance (can be None) on which test function was collected.\"\"\"\n        if self.scope != \"function\":\n            return None\n        return getattr(self._pyfuncitem, \"instance\", None)\n\n    @property\n    def module(self):\n        \"\"\"Python module object where the test function was collected.\"\"\"\n        if self.scope not in (\"function\", \"class\", \"module\"):\n            raise AttributeError(f\"module not available in {self.scope}-scoped context\")\n        mod = self._pyfuncitem.getparent(_pytest.python.Module)\n        assert mod is not None\n        return mod.obj\n\n    @property\n    def path(self) -> Path:\n        \"\"\"Path where the test function was collected.\"\"\"\n        if self.scope not in (\"function\", \"class\", \"module\", \"package\"):\n            raise AttributeError(f\"path not available in {self.scope}-scoped context\")\n        return self._pyfuncitem.path\n\n    @property\n    def keywords(self) -> MutableMapping[str, Any]:\n        \"\"\"Keywords/markers dictionary for the underlying node.\"\"\"\n        node: nodes.Node = self.node\n        return node.keywords\n\n    @property\n    def session(self) -> Session:\n        \"\"\"Pytest session object.\"\"\"\n        return self._pyfuncitem.session\n\n    @abc.abstractmethod\n    def addfinalizer(self, finalizer: Callable[[], object]) -> None:\n        \"\"\"Add finalizer/teardown function to be called without arguments after\n        the last test within the requesting test context finished execution.\"\"\"\n        raise NotImplementedError()\n\n    def applymarker(self, marker: str | MarkDecorator) -> None:\n        \"\"\"Apply a marker to a single test function invocation.\n\n        This method is useful if you don't want to have a keyword/marker\n        on all function invocations.\n\n        :param marker:\n            An object created by a call to ``pytest.mark.NAME(...)``.\n        \"\"\"\n        self.node.add_marker(marker)\n\n    def raiseerror(self, msg: str | None) -> NoReturn:\n        \"\"\"Raise a FixtureLookupError exception.\n\n        :param msg:\n            An optional custom error message.\n        \"\"\"\n        raise FixtureLookupError(None, self, msg)\n\n    def _raise_teardown_lookup_error(self, argname: str) -> NoReturn:\n        msg = (\n            f'The fixture value for \"{argname}\" is not available during teardown '\n            \"because it was not previously requested.\\n\"\n            \"Only fixtures that were already active can be retrieved during teardown.\\n\"\n            \"Request the fixture before teardown begins by declaring it in the fixture \"\n            \"signature or by calling request.getfixturevalue() before the fixture yields.\"\n        )\n        raise FixtureLookupError(argname, self, msg)\n\n    def getfixturevalue(self, argname: str) -> Any:\n        \"\"\"Dynamically run a named fixture function.\n\n        Declaring fixtures via function argument is recommended where possible.\n        But if you can only decide whether to use another fixture at test\n        setup time, you may use this function to retrieve it inside a fixture\n        or test function body.\n\n        This method can be used during the test setup phase or the test run\n        phase. Avoid using it during the teardown phase.\n\n        .. versionchanged:: 9.1\n            Calling ``request.getfixturevalue()`` during teardown to request a\n            fixture that was not already requested\n            :ref:`is deprecated <dynamic-fixture-request-during-teardown>`.\n\n        :param argname:\n            The fixture name.\n        :raises pytest.FixtureLookupError:\n            If the given fixture could not be found.\n        \"\"\"\n        # Note that in addition to the use case described in the docstring,\n        # getfixturevalue() is also called by pytest itself during item and fixture\n        # setup to evaluate the fixtures that are requested statically\n        # (using function parameters, autouse, etc).\n\n        fixturedef = self._get_active_fixturedef(argname)\n        assert fixturedef.cached_result is not None, (\n            f'The fixture value for \"{argname}\" is not available.  '\n            \"This can happen when the fixture has already been torn down.\"\n        )\n        return fixturedef.cached_result[0]\n\n    def _iter_chain(self) -> Iterator[SubRequest]:\n        \"\"\"Yield all SubRequests in the chain, from self up.\n\n        Note: does *not* yield the TopRequest.\n        \"\"\"\n        current = self\n        while isinstance(current, SubRequest):\n            yield current\n            current = current._parent_request\n\n    def _get_active_fixturedef(self, argname: str) -> FixtureDef[object]:\n        if argname == \"request\":\n            return RequestFixtureDef(self)\n\n        # If we already finished computing a fixture by this name in this item,\n        # return it.\n        fixturedef = self._fixture_defs.get(argname)\n        if fixturedef is not None:\n            self._check_scope(fixturedef, fixturedef._scope)\n            return fixturedef\n\n        # Find the appropriate fixturedef.\n        fixturedefs = self._arg2fixturedefs.get(argname, None)\n        if fixturedefs is None:\n            # We arrive here because of a dynamic call to\n            # getfixturevalue(argname) which was naturally\n            # not known at parsing/collection time.\n            fixturedefs = self._fixturemanager.getfixturedefs(argname, self._pyfuncitem)\n        # No fixtures defined with this name.\n        if fixturedefs is None:\n            raise FixtureLookupError(argname, self)\n        # The are no fixtures with this name applicable for the function.\n        if not fixturedefs:\n            raise FixtureLookupError(argname, self)\n\n        # A fixture may override another fixture with the same name, e.g. a\n        # fixture in a module can override a fixture in a conftest, a fixture in\n        # a class can override a fixture in the module, and so on.\n        # An overriding fixture can request its own name (possibly indirectly);\n        # in this case it gets the value of the fixture it overrides, one level\n        # up.\n        # Check how many `argname`s deep we are, and take the next one.\n        # `fixturedefs` is sorted from furthest to closest, so use negative\n        # indexing to go in reverse.\n        index = -1\n        for request in self._iter_chain():\n            if request.fixturename == argname:\n                index -= 1\n        # If already consumed all of the available levels, fail.\n        if -index > len(fixturedefs):\n            raise FixtureLookupError(argname, self)\n        fixturedef = fixturedefs[index]\n\n        # Prepare a SubRequest object for calling the fixture.\n        try:\n            callspec = self._pyfuncitem.callspec\n        except AttributeError:\n            callspec = None\n        if callspec is not None and argname in callspec.params:\n            param = callspec.params[argname]\n            param_index = callspec.indices[argname]\n            # The parametrize invocation scope overrides the fixture's scope.\n            scope = callspec._arg2scope[argname]\n        else:\n            param = NOTSET\n            param_index = 0\n            scope = fixturedef._scope\n            self._check_fixturedef_without_param(fixturedef)\n        # The parametrize invocation scope only controls caching behavior while\n        # allowing wider-scoped fixtures to keep depending on the parametrized\n        # fixture. Scope control is enforced for parametrized fixtures\n        # by recreating the whole fixture tree on parameter change.\n        # Hence `fixturedef._scope`, not `scope`.\n        self._check_scope(fixturedef, fixturedef._scope)\n        subrequest = SubRequest(\n            self, scope, param, param_index, fixturedef, _ispytest=True\n        )\n\n        if not self.session._setupstate.is_node_active(self.node):\n            # TODO(pytest10.1): Remove the `warn` and `if` and call\n            # _raise_teardown_lookup_error unconditionally.\n            warnings.warn(\n                FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN.format(argname=argname),\n                stacklevel=3,\n            )\n            if subrequest.node not in self.session._setupstate.stack:\n                self._raise_teardown_lookup_error(argname)\n\n        # Make sure the fixture value is cached, running it if it isn't\n        fixturedef.execute(request=subrequest)\n\n        self._fixture_defs[argname] = fixturedef\n        return fixturedef\n\n    def _check_fixturedef_without_param(self, fixturedef: FixtureDef[object]) -> None:\n        \"\"\"Check that this request is allowed to execute this fixturedef without\n        a param.\"\"\"\n        funcitem = self._pyfuncitem\n        has_params = fixturedef.params is not None\n        fixtures_not_supported = getattr(funcitem, \"nofuncargs\", False)\n        if has_params and fixtures_not_supported:\n            msg = (\n                f\"{funcitem.name} does not support fixtures, maybe unittest.TestCase subclass?\\n\"\n                f\"Node id: {funcitem.nodeid}\\n\"\n                f\"Function type: {type(funcitem).__name__}\"\n            )\n            fail(msg, pytrace=False)\n        if has_params:\n            frame = inspect.stack()[3]\n            frameinfo = inspect.getframeinfo(frame[0])\n            source_path = absolutepath(frameinfo.filename)\n            source_lineno = frameinfo.lineno\n            try:\n                source_path_str = str(source_path.relative_to(funcitem.config.rootpath))\n            except ValueError:\n                source_path_str = str(source_path)\n            location = getlocation(fixturedef.func, funcitem.config.rootpath)\n            msg = (\n                \"The requested fixture has no parameter defined for test:\\n\"\n                f\"    {funcitem.nodeid}\\n\\n\"\n                f\"Requested fixture '{fixturedef.argname}' defined in:\\n\"\n                f\"{location}\\n\\n\"\n                f\"Requested here:\\n\"\n                f\"{source_path_str}:{source_lineno}\"\n            )\n            fail(msg, pytrace=False)\n\n    def _get_fixturestack(self) -> list[FixtureDef[Any]]:\n        values = [request._fixturedef for request in self._iter_chain()]\n        values.reverse()\n        return values\n\n\n@final\nclass TopRequest(FixtureRequest):\n    \"\"\"The type of the ``request`` fixture in a test function.\"\"\"\n\n    def __init__(self, pyfuncitem: Function, *, _ispytest: bool = False) -> None:\n        super().__init__(\n            fixturename=None,\n            pyfuncitem=pyfuncitem,\n            arg2fixturedefs=pyfuncitem._fixtureinfo.name2fixturedefs,\n            fixture_defs={},\n            _ispytest=_ispytest,\n        )\n\n    @property\n    def _scope(self) -> Scope:\n        return Scope.Function\n\n    def _check_scope(\n        self,\n        requested_fixturedef: FixtureDef[object],\n        requested_scope: Scope,\n    ) -> None:\n        # TopRequest always has function scope so always valid.\n        pass\n\n    @property\n    def node(self):\n        return self._pyfuncitem\n\n    def __repr__(self) -> str:\n        return f\"<FixtureRequest for {self.node!r}>\"\n\n    def _fillfixtures(self) -> None:\n        item = self._pyfuncitem\n        for argname in item.fixturenames:\n            if argname not in item.funcargs:\n                item.funcargs[argname] = self.getfixturevalue(argname)\n\n    def addfinalizer(self, finalizer: Callable[[], object]) -> None:\n        self.node.addfinalizer(finalizer)\n\n\n@final\nclass SubRequest(FixtureRequest):\n    \"\"\"The type of the ``request`` fixture in a fixture function requested\n    (transitively) by a test function.\"\"\"\n\n    def __init__(\n        self,\n        request: FixtureRequest,\n        scope: Scope,\n        param: Any,\n        param_index: int,\n        fixturedef: FixtureDef[object],\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        super().__init__(\n            pyfuncitem=request._pyfuncitem,\n            fixturename=fixturedef.argname,\n            fixture_defs=request._fixture_defs,\n            arg2fixturedefs=request._arg2fixturedefs,\n            _ispytest=_ispytest,\n        )\n        self._parent_request: Final[FixtureRequest] = request\n        self._fixturedef: Final[FixtureDef[object]] = fixturedef\n        if param is not NOTSET:\n            self.param = param\n        self.param_index: Final = param_index\n        self._scope_field: Final = scope\n        if scope is Scope.Function:\n            # This might also be a non-function Item despite its attribute name.\n            node: nodes.Node | None = self._pyfuncitem\n        elif scope is Scope.Package:\n            node = get_scope_package(self._pyfuncitem, self._fixturedef)\n        else:\n            node = get_scope_node(self._pyfuncitem, scope)\n        if node is None and scope is Scope.Class:\n            # Fallback to function item itself.\n            node = self._pyfuncitem\n        assert node, (\n            f'Could not obtain a node for scope \"{scope}\" for function {self._pyfuncitem!r}'\n        )\n        self._node: Final = node\n\n    def __repr__(self) -> str:\n        return f\"<SubRequest {self.fixturename!r} for {self._pyfuncitem!r}>\"\n\n    @property\n    def _scope(self) -> Scope:\n        return self._scope_field\n\n    @property\n    def node(self):\n        return self._node\n\n    def _check_scope(\n        self,\n        requested_fixturedef: FixtureDef[object],\n        requested_scope: Scope,\n    ) -> None:\n        if self._scope > requested_scope:\n            # Try to report something helpful.\n            argname = requested_fixturedef.argname\n            fixture_stack = \"\\n\".join(\n                self._format_fixturedef_line(fixturedef)\n                for fixturedef in self._get_fixturestack()\n            )\n            requested_fixture = self._format_fixturedef_line(requested_fixturedef)\n            fail(\n                f\"ScopeMismatch: You tried to access the {requested_scope.value} scoped \"\n                f\"fixture {argname} with a {self._scope.value} scoped request object. \"\n                f\"Requesting fixture stack:\\n{fixture_stack}\\n\"\n                f\"Requested fixture:\\n{requested_fixture}\",\n                pytrace=False,\n            )\n\n    def _format_fixturedef_line(self, fixturedef: FixtureDef[object]) -> str:\n        factory = fixturedef.func\n        path, lineno = getfslineno(factory)\n        if isinstance(path, Path):\n            path = bestrelpath(self._pyfuncitem.session.path, path)\n        sig = signature(factory)\n        return f\"{path}:{lineno + 1}:  def {factory.__name__}{sig}\"\n\n    def addfinalizer(self, finalizer: Callable[[], object]) -> None:\n        self._fixturedef.addfinalizer(finalizer)\n\n\n@final\nclass FixtureLookupError(LookupError):\n    \"\"\"Could not return a requested fixture (missing or invalid).\"\"\"\n\n    def __init__(\n        self, argname: str | None, request: FixtureRequest, msg: str | None = None\n    ) -> None:\n        self.argname = argname\n        self.request = request\n        self.fixturestack = request._get_fixturestack()\n        self.msg = msg\n\n    def formatrepr(self) -> FixtureLookupErrorRepr:\n        tblines: list[str] = []\n        addline = tblines.append\n        stack = [self.request._pyfuncitem.obj]\n        stack.extend(map(lambda x: x.func, self.fixturestack))\n        msg = self.msg\n        if msg is not None and len(stack) > 1:\n            # The last fixture raise an error, let's present\n            # it at the requesting side.\n            stack = stack[:-1]\n        for function in stack:\n            fspath, lineno = getfslineno(function)\n            try:\n                lines, _ = inspect.getsourcelines(get_real_func(function))\n            except (OSError, IndexError, TypeError):\n                error_msg = \"file %s, line %s: source code not available\"\n                addline(error_msg % (fspath, lineno + 1))\n            else:\n                addline(f\"file {fspath}, line {lineno + 1}\")\n                for i, line in enumerate(lines):\n                    line = line.rstrip()\n                    addline(\"  \" + line)\n                    if line.lstrip().startswith(\"def\"):\n                        break\n\n        if msg is None:\n            fm = self.request._fixturemanager\n            available = set()\n            parent = self.request._pyfuncitem.parent\n            assert parent is not None\n            for name, fixturedefs in fm._arg2fixturedefs.items():\n                faclist = list(fm._matchfactories(fixturedefs, parent))\n                if faclist:\n                    available.add(name)\n            if self.argname in available:\n                msg = (\n                    f\" recursive dependency involving fixture '{self.argname}' detected\"\n                )\n            else:\n                msg = f\"fixture '{self.argname}' not found\"\n            msg += \"\\n available fixtures: {}\".format(\", \".join(sorted(available)))\n            msg += \"\\n use 'pytest --fixtures [testpath]' for help on them.\"\n\n        return FixtureLookupErrorRepr(fspath, lineno, tblines, msg, self.argname)\n\n\nclass FixtureLookupErrorRepr(TerminalRepr):\n    def __init__(\n        self,\n        filename: str | os.PathLike[str],\n        firstlineno: int,\n        tblines: Sequence[str],\n        errorstring: str,\n        argname: str | None,\n    ) -> None:\n        self.tblines = tblines\n        self.errorstring = errorstring\n        self.filename = filename\n        self.firstlineno = firstlineno\n        self.argname = argname\n\n    def toterminal(self, tw: TerminalWriter) -> None:\n        # tw.line(\"FixtureLookupError: %s\" %(self.argname), red=True)\n        for tbline in self.tblines:\n            tw.line(tbline.rstrip())\n        lines = self.errorstring.split(\"\\n\")\n        if lines:\n            tw.line(\n                f\"{FormattedExcinfo.fail_marker}       {lines[0].strip()}\",\n                red=True,\n            )\n            for line in lines[1:]:\n                tw.line(\n                    f\"{FormattedExcinfo.flow_marker}       {line.strip()}\",\n                    red=True,\n                )\n        tw.line()\n        tw.line(f\"{os.fspath(self.filename)}:{self.firstlineno + 1}\")\n\n\ndef call_fixture_func(\n    fixturefunc: _FixtureFunc[FixtureValue], request: FixtureRequest, kwargs\n) -> FixtureValue:\n    if inspect.isgeneratorfunction(fixturefunc):\n        fixturefunc = cast(Callable[..., Generator[FixtureValue]], fixturefunc)\n        generator = fixturefunc(**kwargs)\n        try:\n            fixture_result = next(generator)\n        except StopIteration:\n            raise ValueError(f\"{request.fixturename} did not yield a value\") from None\n        finalizer = functools.partial(_teardown_yield_fixture, fixturefunc, generator)\n        request.addfinalizer(finalizer)\n    else:\n        fixturefunc = cast(Callable[..., FixtureValue], fixturefunc)\n        fixture_result = fixturefunc(**kwargs)\n    return fixture_result\n\n\ndef _teardown_yield_fixture(fixturefunc, it) -> None:\n    \"\"\"Execute the teardown of a fixture function by advancing the iterator\n    after the yield and ensure the iteration ends (if not it means there is\n    more than one yield in the function).\"\"\"\n    try:\n        next(it)\n    except StopIteration:\n        pass\n    else:\n        fs, lineno = getfslineno(fixturefunc)\n        fail(\n            f\"fixture function has more than one 'yield':\\n\\n\"\n            f\"{Source(fixturefunc).indent()}\\n\"\n            f\"{fs}:{lineno + 1}\",\n            pytrace=False,\n        )\n\n\ndef _eval_scope_callable(\n    scope_callable: Callable[[str, Config], _ScopeName],\n    fixture_name: str,\n    config: Config,\n) -> _ScopeName:\n    try:\n        # Type ignored because there is no typing mechanism to specify\n        # keyword arguments, currently.\n        result = scope_callable(fixture_name=fixture_name, config=config)  # type: ignore[call-arg]\n    except Exception as e:\n        raise TypeError(\n            f\"Error evaluating {scope_callable} while defining fixture '{fixture_name}'.\\n\"\n            \"Expected a function with the signature (*, fixture_name, config)\"\n        ) from e\n    if not isinstance(result, str):\n        fail(\n            f\"Expected {scope_callable} to return a 'str' while defining fixture '{fixture_name}', but it returned:\\n\"\n            f\"{result!r}\",\n            pytrace=False,\n        )\n    return result\n\n\nclass FixtureDef(Generic[FixtureValue]):\n    \"\"\"A container for a fixture definition.\n\n    Note: At this time, only explicitly documented fields and methods are\n    considered public stable API.\n    \"\"\"\n\n    def __init__(\n        self,\n        config: Config,\n        baseid: str | None,\n        argname: str,\n        func: _FixtureFunc[FixtureValue],\n        scope: Scope | _ScopeName | Callable[[str, Config], _ScopeName] | None,\n        params: Sequence[object] | None,\n        ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None,\n        *,\n        _ispytest: bool = False,\n        # only used in a deprecationwarning msg, can be removed in pytest9\n        _autouse: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        # The \"base\" node ID for the fixture.\n        #\n        # This is a node ID prefix. A fixture is only available to a node (e.g.\n        # a `Function` item) if the fixture's baseid is a nodeid of a parent of\n        # node.\n        #\n        # For a fixture found in a Collector's object (e.g. a `Module`s module,\n        # a `Class`'s class), the baseid is the Collector's nodeid.\n        #\n        # For a fixture found in a conftest plugin, the baseid is the conftest's\n        # directory path relative to the rootdir.\n        #\n        # For other plugins, the baseid is the empty string (always matches).\n        self.baseid: Final = baseid or \"\"\n        # Whether the fixture was found from a node or a conftest in the\n        # collection tree. Will be false for fixtures defined in non-conftest\n        # plugins.\n        self.has_location: Final = baseid is not None\n        # The fixture factory function.\n        self.func: Final = func\n        # The name by which the fixture may be requested.\n        self.argname: Final = argname\n        if scope is None:\n            scope = Scope.Function\n        elif callable(scope):\n            scope = _eval_scope_callable(scope, argname, config)\n        if isinstance(scope, str):\n            scope = Scope.from_user(\n                scope, descr=f\"Fixture '{func.__name__}'\", where=baseid\n            )\n        self._scope: Final = scope\n        # If the fixture is directly parametrized, the parameter values.\n        self.params: Final = params\n        # If the fixture is directly parametrized, a tuple of explicit IDs to\n        # assign to the parameter values, or a callable to generate an ID given\n        # a parameter value.\n        self.ids: Final = ids\n        # The names requested by the fixtures.\n        self.argnames: Final = getfuncargnames(func, name=argname)\n        # If the fixture was executed, the current value of the fixture.\n        # Can change if the fixture is executed with different parameters.\n        self.cached_result: _FixtureCachedResult[FixtureValue] | None = None\n        self._finalizers: Final[list[Callable[[], object]]] = []\n\n        # only used to emit a deprecationwarning, can be removed in pytest9\n        self._autouse = _autouse\n\n    @property\n    def scope(self) -> _ScopeName:\n        \"\"\"Scope string, one of \"function\", \"class\", \"module\", \"package\", \"session\".\"\"\"\n        return self._scope.value\n\n    def addfinalizer(self, finalizer: Callable[[], object]) -> None:\n        self._finalizers.append(finalizer)\n\n    def finish(self, request: SubRequest) -> None:\n        if self.cached_result is None:\n            # Already finished. It is assumed that finalizers cannot be added in\n            # this state.\n            return\n\n        exceptions: list[BaseException] = []\n        while self._finalizers:\n            fin = self._finalizers.pop()\n            try:\n                fin()\n            except BaseException as e:\n                exceptions.append(e)\n        node = request.node\n        # Even if finalization fails, we invalidate the cached fixture\n        # value and remove all finalizers because they may be bound methods\n        # which will keep instances alive.\n        self.cached_result = None\n        self._finalizers.clear()\n        if len(exceptions) == 1:\n            raise exceptions[0]\n        elif len(exceptions) > 1:\n            msg = f'errors while tearing down fixture \"{self.argname}\" of {node}'\n            raise BaseExceptionGroup(msg, exceptions[::-1])\n\n    def execute(self, request: SubRequest) -> FixtureValue:\n        \"\"\"Return the value of this fixture, executing it if not cached.\"\"\"\n        # Ensure that the dependent fixtures requested by this fixture are loaded.\n        # This needs to be done before checking if we have a cached value, since\n        # if a dependent fixture has their cache invalidated, e.g. due to\n        # parametrization, they finalize themselves and fixtures depending on it\n        # (which will likely include this fixture) setting `self.cached_result = None`.\n        # See #4871\n        requested_fixtures_that_should_finalize_us = []\n        for argname in self.argnames:\n            fixturedef = request._get_active_fixturedef(argname)\n            # Saves requested fixtures in a list so we later can add our finalizer\n            # to them, ensuring that if a requested fixture gets torn down we get torn\n            # down first. This is generally handled by SetupState, but still currently\n            # needed when this fixture is not parametrized but depends on a parametrized\n            # fixture.\n            requested_fixtures_that_should_finalize_us.append(fixturedef)\n\n        # Check for (and return) cached value/exception.\n        if self.cached_result is not None:\n            request_cache_key = self.cache_key(request)\n            cache_key = self.cached_result[1]\n            try:\n                # Attempt to make a normal == check: this might fail for objects\n                # which do not implement the standard comparison (like numpy arrays -- #6497).\n                cache_hit = bool(request_cache_key == cache_key)\n            except (ValueError, RuntimeError):\n                # If the comparison raises, use 'is' as fallback.\n                cache_hit = request_cache_key is cache_key\n\n            if cache_hit:\n                if self.cached_result[2] is not None:\n                    exc, exc_tb = self.cached_result[2]\n                    raise exc.with_traceback(exc_tb)\n                else:\n                    return self.cached_result[0]\n            # We have a previous but differently parametrized fixture instance\n            # so we need to tear it down before creating a new one.\n            self.finish(request)\n            assert self.cached_result is None\n\n        # Add finalizer to requested fixtures we saved previously.\n        # We make sure to do this after checking for cached value to avoid\n        # adding our finalizer multiple times. (#12135)\n        finalizer = functools.partial(self.finish, request=request)\n        for parent_fixture in requested_fixtures_that_should_finalize_us:\n            parent_fixture.addfinalizer(finalizer)\n\n        # Register the pytest_fixture_post_finalizer as the first finalizer,\n        # which is executed last.\n        assert not self._finalizers\n        self.addfinalizer(\n            lambda: request.node.ihook.pytest_fixture_post_finalizer(\n                fixturedef=self, request=request\n            )\n        )\n\n        ihook = request.node.ihook\n        try:\n            # Setup the fixture, run the code in it, and cache the value\n            # in self.cached_result.\n            result: FixtureValue = ihook.pytest_fixture_setup(\n                fixturedef=self, request=request\n            )\n        finally:\n            # Schedule our finalizer, even if the setup failed.\n            request.node.addfinalizer(finalizer)\n\n        return result\n\n    def cache_key(self, request: SubRequest) -> object:\n        return getattr(request, \"param\", None)\n\n    def __repr__(self) -> str:\n        return f\"<FixtureDef argname={self.argname!r} scope={self.scope!r} baseid={self.baseid!r}>\"\n\n\nclass RequestFixtureDef(FixtureDef[FixtureRequest]):\n    \"\"\"A custom FixtureDef for the special \"request\" fixture.\n\n    A new one is generated on-demand whenever \"request\" is requested.\n    \"\"\"\n\n    def __init__(self, request: FixtureRequest) -> None:\n        super().__init__(\n            config=request.config,\n            baseid=None,\n            argname=\"request\",\n            func=lambda: request,\n            scope=Scope.Function,\n            params=None,\n            _ispytest=True,\n        )\n        self.cached_result = (request, [0], None)\n\n    def addfinalizer(self, finalizer: Callable[[], object]) -> None:\n        pass\n\n\ndef resolve_fixture_function(\n    fixturedef: FixtureDef[FixtureValue], request: FixtureRequest\n) -> _FixtureFunc[FixtureValue]:\n    \"\"\"Get the actual callable that can be called to obtain the fixture\n    value.\"\"\"\n    fixturefunc = fixturedef.func\n    # The fixture function needs to be bound to the actual\n    # request.instance so that code working with \"fixturedef\" behaves\n    # as expected.\n    instance = request.instance\n    if instance is not None:\n        # Handle the case where fixture is defined not in a test class, but some other class\n        # (for example a plugin class with a fixture), see #2270.\n        if hasattr(fixturefunc, \"__self__\") and not isinstance(\n            instance,\n            fixturefunc.__self__.__class__,\n        ):\n            return fixturefunc\n        fixturefunc = getimfunc(fixturedef.func)\n        if fixturefunc != fixturedef.func:\n            fixturefunc = fixturefunc.__get__(instance)\n    return fixturefunc\n\n\ndef pytest_fixture_setup(\n    fixturedef: FixtureDef[FixtureValue], request: SubRequest\n) -> FixtureValue:\n    \"\"\"Execution of fixture setup.\"\"\"\n    kwargs = {}\n    for argname in fixturedef.argnames:\n        kwargs[argname] = request.getfixturevalue(argname)\n\n    fixturefunc = resolve_fixture_function(fixturedef, request)\n    my_cache_key = fixturedef.cache_key(request)\n\n    if inspect.isasyncgenfunction(fixturefunc) or inspect.iscoroutinefunction(\n        fixturefunc\n    ):\n        auto_str = \" with autouse=True\" if fixturedef._autouse else \"\"\n        fail(\n            f\"{request.node.name!r} requested an async fixture {request.fixturename!r}{auto_str}, \"\n            \"with no plugin or hook that handled it. This is an error, as pytest does not natively support it.\\n\"\n            \"See: https://docs.pytest.org/en/stable/deprecations.html#sync-test-depending-on-async-fixture\",\n            pytrace=False,\n        )\n\n    try:\n        result = call_fixture_func(fixturefunc, request, kwargs)\n    except TEST_OUTCOME as e:\n        if isinstance(e, skip.Exception):\n            # The test requested a fixture which caused a skip.\n            # Don't show the fixture as the skip location, as then the user\n            # wouldn't know which test skipped.\n            e._use_item_location = True\n        fixturedef.cached_result = (None, my_cache_key, (e, e.__traceback__))\n        raise\n    fixturedef.cached_result = (result, my_cache_key, None)\n    return result\n\n\n@final\n@dataclasses.dataclass(frozen=True)\nclass FixtureFunctionMarker:\n    scope: _ScopeName | Callable[[str, Config], _ScopeName]\n    params: tuple[object, ...] | None\n    autouse: bool = False\n    ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None\n    name: str | None = None\n\n    _ispytest: dataclasses.InitVar[bool] = False\n\n    def __post_init__(self, _ispytest: bool) -> None:\n        check_ispytest(_ispytest)\n\n    def __call__(self, function: FixtureFunction) -> FixtureFunctionDefinition:\n        if inspect.isclass(function):\n            raise ValueError(\"class fixtures not supported (maybe in the future)\")\n\n        if isinstance(function, FixtureFunctionDefinition):\n            raise ValueError(\n                f\"@pytest.fixture is being applied more than once to the same function {function.__name__!r}\"\n            )\n\n        if hasattr(function, \"pytestmark\"):\n            fail(\n                \"Marks cannot be applied to fixtures.\\n\"\n                \"See docs: https://docs.pytest.org/en/stable/deprecations.html#applying-a-mark-to-a-fixture-function\"\n            )\n\n        fixture_definition = FixtureFunctionDefinition(\n            function=function, fixture_function_marker=self, _ispytest=True\n        )\n\n        name = self.name or function.__name__\n        if name == \"request\":\n            location = getlocation(function)\n            fail(\n                f\"'request' is a reserved word for fixtures, use another name:\\n  {location}\",\n                pytrace=False,\n            )\n\n        return fixture_definition\n\n\n# TODO: paramspec/return type annotation tracking and storing\nclass FixtureFunctionDefinition:\n    def __init__(\n        self,\n        *,\n        function: Callable[..., Any],\n        fixture_function_marker: FixtureFunctionMarker,\n        instance: object | None = None,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        self.name = fixture_function_marker.name or function.__name__\n        # In order to show the function that this fixture contains in messages.\n        # Set the __name__ to be same as the function __name__ or the given fixture name.\n        self.__name__ = self.name\n        self._fixture_function_marker = fixture_function_marker\n        if instance is not None:\n            self._fixture_function = cast(\n                Callable[..., Any], function.__get__(instance)\n            )\n        else:\n            self._fixture_function = function\n        functools.update_wrapper(self, function)\n\n    def __repr__(self) -> str:\n        return f\"<pytest_fixture({self._fixture_function})>\"\n\n    def __get__(self, instance, owner=None):\n        \"\"\"Behave like a method if the function it was applied to was a method.\"\"\"\n        return FixtureFunctionDefinition(\n            function=self._fixture_function,\n            fixture_function_marker=self._fixture_function_marker,\n            instance=instance,\n            _ispytest=True,\n        )\n\n    def __call__(self, *args: Any, **kwds: Any) -> Any:\n        message = (\n            f'Fixture \"{self.name}\" called directly. Fixtures are not meant to be called directly,\\n'\n            \"but are created automatically when test functions request them as parameters.\\n\"\n            \"See https://docs.pytest.org/en/stable/explanation/fixtures.html for more information about fixtures, and\\n\"\n            \"https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly\"\n        )\n        fail(message, pytrace=False)\n\n    def _get_wrapped_function(self) -> Callable[..., Any]:\n        return self._fixture_function\n\n\n@overload\ndef fixture(\n    fixture_function: Callable[..., object],\n    *,\n    scope: _ScopeName | Callable[[str, Config], _ScopeName] = ...,\n    params: Iterable[object] | None = ...,\n    autouse: bool = ...,\n    ids: Sequence[object | None] | Callable[[Any], object | None] | None = ...,\n    name: str | None = ...,\n) -> FixtureFunctionDefinition: ...\n\n\n@overload\ndef fixture(\n    fixture_function: None = ...,\n    *,\n    scope: _ScopeName | Callable[[str, Config], _ScopeName] = ...,\n    params: Iterable[object] | None = ...,\n    autouse: bool = ...,\n    ids: Sequence[object | None] | Callable[[Any], object | None] | None = ...,\n    name: str | None = None,\n) -> FixtureFunctionMarker: ...\n\n\ndef fixture(\n    fixture_function: FixtureFunction | None = None,\n    *,\n    scope: _ScopeName | Callable[[str, Config], _ScopeName] = \"function\",\n    params: Iterable[object] | None = None,\n    autouse: bool = False,\n    ids: Sequence[object | None] | Callable[[Any], object | None] | None = None,\n    name: str | None = None,\n) -> FixtureFunctionMarker | FixtureFunctionDefinition:\n    \"\"\"Decorator to mark a fixture factory function.\n\n    This decorator can be used, with or without parameters, to define a\n    fixture function.\n\n    The name of the fixture function can later be referenced to cause its\n    invocation ahead of running tests: test modules or classes can use the\n    ``pytest.mark.usefixtures(fixturename)`` marker.\n\n    Test functions can directly use fixture names as input arguments in which\n    case the fixture instance returned from the fixture function will be\n    injected.\n\n    Fixtures can provide their values to test functions using ``return`` or\n    ``yield`` statements. When using ``yield`` the code block after the\n    ``yield`` statement is executed as teardown code regardless of the test\n    outcome, and must yield exactly once.\n\n    :param scope:\n        The scope for which this fixture is shared; one of ``\"function\"``\n        (default), ``\"class\"``, ``\"module\"``, ``\"package\"`` or ``\"session\"``.\n\n        This parameter may also be a callable which receives ``(fixture_name, config)``\n        as parameters, and must return a ``str`` with one of the values mentioned above.\n\n        See :ref:`dynamic scope` in the docs for more information.\n\n    :param params:\n        An optional list of parameters which will cause multiple invocations\n        of the fixture function and all of the tests using it. The current\n        parameter is available in ``request.param``.\n\n    :param autouse:\n        If True, the fixture func is activated for all tests that can see it.\n        If False (the default), an explicit reference is needed to activate\n        the fixture.\n\n    :param ids:\n        Sequence of ids each corresponding to the params so that they are\n        part of the test id. If no ids are provided they will be generated\n        automatically from the params.\n\n    :param name:\n        The name of the fixture. This defaults to the name of the decorated\n        function. If a fixture is used in the same module in which it is\n        defined, the function name of the fixture will be shadowed by the\n        function arg that requests the fixture; one way to resolve this is to\n        name the decorated function ``fixture_<fixturename>`` and then use\n        ``@pytest.fixture(name='<fixturename>')``.\n    \"\"\"\n    fixture_marker = FixtureFunctionMarker(\n        scope=scope,\n        params=tuple(params) if params is not None else None,\n        autouse=autouse,\n        ids=None if ids is None else ids if callable(ids) else tuple(ids),\n        name=name,\n        _ispytest=True,\n    )\n\n    # Direct decoration.\n    if fixture_function:\n        return fixture_marker(fixture_function)\n\n    return fixture_marker\n\n\ndef yield_fixture(\n    fixture_function=None,\n    *args,\n    scope=\"function\",\n    params=None,\n    autouse=False,\n    ids=None,\n    name=None,\n):\n    \"\"\"(Return a) decorator to mark a yield-fixture factory function.\n\n    .. deprecated:: 3.0\n        Use :py:func:`pytest.fixture` directly instead.\n    \"\"\"\n    warnings.warn(YIELD_FIXTURE, stacklevel=2)\n    return fixture(\n        fixture_function,\n        *args,\n        scope=scope,\n        params=params,\n        autouse=autouse,\n        ids=ids,\n        name=name,\n    )\n\n\n@fixture(scope=\"session\")\ndef pytestconfig(request: FixtureRequest) -> Config:\n    \"\"\"Session-scoped fixture that returns the session's :class:`pytest.Config`\n    object.\n\n    Example::\n\n        def test_foo(pytestconfig):\n            if pytestconfig.get_verbosity() > 0:\n                ...\n\n    \"\"\"\n    return request.config\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    parser.addini(\n        \"usefixtures\",\n        type=\"args\",\n        default=[],\n        help=\"List of default fixtures to be used with this project\",\n    )\n    group = parser.getgroup(\"general\")\n    group.addoption(\n        \"--fixtures\",\n        \"--funcargs\",\n        action=\"store_true\",\n        dest=\"showfixtures\",\n        default=False,\n        help=\"Show available fixtures, sorted by plugin appearance \"\n        \"(fixtures with leading '_' are only shown with '-v')\",\n    )\n    group.addoption(\n        \"--fixtures-per-test\",\n        action=\"store_true\",\n        dest=\"show_fixtures_per_test\",\n        default=False,\n        help=\"Show fixtures per test\",\n    )\n\n\ndef pytest_cmdline_main(config: Config) -> int | ExitCode | None:\n    if config.option.showfixtures:\n        showfixtures(config)\n        return 0\n    if config.option.show_fixtures_per_test:\n        show_fixtures_per_test(config)\n        return 0\n    return None\n\n\ndef _resolve_args_directness(\n    argnames: Sequence[str],\n    indirect: bool | Sequence[str],\n    nodeid: str,\n) -> dict[str, Literal[\"indirect\", \"direct\"]]:\n    \"\"\"Resolve if each parametrized argument must be considered an indirect\n    parameter to a fixture of the same name, or a direct parameter to the\n    parametrized function, based on the ``indirect`` parameter of the\n    parametrize() call.\n\n    :param argnames:\n        List of argument names passed to ``parametrize()``.\n    :param indirect:\n        Same as the ``indirect`` parameter of ``parametrize()``.\n    :param nodeid:\n        Node ID to which the parametrization is applied.\n    :returns:\n        A dict mapping each arg name to either \"indirect\" or \"direct\".\n    \"\"\"\n    arg_directness: dict[str, Literal[\"indirect\", \"direct\"]]\n    if isinstance(indirect, bool):\n        arg_directness = dict.fromkeys(argnames, \"indirect\" if indirect else \"direct\")\n    elif isinstance(indirect, Sequence):\n        arg_directness = dict.fromkeys(argnames, \"direct\")\n        for arg in indirect:\n            if arg not in argnames:\n                fail(\n                    f\"In {nodeid}: indirect fixture '{arg}' doesn't exist\",\n                    pytrace=False,\n                )\n            arg_directness[arg] = \"indirect\"\n    else:\n        fail(\n            f\"In {nodeid}: expected Sequence or boolean for indirect, got {type(indirect).__name__}\",\n            pytrace=False,\n        )\n    return arg_directness\n\n\ndef _get_direct_parametrize_args(node: nodes.Node) -> set[str]:\n    \"\"\"Return all direct parametrization arguments of a node, so we don't\n    mistake them for fixtures.\n\n    Check https://github.com/pytest-dev/pytest/issues/5036.\n\n    These things are done later as well when dealing with parametrization\n    so this could be improved.\n    \"\"\"\n    parametrize_argnames: set[str] = set()\n    for marker in node.iter_markers(name=\"parametrize\"):\n        indirect = marker.kwargs.get(\"indirect\", False)\n        p_argnames, _ = ParameterSet._parse_parametrize_args(\n            *marker.args, **marker.kwargs\n        )\n        p_directness = _resolve_args_directness(p_argnames, indirect, node.nodeid)\n        parametrize_argnames.update(\n            argname\n            for argname, directness in p_directness.items()\n            if directness == \"direct\"\n        )\n    return parametrize_argnames\n\n\ndef deduplicate_names(*seqs: Iterable[str]) -> tuple[str, ...]:\n    \"\"\"De-duplicate the sequence of names while keeping the original order.\"\"\"\n    # Ideally we would use a set, but it does not preserve insertion order.\n    return tuple(dict.fromkeys(name for seq in seqs for name in seq))\n\n\nclass FixtureManager:\n    \"\"\"pytest fixture definitions and information is stored and managed\n    from this class.\n\n    During collection fm.parsefactories() is called multiple times to parse\n    fixture function definitions into FixtureDef objects and internal\n    data structures.\n\n    During collection of test functions, metafunc-mechanics instantiate\n    a FuncFixtureInfo object which is cached per node/func-name.\n    This FuncFixtureInfo object is later retrieved by Function nodes\n    which themselves offer a fixturenames attribute.\n\n    The FuncFixtureInfo object holds information about fixtures and FixtureDefs\n    relevant for a particular function. An initial list of fixtures is\n    assembled like this:\n\n    - config-defined usefixtures\n    - autouse-marked fixtures along the collection chain up from the function\n    - usefixtures markers at module/class/function level\n    - test function funcargs\n\n    Subsequently the funcfixtureinfo.fixturenames attribute is computed\n    as the closure of the fixtures needed to setup the initial fixtures,\n    i.e. fixtures needed by fixture functions themselves are appended\n    to the fixturenames list.\n\n    Upon the test-setup phases all fixturenames are instantiated, retrieved\n    by a lookup of their FuncFixtureInfo.\n    \"\"\"\n\n    def __init__(self, session: Session) -> None:\n        self.session = session\n        self.config: Config = session.config\n        # Maps a fixture name (argname) to all of the FixtureDefs in the test\n        # suite/plugins defined with this name. Populated by parsefactories().\n        # TODO: The order of the FixtureDefs list of each arg is significant,\n        #       explain.\n        self._arg2fixturedefs: Final[dict[str, list[FixtureDef[Any]]]] = {}\n        self._holderobjseen: Final[set[object]] = set()\n        # A mapping from a nodeid to a list of autouse fixtures it defines.\n        self._nodeid_autousenames: Final[dict[str, list[str]]] = {\n            \"\": self.config.getini(\"usefixtures\"),\n        }\n        session.config.pluginmanager.register(self, \"funcmanage\")\n\n    def getfixtureinfo(\n        self,\n        node: nodes.Item,\n        func: Callable[..., object] | None,\n        cls: type | None,\n    ) -> FuncFixtureInfo:\n        \"\"\"Calculate the :class:`FuncFixtureInfo` for an item.\n\n        If ``func`` is None, or if the item sets an attribute\n        ``nofuncargs = True``, then ``func`` is not examined at all.\n\n        :param node:\n            The item requesting the fixtures.\n        :param func:\n            The item's function.\n        :param cls:\n            If the function is a method, the method's class.\n        \"\"\"\n        if func is not None and not getattr(node, \"nofuncargs\", False):\n            argnames = getfuncargnames(func, name=node.name, cls=cls)\n        else:\n            argnames = ()\n        usefixturesnames = self._getusefixturesnames(node)\n        autousenames = self._getautousenames(node)\n        initialnames = deduplicate_names(autousenames, usefixturesnames, argnames)\n\n        direct_parametrize_args = _get_direct_parametrize_args(node)\n\n        names_closure, arg2fixturedefs = self.getfixtureclosure(\n            parentnode=node,\n            initialnames=initialnames,\n            ignore_args=direct_parametrize_args,\n        )\n\n        return FuncFixtureInfo(argnames, initialnames, names_closure, arg2fixturedefs)\n\n    def pytest_plugin_registered(self, plugin: _PluggyPlugin, plugin_name: str) -> None:\n        # Fixtures defined in conftest plugins are only visible to within the\n        # conftest's directory. This is unlike fixtures in non-conftest plugins\n        # which have global visibility. So for conftests, construct the base\n        # nodeid from the plugin name (which is the conftest path).\n        if plugin_name and plugin_name.endswith(\"conftest.py\"):\n            # Note: we explicitly do *not* use `plugin.__file__` here -- The\n            # difference is that plugin_name has the correct capitalization on\n            # case-insensitive systems (Windows) and other normalization issues\n            # (issue #11816).\n            conftestpath = absolutepath(plugin_name)\n            try:\n                nodeid = str(conftestpath.parent.relative_to(self.config.rootpath))\n            except ValueError:\n                nodeid = \"\"\n            if nodeid == \".\":\n                nodeid = \"\"\n            elif nodeid:\n                nodeid = nodes.norm_sep(nodeid)\n        else:\n            nodeid = None\n\n        self.parsefactories(plugin, nodeid)\n\n    def _getautousenames(self, node: nodes.Node) -> Iterator[str]:\n        \"\"\"Return the names of autouse fixtures applicable to node.\"\"\"\n        for parentnode in node.listchain():\n            basenames = self._nodeid_autousenames.get(parentnode.nodeid)\n            if basenames:\n                yield from basenames\n\n    def _getusefixturesnames(self, node: nodes.Item) -> Iterator[str]:\n        \"\"\"Return the names of usefixtures fixtures applicable to node.\"\"\"\n        for marker_node, mark in node.iter_markers_with_node(name=\"usefixtures\"):\n            if not mark.args:\n                marker_node.warn(\n                    PytestWarning(\n                        f\"usefixtures() in {node.nodeid} without arguments has no effect\"\n                    )\n                )\n            yield from mark.args\n\n    def getfixtureclosure(\n        self,\n        parentnode: nodes.Node,\n        initialnames: tuple[str, ...],\n        ignore_args: AbstractSet[str],\n    ) -> tuple[list[str], dict[str, Sequence[FixtureDef[Any]]]]:\n        # Collect the closure of all fixtures, starting with the given\n        # fixturenames as the initial set.  As we have to visit all\n        # factory definitions anyway, we also return an arg2fixturedefs\n        # mapping so that the caller can reuse it and does not have\n        # to re-discover fixturedefs again for each fixturename\n        # (discovering matching fixtures for a given name/node is expensive).\n\n        fixturenames_closure = list(initialnames)\n\n        arg2fixturedefs: dict[str, Sequence[FixtureDef[Any]]] = {}\n\n        # Track the index for each fixture name in the simulated stack.\n        # Needed for handling override chains correctly, similar to _get_active_fixturedef.\n        # Using negative indices: -1 is the most specific (last), -2 is second to last, etc.\n        current_indices: dict[str, int] = {}\n\n        def process_argname(argname: str) -> None:\n            # Optimization: already processed this argname.\n            if current_indices.get(argname) == -1:\n                return\n\n            if argname not in fixturenames_closure:\n                fixturenames_closure.append(argname)\n\n            if argname in ignore_args:\n                return\n\n            fixturedefs = arg2fixturedefs.get(argname)\n            if not fixturedefs:\n                fixturedefs = self.getfixturedefs(argname, parentnode)\n                if not fixturedefs:\n                    # Fixture not defined or not visible (will error during runtest).\n                    return\n                arg2fixturedefs[argname] = fixturedefs\n\n            index = current_indices.get(argname, -1)\n            if -index > len(fixturedefs):\n                # Exhausted the override chain (will error during runtest).\n                return\n            fixturedef = fixturedefs[index]\n\n            current_indices[argname] = index - 1\n            for dep in fixturedef.argnames:\n                process_argname(dep)\n            current_indices[argname] = index\n\n        for name in initialnames:\n            process_argname(name)\n\n        def sort_by_scope(arg_name: str) -> Scope:\n            try:\n                fixturedefs = arg2fixturedefs[arg_name]\n            except KeyError:\n                return Scope.Function\n            else:\n                return fixturedefs[-1]._scope\n\n        fixturenames_closure.sort(key=sort_by_scope, reverse=True)\n        return fixturenames_closure, arg2fixturedefs\n\n    def pytest_generate_tests(self, metafunc: Metafunc) -> None:\n        \"\"\"Generate new tests based on parametrized fixtures used by the given metafunc\"\"\"\n        for argname in metafunc.fixturenames:\n            # Get the FixtureDefs for the argname.\n            fixture_defs = metafunc._arg2fixturedefs.get(argname, ())\n\n            # In the common case we only look at the fixture def with the\n            # closest scope (last in the list). But if the fixture overrides\n            # another fixture, while requesting the super fixture, keep going\n            # in case the super fixture is parametrized (#1953).\n            for fixturedef in reversed(fixture_defs):\n                # Fixture is parametrized, apply it and stop.\n                if fixturedef.params is not None:\n                    metafunc.parametrize(\n                        argname,\n                        fixturedef.params,\n                        indirect=True,\n                        scope=fixturedef.scope,\n                        ids=fixturedef.ids,\n                    )\n                    break\n\n                # Not requesting the overridden super fixture, stop.\n                #\n                # TODO: Handle the case where the super-fixture is transitively\n                # requested (see #7737 and the xfail'd test\n                # test_override_parametrized_fixture_via_transitive_fixture).\n                if argname not in fixturedef.argnames:\n                    break\n\n                # Try next super fixture, if any.\n\n    def pytest_collection_modifyitems(self, items: list[nodes.Item]) -> None:\n        # Separate parametrized setups.\n        items[:] = reorder_items(items)\n\n    def _register_fixture(\n        self,\n        *,\n        name: str,\n        func: _FixtureFunc[object],\n        nodeid: str | None,\n        scope: Scope | _ScopeName | Callable[[str, Config], _ScopeName] = \"function\",\n        params: Sequence[object] | None = None,\n        ids: tuple[object | None, ...] | Callable[[Any], object | None] | None = None,\n        autouse: bool = False,\n    ) -> None:\n        \"\"\"Register a fixture\n\n        :param name:\n            The fixture's name.\n        :param func:\n            The fixture's implementation function.\n        :param nodeid:\n            The visibility of the fixture. The fixture will be available to the\n            node with this nodeid and its children in the collection tree.\n            None means that the fixture is visible to the entire collection tree,\n            e.g. a fixture defined for general use in a plugin.\n        :param scope:\n            The fixture's scope.\n        :param params:\n            The fixture's parametrization params.\n        :param ids:\n            The fixture's IDs.\n        :param autouse:\n            Whether this is an autouse fixture.\n        \"\"\"\n        fixture_def = FixtureDef(\n            config=self.config,\n            baseid=nodeid,\n            argname=name,\n            func=func,\n            scope=scope,\n            params=params,\n            ids=ids,\n            _ispytest=True,\n            _autouse=autouse,\n        )\n\n        faclist = self._arg2fixturedefs.setdefault(name, [])\n        if fixture_def.has_location:\n            faclist.append(fixture_def)\n        else:\n            # fixturedefs with no location are at the front\n            # so this inserts the current fixturedef after the\n            # existing fixturedefs from external plugins but\n            # before the fixturedefs provided in conftests.\n            i = len([f for f in faclist if not f.has_location])\n            faclist.insert(i, fixture_def)\n        if autouse:\n            self._nodeid_autousenames.setdefault(nodeid or \"\", []).append(name)\n\n    @overload\n    def parsefactories(\n        self,\n        node_or_obj: nodes.Node,\n    ) -> None:\n        raise NotImplementedError()\n\n    @overload\n    def parsefactories(\n        self,\n        node_or_obj: object,\n        nodeid: str | None,\n    ) -> None:\n        raise NotImplementedError()\n\n    def parsefactories(\n        self,\n        node_or_obj: nodes.Node | object,\n        nodeid: str | NotSetType | None = NOTSET,\n    ) -> None:\n        \"\"\"Collect fixtures from a collection node or object.\n\n        Found fixtures are parsed into `FixtureDef`s and saved.\n\n        If `node_or_object` is a collection node (with an underlying Python\n        object), the node's object is traversed and the node's nodeid is used to\n        determine the fixtures' visibility. `nodeid` must not be specified in\n        this case.\n\n        If `node_or_object` is an object (e.g. a plugin), the object is\n        traversed and the given `nodeid` is used to determine the fixtures'\n        visibility. `nodeid` must be specified in this case; None and \"\" mean\n        total visibility.\n        \"\"\"\n        if nodeid is not NOTSET:\n            holderobj = node_or_obj\n        else:\n            assert isinstance(node_or_obj, nodes.Node)\n            holderobj = cast(object, node_or_obj.obj)  # type: ignore[attr-defined]\n            assert isinstance(node_or_obj.nodeid, str)\n            nodeid = node_or_obj.nodeid\n        if holderobj in self._holderobjseen:\n            return\n\n        # Avoid accessing `@property` (and other descriptors) when iterating fixtures.\n        if not safe_isclass(holderobj) and not isinstance(holderobj, types.ModuleType):\n            holderobj_tp: object = type(holderobj)\n        else:\n            holderobj_tp = holderobj\n\n        self._holderobjseen.add(holderobj)\n        for name in dir(holderobj):\n            # The attribute can be an arbitrary descriptor, so the attribute\n            # access below can raise. safe_getattr() ignores such exceptions.\n            obj_ub = safe_getattr(holderobj_tp, name, None)\n            if type(obj_ub) is FixtureFunctionDefinition:\n                marker = obj_ub._fixture_function_marker\n                if marker.name:\n                    fixture_name = marker.name\n                else:\n                    fixture_name = name\n\n                # OK we know it is a fixture -- now safe to look up on the _instance_.\n                try:\n                    obj = getattr(holderobj, name)\n                # if the fixture is named in the decorator we cannot find it in the module\n                except AttributeError:\n                    obj = obj_ub\n\n                func = obj._get_wrapped_function()\n\n                self._register_fixture(\n                    name=fixture_name,\n                    nodeid=nodeid,\n                    func=func,\n                    scope=marker.scope,\n                    params=marker.params,\n                    ids=marker.ids,\n                    autouse=marker.autouse,\n                )\n\n    def getfixturedefs(\n        self, argname: str, node: nodes.Node\n    ) -> Sequence[FixtureDef[Any]] | None:\n        \"\"\"Get FixtureDefs for a fixture name which are applicable\n        to a given node.\n\n        Returns None if there are no fixtures at all defined with the given\n        name. (This is different from the case in which there are fixtures\n        with the given name, but none applicable to the node. In this case,\n        an empty result is returned).\n\n        :param argname: Name of the fixture to search for.\n        :param node: The requesting Node.\n        \"\"\"\n        try:\n            fixturedefs = self._arg2fixturedefs[argname]\n        except KeyError:\n            return None\n        return tuple(self._matchfactories(fixturedefs, node))\n\n    def _matchfactories(\n        self, fixturedefs: Iterable[FixtureDef[Any]], node: nodes.Node\n    ) -> Iterator[FixtureDef[Any]]:\n        parentnodeids = {n.nodeid for n in node.iter_parents()}\n        for fixturedef in fixturedefs:\n            if fixturedef.baseid in parentnodeids:\n                yield fixturedef\n\n\ndef show_fixtures_per_test(config: Config) -> int | ExitCode:\n    from _pytest.main import wrap_session\n\n    return wrap_session(config, _show_fixtures_per_test)\n\n\n_PYTEST_DIR = Path(_pytest.__file__).parent\n\n\ndef _pretty_fixture_path(invocation_dir: Path, func) -> str:\n    loc = Path(getlocation(func, invocation_dir))\n    prefix = Path(\"...\", \"_pytest\")\n    try:\n        return str(prefix / loc.relative_to(_PYTEST_DIR))\n    except ValueError:\n        return bestrelpath(invocation_dir, loc)\n\n\ndef _show_fixtures_per_test(config: Config, session: Session) -> None:\n    import _pytest.config\n\n    session.perform_collect()\n    invocation_dir = config.invocation_params.dir\n    tw = _pytest.config.create_terminal_writer(config)\n    verbose = config.get_verbosity()\n\n    def get_best_relpath(func) -> str:\n        loc = getlocation(func, invocation_dir)\n        return bestrelpath(invocation_dir, Path(loc))\n\n    def write_fixture(fixture_def: FixtureDef[object]) -> None:\n        argname = fixture_def.argname\n        if verbose <= 0 and argname.startswith(\"_\"):\n            return\n        prettypath = _pretty_fixture_path(invocation_dir, fixture_def.func)\n        tw.write(f\"{argname}\", green=True)\n        tw.write(f\" -- {prettypath}\", yellow=True)\n        tw.write(\"\\n\")\n        fixture_doc = inspect.getdoc(fixture_def.func)\n        if fixture_doc:\n            write_docstring(\n                tw,\n                fixture_doc.split(\"\\n\\n\", maxsplit=1)[0]\n                if verbose <= 0\n                else fixture_doc,\n            )\n        else:\n            tw.line(\"    no docstring available\", red=True)\n\n    def write_item(item: nodes.Item) -> None:\n        # Not all items have _fixtureinfo attribute.\n        info: FuncFixtureInfo | None = getattr(item, \"_fixtureinfo\", None)\n        if info is None or not info.name2fixturedefs:\n            # This test item does not use any fixtures.\n            return\n        tw.line()\n        tw.sep(\"-\", f\"fixtures used by {item.name}\")\n        # TODO: Fix this type ignore.\n        tw.sep(\"-\", f\"({get_best_relpath(item.function)})\")  # type: ignore[attr-defined]\n        # dict key not used in loop but needed for sorting.\n        for _, fixturedefs in sorted(info.name2fixturedefs.items()):\n            assert fixturedefs is not None\n            if not fixturedefs:\n                continue\n            # Last item is expected to be the one used by the test item.\n            write_fixture(fixturedefs[-1])\n\n    for session_item in session.items:\n        write_item(session_item)\n\n\ndef showfixtures(config: Config) -> int | ExitCode:\n    from _pytest.main import wrap_session\n\n    return wrap_session(config, _showfixtures_main)\n\n\ndef _showfixtures_main(config: Config, session: Session) -> None:\n    import _pytest.config\n\n    session.perform_collect()\n    invocation_dir = config.invocation_params.dir\n    tw = _pytest.config.create_terminal_writer(config)\n    verbose = config.get_verbosity()\n\n    fm = session._fixturemanager\n\n    available = []\n    seen: set[tuple[str, str]] = set()\n\n    for argname, fixturedefs in fm._arg2fixturedefs.items():\n        assert fixturedefs is not None\n        if not fixturedefs:\n            continue\n        for fixturedef in fixturedefs:\n            loc = getlocation(fixturedef.func, invocation_dir)\n            if (fixturedef.argname, loc) in seen:\n                continue\n            seen.add((fixturedef.argname, loc))\n            available.append(\n                (\n                    len(fixturedef.baseid),\n                    fixturedef.func.__module__,\n                    _pretty_fixture_path(invocation_dir, fixturedef.func),\n                    fixturedef.argname,\n                    fixturedef,\n                )\n            )\n\n    available.sort()\n    currentmodule = None\n    for baseid, module, prettypath, argname, fixturedef in available:\n        if currentmodule != module:\n            if not module.startswith(\"_pytest.\"):\n                tw.line()\n                tw.sep(\"-\", f\"fixtures defined from {module}\")\n                currentmodule = module\n        if verbose <= 0 and argname.startswith(\"_\"):\n            continue\n        tw.write(f\"{argname}\", green=True)\n        if fixturedef.scope != \"function\":\n            tw.write(f\" [{fixturedef.scope} scope]\", cyan=True)\n        tw.write(f\" -- {prettypath}\", yellow=True)\n        tw.write(\"\\n\")\n        doc = inspect.getdoc(fixturedef.func)\n        if doc:\n            write_docstring(\n                tw, doc.split(\"\\n\\n\", maxsplit=1)[0] if verbose <= 0 else doc\n            )\n        else:\n            tw.line(\"    no docstring available\", red=True)\n        tw.line()\n\n\ndef write_docstring(tw: TerminalWriter, doc: str, indent: str = \"    \") -> None:\n    for line in doc.split(\"\\n\"):\n        tw.line(indent + line)\n"
  },
  {
    "path": "src/_pytest/freeze_support.py",
    "content": "\"\"\"Provides a function to report all internal modules for using freezing\ntools.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterator\nimport types\n\n\ndef freeze_includes() -> list[str]:\n    \"\"\"Return a list of module names used by pytest that should be\n    included by cx_freeze.\"\"\"\n    import _pytest\n\n    result = list(_iter_all_modules(_pytest))\n    return result\n\n\ndef _iter_all_modules(\n    package: str | types.ModuleType,\n    prefix: str = \"\",\n) -> Iterator[str]:\n    \"\"\"Iterate over the names of all modules that can be found in the given\n    package, recursively.\n\n        >>> import _pytest\n        >>> list(_iter_all_modules(_pytest))\n        ['_pytest._argcomplete', '_pytest._code.code', ...]\n    \"\"\"\n    import os\n    import pkgutil\n\n    if isinstance(package, str):\n        path = package\n    else:\n        # Type ignored because typeshed doesn't define ModuleType.__path__\n        # (only defined on packages).\n        package_path = package.__path__\n        path, prefix = package_path[0], package.__name__ + \".\"\n    for _, name, is_package in pkgutil.iter_modules([path]):\n        if is_package:\n            for m in _iter_all_modules(os.path.join(path, name), prefix=name + \".\"):\n                yield prefix + m\n        else:\n            yield prefix + name\n"
  },
  {
    "path": "src/_pytest/helpconfig.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Version info, help messages, tracing configuration.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nfrom collections.abc import Generator\nfrom collections.abc import Sequence\nimport os\nimport sys\nfrom typing import Any\n\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.config import PrintHelp\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.terminal import TerminalReporter\nimport pytest\n\n\nclass HelpAction(argparse.Action):\n    \"\"\"An argparse Action that will raise a PrintHelp exception in order to skip\n    the rest of the argument parsing when --help is passed.\n\n    This prevents argparse from raising UsageError when `--help` is used along\n    with missing required arguments when any are defined, for example by\n    ``pytest_addoption``. This is similar to the way that the builtin argparse\n    --help option is implemented by raising SystemExit.\n\n    To opt in to this behavior, the parse caller must set\n    `namespace._raise_print_help = True`. Otherwise it just sets the option.\n    \"\"\"\n\n    def __init__(\n        self, option_strings: Sequence[str], dest: str, *, help: str | None = None\n    ) -> None:\n        super().__init__(\n            option_strings=option_strings,\n            dest=dest,\n            nargs=0,\n            const=True,\n            default=False,\n            help=help,\n        )\n\n    def __call__(\n        self,\n        parser: argparse.ArgumentParser,\n        namespace: argparse.Namespace,\n        values: str | Sequence[Any] | None,\n        option_string: str | None = None,\n    ) -> None:\n        setattr(namespace, self.dest, self.const)\n\n        if getattr(namespace, \"_raise_print_help\", False):\n            raise PrintHelp\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"debugconfig\")\n    group.addoption(\n        \"-V\",\n        \"--version\",\n        action=\"count\",\n        default=0,\n        dest=\"version\",\n        help=\"Display pytest version and information about plugins. \"\n        \"When given twice, also display information about plugins.\",\n    )\n    group._addoption(  # private to use reserved lower-case short option\n        \"-h\",\n        \"--help\",\n        action=HelpAction,\n        dest=\"help\",\n        help=\"Show help message and configuration info\",\n    )\n    group._addoption(  # private to use reserved lower-case short option\n        \"-p\",\n        action=\"append\",\n        dest=\"plugins\",\n        default=[],\n        metavar=\"name\",\n        help=\"Early-load given plugin module name or entry point (multi-allowed). \"\n        \"To avoid loading of plugins, use the `no:` prefix, e.g. \"\n        \"`no:doctest`. See also --disable-plugin-autoload.\",\n    )\n    group.addoption(\n        \"--disable-plugin-autoload\",\n        action=\"store_true\",\n        default=False,\n        help=\"Disable plugin auto-loading through entry point packaging metadata. \"\n        \"Only plugins explicitly specified in -p or env var PYTEST_PLUGINS will be loaded.\",\n    )\n    group.addoption(\n        \"--traceconfig\",\n        \"--trace-config\",\n        action=\"store_true\",\n        default=False,\n        help=\"Trace considerations of conftest.py files\",\n    )\n    group.addoption(\n        \"--debug\",\n        action=\"store\",\n        nargs=\"?\",\n        const=\"pytestdebug.log\",\n        dest=\"debug\",\n        metavar=\"DEBUG_FILE_NAME\",\n        help=\"Store internal tracing debug information in this log file. \"\n        \"This file is opened with 'w' and truncated as a result, care advised. \"\n        \"Default: pytestdebug.log.\",\n    )\n    group._addoption(  # private to use reserved lower-case short option\n        \"-o\",\n        \"--override-ini\",\n        dest=\"override_ini\",\n        action=\"append\",\n        help='Override configuration option with \"option=value\" style, '\n        \"e.g. `-o strict_xfail=True -o cache_dir=cache`.\",\n    )\n\n\n@pytest.hookimpl(wrapper=True)\ndef pytest_cmdline_parse() -> Generator[None, Config, Config]:\n    config = yield\n\n    if config.option.debug:\n        # --debug | --debug <file.log> was provided.\n        path = config.option.debug\n        debugfile = open(path, \"w\", encoding=\"utf-8\")\n        debugfile.write(\n            \"versions pytest-{}, \"\n            \"python-{}\\ninvocation_dir={}\\ncwd={}\\nargs={}\\n\\n\".format(\n                pytest.__version__,\n                \".\".join(map(str, sys.version_info)),\n                config.invocation_params.dir,\n                os.getcwd(),\n                config.invocation_params.args,\n            )\n        )\n        config.trace.root.setwriter(debugfile.write)\n        undo_tracing = config.pluginmanager.enable_tracing()\n        sys.stderr.write(f\"writing pytest debug information to {path}\\n\")\n\n        def unset_tracing() -> None:\n            debugfile.close()\n            sys.stderr.write(f\"wrote pytest debug information to {debugfile.name}\\n\")\n            config.trace.root.setwriter(None)\n            undo_tracing()\n\n        config.add_cleanup(unset_tracing)\n\n    return config\n\n\ndef show_version_verbose(config: Config) -> None:\n    \"\"\"Show verbose pytest version installation, including plugins.\"\"\"\n    sys.stdout.write(\n        f\"This is pytest version {pytest.__version__}, imported from {pytest.__file__}\\n\"\n    )\n    plugininfo = getpluginversioninfo(config)\n    if plugininfo:\n        for line in plugininfo:\n            sys.stdout.write(line + \"\\n\")\n\n\ndef pytest_cmdline_main(config: Config) -> int | ExitCode | None:\n    # Note: a single `--version` argument is handled directly by `Config.main()` to avoid starting up the entire\n    # pytest infrastructure just to display the version (#13574).\n    if config.option.version > 1:\n        show_version_verbose(config)\n        return ExitCode.OK\n    elif config.option.help:\n        config._do_configure()\n        showhelp(config)\n        config._ensure_unconfigure()\n        return ExitCode.OK\n    return None\n\n\ndef showhelp(config: Config) -> None:\n    import textwrap\n\n    reporter: TerminalReporter | None = config.pluginmanager.get_plugin(\n        \"terminalreporter\"\n    )\n    assert reporter is not None\n    tw = reporter._tw\n    tw.write(config._parser.optparser.format_help())\n    tw.line()\n    tw.line(\n        \"[pytest] configuration options in the first \"\n        \"pytest.toml|pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:\"\n    )\n    tw.line()\n\n    columns = tw.fullwidth  # costly call\n    indent_len = 24  # based on argparse's max_help_position=24\n    indent = \" \" * indent_len\n    for name in config._parser._inidict:\n        help, type, _default = config._parser._inidict[name]\n        if help is None:\n            raise TypeError(f\"help argument cannot be None for {name}\")\n        spec = f\"{name} ({type}):\"\n        tw.write(f\"  {spec}\")\n        spec_len = len(spec)\n        if spec_len > (indent_len - 3):\n            # Display help starting at a new line.\n            tw.line()\n            helplines = textwrap.wrap(\n                help,\n                columns,\n                initial_indent=indent,\n                subsequent_indent=indent,\n                break_on_hyphens=False,\n            )\n\n            for line in helplines:\n                tw.line(line)\n        else:\n            # Display help starting after the spec, following lines indented.\n            tw.write(\" \" * (indent_len - spec_len - 2))\n            wrapped = textwrap.wrap(help, columns - indent_len, break_on_hyphens=False)\n\n            if wrapped:\n                tw.line(wrapped[0])\n                for line in wrapped[1:]:\n                    tw.line(indent + line)\n\n    tw.line()\n    tw.line(\"Environment variables:\")\n    vars = [\n        (\n            \"CI\",\n            \"When set to a non-empty value, pytest knows it is running in a \"\n            \"CI process and does not truncate summary info\",\n        ),\n        (\"BUILD_NUMBER\", \"Equivalent to CI\"),\n        (\"PYTEST_ADDOPTS\", \"Extra command line options\"),\n        (\"PYTEST_PLUGINS\", \"Comma-separated plugins to load during startup\"),\n        (\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", \"Set to disable plugin auto-loading\"),\n        (\"PYTEST_DEBUG\", \"Set to enable debug tracing of pytest's internals\"),\n        (\"PYTEST_DEBUG_TEMPROOT\", \"Override the system temporary directory\"),\n        (\"PYTEST_THEME\", \"The Pygments style to use for code output\"),\n        (\"PYTEST_THEME_MODE\", \"Set the PYTEST_THEME to be either 'dark' or 'light'\"),\n    ]\n    for name, help in vars:\n        tw.line(f\"  {name:<24} {help}\")\n    tw.line()\n    tw.line()\n\n    tw.line(\"to see available markers type: pytest --markers\")\n    tw.line(\"to see available fixtures type: pytest --fixtures\")\n    tw.line(\n        \"(shown according to specified file_or_dir or current dir \"\n        \"if not specified; fixtures with leading '_' are only shown \"\n        \"with the '-v' option\"\n    )\n\n    for warningreport in reporter.stats.get(\"warnings\", []):\n        tw.line(\"warning : \" + warningreport.message, red=True)\n\n\ndef getpluginversioninfo(config: Config) -> list[str]:\n    lines = []\n    plugininfo = config.pluginmanager.list_plugin_distinfo()\n    if plugininfo:\n        lines.append(\"registered third-party plugins:\")\n        for plugin, dist in plugininfo:\n            loc = getattr(plugin, \"__file__\", repr(plugin))\n            content = f\"{dist.project_name}-{dist.version} at {loc}\"\n            lines.append(\"  \" + content)\n    return lines\n\n\ndef pytest_report_header(config: Config) -> list[str]:\n    lines = []\n    if config.option.debug or config.option.traceconfig:\n        lines.append(f\"using: pytest-{pytest.__version__}\")\n\n        verinfo = getpluginversioninfo(config)\n        if verinfo:\n            lines.extend(verinfo)\n\n    if config.option.traceconfig:\n        lines.append(\"active plugins:\")\n        items = config.pluginmanager.list_name_plugin()\n        for name, plugin in items:\n            if hasattr(plugin, \"__file__\"):\n                r = plugin.__file__\n            else:\n                r = repr(plugin)\n            lines.append(f\"    {name:<20}: {r}\")\n    return lines\n"
  },
  {
    "path": "src/_pytest/hookspec.py",
    "content": "# mypy: allow-untyped-defs\n# ruff: noqa: T100\n\"\"\"Hook specifications for pytest plugins which are invoked by pytest itself\nand by builtin plugins.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Mapping\nfrom collections.abc import Sequence\nfrom pathlib import Path\nfrom typing import Any\nfrom typing import TYPE_CHECKING\n\nfrom pluggy import HookspecMarker\n\n\nif TYPE_CHECKING:\n    import pdb\n    from typing import Literal\n    import warnings\n\n    from _pytest._code.code import ExceptionInfo\n    from _pytest._code.code import ExceptionRepr\n    from _pytest.config import _PluggyPlugin\n    from _pytest.config import Config\n    from _pytest.config import ExitCode\n    from _pytest.config import PytestPluginManager\n    from _pytest.config.argparsing import Parser\n    from _pytest.fixtures import FixtureDef\n    from _pytest.fixtures import SubRequest\n    from _pytest.main import Session\n    from _pytest.nodes import Collector\n    from _pytest.nodes import Item\n    from _pytest.outcomes import Exit\n    from _pytest.python import Class\n    from _pytest.python import Function\n    from _pytest.python import Metafunc\n    from _pytest.python import Module\n    from _pytest.reports import CollectReport\n    from _pytest.reports import TestReport\n    from _pytest.runner import CallInfo\n    from _pytest.terminal import TerminalReporter\n    from _pytest.terminal import TestShortLogReport\n\n\nhookspec = HookspecMarker(\"pytest\")\n\n# -------------------------------------------------------------------------\n# Initialization hooks called for every plugin\n# -------------------------------------------------------------------------\n\n\n@hookspec(historic=True)\ndef pytest_addhooks(pluginmanager: PytestPluginManager) -> None:\n    \"\"\"Called at plugin registration time to allow adding new hooks via a call to\n    :func:`pluginmanager.add_hookspecs(module_or_class, prefix) <pytest.PytestPluginManager.add_hookspecs>`.\n\n    :param pluginmanager: The pytest plugin manager.\n\n    .. note::\n        This hook is incompatible with hook wrappers.\n\n    Use in conftest plugins\n    =======================\n\n    If a conftest plugin implements this hook, it will be called immediately\n    when the conftest is registered.\n    \"\"\"\n\n\n@hookspec(historic=True)\ndef pytest_plugin_registered(\n    plugin: _PluggyPlugin,\n    plugin_name: str,\n    manager: PytestPluginManager,\n) -> None:\n    \"\"\"A new pytest plugin got registered.\n\n    :param plugin: The plugin module or instance.\n    :param plugin_name: The name by which the plugin is registered.\n    :param manager: The pytest plugin manager.\n\n    .. note::\n        This hook is incompatible with hook wrappers.\n\n    Use in conftest plugins\n    =======================\n\n    If a conftest plugin implements this hook, it will be called immediately\n    when the conftest is registered, once for each plugin registered thus far\n    (including itself!), and for all plugins thereafter when they are\n    registered.\n    \"\"\"\n\n\n@hookspec(historic=True)\ndef pytest_addoption(parser: Parser, pluginmanager: PytestPluginManager) -> None:\n    \"\"\"Register argparse-style options and config-style config values,\n    called once at the beginning of a test run.\n\n    :param parser:\n        To add command line options, call\n        :py:func:`parser.addoption(...) <pytest.Parser.addoption>`.\n        To add config-file values call :py:func:`parser.addini(...)\n        <pytest.Parser.addini>`.\n\n    :param pluginmanager:\n        The pytest plugin manager, which can be used to install :py:func:`~pytest.hookspec`'s\n        or :py:func:`~pytest.hookimpl`'s and allow one plugin to call another plugin's hooks\n        to change how command line options are added.\n\n    Options can later be accessed through the\n    :py:class:`config <pytest.Config>` object, respectively:\n\n    - :py:func:`config.getoption(name) <pytest.Config.getoption>` to\n      retrieve the value of a command line option.\n\n    - :py:func:`config.getini(name) <pytest.Config.getini>` to retrieve\n      a value read from a configuration file.\n\n    The config object is passed around on many internal objects via the ``.config``\n    attribute or can be retrieved as the ``pytestconfig`` fixture.\n\n    .. note::\n        This hook is incompatible with hook wrappers.\n\n    Use in conftest plugins\n    =======================\n\n    If a conftest plugin implements this hook, it will be called immediately\n    when the conftest is registered.\n\n    This hook is only called for :ref:`initial conftests <pluginorder>`.\n    \"\"\"\n\n\n@hookspec(historic=True)\ndef pytest_configure(config: Config) -> None:\n    \"\"\"Allow plugins and conftest files to perform initial configuration.\n\n    .. note::\n        This hook is incompatible with hook wrappers.\n\n    :param config: The pytest config object.\n\n    Use in conftest plugins\n    =======================\n\n    This hook is called for every :ref:`initial conftest <pluginorder>` file\n    after command line options have been parsed. After that, the hook is called\n    for other conftest files as they are registered.\n    \"\"\"\n\n\n# -------------------------------------------------------------------------\n# Bootstrapping hooks called for plugins registered early enough:\n# internal and 3rd party plugins.\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_cmdline_parse(\n    pluginmanager: PytestPluginManager, args: list[str]\n) -> Config | None:\n    \"\"\"Return an initialized :class:`~pytest.Config`, parsing the specified args.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    .. note::\n        This hook is only called for plugin classes passed to the\n        ``plugins`` arg when using `pytest.main`_ to perform an in-process\n        test run.\n\n    :param pluginmanager: The pytest plugin manager.\n    :param args: List of arguments passed on the command line.\n    :returns: A pytest config object.\n\n    Use in conftest plugins\n    =======================\n\n    This hook is not called for conftest files.\n    \"\"\"\n\n\ndef pytest_load_initial_conftests(\n    early_config: Config, parser: Parser, args: list[str]\n) -> None:\n    \"\"\"Called to implement the loading of :ref:`initial conftest files\n    <pluginorder>` ahead of command line option parsing.\n\n    :param early_config: The pytest config object.\n    :param args: Arguments passed on the command line.\n    :param parser: To add command line options.\n\n    Use in conftest plugins\n    =======================\n\n    This hook is not called for conftest files.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_cmdline_main(config: Config) -> ExitCode | int | None:\n    \"\"\"Called for performing the main command line action.\n\n    The default implementation will invoke the configure hooks and\n    :hook:`pytest_runtestloop`.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    :param config: The pytest config object.\n    :returns: The exit code.\n\n    Use in conftest plugins\n    =======================\n\n    This hook is only called for :ref:`initial conftests <pluginorder>`.\n    \"\"\"\n\n\n# -------------------------------------------------------------------------\n# collection hooks\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_collection(session: Session) -> object | None:\n    \"\"\"Perform the collection phase for the given session.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n    The return value is not used, but only stops further processing.\n\n    The default collection phase is this (see individual hooks for full details):\n\n    1. Starting from ``session`` as the initial collector:\n\n      1. ``pytest_collectstart(collector)``\n      2. ``report = pytest_make_collect_report(collector)``\n      3. ``pytest_exception_interact(collector, call, report)`` if an interactive exception occurred\n      4. For each collected node:\n\n        1. If an item, ``pytest_itemcollected(item)``\n        2. If a collector, recurse into it.\n\n      5. ``pytest_collectreport(report)``\n\n    2. ``pytest_collection_modifyitems(session, config, items)``\n\n      1. ``pytest_deselected(items)`` for any deselected items (may be called multiple times)\n\n    3. Set ``session.items`` to the list of collected items\n    4. ``pytest_collection_finish(session)``\n    5. Set ``session.testscollected`` to the number of collected items\n\n    You can implement this hook to only perform some action before collection,\n    for example the terminal plugin uses it to start displaying the collection\n    counter (and returns `None`).\n\n    :param session: The pytest session object.\n\n    Use in conftest plugins\n    =======================\n\n    This hook is only called for :ref:`initial conftests <pluginorder>`.\n    \"\"\"\n\n\ndef pytest_collection_modifyitems(\n    session: Session, config: Config, items: list[Item]\n) -> None:\n    \"\"\"Called after collection has been performed. May filter or re-order\n    the items in-place.\n\n    When items are deselected (filtered out from ``items``),\n    the hook :hook:`pytest_deselected` must be called explicitly\n    with the deselected items to properly notify other plugins,\n    e.g. with ``config.hook.pytest_deselected(items=deselected_items)``.\n\n    :param session: The pytest session object.\n    :param config: The pytest config object.\n    :param items: List of item objects.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest plugin can implement this hook.\n    \"\"\"\n\n\ndef pytest_collection_finish(session: Session) -> None:\n    \"\"\"Called after collection has been performed and modified.\n\n    :param session: The pytest session object.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest plugin can implement this hook.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_ignore_collect(collection_path: Path, config: Config) -> bool | None:\n    \"\"\"Return ``True`` to ignore this path for collection.\n\n    Return ``None`` to let other plugins ignore the path for collection.\n\n    Returning ``False`` will forcefully *not* ignore this path for collection,\n    without giving a chance for other plugins to ignore this path.\n\n    This hook is consulted for all files and directories prior to calling\n    more specific hooks.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    :param collection_path: The path to analyze.\n    :type collection_path: pathlib.Path\n    :param path: The path to analyze (deprecated).\n    :param config: The pytest config object.\n\n    .. versionchanged:: 7.0.0\n        The ``collection_path`` parameter was added as a :class:`pathlib.Path`\n        equivalent of the ``path`` parameter. The ``path`` parameter\n        has been deprecated and removed in pytest 9.0.0.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given collection path, only\n    conftest files in parent directories of the collection path are consulted\n    (if the path is a directory, its own conftest file is *not* consulted - a\n    directory cannot ignore itself!).\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_collect_directory(path: Path, parent: Collector) -> Collector | None:\n    \"\"\"Create a :class:`~pytest.Collector` for the given directory, or None if\n    not relevant.\n\n    .. versionadded:: 8.0\n\n    For best results, the returned collector should be a subclass of\n    :class:`~pytest.Directory`, but this is not required.\n\n    The new node needs to have the specified ``parent`` as a parent.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    :param path: The path to analyze.\n    :type path: pathlib.Path\n\n    See :ref:`custom directory collectors` for a simple example of use of this\n    hook.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given collection path, only\n    conftest files in parent directories of the collection path are consulted\n    (if the path is a directory, its own conftest file is *not* consulted - a\n    directory cannot collect itself!).\n    \"\"\"\n\n\ndef pytest_collect_file(file_path: Path, parent: Collector) -> Collector | None:\n    \"\"\"Create a :class:`~pytest.Collector` for the given path, or None if not relevant.\n\n    For best results, the returned collector should be a subclass of\n    :class:`~pytest.File`, but this is not required.\n\n    The new node needs to have the specified ``parent`` as a parent.\n\n    :param file_path: The path to analyze.\n    :type file_path: pathlib.Path\n    :param path: The path to collect (deprecated).\n\n    .. versionchanged:: 7.0.0\n        The ``file_path`` parameter was added as a :class:`pathlib.Path`\n        equivalent of the ``path`` parameter. The ``path`` parameter\n        has been deprecated and removed in pytest 9.0.0.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given file path, only\n    conftest files in parent directories of the file path are consulted.\n    \"\"\"\n\n\n# logging hooks for collection\n\n\ndef pytest_collectstart(collector: Collector) -> None:\n    \"\"\"Collector starts collecting.\n\n    :param collector:\n        The collector.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given collector, only\n    conftest files in the collector's directory and its parent directories are\n    consulted.\n    \"\"\"\n\n\ndef pytest_itemcollected(item: Item) -> None:\n    \"\"\"We just collected a test item.\n\n    :param item:\n        The item.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in the item's directory and its parent directories are consulted.\n    \"\"\"\n\n\ndef pytest_collectreport(report: CollectReport) -> None:\n    \"\"\"Collector finished collecting.\n\n    :param report:\n        The collect report.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given collector, only\n    conftest files in the collector's directory and its parent directories are\n    consulted.\n    \"\"\"\n\n\ndef pytest_deselected(items: Sequence[Item]) -> None:\n    \"\"\"Called for deselected test items, e.g. by keyword.\n\n    Note that this hook has two integration aspects for plugins:\n\n    - it can be *implemented* to be notified of deselected items\n    - it must be *called* from :hook:`pytest_collection_modifyitems`\n      implementations when items are deselected (to properly notify other plugins).\n\n    May be called multiple times.\n\n    :param items:\n        The items.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_make_collect_report(collector: Collector) -> CollectReport | None:\n    \"\"\"Perform :func:`collector.collect() <pytest.Collector.collect>` and return\n    a :class:`~pytest.CollectReport`.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    :param collector:\n        The collector.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given collector, only\n    conftest files in the collector's directory and its parent directories are\n    consulted.\n    \"\"\"\n\n\n# -------------------------------------------------------------------------\n# Python test function related hooks\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_pycollect_makemodule(module_path: Path, parent) -> Module | None:\n    \"\"\"Return a :class:`pytest.Module` collector or None for the given path.\n\n    This hook will be called for each matching test module path.\n    The :hook:`pytest_collect_file` hook needs to be used if you want to\n    create test modules for files that do not match as a test module.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    :param module_path: The path of the module to collect.\n    :type module_path: pathlib.Path\n    :param path: The path of the module to collect (deprecated).\n\n    .. versionchanged:: 7.0.0\n        The ``module_path`` parameter was added as a :class:`pathlib.Path`\n        equivalent of the ``path`` parameter. The ``path`` parameter has been\n        deprecated in favor of ``module_path`` and removed in pytest 9.0.0.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given parent collector,\n    only conftest files in the collector's directory and its parent directories\n    are consulted.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_pycollect_makeitem(\n    collector: Module | Class, name: str, obj: object\n) -> None | Item | Collector | list[Item | Collector]:\n    \"\"\"Return a custom item/collector for a Python object in a module, or None.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    :param collector:\n        The module/class collector.\n    :param name:\n        The name of the object in the module/class.\n    :param obj:\n        The object.\n    :returns:\n        The created items/collectors.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given collector, only\n    conftest files in the collector's directory and its parent directories\n    are consulted.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_pyfunc_call(pyfuncitem: Function) -> object | None:\n    \"\"\"Call underlying test function.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    :param pyfuncitem:\n        The function item.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only\n    conftest files in the item's directory and its parent directories\n    are consulted.\n    \"\"\"\n\n\ndef pytest_generate_tests(metafunc: Metafunc) -> None:\n    \"\"\"Generate (multiple) parametrized calls to a test function.\n\n    :param metafunc:\n        The :class:`~pytest.Metafunc` helper for the test function.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given function definition,\n    only conftest files in the functions's directory and its parent directories\n    are consulted.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_make_parametrize_id(config: Config, val: object, argname: str) -> str | None:\n    \"\"\"Return a user-friendly string representation of the given ``val``\n    that will be used by @pytest.mark.parametrize calls, or None if the hook\n    doesn't know about ``val``.\n\n    The parameter name is available as ``argname``, if required.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    :param config: The pytest config object.\n    :param val: The parametrized value.\n    :param argname: The automatic parameter name produced by pytest.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook.\n    \"\"\"\n\n\n# -------------------------------------------------------------------------\n# runtest related hooks\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_runtestloop(session: Session) -> object | None:\n    \"\"\"Perform the main runtest loop (after collection finished).\n\n    The default hook implementation performs the runtest protocol for all items\n    collected in the session (``session.items``), unless the collection failed\n    or the ``collectonly`` pytest option is set.\n\n    If at any point :py:func:`pytest.exit` is called, the loop is\n    terminated immediately.\n\n    If at any point ``session.shouldfail`` or ``session.shouldstop`` are set, the\n    loop is terminated after the runtest protocol for the current item is finished.\n\n    :param session: The pytest session object.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n    The return value is not used, but only stops further processing.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_runtest_protocol(item: Item, nextitem: Item | None) -> object | None:\n    \"\"\"Perform the runtest protocol for a single test item.\n\n    The default runtest protocol is this (see individual hooks for full details):\n\n    - ``pytest_runtest_logstart(nodeid, location)``\n\n    - Setup phase:\n        - ``call = pytest_runtest_setup(item)`` (wrapped in ``CallInfo(when=\"setup\")``)\n        - ``report = pytest_runtest_makereport(item, call)``\n        - ``pytest_runtest_logreport(report)``\n        - ``pytest_exception_interact(call, report)`` if an interactive exception occurred\n\n    - Call phase, if the setup passed and the ``setuponly`` pytest option is not set:\n        - ``call = pytest_runtest_call(item)`` (wrapped in ``CallInfo(when=\"call\")``)\n        - ``report = pytest_runtest_makereport(item, call)``\n        - ``pytest_runtest_logreport(report)``\n        - ``pytest_exception_interact(call, report)`` if an interactive exception occurred\n\n    - Teardown phase:\n        - ``call = pytest_runtest_teardown(item, nextitem)`` (wrapped in ``CallInfo(when=\"teardown\")``)\n        - ``report = pytest_runtest_makereport(item, call)``\n        - ``pytest_runtest_logreport(report)``\n        - ``pytest_exception_interact(call, report)`` if an interactive exception occurred\n\n    - ``pytest_runtest_logfinish(nodeid, location)``\n\n    :param item: Test item for which the runtest protocol is performed.\n    :param nextitem: The scheduled-to-be-next test item (or None if this is the end my friend).\n\n    Stops at first non-None result, see :ref:`firstresult`.\n    The return value is not used, but only stops further processing.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook.\n    \"\"\"\n\n\ndef pytest_runtest_logstart(nodeid: str, location: tuple[str, int | None, str]) -> None:\n    \"\"\"Called at the start of running the runtest protocol for a single item.\n\n    See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.\n\n    :param nodeid: Full node ID of the item.\n    :param location: A tuple of ``(filename, lineno, testname)``\n        where ``filename`` is a file path relative to ``config.rootpath``\n        and ``lineno`` is 0-based.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in the item's directory and its parent directories are consulted.\n    \"\"\"\n\n\ndef pytest_runtest_logfinish(\n    nodeid: str, location: tuple[str, int | None, str]\n) -> None:\n    \"\"\"Called at the end of running the runtest protocol for a single item.\n\n    See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.\n\n    :param nodeid: Full node ID of the item.\n    :param location: A tuple of ``(filename, lineno, testname)``\n        where ``filename`` is a file path relative to ``config.rootpath``\n        and ``lineno`` is 0-based.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in the item's directory and its parent directories are consulted.\n    \"\"\"\n\n\ndef pytest_runtest_setup(item: Item) -> None:\n    \"\"\"Called to perform the setup phase for a test item.\n\n    The default implementation runs ``setup()`` on ``item`` and all of its\n    parents (which haven't been setup yet). This includes obtaining the\n    values of fixtures required by the item (which haven't been obtained\n    yet).\n\n    :param item:\n        The item.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in the item's directory and its parent directories are consulted.\n    \"\"\"\n\n\ndef pytest_runtest_call(item: Item) -> None:\n    \"\"\"Called to run the test for test item (the call phase).\n\n    The default implementation calls ``item.runtest()``.\n\n    :param item:\n        The item.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in the item's directory and its parent directories are consulted.\n    \"\"\"\n\n\ndef pytest_runtest_teardown(item: Item, nextitem: Item | None) -> None:\n    \"\"\"Called to perform the teardown phase for a test item.\n\n    The default implementation runs the finalizers and calls ``teardown()``\n    on ``item`` and all of its parents (which need to be torn down). This\n    includes running the teardown phase of fixtures required by the item (if\n    they go out of scope).\n\n    :param item:\n        The item.\n    :param nextitem:\n        The scheduled-to-be-next test item (None if no further test item is\n        scheduled). This argument is used to perform exact teardowns, i.e.\n        calling just enough finalizers so that nextitem only needs to call\n        setup functions.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in the item's directory and its parent directories are consulted.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> TestReport | None:\n    \"\"\"Called to create a :class:`~pytest.TestReport` for each of\n    the setup, call and teardown runtest phases of a test item.\n\n    See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.\n\n    :param item: The item.\n    :param call: The :class:`~pytest.CallInfo` for the phase.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in the item's directory and its parent directories are consulted.\n    \"\"\"\n\n\ndef pytest_runtest_logreport(report: TestReport) -> None:\n    \"\"\"Process the :class:`~pytest.TestReport` produced for each\n    of the setup, call and teardown runtest phases of an item.\n\n    See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in the item's directory and its parent directories are consulted.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_report_to_serializable(\n    config: Config,\n    report: CollectReport | TestReport,\n) -> dict[str, Any] | None:\n    \"\"\"Serialize the given report object into a data structure suitable for\n    sending over the wire, e.g. converted to JSON.\n\n    :param config: The pytest config object.\n    :param report: The report.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. The exact details may depend\n    on the plugin which calls the hook.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_report_from_serializable(\n    config: Config,\n    data: dict[str, Any],\n) -> CollectReport | TestReport | None:\n    \"\"\"Restore a report object previously serialized with\n    :hook:`pytest_report_to_serializable`.\n\n    :param config: The pytest config object.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. The exact details may depend\n    on the plugin which calls the hook.\n    \"\"\"\n\n\n# -------------------------------------------------------------------------\n# Fixture related hooks\n# -------------------------------------------------------------------------\n\n\n@hookspec(firstresult=True)\ndef pytest_fixture_setup(\n    fixturedef: FixtureDef[Any], request: SubRequest\n) -> object | None:\n    \"\"\"Perform fixture setup execution.\n\n    :param fixturedef:\n        The fixture definition object.\n    :param request:\n        The fixture request object.\n    :returns:\n        The return value of the call to the fixture function.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    .. note::\n        If the fixture function returns None, other implementations of\n        this hook function will continue to be called, according to the\n        behavior of the :ref:`firstresult` option.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given fixture, only\n    conftest files in the fixture scope's directory and its parent directories\n    are consulted.\n    \"\"\"\n\n\ndef pytest_fixture_post_finalizer(\n    fixturedef: FixtureDef[Any], request: SubRequest\n) -> None:\n    \"\"\"Called after fixture teardown, but before the cache is cleared, so\n    the fixture result ``fixturedef.cached_result`` is still available (not\n    ``None``).\n\n    :param fixturedef:\n        The fixture definition object.\n    :param request:\n        The fixture request object.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given fixture, only\n    conftest files in the fixture scope's directory and its parent directories\n    are consulted.\n    \"\"\"\n\n\n# -------------------------------------------------------------------------\n# test session related hooks\n# -------------------------------------------------------------------------\n\n\ndef pytest_sessionstart(session: Session) -> None:\n    \"\"\"Called after the ``Session`` object has been created and before performing collection\n    and entering the run test loop.\n\n    :param session: The pytest session object.\n\n    Use in conftest plugins\n    =======================\n\n    This hook is only called for :ref:`initial conftests <pluginorder>`.\n    \"\"\"\n\n\ndef pytest_sessionfinish(\n    session: Session,\n    exitstatus: int | ExitCode,\n) -> None:\n    \"\"\"Called after whole test run finished, right before returning the exit status to the system.\n\n    :param session: The pytest session object.\n    :param exitstatus: The status which pytest will return to the system.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook.\n    \"\"\"\n\n\ndef pytest_unconfigure(config: Config) -> None:\n    \"\"\"Called before test process is exited.\n\n    :param config: The pytest config object.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook.\n    \"\"\"\n\n\n# -------------------------------------------------------------------------\n# hooks for customizing the assert methods\n# -------------------------------------------------------------------------\n\n\ndef pytest_assertrepr_compare(\n    config: Config, op: str, left: object, right: object\n) -> list[str] | None:\n    \"\"\"Return explanation for comparisons in failing assert expressions.\n\n    Return None for no custom explanation, otherwise return a list\n    of strings. The strings will be joined by newlines but any newlines\n    *in* a string will be escaped. Note that all but the first line will\n    be indented slightly, the intention is for the first line to be a summary.\n\n    :param config: The pytest config object.\n    :param op: The operator, e.g. `\"==\"`, `\"!=\"`, `\"not in\"`.\n    :param left: The left operand.\n    :param right: The right operand.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in the item's directory and its parent directories are consulted.\n    \"\"\"\n\n\ndef pytest_assertion_pass(item: Item, lineno: int, orig: str, expl: str) -> None:\n    \"\"\"Called whenever an assertion passes.\n\n    .. versionadded:: 5.0\n\n    Use this hook to do some processing after a passing assertion.\n    The original assertion information is available in the `orig` string\n    and the pytest introspected assertion information is available in the\n    `expl` string.\n\n    This hook must be explicitly enabled by the :confval:`enable_assertion_pass_hook`\n    configuration option:\n\n    .. tab:: toml\n\n        .. code-block:: toml\n\n            [pytest]\n            enable_assertion_pass_hook = true\n\n    .. tab:: ini\n\n        .. code-block:: ini\n\n            [pytest]\n            enable_assertion_pass_hook = true\n\n    You need to **clean the .pyc** files in your project directory and interpreter libraries\n    when enabling this option, as assertions will require to be re-written.\n\n    :param item: pytest item object of current test.\n    :param lineno: Line number of the assert statement.\n    :param orig: String with the original assertion.\n    :param expl: String with the assert explanation.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in the item's directory and its parent directories are consulted.\n    \"\"\"\n\n\n# -------------------------------------------------------------------------\n# Hooks for influencing reporting (invoked from _pytest_terminal).\n# -------------------------------------------------------------------------\n\n\ndef pytest_report_header(config: Config, start_path: Path) -> str | list[str]:  # type: ignore[empty-body]\n    \"\"\"Return a string or list of strings to be displayed as header info for terminal reporting.\n\n    :param config: The pytest config object.\n    :param start_path: The starting dir.\n    :type start_path: pathlib.Path\n    :param startdir: The starting dir (deprecated).\n\n    .. note::\n\n        Lines returned by a plugin are displayed before those of plugins which\n        ran before it.\n        If you want to have your line(s) displayed first, use\n        :ref:`trylast=True <plugin-hookorder>`.\n\n    .. versionchanged:: 7.0.0\n        The ``start_path`` parameter was added as a :class:`pathlib.Path`\n        equivalent of the ``startdir`` parameter. The ``startdir`` parameter\n        has been deprecated and removed in pytest 9.0.0.\n\n    Use in conftest plugins\n    =======================\n\n    This hook is only called for :ref:`initial conftests <pluginorder>`.\n    \"\"\"\n\n\ndef pytest_report_collectionfinish(  # type: ignore[empty-body]\n    config: Config,\n    start_path: Path,\n    items: Sequence[Item],\n) -> str | list[str]:\n    \"\"\"Return a string or list of strings to be displayed after collection\n    has finished successfully.\n\n    These strings will be displayed after the standard \"collected X items\" message.\n\n    .. versionadded:: 3.2\n\n    :param config: The pytest config object.\n    :param start_path: The starting dir.\n    :type start_path: pathlib.Path\n    :param startdir: The starting dir (deprecated).\n    :param items: List of pytest items that are going to be executed; this list should not be modified.\n\n    .. note::\n\n        Lines returned by a plugin are displayed before those of plugins which\n        ran before it.\n        If you want to have your line(s) displayed first, use\n        :ref:`trylast=True <plugin-hookorder>`.\n\n    .. versionchanged:: 7.0.0\n        The ``start_path`` parameter was added as a :class:`pathlib.Path`\n        equivalent of the ``startdir`` parameter. The ``startdir`` parameter\n        has been deprecated and removed in pytest 9.0.0.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest plugin can implement this hook.\n    \"\"\"\n\n\n@hookspec(firstresult=True)\ndef pytest_report_teststatus(  # type:ignore[empty-body]\n    report: CollectReport | TestReport, config: Config\n) -> TestShortLogReport | tuple[str, str, str | tuple[str, Mapping[str, bool]]]:\n    \"\"\"Return result-category, shortletter and verbose word for status\n    reporting.\n\n    The result-category is a category in which to count the result, for\n    example \"passed\", \"skipped\", \"error\" or the empty string.\n\n    The shortletter is shown as testing progresses, for example \".\", \"s\",\n    \"E\" or the empty string.\n\n    The verbose word is shown as testing progresses in verbose mode, for\n    example \"PASSED\", \"SKIPPED\", \"ERROR\" or the empty string.\n\n    pytest may style these implicitly according to the report outcome.\n    To provide explicit styling, return a tuple for the verbose word,\n    for example ``\"rerun\", \"R\", (\"RERUN\", {\"yellow\": True})``.\n\n    :param report: The report object whose status is to be returned.\n    :param config: The pytest config object.\n    :returns: The test status.\n\n    Stops at first non-None result, see :ref:`firstresult`.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest plugin can implement this hook.\n    \"\"\"\n\n\ndef pytest_terminal_summary(\n    terminalreporter: TerminalReporter,\n    exitstatus: ExitCode,\n    config: Config,\n) -> None:\n    \"\"\"Add a section to terminal summary reporting.\n\n    :param terminalreporter: The internal terminal reporter object.\n    :param exitstatus: The exit status that will be reported back to the OS.\n    :param config: The pytest config object.\n\n    .. versionadded:: 4.2\n        The ``config`` parameter.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest plugin can implement this hook.\n    \"\"\"\n\n\n@hookspec(historic=True)\ndef pytest_warning_recorded(\n    warning_message: warnings.WarningMessage,\n    when: Literal[\"config\", \"collect\", \"runtest\"],\n    nodeid: str,\n    location: tuple[str, int, str] | None,\n) -> None:\n    \"\"\"Process a warning captured by the internal pytest warnings plugin.\n\n    :param warning_message:\n        The captured warning. This is the same object produced by :class:`warnings.catch_warnings`,\n        and contains the same attributes as the parameters of :py:func:`warnings.showwarning`.\n\n    :param when:\n        Indicates when the warning was captured. Possible values:\n\n        * ``\"config\"``: during pytest configuration/initialization stage.\n        * ``\"collect\"``: during test collection.\n        * ``\"runtest\"``: during test execution.\n\n    :param nodeid:\n        Full id of the item. Empty string for warnings that are not specific to\n        a particular node.\n\n    :param location:\n        When available, holds information about the execution context of the captured\n        warning (filename, linenumber, function). ``function`` evaluates to <module>\n        when the execution context is at the module level.\n\n    .. versionadded:: 6.0\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. If the warning is specific to a\n    particular node, only conftest files in parent directories of the node are\n    consulted.\n    \"\"\"\n\n\n# -------------------------------------------------------------------------\n# Hooks for influencing skipping\n# -------------------------------------------------------------------------\n\n\ndef pytest_markeval_namespace(  # type:ignore[empty-body]\n    config: Config,\n) -> dict[str, Any]:\n    \"\"\"Called when constructing the globals dictionary used for\n    evaluating string conditions in xfail/skipif markers.\n\n    This is useful when the condition for a marker requires\n    objects that are expensive or impossible to obtain during\n    collection time, which is required by normal boolean\n    conditions.\n\n    .. versionadded:: 6.2\n\n    :param config: The pytest config object.\n    :returns: A dictionary of additional globals to add.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given item, only conftest\n    files in parent directories of the item are consulted.\n    \"\"\"\n\n\n# -------------------------------------------------------------------------\n# error handling and internal debugging hooks\n# -------------------------------------------------------------------------\n\n\ndef pytest_internalerror(\n    excrepr: ExceptionRepr,\n    excinfo: ExceptionInfo[BaseException],\n) -> bool | None:\n    \"\"\"Called for internal errors.\n\n    Return True to suppress the fallback handling of printing an\n    INTERNALERROR message directly to sys.stderr.\n\n    :param excrepr: The exception repr object.\n    :param excinfo: The exception info.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest plugin can implement this hook.\n    \"\"\"\n\n\ndef pytest_keyboard_interrupt(\n    excinfo: ExceptionInfo[KeyboardInterrupt | Exit],\n) -> None:\n    \"\"\"Called for keyboard interrupt.\n\n    :param excinfo: The exception info.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest plugin can implement this hook.\n    \"\"\"\n\n\ndef pytest_exception_interact(\n    node: Item | Collector,\n    call: CallInfo[Any],\n    report: CollectReport | TestReport,\n) -> None:\n    \"\"\"Called when an exception was raised which can potentially be\n    interactively handled.\n\n    May be called during collection (see :hook:`pytest_make_collect_report`),\n    in which case ``report`` is a :class:`~pytest.CollectReport`.\n\n    May be called during runtest of an item (see :hook:`pytest_runtest_protocol`),\n    in which case ``report`` is a :class:`~pytest.TestReport`.\n\n    This hook is not called if the exception that was raised is an internal\n    exception like ``skip.Exception``.\n\n    :param node:\n        The item or collector.\n    :param call:\n        The call information. Contains the exception.\n    :param report:\n        The collection or test report.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest file can implement this hook. For a given node, only conftest\n    files in parent directories of the node are consulted.\n    \"\"\"\n\n\ndef pytest_enter_pdb(config: Config, pdb: pdb.Pdb) -> None:\n    \"\"\"Called upon pdb.set_trace().\n\n    Can be used by plugins to take special action just before the python\n    debugger enters interactive mode.\n\n    :param config: The pytest config object.\n    :param pdb: The Pdb instance.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest plugin can implement this hook.\n    \"\"\"\n\n\ndef pytest_leave_pdb(config: Config, pdb: pdb.Pdb) -> None:\n    \"\"\"Called when leaving pdb (e.g. with continue after pdb.set_trace()).\n\n    Can be used by plugins to take special action just after the python\n    debugger leaves interactive mode.\n\n    :param config: The pytest config object.\n    :param pdb: The Pdb instance.\n\n    Use in conftest plugins\n    =======================\n\n    Any conftest plugin can implement this hook.\n    \"\"\"\n"
  },
  {
    "path": "src/_pytest/junitxml.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Report test results in JUnit-XML format, for use with Jenkins and build\nintegration servers.\n\nBased on initial code from Ross Lawley.\n\nOutput conforms to\nhttps://github.com/jenkinsci/xunit-plugin/blob/master/src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nimport functools\nimport os\nimport platform\nimport re\nimport xml.etree.ElementTree as ET\n\nfrom _pytest import nodes\nfrom _pytest import timing\nfrom _pytest._code.code import ExceptionRepr\nfrom _pytest._code.code import ReprFileLocation\nfrom _pytest.config import Config\nfrom _pytest.config import filename_arg\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.reports import TestReport\nfrom _pytest.stash import StashKey\nfrom _pytest.terminal import TerminalReporter\nimport pytest\n\n\nxml_key = StashKey[\"LogXML\"]()\n\n\ndef bin_xml_escape(arg: object) -> str:\n    r\"\"\"Visually escape invalid XML characters.\n\n    For example, transforms\n        'hello\\aworld\\b'\n    into\n        'hello#x07world#x08'\n    Note that the #xABs are *not* XML escapes - missing the ampersand &#xAB.\n    The idea is to escape visually for the user rather than for XML itself.\n    \"\"\"\n\n    def repl(matchobj: re.Match[str]) -> str:\n        i = ord(matchobj.group())\n        if i <= 0xFF:\n            return f\"#x{i:02X}\"\n        else:\n            return f\"#x{i:04X}\"\n\n    # The spec range of valid chars is:\n    # Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]\n    # For an unknown(?) reason, we disallow #x7F (DEL) as well.\n    illegal_xml_re = (\n        \"[^\\u0009\\u000a\\u000d\\u0020-\\u007e\\u0080-\\ud7ff\\ue000-\\ufffd\\u10000-\\u10ffff]\"\n    )\n    return re.sub(illegal_xml_re, repl, str(arg))\n\n\ndef merge_family(left, right) -> None:\n    result = {}\n    for kl, vl in left.items():\n        for kr, vr in right.items():\n            if not isinstance(vl, list):\n                raise TypeError(type(vl))\n            result[kl] = vl + vr\n    left.update(result)\n\n\nfamilies = {  # pylint: disable=dict-init-mutate\n    \"_base\": {\"testcase\": [\"classname\", \"name\"]},\n    \"_base_legacy\": {\"testcase\": [\"file\", \"line\", \"url\"]},\n}\n# xUnit 1.x inherits legacy attributes.\nfamilies[\"xunit1\"] = families[\"_base\"].copy()\nmerge_family(families[\"xunit1\"], families[\"_base_legacy\"])\n\n# xUnit 2.x uses strict base attributes.\nfamilies[\"xunit2\"] = families[\"_base\"]\n\n\nclass _NodeReporter:\n    def __init__(self, nodeid: str | TestReport, xml: LogXML) -> None:\n        self.id = nodeid\n        self.xml = xml\n        self.add_stats = self.xml.add_stats\n        self.family = self.xml.family\n        self.duration = 0.0\n        self.properties: list[tuple[str, str]] = []\n        self.nodes: list[ET.Element] = []\n        self.attrs: dict[str, str] = {}\n\n    def append(self, node: ET.Element) -> None:\n        self.xml.add_stats(node.tag)\n        self.nodes.append(node)\n\n    def add_property(self, name: str, value: object) -> None:\n        self.properties.append((str(name), bin_xml_escape(value)))\n\n    def add_attribute(self, name: str, value: object) -> None:\n        self.attrs[str(name)] = bin_xml_escape(value)\n\n    def make_properties_node(self) -> ET.Element | None:\n        \"\"\"Return a Junit node containing custom properties, if any.\"\"\"\n        if self.properties:\n            properties = ET.Element(\"properties\")\n            for name, value in self.properties:\n                properties.append(ET.Element(\"property\", name=name, value=value))\n            return properties\n        return None\n\n    def record_testreport(self, testreport: TestReport) -> None:\n        names = mangle_test_address(testreport.nodeid)\n        existing_attrs = self.attrs\n        classnames = names[:-1]\n        if self.xml.prefix:\n            classnames.insert(0, self.xml.prefix)\n        attrs: dict[str, str] = {\n            \"classname\": \".\".join(classnames),\n            \"name\": bin_xml_escape(names[-1]),\n            \"file\": testreport.location[0],\n        }\n        if testreport.location[1] is not None:\n            attrs[\"line\"] = str(testreport.location[1])\n        if hasattr(testreport, \"url\"):\n            attrs[\"url\"] = testreport.url\n        self.attrs = attrs\n        self.attrs.update(existing_attrs)  # Restore any user-defined attributes.\n\n        # Preserve legacy testcase behavior.\n        if self.family == \"xunit1\":\n            return\n\n        # Filter out attributes not permitted by this test family.\n        # Including custom attributes because they are not valid here.\n        temp_attrs = {}\n        for key in self.attrs:\n            if key in families[self.family][\"testcase\"]:\n                temp_attrs[key] = self.attrs[key]\n        self.attrs = temp_attrs\n\n    def to_xml(self) -> ET.Element:\n        testcase = ET.Element(\"testcase\", self.attrs, time=f\"{self.duration:.3f}\")\n        properties = self.make_properties_node()\n        if properties is not None:\n            testcase.append(properties)\n        testcase.extend(self.nodes)\n        return testcase\n\n    def _add_simple(self, tag: str, message: str, data: str | None = None) -> None:\n        node = ET.Element(tag, message=message)\n        node.text = bin_xml_escape(data)\n        self.append(node)\n\n    def write_captured_output(self, report: TestReport) -> None:\n        if not self.xml.log_passing_tests and report.passed:\n            return\n\n        content_out = report.capstdout\n        content_log = report.caplog\n        content_err = report.capstderr\n        if self.xml.logging == \"no\":\n            return\n        content_all = \"\"\n        if self.xml.logging in [\"log\", \"all\"]:\n            content_all = self._prepare_content(content_log, \" Captured Log \")\n        if self.xml.logging in [\"system-out\", \"out-err\", \"all\"]:\n            content_all += self._prepare_content(content_out, \" Captured Out \")\n            self._write_content(report, content_all, \"system-out\")\n            content_all = \"\"\n        if self.xml.logging in [\"system-err\", \"out-err\", \"all\"]:\n            content_all += self._prepare_content(content_err, \" Captured Err \")\n            self._write_content(report, content_all, \"system-err\")\n            content_all = \"\"\n        if content_all:\n            self._write_content(report, content_all, \"system-out\")\n\n    def _prepare_content(self, content: str, header: str) -> str:\n        return \"\\n\".join([header.center(80, \"-\"), content, \"\"])\n\n    def _write_content(self, report: TestReport, content: str, jheader: str) -> None:\n        tag = ET.Element(jheader)\n        tag.text = bin_xml_escape(content)\n        self.append(tag)\n\n    def append_pass(self, report: TestReport) -> None:\n        self.add_stats(\"passed\")\n\n    def append_failure(self, report: TestReport) -> None:\n        # msg = str(report.longrepr.reprtraceback.extraline)\n        if hasattr(report, \"wasxfail\"):\n            self._add_simple(\"skipped\", \"xfail-marked test passes unexpectedly\")\n        else:\n            assert report.longrepr is not None\n            reprcrash: ReprFileLocation | None = getattr(\n                report.longrepr, \"reprcrash\", None\n            )\n            if reprcrash is not None:\n                message = reprcrash.message\n            else:\n                message = str(report.longrepr)\n            message = bin_xml_escape(message)\n            self._add_simple(\"failure\", message, str(report.longrepr))\n\n    def append_collect_error(self, report: TestReport) -> None:\n        # msg = str(report.longrepr.reprtraceback.extraline)\n        assert report.longrepr is not None\n        self._add_simple(\"error\", \"collection failure\", str(report.longrepr))\n\n    def append_collect_skipped(self, report: TestReport) -> None:\n        self._add_simple(\"skipped\", \"collection skipped\", str(report.longrepr))\n\n    def append_error(self, report: TestReport) -> None:\n        assert report.longrepr is not None\n        reprcrash: ReprFileLocation | None = getattr(report.longrepr, \"reprcrash\", None)\n        if reprcrash is not None:\n            reason = reprcrash.message\n        else:\n            reason = str(report.longrepr)\n\n        if report.when == \"teardown\":\n            msg = f'failed on teardown with \"{reason}\"'\n        else:\n            msg = f'failed on setup with \"{reason}\"'\n        self._add_simple(\"error\", bin_xml_escape(msg), str(report.longrepr))\n\n    def append_skipped(self, report: TestReport) -> None:\n        if hasattr(report, \"wasxfail\"):\n            xfailreason = report.wasxfail\n            if xfailreason.startswith(\"reason: \"):\n                xfailreason = xfailreason[8:]\n            xfailreason = bin_xml_escape(xfailreason)\n            skipped = ET.Element(\"skipped\", type=\"pytest.xfail\", message=xfailreason)\n            self.append(skipped)\n        else:\n            assert isinstance(report.longrepr, tuple)\n            filename, lineno, skipreason = report.longrepr\n            if skipreason.startswith(\"Skipped: \"):\n                skipreason = skipreason[9:]\n            details = f\"{filename}:{lineno}: {skipreason}\"\n\n            skipped = ET.Element(\n                \"skipped\", type=\"pytest.skip\", message=bin_xml_escape(skipreason)\n            )\n            skipped.text = bin_xml_escape(details)\n            self.append(skipped)\n            self.write_captured_output(report)\n\n    def finalize(self) -> None:\n        data = self.to_xml()\n        self.__dict__.clear()\n        # Type ignored because mypy doesn't like overriding a method.\n        # Also the return value doesn't match...\n        self.to_xml = lambda: data  # type: ignore[method-assign]\n\n\ndef _warn_incompatibility_with_xunit2(\n    request: FixtureRequest, fixture_name: str\n) -> None:\n    \"\"\"Emit a PytestWarning about the given fixture being incompatible with newer xunit revisions.\"\"\"\n    from _pytest.warning_types import PytestWarning\n\n    xml = request.config.stash.get(xml_key, None)\n    if xml is not None and xml.family not in (\"xunit1\", \"legacy\"):\n        request.node.warn(\n            PytestWarning(\n                f\"{fixture_name} is incompatible with junit_family '{xml.family}' (use 'legacy' or 'xunit1')\"\n            )\n        )\n\n\n@pytest.fixture\ndef record_property(request: FixtureRequest) -> Callable[[str, object], None]:\n    \"\"\"Add extra properties to the calling test.\n\n    User properties become part of the test report and are available to the\n    configured reporters, like JUnit XML.\n\n    The fixture is callable with ``name, value``. The value is automatically\n    XML-encoded.\n\n    Example::\n\n        def test_function(record_property):\n            record_property(\"example_key\", 1)\n    \"\"\"\n    _warn_incompatibility_with_xunit2(request, \"record_property\")\n\n    def append_property(name: str, value: object) -> None:\n        request.node.user_properties.append((name, value))\n\n    return append_property\n\n\n@pytest.fixture\ndef record_xml_attribute(request: FixtureRequest) -> Callable[[str, object], None]:\n    \"\"\"Add extra xml attributes to the tag for the calling test.\n\n    The fixture is callable with ``name, value``. The value is\n    automatically XML-encoded.\n    \"\"\"\n    from _pytest.warning_types import PytestExperimentalApiWarning\n\n    request.node.warn(\n        PytestExperimentalApiWarning(\"record_xml_attribute is an experimental feature\")\n    )\n\n    _warn_incompatibility_with_xunit2(request, \"record_xml_attribute\")\n\n    # Declare noop\n    def add_attr_noop(name: str, value: object) -> None:\n        pass\n\n    attr_func = add_attr_noop\n\n    xml = request.config.stash.get(xml_key, None)\n    if xml is not None:\n        node_reporter = xml.node_reporter(request.node.nodeid)\n        attr_func = node_reporter.add_attribute\n\n    return attr_func\n\n\ndef _check_record_param_type(param: str, v: str) -> None:\n    \"\"\"Used by record_testsuite_property to check that the given parameter name is of the proper\n    type.\"\"\"\n    __tracebackhide__ = True\n    if not isinstance(v, str):\n        msg = \"{param} parameter needs to be a string, but {g} given\"  # type: ignore[unreachable]\n        raise TypeError(msg.format(param=param, g=type(v).__name__))\n\n\n@pytest.fixture(scope=\"session\")\ndef record_testsuite_property(request: FixtureRequest) -> Callable[[str, object], None]:\n    \"\"\"Record a new ``<property>`` tag as child of the root ``<testsuite>``.\n\n    This is suitable to writing global information regarding the entire test\n    suite, and is compatible with ``xunit2`` JUnit family.\n\n    This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:\n\n    .. code-block:: python\n\n        def test_foo(record_testsuite_property):\n            record_testsuite_property(\"ARCH\", \"PPC\")\n            record_testsuite_property(\"STORAGE_TYPE\", \"CEPH\")\n\n    :param name:\n        The property name.\n    :param value:\n        The property value. Will be converted to a string.\n\n    .. warning::\n\n        Currently this fixture **does not work** with the\n        `pytest-xdist <https://github.com/pytest-dev/pytest-xdist>`__ plugin. See\n        :issue:`7767` for details.\n    \"\"\"\n    __tracebackhide__ = True\n\n    def record_func(name: str, value: object) -> None:\n        \"\"\"No-op function in case --junit-xml was not passed in the command-line.\"\"\"\n        __tracebackhide__ = True\n        _check_record_param_type(\"name\", name)\n\n    xml = request.config.stash.get(xml_key, None)\n    if xml is not None:\n        record_func = xml.add_global_property\n    return record_func\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"terminal reporting\")\n    group.addoption(\n        \"--junitxml\",\n        \"--junit-xml\",\n        action=\"store\",\n        dest=\"xmlpath\",\n        metavar=\"path\",\n        type=functools.partial(filename_arg, optname=\"--junitxml\"),\n        default=None,\n        help=\"Create junit-xml style report file at given path\",\n    )\n    group.addoption(\n        \"--junitprefix\",\n        \"--junit-prefix\",\n        action=\"store\",\n        metavar=\"str\",\n        default=None,\n        help=\"Prepend prefix to classnames in junit-xml output\",\n    )\n    parser.addini(\n        \"junit_suite_name\", \"Test suite name for JUnit report\", default=\"pytest\"\n    )\n    parser.addini(\n        \"junit_logging\",\n        \"Write captured log messages to JUnit report: \"\n        \"one of no|log|system-out|system-err|out-err|all\",\n        default=\"no\",\n    )\n    parser.addini(\n        \"junit_log_passing_tests\",\n        \"Capture log information for passing tests to JUnit report: \",\n        type=\"bool\",\n        default=True,\n    )\n    parser.addini(\n        \"junit_duration_report\",\n        \"Duration time to report: one of total|call\",\n        default=\"total\",\n    )  # choices=['total', 'call'])\n    parser.addini(\n        \"junit_family\",\n        \"Emit XML for schema: one of legacy|xunit1|xunit2\",\n        default=\"xunit2\",\n    )\n\n\ndef pytest_configure(config: Config) -> None:\n    xmlpath = config.option.xmlpath\n    # Prevent opening xmllog on worker nodes (xdist).\n    if xmlpath and not hasattr(config, \"workerinput\"):\n        junit_family = config.getini(\"junit_family\")\n        config.stash[xml_key] = LogXML(\n            xmlpath,\n            config.option.junitprefix,\n            config.getini(\"junit_suite_name\"),\n            config.getini(\"junit_logging\"),\n            config.getini(\"junit_duration_report\"),\n            junit_family,\n            config.getini(\"junit_log_passing_tests\"),\n        )\n        config.pluginmanager.register(config.stash[xml_key])\n\n\ndef pytest_unconfigure(config: Config) -> None:\n    xml = config.stash.get(xml_key, None)\n    if xml:\n        del config.stash[xml_key]\n        config.pluginmanager.unregister(xml)\n\n\ndef mangle_test_address(address: str) -> list[str]:\n    path, possible_open_bracket, params = address.partition(\"[\")\n    names = path.split(\"::\")\n    # Convert file path to dotted path.\n    names[0] = names[0].replace(nodes.SEP, \".\")\n    names[0] = re.sub(r\"\\.py$\", \"\", names[0])\n    # Put any params back.\n    names[-1] += possible_open_bracket + params\n    return names\n\n\nclass LogXML:\n    def __init__(\n        self,\n        logfile,\n        prefix: str | None,\n        suite_name: str = \"pytest\",\n        logging: str = \"no\",\n        report_duration: str = \"total\",\n        family=\"xunit1\",\n        log_passing_tests: bool = True,\n    ) -> None:\n        logfile = os.path.expanduser(os.path.expandvars(logfile))\n        self.logfile = os.path.normpath(os.path.abspath(logfile))\n        self.prefix = prefix\n        self.suite_name = suite_name\n        self.logging = logging\n        self.log_passing_tests = log_passing_tests\n        self.report_duration = report_duration\n        self.family = family\n        self.stats: dict[str, int] = dict.fromkeys(\n            [\"error\", \"passed\", \"failure\", \"skipped\"], 0\n        )\n        self.node_reporters: dict[tuple[str | TestReport, object], _NodeReporter] = {}\n        self.node_reporters_ordered: list[_NodeReporter] = []\n        self.global_properties: list[tuple[str, str]] = []\n\n        # List of reports that failed on call but teardown is pending.\n        self.open_reports: list[TestReport] = []\n        self.cnt_double_fail_tests = 0\n\n        # Replaces convenience family with real family.\n        if self.family == \"legacy\":\n            self.family = \"xunit1\"\n\n    def finalize(self, report: TestReport) -> None:\n        nodeid = getattr(report, \"nodeid\", report)\n        # Local hack to handle xdist report order.\n        workernode = getattr(report, \"node\", None)\n        reporter = self.node_reporters.pop((nodeid, workernode))\n\n        for propname, propvalue in report.user_properties:\n            reporter.add_property(propname, str(propvalue))\n\n        if reporter is not None:\n            reporter.finalize()\n\n    def node_reporter(self, report: TestReport | str) -> _NodeReporter:\n        nodeid: str | TestReport = getattr(report, \"nodeid\", report)\n        # Local hack to handle xdist report order.\n        workernode = getattr(report, \"node\", None)\n\n        key = nodeid, workernode\n\n        if key in self.node_reporters:\n            # TODO: breaks for --dist=each\n            return self.node_reporters[key]\n\n        reporter = _NodeReporter(nodeid, self)\n\n        self.node_reporters[key] = reporter\n        self.node_reporters_ordered.append(reporter)\n\n        return reporter\n\n    def add_stats(self, key: str) -> None:\n        if key in self.stats:\n            self.stats[key] += 1\n\n    def _opentestcase(self, report: TestReport) -> _NodeReporter:\n        reporter = self.node_reporter(report)\n        reporter.record_testreport(report)\n        return reporter\n\n    def pytest_runtest_logreport(self, report: TestReport) -> None:\n        \"\"\"Handle a setup/call/teardown report, generating the appropriate\n        XML tags as necessary.\n\n        Note: due to plugins like xdist, this hook may be called in interlaced\n        order with reports from other nodes. For example:\n\n        Usual call order:\n            -> setup node1\n            -> call node1\n            -> teardown node1\n            -> setup node2\n            -> call node2\n            -> teardown node2\n\n        Possible call order in xdist:\n            -> setup node1\n            -> call node1\n            -> setup node2\n            -> call node2\n            -> teardown node2\n            -> teardown node1\n        \"\"\"\n        close_report = None\n        if report.passed:\n            if report.when == \"call\":  # ignore setup/teardown\n                reporter = self._opentestcase(report)\n                reporter.append_pass(report)\n        elif report.failed:\n            if report.when == \"teardown\":\n                # The following vars are needed when xdist plugin is used.\n                report_wid = getattr(report, \"worker_id\", None)\n                report_ii = getattr(report, \"item_index\", None)\n                close_report = next(\n                    (\n                        rep\n                        for rep in self.open_reports\n                        if (\n                            rep.nodeid == report.nodeid\n                            and getattr(rep, \"item_index\", None) == report_ii\n                            and getattr(rep, \"worker_id\", None) == report_wid\n                        )\n                    ),\n                    None,\n                )\n                if close_report:\n                    # We need to open new testcase in case we have failure in\n                    # call and error in teardown in order to follow junit\n                    # schema.\n                    self.finalize(close_report)\n                    self.cnt_double_fail_tests += 1\n            reporter = self._opentestcase(report)\n            if report.when == \"call\":\n                reporter.append_failure(report)\n                self.open_reports.append(report)\n                if not self.log_passing_tests:\n                    reporter.write_captured_output(report)\n            else:\n                reporter.append_error(report)\n        elif report.skipped:\n            reporter = self._opentestcase(report)\n            reporter.append_skipped(report)\n        self.update_testcase_duration(report)\n        if report.when == \"teardown\":\n            reporter = self._opentestcase(report)\n            reporter.write_captured_output(report)\n\n            self.finalize(report)\n            report_wid = getattr(report, \"worker_id\", None)\n            report_ii = getattr(report, \"item_index\", None)\n            close_report = next(\n                (\n                    rep\n                    for rep in self.open_reports\n                    if (\n                        rep.nodeid == report.nodeid\n                        and getattr(rep, \"item_index\", None) == report_ii\n                        and getattr(rep, \"worker_id\", None) == report_wid\n                    )\n                ),\n                None,\n            )\n            if close_report:\n                self.open_reports.remove(close_report)\n\n    def update_testcase_duration(self, report: TestReport) -> None:\n        \"\"\"Accumulate total duration for nodeid from given report and update\n        the Junit.testcase with the new total if already created.\"\"\"\n        if self.report_duration in {\"total\", report.when}:\n            reporter = self.node_reporter(report)\n            reporter.duration += getattr(report, \"duration\", 0.0)\n\n    def pytest_collectreport(self, report: TestReport) -> None:\n        if not report.passed:\n            reporter = self._opentestcase(report)\n            if report.failed:\n                reporter.append_collect_error(report)\n            else:\n                reporter.append_collect_skipped(report)\n\n    def pytest_internalerror(self, excrepr: ExceptionRepr) -> None:\n        reporter = self.node_reporter(\"internal\")\n        reporter.attrs.update(classname=\"pytest\", name=\"internal\")\n        reporter._add_simple(\"error\", \"internal error\", str(excrepr))\n\n    def pytest_sessionstart(self) -> None:\n        self.suite_start = timing.Instant()\n\n    def pytest_sessionfinish(self) -> None:\n        dirname = os.path.dirname(os.path.abspath(self.logfile))\n        # exist_ok avoids filesystem race conditions between checking path existence and requesting creation\n        os.makedirs(dirname, exist_ok=True)\n\n        with open(self.logfile, \"w\", encoding=\"utf-8\") as logfile:\n            duration = self.suite_start.elapsed()\n\n            numtests = (\n                self.stats[\"passed\"]\n                + self.stats[\"failure\"]\n                + self.stats[\"skipped\"]\n                + self.stats[\"error\"]\n                - self.cnt_double_fail_tests\n            )\n            logfile.write('<?xml version=\"1.0\" encoding=\"utf-8\"?>')\n\n            suite_node = ET.Element(\n                \"testsuite\",\n                name=self.suite_name,\n                errors=str(self.stats[\"error\"]),\n                failures=str(self.stats[\"failure\"]),\n                skipped=str(self.stats[\"skipped\"]),\n                tests=str(numtests),\n                time=f\"{duration.seconds:.3f}\",\n                timestamp=self.suite_start.as_utc().astimezone().isoformat(),\n                hostname=platform.node(),\n            )\n            global_properties = self._get_global_properties_node()\n            if global_properties is not None:\n                suite_node.append(global_properties)\n            for node_reporter in self.node_reporters_ordered:\n                suite_node.append(node_reporter.to_xml())\n            testsuites = ET.Element(\"testsuites\")\n            testsuites.set(\"name\", \"pytest tests\")\n            testsuites.append(suite_node)\n            logfile.write(ET.tostring(testsuites, encoding=\"unicode\"))\n\n    def pytest_terminal_summary(\n        self, terminalreporter: TerminalReporter, config: pytest.Config\n    ) -> None:\n        if config.get_verbosity() >= 0:\n            terminalreporter.write_sep(\"-\", f\"generated xml file: {self.logfile}\")\n\n    def add_global_property(self, name: str, value: object) -> None:\n        __tracebackhide__ = True\n        _check_record_param_type(\"name\", name)\n        self.global_properties.append((name, bin_xml_escape(value)))\n\n    def _get_global_properties_node(self) -> ET.Element | None:\n        \"\"\"Return a Junit node containing custom properties, if any.\"\"\"\n        if self.global_properties:\n            properties = ET.Element(\"properties\")\n            for name, value in self.global_properties:\n                properties.append(ET.Element(\"property\", name=name, value=value))\n            return properties\n        return None\n"
  },
  {
    "path": "src/_pytest/legacypath.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Add backward compatibility support for the legacy py path type.\"\"\"\n\nfrom __future__ import annotations\n\nimport dataclasses\nfrom pathlib import Path\nimport shlex\nimport subprocess\nfrom typing import Final\nfrom typing import final\nfrom typing import TYPE_CHECKING\n\nfrom iniconfig import SectionWrapper\n\nfrom _pytest.cacheprovider import Cache\nfrom _pytest.compat import LEGACY_PATH\nfrom _pytest.compat import legacy_path\nfrom _pytest.config import Config\nfrom _pytest.config import hookimpl\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.fixtures import fixture\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.main import Session\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import Item\nfrom _pytest.nodes import Node\nfrom _pytest.pytester import HookRecorder\nfrom _pytest.pytester import Pytester\nfrom _pytest.pytester import RunResult\nfrom _pytest.terminal import TerminalReporter\nfrom _pytest.tmpdir import TempPathFactory\n\n\nif TYPE_CHECKING:\n    import pexpect\n\n\n@final\nclass Testdir:\n    \"\"\"\n    Similar to :class:`Pytester`, but this class works with legacy legacy_path objects instead.\n\n    All methods just forward to an internal :class:`Pytester` instance, converting results\n    to `legacy_path` objects as necessary.\n    \"\"\"\n\n    __test__ = False\n\n    CLOSE_STDIN: Final = Pytester.CLOSE_STDIN\n    TimeoutExpired: Final = Pytester.TimeoutExpired\n\n    def __init__(self, pytester: Pytester, *, _ispytest: bool = False) -> None:\n        check_ispytest(_ispytest)\n        self._pytester = pytester\n\n    @property\n    def tmpdir(self) -> LEGACY_PATH:\n        \"\"\"Temporary directory where tests are executed.\"\"\"\n        return legacy_path(self._pytester.path)\n\n    @property\n    def test_tmproot(self) -> LEGACY_PATH:\n        return legacy_path(self._pytester._test_tmproot)\n\n    @property\n    def request(self):\n        return self._pytester._request\n\n    @property\n    def plugins(self):\n        return self._pytester.plugins\n\n    @plugins.setter\n    def plugins(self, plugins):\n        self._pytester.plugins = plugins\n\n    @property\n    def monkeypatch(self) -> MonkeyPatch:\n        return self._pytester._monkeypatch\n\n    def make_hook_recorder(self, pluginmanager) -> HookRecorder:\n        \"\"\"See :meth:`Pytester.make_hook_recorder`.\"\"\"\n        return self._pytester.make_hook_recorder(pluginmanager)\n\n    def chdir(self) -> None:\n        \"\"\"See :meth:`Pytester.chdir`.\"\"\"\n        return self._pytester.chdir()\n\n    def finalize(self) -> None:\n        return self._pytester._finalize()\n\n    def makefile(self, ext, *args, **kwargs) -> LEGACY_PATH:\n        \"\"\"See :meth:`Pytester.makefile`.\"\"\"\n        if ext and not ext.startswith(\".\"):\n            # pytester.makefile is going to throw a ValueError in a way that\n            # testdir.makefile did not, because\n            # pathlib.Path is stricter suffixes than py.path\n            # This ext arguments is likely user error, but since testdir has\n            # allowed this, we will prepend \".\" as a workaround to avoid breaking\n            # testdir usage that worked before\n            ext = \".\" + ext\n        return legacy_path(self._pytester.makefile(ext, *args, **kwargs))\n\n    def makeconftest(self, source) -> LEGACY_PATH:\n        \"\"\"See :meth:`Pytester.makeconftest`.\"\"\"\n        return legacy_path(self._pytester.makeconftest(source))\n\n    def makeini(self, source) -> LEGACY_PATH:\n        \"\"\"See :meth:`Pytester.makeini`.\"\"\"\n        return legacy_path(self._pytester.makeini(source))\n\n    def getinicfg(self, source: str) -> SectionWrapper:\n        \"\"\"See :meth:`Pytester.getinicfg`.\"\"\"\n        return self._pytester.getinicfg(source)\n\n    def makepyprojecttoml(self, source) -> LEGACY_PATH:\n        \"\"\"See :meth:`Pytester.makepyprojecttoml`.\"\"\"\n        return legacy_path(self._pytester.makepyprojecttoml(source))\n\n    def makepyfile(self, *args, **kwargs) -> LEGACY_PATH:\n        \"\"\"See :meth:`Pytester.makepyfile`.\"\"\"\n        return legacy_path(self._pytester.makepyfile(*args, **kwargs))\n\n    def maketxtfile(self, *args, **kwargs) -> LEGACY_PATH:\n        \"\"\"See :meth:`Pytester.maketxtfile`.\"\"\"\n        return legacy_path(self._pytester.maketxtfile(*args, **kwargs))\n\n    def syspathinsert(self, path=None) -> None:\n        \"\"\"See :meth:`Pytester.syspathinsert`.\"\"\"\n        return self._pytester.syspathinsert(path)\n\n    def mkdir(self, name) -> LEGACY_PATH:\n        \"\"\"See :meth:`Pytester.mkdir`.\"\"\"\n        return legacy_path(self._pytester.mkdir(name))\n\n    def mkpydir(self, name) -> LEGACY_PATH:\n        \"\"\"See :meth:`Pytester.mkpydir`.\"\"\"\n        return legacy_path(self._pytester.mkpydir(name))\n\n    def copy_example(self, name=None) -> LEGACY_PATH:\n        \"\"\"See :meth:`Pytester.copy_example`.\"\"\"\n        return legacy_path(self._pytester.copy_example(name))\n\n    def getnode(self, config: Config, arg) -> Item | Collector | None:\n        \"\"\"See :meth:`Pytester.getnode`.\"\"\"\n        return self._pytester.getnode(config, arg)\n\n    def getpathnode(self, path):\n        \"\"\"See :meth:`Pytester.getpathnode`.\"\"\"\n        return self._pytester.getpathnode(path)\n\n    def genitems(self, colitems: list[Item | Collector]) -> list[Item]:\n        \"\"\"See :meth:`Pytester.genitems`.\"\"\"\n        return self._pytester.genitems(colitems)\n\n    def runitem(self, source):\n        \"\"\"See :meth:`Pytester.runitem`.\"\"\"\n        return self._pytester.runitem(source)\n\n    def inline_runsource(self, source, *cmdlineargs):\n        \"\"\"See :meth:`Pytester.inline_runsource`.\"\"\"\n        return self._pytester.inline_runsource(source, *cmdlineargs)\n\n    def inline_genitems(self, *args):\n        \"\"\"See :meth:`Pytester.inline_genitems`.\"\"\"\n        return self._pytester.inline_genitems(*args)\n\n    def inline_run(self, *args, plugins=(), no_reraise_ctrlc: bool = False):\n        \"\"\"See :meth:`Pytester.inline_run`.\"\"\"\n        return self._pytester.inline_run(\n            *args, plugins=plugins, no_reraise_ctrlc=no_reraise_ctrlc\n        )\n\n    def runpytest_inprocess(self, *args, **kwargs) -> RunResult:\n        \"\"\"See :meth:`Pytester.runpytest_inprocess`.\"\"\"\n        return self._pytester.runpytest_inprocess(*args, **kwargs)\n\n    def runpytest(self, *args, **kwargs) -> RunResult:\n        \"\"\"See :meth:`Pytester.runpytest`.\"\"\"\n        return self._pytester.runpytest(*args, **kwargs)\n\n    def parseconfig(self, *args) -> Config:\n        \"\"\"See :meth:`Pytester.parseconfig`.\"\"\"\n        return self._pytester.parseconfig(*args)\n\n    def parseconfigure(self, *args) -> Config:\n        \"\"\"See :meth:`Pytester.parseconfigure`.\"\"\"\n        return self._pytester.parseconfigure(*args)\n\n    def getitem(self, source, funcname=\"test_func\"):\n        \"\"\"See :meth:`Pytester.getitem`.\"\"\"\n        return self._pytester.getitem(source, funcname)\n\n    def getitems(self, source):\n        \"\"\"See :meth:`Pytester.getitems`.\"\"\"\n        return self._pytester.getitems(source)\n\n    def getmodulecol(self, source, configargs=(), withinit=False):\n        \"\"\"See :meth:`Pytester.getmodulecol`.\"\"\"\n        return self._pytester.getmodulecol(\n            source, configargs=configargs, withinit=withinit\n        )\n\n    def collect_by_name(self, modcol: Collector, name: str) -> Item | Collector | None:\n        \"\"\"See :meth:`Pytester.collect_by_name`.\"\"\"\n        return self._pytester.collect_by_name(modcol, name)\n\n    def popen(\n        self,\n        cmdargs,\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n        stdin=CLOSE_STDIN,\n        **kw,\n    ):\n        \"\"\"See :meth:`Pytester.popen`.\"\"\"\n        return self._pytester.popen(cmdargs, stdout, stderr, stdin, **kw)\n\n    def run(self, *cmdargs, timeout=None, stdin=CLOSE_STDIN) -> RunResult:\n        \"\"\"See :meth:`Pytester.run`.\"\"\"\n        return self._pytester.run(*cmdargs, timeout=timeout, stdin=stdin)\n\n    def runpython(self, script) -> RunResult:\n        \"\"\"See :meth:`Pytester.runpython`.\"\"\"\n        return self._pytester.runpython(script)\n\n    def runpython_c(self, command):\n        \"\"\"See :meth:`Pytester.runpython_c`.\"\"\"\n        return self._pytester.runpython_c(command)\n\n    def runpytest_subprocess(self, *args, timeout=None) -> RunResult:\n        \"\"\"See :meth:`Pytester.runpytest_subprocess`.\"\"\"\n        return self._pytester.runpytest_subprocess(*args, timeout=timeout)\n\n    def spawn_pytest(self, string: str, expect_timeout: float = 10.0) -> pexpect.spawn:\n        \"\"\"See :meth:`Pytester.spawn_pytest`.\"\"\"\n        return self._pytester.spawn_pytest(string, expect_timeout=expect_timeout)\n\n    def spawn(self, cmd: str, expect_timeout: float = 10.0) -> pexpect.spawn:\n        \"\"\"See :meth:`Pytester.spawn`.\"\"\"\n        return self._pytester.spawn(cmd, expect_timeout=expect_timeout)\n\n    def __repr__(self) -> str:\n        return f\"<Testdir {self.tmpdir!r}>\"\n\n    def __str__(self) -> str:\n        return str(self.tmpdir)\n\n\nclass LegacyTestdirPlugin:\n    @staticmethod\n    @fixture\n    def testdir(pytester: Pytester) -> Testdir:\n        \"\"\"\n        Identical to :fixture:`pytester`, and provides an instance whose methods return\n        legacy ``LEGACY_PATH`` objects instead when applicable.\n\n        New code should avoid using :fixture:`testdir` in favor of :fixture:`pytester`.\n        \"\"\"\n        return Testdir(pytester, _ispytest=True)\n\n\n@final\n@dataclasses.dataclass\nclass TempdirFactory:\n    \"\"\"Backward compatibility wrapper that implements ``py.path.local``\n    for :class:`TempPathFactory`.\n\n    .. note::\n        These days, it is preferred to use ``tmp_path_factory``.\n\n        :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.\n\n    \"\"\"\n\n    _tmppath_factory: TempPathFactory\n\n    def __init__(\n        self, tmppath_factory: TempPathFactory, *, _ispytest: bool = False\n    ) -> None:\n        check_ispytest(_ispytest)\n        self._tmppath_factory = tmppath_factory\n\n    def mktemp(self, basename: str, numbered: bool = True) -> LEGACY_PATH:\n        \"\"\"Same as :meth:`TempPathFactory.mktemp`, but returns a ``py.path.local`` object.\"\"\"\n        return legacy_path(self._tmppath_factory.mktemp(basename, numbered).resolve())\n\n    def getbasetemp(self) -> LEGACY_PATH:\n        \"\"\"Same as :meth:`TempPathFactory.getbasetemp`, but returns a ``py.path.local`` object.\"\"\"\n        return legacy_path(self._tmppath_factory.getbasetemp().resolve())\n\n\nclass LegacyTmpdirPlugin:\n    @staticmethod\n    @fixture(scope=\"session\")\n    def tmpdir_factory(request: FixtureRequest) -> TempdirFactory:\n        \"\"\"Return a :class:`pytest.TempdirFactory` instance for the test session.\"\"\"\n        # Set dynamically by pytest_configure().\n        return request.config._tmpdirhandler  # type: ignore\n\n    @staticmethod\n    @fixture\n    def tmpdir(tmp_path: Path) -> LEGACY_PATH:\n        \"\"\"Return a temporary directory (as `legacy_path`_ object)\n        which is unique to each test function invocation.\n        The temporary directory is created as a subdirectory\n        of the base temporary directory, with configurable retention,\n        as discussed in :ref:`temporary directory location and retention`.\n\n        .. note::\n            These days, it is preferred to use ``tmp_path``.\n\n            :ref:`About the tmpdir and tmpdir_factory fixtures<tmpdir and tmpdir_factory>`.\n\n        .. _legacy_path: https://py.readthedocs.io/en/latest/path.html\n        \"\"\"\n        return legacy_path(tmp_path)\n\n\ndef Cache_makedir(self: Cache, name: str) -> LEGACY_PATH:\n    \"\"\"Return a directory path object with the given name.\n\n    Same as :func:`mkdir`, but returns a legacy py path instance.\n    \"\"\"\n    return legacy_path(self.mkdir(name))\n\n\ndef FixtureRequest_fspath(self: FixtureRequest) -> LEGACY_PATH:\n    \"\"\"(deprecated) The file system path of the test module which collected this test.\"\"\"\n    return legacy_path(self.path)\n\n\ndef TerminalReporter_startdir(self: TerminalReporter) -> LEGACY_PATH:\n    \"\"\"The directory from which pytest was invoked.\n\n    Prefer to use ``startpath`` which is a :class:`pathlib.Path`.\n\n    :type: LEGACY_PATH\n    \"\"\"\n    return legacy_path(self.startpath)\n\n\ndef Config_invocation_dir(self: Config) -> LEGACY_PATH:\n    \"\"\"The directory from which pytest was invoked.\n\n    Prefer to use :attr:`invocation_params.dir <InvocationParams.dir>`,\n    which is a :class:`pathlib.Path`.\n\n    :type: LEGACY_PATH\n    \"\"\"\n    return legacy_path(str(self.invocation_params.dir))\n\n\ndef Config_rootdir(self: Config) -> LEGACY_PATH:\n    \"\"\"The path to the :ref:`rootdir <rootdir>`.\n\n    Prefer to use :attr:`rootpath`, which is a :class:`pathlib.Path`.\n\n    :type: LEGACY_PATH\n    \"\"\"\n    return legacy_path(str(self.rootpath))\n\n\ndef Config_inifile(self: Config) -> LEGACY_PATH | None:\n    \"\"\"The path to the :ref:`configfile <configfiles>`.\n\n    Prefer to use :attr:`inipath`, which is a :class:`pathlib.Path`.\n\n    :type: Optional[LEGACY_PATH]\n    \"\"\"\n    return legacy_path(str(self.inipath)) if self.inipath else None\n\n\ndef Session_startdir(self: Session) -> LEGACY_PATH:\n    \"\"\"The path from which pytest was invoked.\n\n    Prefer to use ``startpath`` which is a :class:`pathlib.Path`.\n\n    :type: LEGACY_PATH\n    \"\"\"\n    return legacy_path(self.startpath)\n\n\ndef Config__getini_unknown_type(self, name: str, type: str, value: str | list[str]):\n    if type == \"pathlist\":\n        # TODO: This assert is probably not valid in all cases.\n        assert self.inipath is not None\n        dp = self.inipath.parent\n        input_values = shlex.split(value) if isinstance(value, str) else value\n        return [legacy_path(str(dp / x)) for x in input_values]\n    else:\n        raise ValueError(f\"unknown configuration type: {type}\", value)\n\n\ndef Node_fspath(self: Node) -> LEGACY_PATH:\n    \"\"\"(deprecated) returns a legacy_path copy of self.path\"\"\"\n    return legacy_path(self.path)\n\n\ndef Node_fspath_set(self: Node, value: LEGACY_PATH) -> None:\n    self.path = Path(value)\n\n\n@hookimpl(tryfirst=True)\ndef pytest_load_initial_conftests(early_config: Config) -> None:\n    \"\"\"Monkeypatch legacy path attributes in several classes, as early as possible.\"\"\"\n    mp = MonkeyPatch()\n    early_config.add_cleanup(mp.undo)\n\n    # Add Cache.makedir().\n    mp.setattr(Cache, \"makedir\", Cache_makedir, raising=False)\n\n    # Add FixtureRequest.fspath property.\n    mp.setattr(FixtureRequest, \"fspath\", property(FixtureRequest_fspath), raising=False)\n\n    # Add TerminalReporter.startdir property.\n    mp.setattr(\n        TerminalReporter, \"startdir\", property(TerminalReporter_startdir), raising=False\n    )\n\n    # Add Config.{invocation_dir,rootdir,inifile} properties.\n    mp.setattr(Config, \"invocation_dir\", property(Config_invocation_dir), raising=False)\n    mp.setattr(Config, \"rootdir\", property(Config_rootdir), raising=False)\n    mp.setattr(Config, \"inifile\", property(Config_inifile), raising=False)\n\n    # Add Session.startdir property.\n    mp.setattr(Session, \"startdir\", property(Session_startdir), raising=False)\n\n    # Add pathlist configuration type.\n    mp.setattr(Config, \"_getini_unknown_type\", Config__getini_unknown_type)\n\n    # Add Node.fspath property.\n    mp.setattr(Node, \"fspath\", property(Node_fspath, Node_fspath_set), raising=False)\n\n\n@hookimpl\ndef pytest_configure(config: Config) -> None:\n    \"\"\"Installs the LegacyTmpdirPlugin if the ``tmpdir`` plugin is also installed.\"\"\"\n    if config.pluginmanager.has_plugin(\"tmpdir\"):\n        mp = MonkeyPatch()\n        config.add_cleanup(mp.undo)\n        # Create TmpdirFactory and attach it to the config object.\n        #\n        # This is to comply with existing plugins which expect the handler to be\n        # available at pytest_configure time, but ideally should be moved entirely\n        # to the tmpdir_factory session fixture.\n        try:\n            tmp_path_factory = config._tmp_path_factory  # type: ignore[attr-defined]\n        except AttributeError:\n            # tmpdir plugin is blocked.\n            pass\n        else:\n            _tmpdirhandler = TempdirFactory(tmp_path_factory, _ispytest=True)\n            mp.setattr(config, \"_tmpdirhandler\", _tmpdirhandler, raising=False)\n\n        config.pluginmanager.register(LegacyTmpdirPlugin, \"legacypath-tmpdir\")\n\n\n@hookimpl\ndef pytest_plugin_registered(plugin: object, manager: PytestPluginManager) -> None:\n    # pytester is not loaded by default and is commonly loaded from a conftest,\n    # so checking for it in `pytest_configure` is not enough.\n    is_pytester = plugin is manager.get_plugin(\"pytester\")\n    if is_pytester and not manager.is_registered(LegacyTestdirPlugin):\n        manager.register(LegacyTestdirPlugin, \"legacypath-pytester\")\n"
  },
  {
    "path": "src/_pytest/logging.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Access and control log capturing.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nfrom collections.abc import Mapping\nfrom collections.abc import Set as AbstractSet\nfrom contextlib import contextmanager\nfrom contextlib import nullcontext\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom datetime import timezone\nimport io\nfrom io import StringIO\nimport logging\nfrom logging import LogRecord\nimport os\nfrom pathlib import Path\nimport re\nfrom types import TracebackType\nfrom typing import final\nfrom typing import Generic\nfrom typing import Literal\nfrom typing import TYPE_CHECKING\nfrom typing import TypeVar\n\nfrom _pytest import nodes\nfrom _pytest._io import TerminalWriter\nfrom _pytest.capture import CaptureManager\nfrom _pytest.config import _strtobool\nfrom _pytest.config import Config\nfrom _pytest.config import create_terminal_writer\nfrom _pytest.config import hookimpl\nfrom _pytest.config import UsageError\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.fixtures import fixture\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.main import Session\nfrom _pytest.stash import StashKey\nfrom _pytest.terminal import TerminalReporter\n\n\nif TYPE_CHECKING:\n    logging_StreamHandler = logging.StreamHandler[StringIO]\nelse:\n    logging_StreamHandler = logging.StreamHandler\n\nDEFAULT_LOG_FORMAT = \"%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s\"\nDEFAULT_LOG_DATE_FORMAT = \"%H:%M:%S\"\n_ANSI_ESCAPE_SEQ = re.compile(r\"\\x1b\\[[\\d;]+m\")\ncaplog_handler_key = StashKey[\"LogCaptureHandler\"]()\ncaplog_records_key = StashKey[dict[str, list[logging.LogRecord]]]()\n\n\ndef _remove_ansi_escape_sequences(text: str) -> str:\n    return _ANSI_ESCAPE_SEQ.sub(\"\", text)\n\n\nclass DatetimeFormatter(logging.Formatter):\n    \"\"\"A logging formatter which formats record with\n    :func:`datetime.datetime.strftime` formatter instead of\n    :func:`time.strftime` in case of microseconds in format string.\n    \"\"\"\n\n    def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str:\n        if datefmt and \"%f\" in datefmt:\n            ct = self.converter(record.created)\n            tz = timezone(timedelta(seconds=ct.tm_gmtoff), ct.tm_zone)\n            # Construct `datetime.datetime` object from `struct_time`\n            # and msecs information from `record`\n            # Using int() instead of round() to avoid it exceeding 1_000_000 and causing a ValueError (#11861).\n            dt = datetime(*ct[0:6], microsecond=int(record.msecs * 1000), tzinfo=tz)\n            return dt.strftime(datefmt)\n        # Use `logging.Formatter` for non-microsecond formats\n        return super().formatTime(record, datefmt)\n\n\nclass ColoredLevelFormatter(DatetimeFormatter):\n    \"\"\"A logging formatter which colorizes the %(levelname)..s part of the\n    log format passed to __init__.\"\"\"\n\n    LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = {\n        logging.CRITICAL: {\"red\"},\n        logging.ERROR: {\"red\", \"bold\"},\n        logging.WARNING: {\"yellow\"},\n        logging.WARN: {\"yellow\"},\n        logging.INFO: {\"green\"},\n        logging.DEBUG: {\"purple\"},\n        logging.NOTSET: set(),\n    }\n    LEVELNAME_FMT_REGEX = re.compile(r\"%\\(levelname\\)([+-.]?\\d*(?:\\.\\d+)?s)\")\n\n    def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None:\n        super().__init__(*args, **kwargs)\n        self._terminalwriter = terminalwriter\n        self._original_fmt = self._style._fmt\n        self._level_to_fmt_mapping: dict[int, str] = {}\n\n        for level, color_opts in self.LOGLEVEL_COLOROPTS.items():\n            self.add_color_level(level, *color_opts)\n\n    def add_color_level(self, level: int, *color_opts: str) -> None:\n        \"\"\"Add or update color opts for a log level.\n\n        :param level:\n            Log level to apply a style to, e.g. ``logging.INFO``.\n        :param color_opts:\n            ANSI escape sequence color options. Capitalized colors indicates\n            background color, i.e. ``'green', 'Yellow', 'bold'`` will give bold\n            green text on yellow background.\n\n        .. warning::\n            This is an experimental API.\n        \"\"\"\n        assert self._fmt is not None\n        levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt)\n        if not levelname_fmt_match:\n            return\n        levelname_fmt = levelname_fmt_match.group()\n\n        formatted_levelname = levelname_fmt % {\"levelname\": logging.getLevelName(level)}\n\n        # add ANSI escape sequences around the formatted levelname\n        color_kwargs = {name: True for name in color_opts}\n        colorized_formatted_levelname = self._terminalwriter.markup(\n            formatted_levelname, **color_kwargs\n        )\n        self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub(\n            colorized_formatted_levelname, self._fmt\n        )\n\n    def format(self, record: logging.LogRecord) -> str:\n        fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt)\n        self._style._fmt = fmt\n        return super().format(record)\n\n\nclass PercentStyleMultiline(logging.PercentStyle):\n    \"\"\"A logging style with special support for multiline messages.\n\n    If the message of a record consists of multiple lines, this style\n    formats the message as if each line were logged separately.\n    \"\"\"\n\n    def __init__(self, fmt: str, auto_indent: int | str | bool | None) -> None:\n        super().__init__(fmt)\n        self._auto_indent = self._get_auto_indent(auto_indent)\n\n    @staticmethod\n    def _get_auto_indent(auto_indent_option: int | str | bool | None) -> int:\n        \"\"\"Determine the current auto indentation setting.\n\n        Specify auto indent behavior (on/off/fixed) by passing in\n        extra={\"auto_indent\": [value]} to the call to logging.log() or\n        using a --log-auto-indent [value] command line or the\n        log_auto_indent [value] config option.\n\n        Default behavior is auto-indent off.\n\n        Using the string \"True\" or \"on\" or the boolean True as the value\n        turns auto indent on, using the string \"False\" or \"off\" or the\n        boolean False or the int 0 turns it off, and specifying a\n        positive integer fixes the indentation position to the value\n        specified.\n\n        Any other values for the option are invalid, and will silently be\n        converted to the default.\n\n        :param None|bool|int|str auto_indent_option:\n            User specified option for indentation from command line, config\n            or extra kwarg. Accepts int, bool or str. str option accepts the\n            same range of values as boolean config options, as well as\n            positive integers represented in str form.\n\n        :returns:\n            Indentation value, which can be\n            -1 (automatically determine indentation) or\n            0 (auto-indent turned off) or\n            >0 (explicitly set indentation position).\n        \"\"\"\n        if auto_indent_option is None:\n            return 0\n        elif isinstance(auto_indent_option, bool):\n            if auto_indent_option:\n                return -1\n            else:\n                return 0\n        elif isinstance(auto_indent_option, int):\n            return int(auto_indent_option)\n        elif isinstance(auto_indent_option, str):\n            try:\n                return int(auto_indent_option)\n            except ValueError:\n                pass\n            try:\n                if _strtobool(auto_indent_option):\n                    return -1\n            except ValueError:\n                return 0\n\n        return 0\n\n    def format(self, record: logging.LogRecord) -> str:\n        if \"\\n\" in record.message:\n            if hasattr(record, \"auto_indent\"):\n                # Passed in from the \"extra={}\" kwarg on the call to logging.log().\n                auto_indent = self._get_auto_indent(record.auto_indent)\n            else:\n                auto_indent = self._auto_indent\n\n            if auto_indent:\n                lines = record.message.splitlines()\n                formatted = self._fmt % {**record.__dict__, \"message\": lines[0]}\n\n                if auto_indent < 0:\n                    indentation = _remove_ansi_escape_sequences(formatted).find(\n                        lines[0]\n                    )\n                else:\n                    # Optimizes logging by allowing a fixed indentation.\n                    indentation = auto_indent\n                lines[0] = formatted\n                return (\"\\n\" + \" \" * indentation).join(lines)\n        return self._fmt % record.__dict__\n\n\ndef get_option_ini(config: Config, *names: str):\n    for name in names:\n        ret = config.getoption(name)  # 'default' arg won't work as expected\n        if ret is None:\n            ret = config.getini(name)\n        if ret:\n            return ret\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    \"\"\"Add options to control log capturing.\"\"\"\n    group = parser.getgroup(\"logging\")\n\n    def add_option_ini(option, dest, default=None, type=None, **kwargs):\n        parser.addini(\n            dest, default=default, type=type, help=\"Default value for \" + option\n        )\n        group.addoption(option, dest=dest, **kwargs)\n\n    add_option_ini(\n        \"--log-level\",\n        dest=\"log_level\",\n        default=None,\n        metavar=\"LEVEL\",\n        help=(\n            \"Level of messages to catch/display.\"\n            \" Not set by default, so it depends on the root/parent log handler's\"\n            ' effective level, where it is \"WARNING\" by default.'\n        ),\n    )\n    add_option_ini(\n        \"--log-format\",\n        dest=\"log_format\",\n        default=DEFAULT_LOG_FORMAT,\n        help=\"Log format used by the logging module\",\n    )\n    add_option_ini(\n        \"--log-date-format\",\n        dest=\"log_date_format\",\n        default=DEFAULT_LOG_DATE_FORMAT,\n        help=\"Log date format used by the logging module\",\n    )\n    parser.addini(\n        \"log_cli\",\n        default=False,\n        type=\"bool\",\n        help='Enable log display during test run (also known as \"live logging\")',\n    )\n    add_option_ini(\n        \"--log-cli-level\", dest=\"log_cli_level\", default=None, help=\"CLI logging level\"\n    )\n    add_option_ini(\n        \"--log-cli-format\",\n        dest=\"log_cli_format\",\n        default=None,\n        help=\"Log format used by the logging module\",\n    )\n    add_option_ini(\n        \"--log-cli-date-format\",\n        dest=\"log_cli_date_format\",\n        default=None,\n        help=\"Log date format used by the logging module\",\n    )\n    add_option_ini(\n        \"--log-file\",\n        dest=\"log_file\",\n        default=None,\n        help=\"Path to a file when logging will be written to\",\n    )\n    add_option_ini(\n        \"--log-file-mode\",\n        dest=\"log_file_mode\",\n        default=\"w\",\n        choices=[\"w\", \"a\"],\n        help=\"Log file open mode\",\n    )\n    add_option_ini(\n        \"--log-file-level\",\n        dest=\"log_file_level\",\n        default=None,\n        help=\"Log file logging level\",\n    )\n    add_option_ini(\n        \"--log-file-format\",\n        dest=\"log_file_format\",\n        default=None,\n        help=\"Log format used by the logging module\",\n    )\n    add_option_ini(\n        \"--log-file-date-format\",\n        dest=\"log_file_date_format\",\n        default=None,\n        help=\"Log date format used by the logging module\",\n    )\n    add_option_ini(\n        \"--log-auto-indent\",\n        dest=\"log_auto_indent\",\n        default=None,\n        help=\"Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.\",\n    )\n    group.addoption(\n        \"--log-disable\",\n        action=\"append\",\n        default=[],\n        dest=\"logger_disable\",\n        help=\"Disable a logger by name. Can be passed multiple times.\",\n    )\n\n\n_HandlerType = TypeVar(\"_HandlerType\", bound=logging.Handler)\n\n\n# Not using @contextmanager for performance reasons.\nclass catching_logs(Generic[_HandlerType]):\n    \"\"\"Context manager that prepares the whole logging machinery properly.\"\"\"\n\n    __slots__ = (\"handler\", \"level\", \"orig_level\")\n\n    def __init__(self, handler: _HandlerType, level: int | None = None) -> None:\n        self.handler = handler\n        self.level = level\n\n    def __enter__(self) -> _HandlerType:\n        root_logger = logging.getLogger()\n        if self.level is not None:\n            self.handler.setLevel(self.level)\n        root_logger.addHandler(self.handler)\n        if self.level is not None:\n            self.orig_level = root_logger.level\n            root_logger.setLevel(min(self.orig_level, self.level))\n        return self.handler\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        root_logger = logging.getLogger()\n        if self.level is not None:\n            root_logger.setLevel(self.orig_level)\n        root_logger.removeHandler(self.handler)\n\n\nclass LogCaptureHandler(logging_StreamHandler):\n    \"\"\"A logging handler that stores log records and the log text.\"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"Create a new log handler.\"\"\"\n        super().__init__(StringIO())\n        self.records: list[logging.LogRecord] = []\n\n    def emit(self, record: logging.LogRecord) -> None:\n        \"\"\"Keep the log records in a list in addition to the log text.\"\"\"\n        self.records.append(record)\n        super().emit(record)\n\n    def reset(self) -> None:\n        self.records = []\n        self.stream = StringIO()\n\n    def clear(self) -> None:\n        self.records.clear()\n        self.stream = StringIO()\n\n    def handleError(self, record: logging.LogRecord) -> None:\n        if logging.raiseExceptions:\n            # Fail the test if the log message is bad (emit failed).\n            # The default behavior of logging is to print \"Logging error\"\n            # to stderr with the call stack and some extra details.\n            # pytest wants to make such mistakes visible during testing.\n            raise  # noqa: PLE0704\n\n\n@final\nclass LogCaptureFixture:\n    \"\"\"Provides access and control of log capturing.\"\"\"\n\n    def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None:\n        check_ispytest(_ispytest)\n        self._item = item\n        self._initial_handler_level: int | None = None\n        # Dict of log name -> log level.\n        self._initial_logger_levels: dict[str | None, int] = {}\n        self._initial_disabled_logging_level: int | None = None\n\n    def _finalize(self) -> None:\n        \"\"\"Finalize the fixture.\n\n        This restores the log levels and the disabled logging levels changed by :meth:`set_level`.\n        \"\"\"\n        # Restore log levels.\n        if self._initial_handler_level is not None:\n            self.handler.setLevel(self._initial_handler_level)\n        for logger_name, level in self._initial_logger_levels.items():\n            logger = logging.getLogger(logger_name)\n            logger.setLevel(level)\n        # Disable logging at the original disabled logging level.\n        if self._initial_disabled_logging_level is not None:\n            logging.disable(self._initial_disabled_logging_level)\n            self._initial_disabled_logging_level = None\n\n    @property\n    def handler(self) -> LogCaptureHandler:\n        \"\"\"Get the logging handler used by the fixture.\"\"\"\n        return self._item.stash[caplog_handler_key]\n\n    def get_records(\n        self, when: Literal[\"setup\", \"call\", \"teardown\"]\n    ) -> list[logging.LogRecord]:\n        \"\"\"Get the logging records for one of the possible test phases.\n\n        :param when:\n            Which test phase to obtain the records from.\n            Valid values are: \"setup\", \"call\" and \"teardown\".\n\n        :returns: The list of captured records at the given stage.\n\n        .. versionadded:: 3.4\n        \"\"\"\n        return self._item.stash[caplog_records_key].get(when, [])\n\n    @property\n    def text(self) -> str:\n        \"\"\"The formatted log text.\"\"\"\n        return _remove_ansi_escape_sequences(self.handler.stream.getvalue())\n\n    @property\n    def records(self) -> list[logging.LogRecord]:\n        \"\"\"The list of log records.\"\"\"\n        return self.handler.records\n\n    @property\n    def record_tuples(self) -> list[tuple[str, int, str]]:\n        \"\"\"A list of a stripped down version of log records intended\n        for use in assertion comparison.\n\n        The format of the tuple is:\n\n            (logger_name, log_level, message)\n        \"\"\"\n        return [(r.name, r.levelno, r.getMessage()) for r in self.records]\n\n    @property\n    def messages(self) -> list[str]:\n        \"\"\"A list of format-interpolated log messages.\n\n        Unlike 'records', which contains the format string and parameters for\n        interpolation, log messages in this list are all interpolated.\n\n        Unlike 'text', which contains the output from the handler, log\n        messages in this list are unadorned with levels, timestamps, etc,\n        making exact comparisons more reliable.\n\n        Note that traceback or stack info (from :func:`logging.exception` or\n        the `exc_info` or `stack_info` arguments to the logging functions) is\n        not included, as this is added by the formatter in the handler.\n\n        .. versionadded:: 3.7\n        \"\"\"\n        return [r.getMessage() for r in self.records]\n\n    def clear(self) -> None:\n        \"\"\"Reset the list of log records and the captured log text.\"\"\"\n        self.handler.clear()\n\n    def _force_enable_logging(\n        self, level: int | str, logger_obj: logging.Logger\n    ) -> int:\n        \"\"\"Enable the desired logging level if the global level was disabled via ``logging.disabled``.\n\n        Only enables logging levels greater than or equal to the requested ``level``.\n\n        Does nothing if the desired ``level`` wasn't disabled.\n\n        :param level:\n            The logger level caplog should capture.\n            All logging is enabled if a non-standard logging level string is supplied.\n            Valid level strings are in :data:`logging._nameToLevel`.\n        :param logger_obj: The logger object to check.\n\n        :return: The original disabled logging level.\n        \"\"\"\n        original_disable_level: int = logger_obj.manager.disable\n\n        if isinstance(level, str):\n            # Try to translate the level string to an int for `logging.disable()`\n            level = logging.getLevelName(level)  # type: ignore[deprecated]\n\n        if not isinstance(level, int):\n            # The level provided was not valid, so just un-disable all logging.\n            logging.disable(logging.NOTSET)\n        elif not logger_obj.isEnabledFor(level):\n            # Each level is `10` away from other levels.\n            # https://docs.python.org/3/library/logging.html#logging-levels\n            disable_level = max(level - 10, logging.NOTSET)\n            logging.disable(disable_level)\n\n        return original_disable_level\n\n    def set_level(self, level: int | str, logger: str | None = None) -> None:\n        \"\"\"Set the threshold level of a logger for the duration of a test.\n\n        Logging messages which are less severe than this level will not be captured.\n\n        .. versionchanged:: 3.4\n            The levels of the loggers changed by this function will be\n            restored to their initial values at the end of the test.\n\n        Will enable the requested logging level if it was disabled via :func:`logging.disable`.\n\n        :param level: The level.\n        :param logger: The logger to update. If not given, the root logger.\n        \"\"\"\n        logger_obj = logging.getLogger(logger)\n        # Save the original log-level to restore it during teardown.\n        self._initial_logger_levels.setdefault(logger, logger_obj.level)\n        logger_obj.setLevel(level)\n        if self._initial_handler_level is None:\n            self._initial_handler_level = self.handler.level\n        self.handler.setLevel(level)\n        initial_disabled_logging_level = self._force_enable_logging(level, logger_obj)\n        if self._initial_disabled_logging_level is None:\n            self._initial_disabled_logging_level = initial_disabled_logging_level\n\n    @contextmanager\n    def at_level(self, level: int | str, logger: str | None = None) -> Generator[None]:\n        \"\"\"Context manager that sets the level for capturing of logs. After\n        the end of the 'with' statement the level is restored to its original\n        value.\n\n        Will enable the requested logging level if it was disabled via :func:`logging.disable`.\n\n        :param level: The level.\n        :param logger: The logger to update. If not given, the root logger.\n        \"\"\"\n        logger_obj = logging.getLogger(logger)\n        orig_level = logger_obj.level\n        logger_obj.setLevel(level)\n        handler_orig_level = self.handler.level\n        self.handler.setLevel(level)\n        original_disable_level = self._force_enable_logging(level, logger_obj)\n        try:\n            yield\n        finally:\n            logger_obj.setLevel(orig_level)\n            self.handler.setLevel(handler_orig_level)\n            logging.disable(original_disable_level)\n\n    @contextmanager\n    def filtering(self, filter_: logging.Filter) -> Generator[None]:\n        \"\"\"Context manager that temporarily adds the given filter to the caplog's\n        :meth:`handler` for the 'with' statement block, and removes that filter at the\n        end of the block.\n\n        :param filter_: A custom :class:`logging.Filter` object.\n\n        .. versionadded:: 7.5\n        \"\"\"\n        self.handler.addFilter(filter_)\n        try:\n            yield\n        finally:\n            self.handler.removeFilter(filter_)\n\n\n@fixture\ndef caplog(request: FixtureRequest) -> Generator[LogCaptureFixture]:\n    \"\"\"Access and control log capturing.\n\n    Captured logs are available through the following properties/methods::\n\n    * caplog.messages        -> list of format-interpolated log messages\n    * caplog.text            -> string containing formatted log output\n    * caplog.records         -> list of logging.LogRecord instances\n    * caplog.record_tuples   -> list of (logger_name, level, message) tuples\n    * caplog.clear()         -> clear captured records and formatted log output string\n    \"\"\"\n    result = LogCaptureFixture(request.node, _ispytest=True)\n    yield result\n    result._finalize()\n\n\ndef get_log_level_for_setting(config: Config, *setting_names: str) -> int | None:\n    for setting_name in setting_names:\n        log_level = config.getoption(setting_name)\n        if log_level is None:\n            log_level = config.getini(setting_name)\n        if log_level:\n            break\n    else:\n        return None\n\n    if isinstance(log_level, str):\n        log_level = log_level.upper()\n    try:\n        return int(getattr(logging, log_level, log_level))\n    except ValueError as e:\n        # Python logging does not recognise this as a logging level\n        raise UsageError(\n            f\"'{log_level}' is not recognized as a logging level name for \"\n            f\"'{setting_name}'. Please consider passing the \"\n            \"logging level num instead.\"\n        ) from e\n\n\n# run after terminalreporter/capturemanager are configured\n@hookimpl(trylast=True)\ndef pytest_configure(config: Config) -> None:\n    config.pluginmanager.register(LoggingPlugin(config), \"logging-plugin\")\n\n\nclass LoggingPlugin:\n    \"\"\"Attaches to the logging module and captures log messages for each test.\"\"\"\n\n    def __init__(self, config: Config) -> None:\n        \"\"\"Create a new plugin to capture log messages.\n\n        The formatter can be safely shared across all handlers so\n        create a single one for the entire test session here.\n        \"\"\"\n        self._config = config\n\n        # Report logging.\n        self.formatter = self._create_formatter(\n            get_option_ini(config, \"log_format\"),\n            get_option_ini(config, \"log_date_format\"),\n            get_option_ini(config, \"log_auto_indent\"),\n        )\n        self.log_level = get_log_level_for_setting(config, \"log_level\")\n        self.caplog_handler = LogCaptureHandler()\n        self.caplog_handler.setFormatter(self.formatter)\n        self.report_handler = LogCaptureHandler()\n        self.report_handler.setFormatter(self.formatter)\n\n        # File logging.\n        self.log_file_level = get_log_level_for_setting(\n            config, \"log_file_level\", \"log_level\"\n        )\n        log_file = get_option_ini(config, \"log_file\") or os.devnull\n        if log_file != os.devnull:\n            directory = os.path.dirname(os.path.abspath(log_file))\n            if not os.path.isdir(directory):\n                os.makedirs(directory)\n\n        self.log_file_mode = get_option_ini(config, \"log_file_mode\") or \"w\"\n        self.log_file_handler = _FileHandler(\n            log_file, mode=self.log_file_mode, encoding=\"UTF-8\"\n        )\n        log_file_format = get_option_ini(config, \"log_file_format\", \"log_format\")\n        log_file_date_format = get_option_ini(\n            config, \"log_file_date_format\", \"log_date_format\"\n        )\n\n        log_file_formatter = DatetimeFormatter(\n            log_file_format, datefmt=log_file_date_format\n        )\n        self.log_file_handler.setFormatter(log_file_formatter)\n\n        # CLI/live logging.\n        self.log_cli_level = get_log_level_for_setting(\n            config, \"log_cli_level\", \"log_level\"\n        )\n        if self._log_cli_enabled():\n            terminal_reporter = config.pluginmanager.get_plugin(\"terminalreporter\")\n            # Guaranteed by `_log_cli_enabled()`.\n            assert terminal_reporter is not None\n            capture_manager = config.pluginmanager.get_plugin(\"capturemanager\")\n            # if capturemanager plugin is disabled, live logging still works.\n            self.log_cli_handler: (\n                _LiveLoggingStreamHandler | _LiveLoggingNullHandler\n            ) = _LiveLoggingStreamHandler(terminal_reporter, capture_manager)\n        else:\n            self.log_cli_handler = _LiveLoggingNullHandler()\n        log_cli_formatter = self._create_formatter(\n            get_option_ini(config, \"log_cli_format\", \"log_format\"),\n            get_option_ini(config, \"log_cli_date_format\", \"log_date_format\"),\n            get_option_ini(config, \"log_auto_indent\"),\n        )\n        self.log_cli_handler.setFormatter(log_cli_formatter)\n        self._disable_loggers(loggers_to_disable=config.option.logger_disable)\n\n    def _disable_loggers(self, loggers_to_disable: list[str]) -> None:\n        if not loggers_to_disable:\n            return\n\n        for name in loggers_to_disable:\n            logger = logging.getLogger(name)\n            logger.disabled = True\n\n    def _create_formatter(self, log_format, log_date_format, auto_indent):\n        # Color option doesn't exist if terminal plugin is disabled.\n        color = getattr(self._config.option, \"color\", \"no\")\n        if color != \"no\" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search(\n            log_format\n        ):\n            formatter: logging.Formatter = ColoredLevelFormatter(\n                create_terminal_writer(self._config), log_format, log_date_format\n            )\n        else:\n            formatter = DatetimeFormatter(log_format, log_date_format)\n\n        formatter._style = PercentStyleMultiline(\n            formatter._style._fmt, auto_indent=auto_indent\n        )\n\n        return formatter\n\n    def set_log_path(self, fname: str) -> None:\n        \"\"\"Set the filename parameter for Logging.FileHandler().\n\n        Creates parent directory if it does not exist.\n\n        .. warning::\n            This is an experimental API.\n        \"\"\"\n        fpath = Path(fname)\n\n        if not fpath.is_absolute():\n            fpath = self._config.rootpath / fpath\n\n        if not fpath.parent.exists():\n            fpath.parent.mkdir(exist_ok=True, parents=True)\n\n        # https://github.com/python/mypy/issues/11193\n        stream: io.TextIOWrapper = fpath.open(mode=self.log_file_mode, encoding=\"UTF-8\")  # type: ignore[assignment]\n        old_stream = self.log_file_handler.setStream(stream)\n        if old_stream:\n            old_stream.close()\n\n    def _log_cli_enabled(self) -> bool:\n        \"\"\"Return whether live logging is enabled.\"\"\"\n        enabled = self._config.getoption(\n            \"--log-cli-level\"\n        ) is not None or self._config.getini(\"log_cli\")\n        if not enabled:\n            return False\n\n        terminal_reporter = self._config.pluginmanager.get_plugin(\"terminalreporter\")\n        if terminal_reporter is None:\n            # terminal reporter is disabled e.g. by pytest-xdist.\n            return False\n\n        return True\n\n    @hookimpl(wrapper=True, tryfirst=True)\n    def pytest_sessionstart(self) -> Generator[None]:\n        self.log_cli_handler.set_when(\"sessionstart\")\n\n        with catching_logs(self.log_cli_handler, level=self.log_cli_level):\n            with catching_logs(self.log_file_handler, level=self.log_file_level):\n                return (yield)\n\n    @hookimpl(wrapper=True, tryfirst=True)\n    def pytest_collection(self) -> Generator[None]:\n        self.log_cli_handler.set_when(\"collection\")\n\n        with catching_logs(self.log_cli_handler, level=self.log_cli_level):\n            with catching_logs(self.log_file_handler, level=self.log_file_level):\n                return (yield)\n\n    @hookimpl(wrapper=True)\n    def pytest_runtestloop(self, session: Session) -> Generator[None, object, object]:\n        if session.config.option.collectonly:\n            return (yield)\n\n        if self._log_cli_enabled() and self._config.get_verbosity() < 1:\n            # The verbose flag is needed to avoid messy test progress output.\n            self._config.option.verbose = 1\n\n        with catching_logs(self.log_cli_handler, level=self.log_cli_level):\n            with catching_logs(self.log_file_handler, level=self.log_file_level):\n                return (yield)  # Run all the tests.\n\n    @hookimpl\n    def pytest_runtest_logstart(self) -> None:\n        self.log_cli_handler.reset()\n        self.log_cli_handler.set_when(\"start\")\n\n    @hookimpl\n    def pytest_runtest_logreport(self) -> None:\n        self.log_cli_handler.set_when(\"logreport\")\n\n    @contextmanager\n    def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None]:\n        \"\"\"Implement the internals of the pytest_runtest_xxx() hooks.\"\"\"\n        with (\n            catching_logs(\n                self.caplog_handler,\n                level=self.log_level,\n            ) as caplog_handler,\n            catching_logs(\n                self.report_handler,\n                level=self.log_level,\n            ) as report_handler,\n        ):\n            caplog_handler.reset()\n            report_handler.reset()\n            item.stash[caplog_records_key][when] = caplog_handler.records\n            item.stash[caplog_handler_key] = caplog_handler\n\n            try:\n                yield\n            finally:\n                log = report_handler.stream.getvalue().strip()\n                item.add_report_section(when, \"log\", log)\n\n    @hookimpl(wrapper=True)\n    def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None]:\n        self.log_cli_handler.set_when(\"setup\")\n\n        empty: dict[str, list[logging.LogRecord]] = {}\n        item.stash[caplog_records_key] = empty\n        with self._runtest_for(item, \"setup\"):\n            yield\n\n    @hookimpl(wrapper=True)\n    def pytest_runtest_call(self, item: nodes.Item) -> Generator[None]:\n        self.log_cli_handler.set_when(\"call\")\n\n        with self._runtest_for(item, \"call\"):\n            yield\n\n    @hookimpl(wrapper=True)\n    def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None]:\n        self.log_cli_handler.set_when(\"teardown\")\n\n        try:\n            with self._runtest_for(item, \"teardown\"):\n                yield\n        finally:\n            del item.stash[caplog_records_key]\n            del item.stash[caplog_handler_key]\n\n    @hookimpl\n    def pytest_runtest_logfinish(self) -> None:\n        self.log_cli_handler.set_when(\"finish\")\n\n    @hookimpl(wrapper=True, tryfirst=True)\n    def pytest_sessionfinish(self) -> Generator[None]:\n        self.log_cli_handler.set_when(\"sessionfinish\")\n\n        with catching_logs(self.log_cli_handler, level=self.log_cli_level):\n            with catching_logs(self.log_file_handler, level=self.log_file_level):\n                return (yield)\n\n    @hookimpl\n    def pytest_unconfigure(self) -> None:\n        # Close the FileHandler explicitly.\n        # (logging.shutdown might have lost the weakref?!)\n        self.log_file_handler.close()\n\n\nclass _FileHandler(logging.FileHandler):\n    \"\"\"A logging FileHandler with pytest tweaks.\"\"\"\n\n    def handleError(self, record: logging.LogRecord) -> None:\n        # Handled by LogCaptureHandler.\n        pass\n\n\nclass _LiveLoggingStreamHandler(logging_StreamHandler):\n    \"\"\"A logging StreamHandler used by the live logging feature: it will\n    write a newline before the first log message in each test.\n\n    During live logging we must also explicitly disable stdout/stderr\n    capturing otherwise it will get captured and won't appear in the\n    terminal.\n    \"\"\"\n\n    # Officially stream needs to be a IO[str], but TerminalReporter\n    # isn't. So force it.\n    stream: TerminalReporter = None  # type: ignore\n\n    def __init__(\n        self,\n        terminal_reporter: TerminalReporter,\n        capture_manager: CaptureManager | None,\n    ) -> None:\n        super().__init__(stream=terminal_reporter)  # type: ignore[arg-type]\n        self.capture_manager = capture_manager\n        self.reset()\n        self.set_when(None)\n        self._test_outcome_written = False\n\n    def reset(self) -> None:\n        \"\"\"Reset the handler; should be called before the start of each test.\"\"\"\n        self._first_record_emitted = False\n\n    def set_when(self, when: str | None) -> None:\n        \"\"\"Prepare for the given test phase (setup/call/teardown).\"\"\"\n        self._when = when\n        self._section_name_shown = False\n        if when == \"start\":\n            self._test_outcome_written = False\n\n    def emit(self, record: logging.LogRecord) -> None:\n        ctx_manager = (\n            self.capture_manager.global_and_fixture_disabled()\n            if self.capture_manager\n            else nullcontext()\n        )\n        with ctx_manager:\n            if not self._first_record_emitted:\n                self.stream.write(\"\\n\")\n                self._first_record_emitted = True\n            elif self._when in (\"teardown\", \"finish\"):\n                if not self._test_outcome_written:\n                    self._test_outcome_written = True\n                    self.stream.write(\"\\n\")\n            if not self._section_name_shown and self._when:\n                self.stream.section(\"live log \" + self._when, sep=\"-\", bold=True)\n                self._section_name_shown = True\n            super().emit(record)\n\n    def handleError(self, record: logging.LogRecord) -> None:\n        # Handled by LogCaptureHandler.\n        pass\n\n\nclass _LiveLoggingNullHandler(logging.NullHandler):\n    \"\"\"A logging handler used when live logging is disabled.\"\"\"\n\n    def reset(self) -> None:\n        pass\n\n    def set_when(self, when: str) -> None:\n        pass\n\n    def handleError(self, record: logging.LogRecord) -> None:\n        # Handled by LogCaptureHandler.\n        pass\n"
  },
  {
    "path": "src/_pytest/main.py",
    "content": "\"\"\"Core implementation of the testing process: init, session, runtest loop.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nfrom collections.abc import Callable\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nfrom collections.abc import Sequence\nfrom collections.abc import Set as AbstractSet\nimport dataclasses\nimport fnmatch\nimport functools\nimport importlib\nimport importlib.util\nimport os\nfrom pathlib import Path\nimport sys\nfrom typing import final\nfrom typing import Literal\nfrom typing import overload\nfrom typing import TYPE_CHECKING\nimport warnings\n\nimport pluggy\n\nfrom _pytest import nodes\nimport _pytest._code\nfrom _pytest.config import Config\nfrom _pytest.config import directory_arg\nfrom _pytest.config import ExitCode\nfrom _pytest.config import hookimpl\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.config import UsageError\nfrom _pytest.config.argparsing import OverrideIniAction\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.outcomes import exit\nfrom _pytest.pathlib import absolutepath\nfrom _pytest.pathlib import bestrelpath\nfrom _pytest.pathlib import fnmatch_ex\nfrom _pytest.pathlib import safe_exists\nfrom _pytest.pathlib import samefile_nofollow\nfrom _pytest.pathlib import scandir\nfrom _pytest.reports import CollectReport\nfrom _pytest.reports import TestReport\nfrom _pytest.runner import collect_one_node\nfrom _pytest.runner import SetupState\nfrom _pytest.warning_types import PytestWarning\n\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\n    from _pytest.fixtures import FixtureManager\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"general\")\n    group._addoption(  # private to use reserved lower-case short option\n        \"-x\",\n        \"--exitfirst\",\n        action=\"store_const\",\n        dest=\"maxfail\",\n        const=1,\n        help=\"Exit instantly on first error or failed test\",\n    )\n    group.addoption(\n        \"--maxfail\",\n        metavar=\"num\",\n        action=\"store\",\n        type=int,\n        dest=\"maxfail\",\n        default=0,\n        help=\"Exit after first num failures or errors\",\n    )\n    group.addoption(\n        \"--strict-config\",\n        action=OverrideIniAction,\n        ini_option=\"strict_config\",\n        ini_value=\"true\",\n        help=\"Enables the strict_config option\",\n    )\n    group.addoption(\n        \"--strict-markers\",\n        action=OverrideIniAction,\n        ini_option=\"strict_markers\",\n        ini_value=\"true\",\n        help=\"Enables the strict_markers option\",\n    )\n    group.addoption(\n        \"--strict\",\n        action=OverrideIniAction,\n        ini_option=\"strict\",\n        ini_value=\"true\",\n        help=\"Enables the strict option\",\n    )\n    parser.addini(\n        \"strict_config\",\n        \"Any warnings encountered while parsing the `pytest` section of the \"\n        \"configuration file raise errors\",\n        type=\"bool\",\n        # None => fallback to `strict`.\n        default=None,\n    )\n    parser.addini(\n        \"strict_markers\",\n        \"Markers not registered in the `markers` section of the configuration \"\n        \"file raise errors\",\n        type=\"bool\",\n        # None => fallback to `strict`.\n        default=None,\n    )\n    parser.addini(\n        \"strict\",\n        \"Enables all strictness options, currently: \"\n        \"strict_config, strict_markers, strict_xfail, strict_parametrization_ids\",\n        type=\"bool\",\n        default=False,\n    )\n\n    group = parser.getgroup(\"pytest-warnings\")\n    group.addoption(\n        \"-W\",\n        \"--pythonwarnings\",\n        action=\"append\",\n        help=\"Set which warnings to report, see -W option of Python itself\",\n    )\n    parser.addini(\n        \"filterwarnings\",\n        type=\"linelist\",\n        help=\"Each line specifies a pattern for \"\n        \"warnings.filterwarnings. \"\n        \"Processed after -W/--pythonwarnings.\",\n    )\n\n    group = parser.getgroup(\"collect\", \"collection\")\n    group.addoption(\n        \"--collectonly\",\n        \"--collect-only\",\n        \"--co\",\n        action=\"store_true\",\n        help=\"Only collect tests, don't execute them\",\n    )\n    group.addoption(\n        \"--pyargs\",\n        action=\"store_true\",\n        help=\"Try to interpret all arguments as Python packages\",\n    )\n    group.addoption(\n        \"--ignore\",\n        action=\"append\",\n        metavar=\"path\",\n        help=\"Ignore path during collection (multi-allowed)\",\n    )\n    group.addoption(\n        \"--ignore-glob\",\n        action=\"append\",\n        metavar=\"path\",\n        help=\"Ignore path pattern during collection (multi-allowed)\",\n    )\n    group.addoption(\n        \"--deselect\",\n        action=\"append\",\n        metavar=\"nodeid_prefix\",\n        help=\"Deselect item (via node id prefix) during collection (multi-allowed)\",\n    )\n    group.addoption(\n        \"--confcutdir\",\n        dest=\"confcutdir\",\n        default=None,\n        metavar=\"dir\",\n        type=functools.partial(directory_arg, optname=\"--confcutdir\"),\n        help=\"Only load conftest.py's relative to specified dir\",\n    )\n    group.addoption(\n        \"--noconftest\",\n        action=\"store_true\",\n        dest=\"noconftest\",\n        default=False,\n        help=\"Don't load any conftest.py files\",\n    )\n    group.addoption(\n        \"--keepduplicates\",\n        \"--keep-duplicates\",\n        action=\"store_true\",\n        dest=\"keepduplicates\",\n        default=False,\n        help=\"Keep duplicate tests\",\n    )\n    group.addoption(\n        \"--collect-in-virtualenv\",\n        action=\"store_true\",\n        dest=\"collect_in_virtualenv\",\n        default=False,\n        help=\"Don't ignore tests in a local virtualenv directory\",\n    )\n    group.addoption(\n        \"--continue-on-collection-errors\",\n        action=\"store_true\",\n        default=False,\n        dest=\"continue_on_collection_errors\",\n        help=\"Force test execution even if collection errors occur\",\n    )\n    group.addoption(\n        \"--import-mode\",\n        default=\"prepend\",\n        choices=[\"prepend\", \"append\", \"importlib\"],\n        dest=\"importmode\",\n        help=\"Prepend/append to sys.path when importing test modules and conftest \"\n        \"files. Default: prepend.\",\n    )\n    parser.addini(\n        \"norecursedirs\",\n        \"Directory patterns to avoid for recursion\",\n        type=\"args\",\n        default=[\n            \"*.egg\",\n            \".*\",\n            \"_darcs\",\n            \"build\",\n            \"CVS\",\n            \"dist\",\n            \"node_modules\",\n            \"venv\",\n            \"{arch}\",\n        ],\n    )\n    parser.addini(\n        \"testpaths\",\n        \"Directories to search for tests when no files or directories are given on the \"\n        \"command line\",\n        type=\"args\",\n        default=[],\n    )\n    parser.addini(\n        \"collect_imported_tests\",\n        \"Whether to collect tests in imported modules outside `testpaths`\",\n        type=\"bool\",\n        default=True,\n    )\n    parser.addini(\n        \"consider_namespace_packages\",\n        type=\"bool\",\n        default=False,\n        help=\"Consider namespace packages when resolving module names during import\",\n    )\n\n    group = parser.getgroup(\"debugconfig\", \"test session debugging and configuration\")\n    group._addoption(  # private to use reserved lower-case short option\n        \"-c\",\n        \"--config-file\",\n        metavar=\"FILE\",\n        type=str,\n        dest=\"inifilename\",\n        help=\"Load configuration from `FILE` instead of trying to locate one of the \"\n        \"implicit configuration files.\",\n    )\n    group.addoption(\n        \"--rootdir\",\n        action=\"store\",\n        dest=\"rootdir\",\n        help=\"Define root directory for tests. Can be relative path: 'root_dir', './root_dir', \"\n        \"'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: \"\n        \"'$HOME/root_dir'.\",\n    )\n    group.addoption(\n        \"--basetemp\",\n        dest=\"basetemp\",\n        default=None,\n        type=validate_basetemp,\n        metavar=\"dir\",\n        help=(\n            \"Base temporary directory for this test run. \"\n            \"(Warning: this directory is removed if it exists.)\"\n        ),\n    )\n\n\ndef validate_basetemp(path: str) -> str:\n    # GH 7119\n    msg = \"basetemp must not be empty, the current working directory or any parent directory of it\"\n\n    # empty path\n    if not path:\n        raise argparse.ArgumentTypeError(msg)\n\n    def is_ancestor(base: Path, query: Path) -> bool:\n        \"\"\"Return whether query is an ancestor of base.\"\"\"\n        if base == query:\n            return True\n        return query in base.parents\n\n    # check if path is an ancestor of cwd\n    if is_ancestor(Path.cwd(), Path(path).absolute()):\n        raise argparse.ArgumentTypeError(msg)\n\n    # check symlinks for ancestors\n    if is_ancestor(Path.cwd().resolve(), Path(path).resolve()):\n        raise argparse.ArgumentTypeError(msg)\n\n    return path\n\n\ndef wrap_session(\n    config: Config, doit: Callable[[Config, Session], int | ExitCode | None]\n) -> int | ExitCode:\n    \"\"\"Skeleton command line program.\"\"\"\n    session = Session.from_config(config)\n    session.exitstatus = ExitCode.OK\n    initstate = 0\n    try:\n        try:\n            config._do_configure()\n            initstate = 1\n            config.hook.pytest_sessionstart(session=session)\n            initstate = 2\n            session.exitstatus = doit(config, session) or 0\n        except UsageError:\n            session.exitstatus = ExitCode.USAGE_ERROR\n            raise\n        except Failed:\n            session.exitstatus = ExitCode.TESTS_FAILED\n        except (KeyboardInterrupt, exit.Exception):\n            excinfo = _pytest._code.ExceptionInfo.from_current()\n            exitstatus: int | ExitCode = ExitCode.INTERRUPTED\n            if isinstance(excinfo.value, exit.Exception):\n                if excinfo.value.returncode is not None:\n                    exitstatus = excinfo.value.returncode\n                if initstate < 2:\n                    sys.stderr.write(f\"{excinfo.typename}: {excinfo.value.msg}\\n\")\n            config.hook.pytest_keyboard_interrupt(excinfo=excinfo)\n            session.exitstatus = exitstatus\n        except BaseException:\n            session.exitstatus = ExitCode.INTERNAL_ERROR\n            excinfo = _pytest._code.ExceptionInfo.from_current()\n            try:\n                config.notify_exception(excinfo, config.option)\n            except exit.Exception as exc:\n                if exc.returncode is not None:\n                    session.exitstatus = exc.returncode\n                sys.stderr.write(f\"{type(exc).__name__}: {exc}\\n\")\n            else:\n                if isinstance(excinfo.value, SystemExit):\n                    sys.stderr.write(\"mainloop: caught unexpected SystemExit!\\n\")\n\n    finally:\n        # Explicitly break reference cycle.\n        excinfo = None  # type: ignore\n        os.chdir(session.startpath)\n        if initstate >= 2:\n            try:\n                config.hook.pytest_sessionfinish(\n                    session=session, exitstatus=session.exitstatus\n                )\n            except exit.Exception as exc:\n                if exc.returncode is not None:\n                    session.exitstatus = exc.returncode\n                sys.stderr.write(f\"{type(exc).__name__}: {exc}\\n\")\n        config._ensure_unconfigure()\n    return session.exitstatus\n\n\ndef pytest_cmdline_main(config: Config) -> int | ExitCode:\n    return wrap_session(config, _main)\n\n\ndef _main(config: Config, session: Session) -> int | ExitCode | None:\n    \"\"\"Default command line protocol for initialization, session,\n    running tests and reporting.\"\"\"\n    config.hook.pytest_collection(session=session)\n    config.hook.pytest_runtestloop(session=session)\n\n    if session.testsfailed:\n        return ExitCode.TESTS_FAILED\n    elif session.testscollected == 0:\n        return ExitCode.NO_TESTS_COLLECTED\n    return None\n\n\ndef pytest_collection(session: Session) -> None:\n    session.perform_collect()\n\n\ndef pytest_runtestloop(session: Session) -> bool:\n    if session.testsfailed and not session.config.option.continue_on_collection_errors:\n        raise session.Interrupted(\n            f\"{session.testsfailed} error{'s' if session.testsfailed != 1 else ''} during collection\"\n        )\n\n    if session.config.option.collectonly:\n        return True\n\n    for i, item in enumerate(session.items):\n        nextitem = session.items[i + 1] if i + 1 < len(session.items) else None\n        item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)\n        if session.shouldfail:\n            raise session.Failed(session.shouldfail)\n        if session.shouldstop:\n            raise session.Interrupted(session.shouldstop)\n    return True\n\n\ndef _in_venv(path: Path) -> bool:\n    \"\"\"Attempt to detect if ``path`` is the root of a Virtual Environment by\n    checking for the existence of the pyvenv.cfg file.\n\n    [https://peps.python.org/pep-0405/]\n\n    For regression protection we also check for conda environments that do not include pyenv.cfg yet --\n    https://github.com/conda/conda/issues/13337 is the conda issue tracking adding pyenv.cfg.\n\n    Checking for the `conda-meta/history` file per https://github.com/pytest-dev/pytest/issues/12652#issuecomment-2246336902.\n\n    \"\"\"\n    try:\n        return (\n            path.joinpath(\"pyvenv.cfg\").is_file()\n            or path.joinpath(\"conda-meta\", \"history\").is_file()\n        )\n    except OSError:\n        return False\n\n\ndef pytest_ignore_collect(collection_path: Path, config: Config) -> bool | None:\n    if collection_path.name == \"__pycache__\":\n        return True\n\n    ignore_paths = config._getconftest_pathlist(\n        \"collect_ignore\", path=collection_path.parent\n    )\n    ignore_paths = ignore_paths or []\n    excludeopt = config.getoption(\"ignore\")\n    if excludeopt:\n        ignore_paths.extend(absolutepath(x) for x in excludeopt)\n\n    if collection_path in ignore_paths:\n        return True\n\n    ignore_globs = config._getconftest_pathlist(\n        \"collect_ignore_glob\", path=collection_path.parent\n    )\n    ignore_globs = ignore_globs or []\n    excludeglobopt = config.getoption(\"ignore_glob\")\n    if excludeglobopt:\n        ignore_globs.extend(absolutepath(x) for x in excludeglobopt)\n\n    if any(fnmatch.fnmatch(str(collection_path), str(glob)) for glob in ignore_globs):\n        return True\n\n    allow_in_venv = config.getoption(\"collect_in_virtualenv\")\n    if not allow_in_venv and _in_venv(collection_path):\n        return True\n\n    if collection_path.is_dir():\n        norecursepatterns = config.getini(\"norecursedirs\")\n        if any(fnmatch_ex(pat, collection_path) for pat in norecursepatterns):\n            return True\n\n    return None\n\n\ndef pytest_collect_directory(\n    path: Path, parent: nodes.Collector\n) -> nodes.Collector | None:\n    return Dir.from_parent(parent, path=path)\n\n\ndef pytest_collection_modifyitems(items: list[nodes.Item], config: Config) -> None:\n    deselect_prefixes = tuple(config.getoption(\"deselect\") or [])\n    if not deselect_prefixes:\n        return\n\n    remaining = []\n    deselected = []\n    for colitem in items:\n        if colitem.nodeid.startswith(deselect_prefixes):\n            deselected.append(colitem)\n        else:\n            remaining.append(colitem)\n\n    if deselected:\n        config.hook.pytest_deselected(items=deselected)\n        items[:] = remaining\n\n\nclass FSHookProxy:\n    def __init__(\n        self,\n        pm: PytestPluginManager,\n        remove_mods: AbstractSet[object],\n    ) -> None:\n        self.pm = pm\n        self.remove_mods = remove_mods\n\n    def __getattr__(self, name: str) -> pluggy.HookCaller:\n        x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods)\n        self.__dict__[name] = x\n        return x\n\n\nclass Interrupted(KeyboardInterrupt):\n    \"\"\"Signals that the test run was interrupted.\"\"\"\n\n    __module__ = \"builtins\"  # For py3.\n\n\nclass Failed(Exception):\n    \"\"\"Signals a stop as failed test run.\"\"\"\n\n\n@dataclasses.dataclass\nclass _bestrelpath_cache(dict[Path, str]):\n    __slots__ = (\"path\",)\n\n    path: Path\n\n    def __missing__(self, path: Path) -> str:\n        r = bestrelpath(self.path, path)\n        self[path] = r\n        return r\n\n\n@final\nclass Dir(nodes.Directory):\n    \"\"\"Collector of files in a file system directory.\n\n    .. versionadded:: 8.0\n\n    .. note::\n\n        Python directories with an `__init__.py` file are instead collected by\n        :class:`~pytest.Package` by default. Both are :class:`~pytest.Directory`\n        collectors.\n    \"\"\"\n\n    @classmethod\n    def from_parent(  # type: ignore[override]\n        cls,\n        parent: nodes.Collector,\n        *,\n        path: Path,\n    ) -> Self:\n        \"\"\"The public constructor.\n\n        :param parent: The parent collector of this Dir.\n        :param path: The directory's path.\n        :type path: pathlib.Path\n        \"\"\"\n        return super().from_parent(parent=parent, path=path)\n\n    def collect(self) -> Iterable[nodes.Item | nodes.Collector]:\n        config = self.config\n        col: nodes.Collector | None\n        cols: Sequence[nodes.Collector]\n        ihook = self.ihook\n        for direntry in scandir(self.path):\n            if direntry.is_dir():\n                path = Path(direntry.path)\n                if not self.session.isinitpath(path, with_parents=True):\n                    if ihook.pytest_ignore_collect(collection_path=path, config=config):\n                        continue\n                col = ihook.pytest_collect_directory(path=path, parent=self)\n                if col is not None:\n                    yield col\n\n            elif direntry.is_file():\n                path = Path(direntry.path)\n                if not self.session.isinitpath(path):\n                    if ihook.pytest_ignore_collect(collection_path=path, config=config):\n                        continue\n                cols = ihook.pytest_collect_file(file_path=path, parent=self)\n                yield from cols\n\n\n@final\nclass Session(nodes.Collector):\n    \"\"\"The root of the collection tree.\n\n    ``Session`` collects the initial paths given as arguments to pytest.\n    \"\"\"\n\n    Interrupted = Interrupted\n    Failed = Failed\n    # Set on the session by runner.pytest_sessionstart.\n    _setupstate: SetupState\n    # Set on the session by fixtures.pytest_sessionstart.\n    _fixturemanager: FixtureManager\n    exitstatus: int | ExitCode\n\n    def __init__(self, config: Config) -> None:\n        super().__init__(\n            name=\"\",\n            path=config.rootpath,\n            fspath=None,\n            parent=None,\n            config=config,\n            session=self,\n            nodeid=\"\",\n        )\n        self.testsfailed = 0\n        self.testscollected = 0\n        self._shouldstop: bool | str = False\n        self._shouldfail: bool | str = False\n        self.trace = config.trace.root.get(\"collection\")\n        self._initialpaths: frozenset[Path] = frozenset()\n        self._initialpaths_with_parents: frozenset[Path] = frozenset()\n        self._notfound: list[tuple[str, Sequence[nodes.Collector]]] = []\n        self._initial_parts: list[CollectionArgument] = []\n        self._collection_cache: dict[nodes.Collector, CollectReport] = {}\n        self.items: list[nodes.Item] = []\n\n        self._bestrelpathcache: dict[Path, str] = _bestrelpath_cache(config.rootpath)\n\n        self.config.pluginmanager.register(self, name=\"session\")\n\n    @classmethod\n    def from_config(cls, config: Config) -> Session:\n        session: Session = cls._create(config=config)\n        return session\n\n    def __repr__(self) -> str:\n        return (\n            f\"<{self.__class__.__name__} {self.name} \"\n            f\"exitstatus=%r \"\n            f\"testsfailed={self.testsfailed} \"\n            f\"testscollected={self.testscollected}>\"\n        ) % getattr(self, \"exitstatus\", \"<UNSET>\")\n\n    @property\n    def shouldstop(self) -> bool | str:\n        return self._shouldstop\n\n    @shouldstop.setter\n    def shouldstop(self, value: bool | str) -> None:\n        # The runner checks shouldfail and assumes that if it is set we are\n        # definitely stopping, so prevent unsetting it.\n        if value is False and self._shouldstop:\n            warnings.warn(\n                PytestWarning(\n                    \"session.shouldstop cannot be unset after it has been set; ignoring.\"\n                ),\n                stacklevel=2,\n            )\n            return\n        self._shouldstop = value\n\n    @property\n    def shouldfail(self) -> bool | str:\n        return self._shouldfail\n\n    @shouldfail.setter\n    def shouldfail(self, value: bool | str) -> None:\n        # The runner checks shouldfail and assumes that if it is set we are\n        # definitely stopping, so prevent unsetting it.\n        if value is False and self._shouldfail:\n            warnings.warn(\n                PytestWarning(\n                    \"session.shouldfail cannot be unset after it has been set; ignoring.\"\n                ),\n                stacklevel=2,\n            )\n            return\n        self._shouldfail = value\n\n    @property\n    def startpath(self) -> Path:\n        \"\"\"The path from which pytest was invoked.\n\n        .. versionadded:: 7.0.0\n        \"\"\"\n        return self.config.invocation_params.dir\n\n    def _node_location_to_relpath(self, node_path: Path) -> str:\n        # bestrelpath is a quite slow function.\n        return self._bestrelpathcache[node_path]\n\n    @hookimpl(tryfirst=True)\n    def pytest_collectstart(self) -> None:\n        if self.shouldfail:\n            raise self.Failed(self.shouldfail)\n        if self.shouldstop:\n            raise self.Interrupted(self.shouldstop)\n\n    @hookimpl(tryfirst=True)\n    def pytest_runtest_logreport(self, report: TestReport | CollectReport) -> None:\n        if report.failed and not hasattr(report, \"wasxfail\"):\n            self.testsfailed += 1\n            maxfail = self.config.getvalue(\"maxfail\")\n            if maxfail and self.testsfailed >= maxfail:\n                self.shouldfail = f\"stopping after {self.testsfailed} failures\"\n\n    pytest_collectreport = pytest_runtest_logreport\n\n    def isinitpath(\n        self,\n        path: str | os.PathLike[str],\n        *,\n        with_parents: bool = False,\n    ) -> bool:\n        \"\"\"Is path an initial path?\n\n        An initial path is a path explicitly given to pytest on the command\n        line.\n\n        :param with_parents:\n            If set, also return True if the path is a parent of an initial path.\n\n        .. versionchanged:: 8.0\n            Added the ``with_parents`` parameter.\n        \"\"\"\n        # Optimization: Path(Path(...)) is much slower than isinstance.\n        path_ = path if isinstance(path, Path) else Path(path)\n        if with_parents:\n            return path_ in self._initialpaths_with_parents\n        else:\n            return path_ in self._initialpaths\n\n    def gethookproxy(self, fspath: os.PathLike[str]) -> pluggy.HookRelay:\n        # Optimization: Path(Path(...)) is much slower than isinstance.\n        path = fspath if isinstance(fspath, Path) else Path(fspath)\n        pm = self.config.pluginmanager\n        # Check if we have the common case of running\n        # hooks with all conftest.py files.\n        my_conftestmodules = pm._getconftestmodules(path)\n        remove_mods = pm._conftest_plugins.difference(my_conftestmodules)\n        proxy: pluggy.HookRelay\n        if remove_mods:\n            # One or more conftests are not in use at this path.\n            proxy = FSHookProxy(pm, remove_mods)  # type: ignore[assignment]\n        else:\n            # All plugins are active for this fspath.\n            proxy = self.config.hook\n        return proxy\n\n    def _collect_path(\n        self,\n        path: Path,\n        path_cache: dict[Path, Sequence[nodes.Collector]],\n    ) -> Sequence[nodes.Collector]:\n        \"\"\"Create a Collector for the given path.\n\n        `path_cache` makes it so the same Collectors are returned for the same\n        path.\n        \"\"\"\n        if path in path_cache:\n            return path_cache[path]\n\n        if path.is_dir():\n            ihook = self.gethookproxy(path.parent)\n            col: nodes.Collector | None = ihook.pytest_collect_directory(\n                path=path, parent=self\n            )\n            cols: Sequence[nodes.Collector] = (col,) if col is not None else ()\n\n        elif path.is_file():\n            ihook = self.gethookproxy(path)\n            cols = ihook.pytest_collect_file(file_path=path, parent=self)\n\n        else:\n            # Broken symlink or invalid/missing file.\n            cols = ()\n\n        path_cache[path] = cols\n        return cols\n\n    @overload\n    def perform_collect(\n        self, args: Sequence[str] | None = ..., genitems: Literal[True] = ...\n    ) -> Sequence[nodes.Item]: ...\n\n    @overload\n    def perform_collect(\n        self, args: Sequence[str] | None = ..., genitems: bool = ...\n    ) -> Sequence[nodes.Item | nodes.Collector]: ...\n\n    def perform_collect(\n        self, args: Sequence[str] | None = None, genitems: bool = True\n    ) -> Sequence[nodes.Item | nodes.Collector]:\n        \"\"\"Perform the collection phase for this session.\n\n        This is called by the default :hook:`pytest_collection` hook\n        implementation; see the documentation of this hook for more details.\n        For testing purposes, it may also be called directly on a fresh\n        ``Session``.\n\n        This function normally recursively expands any collectors collected\n        from the session to their items, and only items are returned. For\n        testing purposes, this may be suppressed by passing ``genitems=False``,\n        in which case the return value contains these collectors unexpanded,\n        and ``session.items`` is empty.\n        \"\"\"\n        if args is None:\n            args = self.config.args\n\n        self.trace(\"perform_collect\", self, args)\n        self.trace.root.indent += 1\n\n        hook = self.config.hook\n\n        self._notfound = []\n        self._initial_parts = []\n        self._collection_cache = {}\n        self.items = []\n        items: Sequence[nodes.Item | nodes.Collector] = self.items\n        consider_namespace_packages: bool = self.config.getini(\n            \"consider_namespace_packages\"\n        )\n        try:\n            initialpaths: list[Path] = []\n            initialpaths_with_parents: list[Path] = []\n\n            collection_args = [\n                resolve_collection_argument(\n                    self.config.invocation_params.dir,\n                    arg,\n                    i,\n                    as_pypath=self.config.option.pyargs,\n                    consider_namespace_packages=consider_namespace_packages,\n                )\n                for i, arg in enumerate(args)\n            ]\n\n            if not self.config.getoption(\"keepduplicates\"):\n                # Normalize the collection arguments -- remove duplicates and overlaps.\n                self._initial_parts = normalize_collection_arguments(collection_args)\n            else:\n                self._initial_parts = collection_args\n\n            for collection_argument in self._initial_parts:\n                initialpaths.append(collection_argument.path)\n                initialpaths_with_parents.append(collection_argument.path)\n                initialpaths_with_parents.extend(collection_argument.path.parents)\n            self._initialpaths = frozenset(initialpaths)\n            self._initialpaths_with_parents = frozenset(initialpaths_with_parents)\n\n            rep = collect_one_node(self)\n            self.ihook.pytest_collectreport(report=rep)\n            self.trace.root.indent -= 1\n            if self._notfound:\n                errors = []\n                for arg, collectors in self._notfound:\n                    if collectors:\n                        errors.append(\n                            f\"not found: {arg}\\n(no match in any of {collectors!r})\"\n                        )\n                    else:\n                        errors.append(f\"found no collectors for {arg}\")\n\n                raise UsageError(*errors)\n\n            if not genitems:\n                items = rep.result\n            else:\n                if rep.passed:\n                    for node in rep.result:\n                        self.items.extend(self.genitems(node))\n\n            self.config.pluginmanager.check_pending()\n            hook.pytest_collection_modifyitems(\n                session=self, config=self.config, items=items\n            )\n        finally:\n            self._notfound = []\n            self._initial_parts = []\n            self._collection_cache = {}\n            hook.pytest_collection_finish(session=self)\n\n        if genitems:\n            self.testscollected = len(items)\n\n        return items\n\n    def _collect_one_node(\n        self,\n        node: nodes.Collector,\n        handle_dupes: bool = True,\n    ) -> tuple[CollectReport, bool]:\n        if node in self._collection_cache and handle_dupes:\n            rep = self._collection_cache[node]\n            return rep, True\n        else:\n            rep = collect_one_node(node)\n            self._collection_cache[node] = rep\n            return rep, False\n\n    def collect(self) -> Iterator[nodes.Item | nodes.Collector]:\n        # This is a cache for the root directories of the initial paths.\n        # We can't use collection_cache for Session because of its special\n        # role as the bootstrapping collector.\n        path_cache: dict[Path, Sequence[nodes.Collector]] = {}\n\n        pm = self.config.pluginmanager\n\n        for collection_argument in self._initial_parts:\n            self.trace(\"processing argument\", collection_argument)\n            self.trace.root.indent += 1\n\n            argpath = collection_argument.path\n            names = collection_argument.parts\n            parametrization = collection_argument.parametrization\n            module_name = collection_argument.module_name\n\n            # resolve_collection_argument() ensures this.\n            if argpath.is_dir():\n                assert not names, f\"invalid arg {(argpath, names)!r}\"\n\n            paths = [argpath]\n            # Add relevant parents of the path, from the root, e.g.\n            #   /a/b/c.py -> [/, /a, /a/b, /a/b/c.py]\n            if module_name is None:\n                # Paths outside of the confcutdir should not be considered.\n                for path in argpath.parents:\n                    if not pm._is_in_confcutdir(path):\n                        break\n                    paths.insert(0, path)\n            else:\n                # For --pyargs arguments, only consider paths matching the module\n                # name. Paths beyond the package hierarchy are not included.\n                module_name_parts = module_name.split(\".\")\n                for i, path in enumerate(argpath.parents, 2):\n                    if i > len(module_name_parts) or path.stem != module_name_parts[-i]:\n                        break\n                    paths.insert(0, path)\n\n            # Start going over the parts from the root, collecting each level\n            # and discarding all nodes which don't match the level's part.\n            any_matched_in_initial_part = False\n            notfound_collectors = []\n            work: list[tuple[nodes.Collector | nodes.Item, list[Path | str]]] = [\n                (self, [*paths, *names])\n            ]\n            while work:\n                matchnode, matchparts = work.pop()\n\n                # Pop'd all of the parts, this is a match.\n                if not matchparts:\n                    yield matchnode\n                    any_matched_in_initial_part = True\n                    continue\n\n                # Should have been matched by now, discard.\n                if not isinstance(matchnode, nodes.Collector):\n                    continue\n\n                # Collect this level of matching.\n                # Collecting Session (self) is done directly to avoid endless\n                # recursion to this function.\n                subnodes: Sequence[nodes.Collector | nodes.Item]\n                if isinstance(matchnode, Session):\n                    assert isinstance(matchparts[0], Path)\n                    subnodes = matchnode._collect_path(matchparts[0], path_cache)\n                else:\n                    # For backward compat, files given directly multiple\n                    # times on the command line should not be deduplicated.\n                    handle_dupes = not (\n                        len(matchparts) == 1\n                        and isinstance(matchparts[0], Path)\n                        and matchparts[0].is_file()\n                    )\n                    rep, duplicate = self._collect_one_node(matchnode, handle_dupes)\n                    if not duplicate and not rep.passed:\n                        # Report collection failures here to avoid failing to\n                        # run some test specified in the command line because\n                        # the module could not be imported (#134).\n                        matchnode.ihook.pytest_collectreport(report=rep)\n                    if not rep.passed:\n                        continue\n                    subnodes = rep.result\n\n                # Prune this level.\n                any_matched_in_collector = False\n                for node in reversed(subnodes):\n                    # Path part e.g. `/a/b/` in `/a/b/test_file.py::TestIt::test_it`.\n                    if isinstance(matchparts[0], Path):\n                        is_match = node.path == matchparts[0]\n                        if sys.platform == \"win32\" and not is_match:\n                            # In case the file paths do not match, fallback to samefile() to\n                            # account for short-paths on Windows (#11895). But use a version\n                            # which doesn't resolve symlinks, otherwise we might match the\n                            # same file more than once (#12039).\n                            is_match = samefile_nofollow(node.path, matchparts[0])\n\n                    # Name part e.g. `TestIt` in `/a/b/test_file.py::TestIt::test_it`.\n                    else:\n                        if len(matchparts) == 1:\n                            # This the last part, one parametrization goes.\n                            if parametrization is not None:\n                                # A parametrized arg must match exactly.\n                                is_match = node.name == matchparts[0] + parametrization\n                            else:\n                                # A non-parameterized arg matches all parametrizations (if any).\n                                # TODO: Remove the hacky split once the collection structure\n                                # contains parametrization.\n                                is_match = node.name.split(\"[\")[0] == matchparts[0]\n                        else:\n                            is_match = node.name == matchparts[0]\n                    if is_match:\n                        work.append((node, matchparts[1:]))\n                        any_matched_in_collector = True\n\n                if not any_matched_in_collector:\n                    notfound_collectors.append(matchnode)\n\n            if not any_matched_in_initial_part:\n                report_arg = \"::\".join((str(argpath), *names))\n                self._notfound.append((report_arg, notfound_collectors))\n\n            self.trace.root.indent -= 1\n\n    def genitems(self, node: nodes.Item | nodes.Collector) -> Iterator[nodes.Item]:\n        self.trace(\"genitems\", node)\n        if isinstance(node, nodes.Item):\n            node.ihook.pytest_itemcollected(item=node)\n            yield node\n        else:\n            assert isinstance(node, nodes.Collector)\n            # For backward compat, dedup only applies to files.\n            handle_dupes = not isinstance(node, nodes.File)\n            rep, duplicate = self._collect_one_node(node, handle_dupes)\n            if rep.passed:\n                for subnode in rep.result:\n                    yield from self.genitems(subnode)\n            if not duplicate:\n                node.ihook.pytest_collectreport(report=rep)\n\n\ndef search_pypath(\n    module_name: str, *, consider_namespace_packages: bool = False\n) -> str | None:\n    \"\"\"Search sys.path for the given a dotted module name, and return its file\n    system path if found.\"\"\"\n    try:\n        spec = importlib.util.find_spec(module_name)\n    # AttributeError: looks like package module, but actually filename\n    # ImportError: module does not exist\n    # ValueError: not a module name\n    except (AttributeError, ImportError, ValueError):\n        return None\n\n    if spec is None:\n        return None\n\n    if (\n        spec.submodule_search_locations is None\n        or len(spec.submodule_search_locations) == 0\n    ):\n        # Must be a simple module.\n        return spec.origin\n\n    if consider_namespace_packages:\n        # If submodule_search_locations is set, it's a package (regular or namespace).\n        # Typically there is a single entry, but documentation claims it can be empty too\n        #  (e.g. if the package has no physical location).\n        return spec.submodule_search_locations[0]\n\n    if spec.origin is None:\n        # This is only the case for namespace packages\n        return None\n\n    return os.path.dirname(spec.origin)\n\n\n@dataclasses.dataclass(frozen=True)\nclass CollectionArgument:\n    \"\"\"A resolved collection argument.\"\"\"\n\n    path: Path\n    parts: Sequence[str]\n    parametrization: str | None\n    module_name: str | None\n    original_index: int\n\n\ndef resolve_collection_argument(\n    invocation_path: Path,\n    arg: str,\n    arg_index: int,\n    *,\n    as_pypath: bool = False,\n    consider_namespace_packages: bool = False,\n) -> CollectionArgument:\n    \"\"\"Parse path arguments optionally containing selection parts and return (fspath, names).\n\n    Command-line arguments can point to files and/or directories, and optionally contain\n    parts for specific tests selection, for example:\n\n        \"pkg/tests/test_foo.py::TestClass::test_foo\"\n\n    This function ensures the path exists, and returns a resolved `CollectionArgument`:\n\n        CollectionArgument(\n            path=Path(\"/full/path/to/pkg/tests/test_foo.py\"),\n            parts=[\"TestClass\", \"test_foo\"],\n            module_name=None,\n        )\n\n    When as_pypath is True, expects that the command-line argument actually contains\n    module paths instead of file-system paths:\n\n        \"pkg.tests.test_foo::TestClass::test_foo[a,b]\"\n\n    In which case we search sys.path for a matching module, and then return the *path* to the\n    found module, which may look like this:\n\n        CollectionArgument(\n            path=Path(\"/home/u/myvenv/lib/site-packages/pkg/tests/test_foo.py\"),\n            parts=[\"TestClass\", \"test_foo\"],\n            parametrization=\"[a,b]\",\n            module_name=\"pkg.tests.test_foo\",\n        )\n\n    If the path doesn't exist, raise UsageError.\n    If the path is a directory and selection parts are present, raise UsageError.\n    \"\"\"\n    base, squacket, rest = arg.partition(\"[\")\n    strpath, *parts = base.split(\"::\")\n    if squacket and not parts:\n        raise UsageError(f\"path cannot contain [] parametrization: {arg}\")\n    parametrization = f\"{squacket}{rest}\" if squacket else None\n    module_name = None\n    if as_pypath:\n        pyarg_strpath = search_pypath(\n            strpath, consider_namespace_packages=consider_namespace_packages\n        )\n        if pyarg_strpath is not None:\n            module_name = strpath\n            strpath = pyarg_strpath\n    fspath = invocation_path / strpath\n    fspath = absolutepath(fspath)\n    if not safe_exists(fspath):\n        msg = (\n            \"module or package not found: {arg} (missing __init__.py?)\"\n            if as_pypath\n            else \"file or directory not found: {arg}\"\n        )\n        raise UsageError(msg.format(arg=arg))\n    if parts and fspath.is_dir():\n        msg = (\n            \"package argument cannot contain :: selection parts: {arg}\"\n            if as_pypath\n            else \"directory argument cannot contain :: selection parts: {arg}\"\n        )\n        raise UsageError(msg.format(arg=arg))\n    return CollectionArgument(\n        path=fspath,\n        parts=parts,\n        parametrization=parametrization,\n        module_name=module_name,\n        original_index=arg_index,\n    )\n\n\ndef is_collection_argument_subsumed_by(\n    arg: CollectionArgument, by: CollectionArgument\n) -> bool:\n    \"\"\"Check if `arg` is subsumed (contained) by `by`.\"\"\"\n    # First check path subsumption.\n    if by.path != arg.path:\n        # `by` subsumes `arg` if `by` is a parent directory of `arg` and has no\n        # parts (collects everything in that directory).\n        if not by.parts:\n            return arg.path.is_relative_to(by.path)\n        return False\n    # Paths are equal, check parts.\n    # For example: (\"TestClass\",) is a prefix of (\"TestClass\", \"test_method\").\n    if len(by.parts) > len(arg.parts) or arg.parts[: len(by.parts)] != by.parts:\n        return False\n    # Paths and parts are equal, check parametrization.\n    # A `by` without parametrization (None) matches everything, e.g.\n    # `pytest x.py::test_it` matches `x.py::test_it[0]`. Otherwise must be\n    # exactly equal.\n    if by.parametrization is not None and by.parametrization != arg.parametrization:\n        return False\n    return True\n\n\ndef normalize_collection_arguments(\n    collection_args: Sequence[CollectionArgument],\n) -> list[CollectionArgument]:\n    \"\"\"Normalize collection arguments to eliminate overlapping paths and parts.\n\n    Detects when collection arguments overlap in either paths or parts and only\n    keeps the shorter prefix, or the earliest argument if duplicate, preserving\n    order. The result is prefix-free.\n    \"\"\"\n    # A quadratic algorithm is not acceptable since large inputs are possible.\n    # So this uses an O(n*log(n)) algorithm which takes advantage of the\n    # property that after sorting, a collection argument will immediately\n    # precede collection arguments it subsumes. An O(n) algorithm is not worth\n    # it.\n    collection_args_sorted = sorted(\n        collection_args,\n        key=lambda arg: (arg.path, arg.parts, arg.parametrization or \"\"),\n    )\n    normalized: list[CollectionArgument] = []\n    last_kept = None\n    for arg in collection_args_sorted:\n        if last_kept is None or not is_collection_argument_subsumed_by(arg, last_kept):\n            normalized.append(arg)\n            last_kept = arg\n    normalized.sort(key=lambda arg: arg.original_index)\n    return normalized\n"
  },
  {
    "path": "src/_pytest/mark/__init__.py",
    "content": "\"\"\"Generic mechanism for marking and selecting python functions.\"\"\"\n\nfrom __future__ import annotations\n\nimport collections\nfrom collections.abc import Collection\nfrom collections.abc import Iterable\nfrom collections.abc import Set as AbstractSet\nimport dataclasses\nfrom typing import TYPE_CHECKING\n\nfrom .expression import Expression\nfrom .structures import _HiddenParam\nfrom .structures import EMPTY_PARAMETERSET_OPTION\nfrom .structures import get_empty_parameterset_mark\nfrom .structures import HIDDEN_PARAM\nfrom .structures import Mark\nfrom .structures import MARK_GEN\nfrom .structures import MarkDecorator\nfrom .structures import MarkGenerator\nfrom .structures import ParameterSet\nfrom _pytest.compat import NOTSET\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.config import hookimpl\nfrom _pytest.config import UsageError\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.stash import StashKey\n\n\nif TYPE_CHECKING:\n    from _pytest.nodes import Item\n\n\n__all__ = [\n    \"HIDDEN_PARAM\",\n    \"MARK_GEN\",\n    \"Mark\",\n    \"MarkDecorator\",\n    \"MarkGenerator\",\n    \"ParameterSet\",\n    \"get_empty_parameterset_mark\",\n]\n\n\nold_mark_config_key = StashKey[Config | None]()\n\n\ndef param(\n    *values: object,\n    marks: MarkDecorator | Collection[MarkDecorator | Mark] = (),\n    id: str | _HiddenParam | None = None,\n) -> ParameterSet:\n    \"\"\"Specify a parameter in `pytest.mark.parametrize`_ calls or\n    :ref:`parametrized fixtures <fixture-parametrize-marks>`.\n\n    .. code-block:: python\n\n        @pytest.mark.parametrize(\n            \"test_input,expected\",\n            [\n                (\"3+5\", 8),\n                pytest.param(\"6*9\", 42, marks=pytest.mark.xfail),\n            ],\n        )\n        def test_eval(test_input, expected):\n            assert eval(test_input) == expected\n\n    :param values: Variable args of the values of the parameter set, in order.\n\n    :param marks:\n        A single mark or a list of marks to be applied to this parameter set.\n\n        :ref:`pytest.mark.usefixtures <pytest.mark.usefixtures ref>` cannot be added via this parameter.\n\n    :type id: str | Literal[pytest.HIDDEN_PARAM] | None\n    :param id:\n        The id to attribute to this parameter set.\n\n        .. versionadded:: 8.4\n            :ref:`hidden-param` means to hide the parameter set\n            from the test name. Can only be used at most 1 time, as\n            test names need to be unique.\n    \"\"\"\n    return ParameterSet.param(*values, marks=marks, id=id)\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"general\")\n    group._addoption(  # private to use reserved lower-case short option\n        \"-k\",\n        action=\"store\",\n        dest=\"keyword\",\n        default=\"\",\n        metavar=\"EXPRESSION\",\n        help=\"Only run tests which match the given substring expression. \"\n        \"An expression is a Python evaluable expression \"\n        \"where all names are substring-matched against test names \"\n        \"and their parent classes. Example: -k 'test_method or test_\"\n        \"other' matches all test functions and classes whose name \"\n        \"contains 'test_method' or 'test_other', while -k 'not test_method' \"\n        \"matches those that don't contain 'test_method' in their names. \"\n        \"-k 'not test_method and not test_other' will eliminate the matches. \"\n        \"Additionally keywords are matched to classes and functions \"\n        \"containing extra names in their 'extra_keyword_matches' set, \"\n        \"as well as functions which have names assigned directly to them. \"\n        \"The matching is case-insensitive.\",\n    )\n\n    group._addoption(  # private to use reserved lower-case short option\n        \"-m\",\n        action=\"store\",\n        dest=\"markexpr\",\n        default=\"\",\n        metavar=\"MARKEXPR\",\n        help=\"Only run tests matching given mark expression. \"\n        \"For example: -m 'mark1 and not mark2'.\",\n    )\n\n    group.addoption(\n        \"--markers\",\n        action=\"store_true\",\n        help=\"show markers (builtin, plugin and per-project ones).\",\n    )\n\n    parser.addini(\"markers\", \"Register new markers for test functions\", \"linelist\")\n    parser.addini(EMPTY_PARAMETERSET_OPTION, \"Default marker for empty parametersets\")\n\n\n@hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config: Config) -> int | ExitCode | None:\n    import _pytest.config\n\n    if config.option.markers:\n        config._do_configure()\n        tw = _pytest.config.create_terminal_writer(config)\n        for line in config.getini(\"markers\"):\n            parts = line.split(\":\", 1)\n            name = parts[0]\n            rest = parts[1] if len(parts) == 2 else \"\"\n            tw.write(f\"@pytest.mark.{name}:\", bold=True)\n            tw.line(rest)\n            tw.line()\n        config._ensure_unconfigure()\n        return 0\n\n    return None\n\n\n@dataclasses.dataclass\nclass KeywordMatcher:\n    \"\"\"A matcher for keywords.\n\n    Given a list of names, matches any substring of one of these names. The\n    string inclusion check is case-insensitive.\n\n    Will match on the name of colitem, including the names of its parents.\n    Only matches names of items which are either a :class:`Class` or a\n    :class:`Function`.\n\n    Additionally, matches on names in the 'extra_keyword_matches' set of\n    any item, as well as names directly assigned to test functions.\n    \"\"\"\n\n    __slots__ = (\"_names\",)\n\n    _names: AbstractSet[str]\n\n    @classmethod\n    def from_item(cls, item: Item) -> KeywordMatcher:\n        mapped_names = set()\n\n        # Add the names of the current item and any parent items,\n        # except the Session and root Directory's which are not\n        # interesting for matching.\n        import pytest\n\n        for node in item.listchain():\n            if isinstance(node, pytest.Session):\n                continue\n            if isinstance(node, pytest.Directory) and isinstance(\n                node.parent, pytest.Session\n            ):\n                continue\n            mapped_names.add(node.name)\n\n        # Add the names added as extra keywords to current or parent items.\n        mapped_names.update(item.listextrakeywords())\n\n        # Add the names attached to the current function through direct assignment.\n        function_obj = getattr(item, \"function\", None)\n        if function_obj:\n            mapped_names.update(function_obj.__dict__)\n\n        # Add the markers to the keywords as we no longer handle them correctly.\n        mapped_names.update(mark.name for mark in item.iter_markers())\n\n        return cls(mapped_names)\n\n    def __call__(self, subname: str, /, **kwargs: str | int | bool | None) -> bool:\n        if kwargs:\n            raise UsageError(\"Keyword expressions do not support call parameters.\")\n        subname = subname.lower()\n        return any(subname in name.lower() for name in self._names)\n\n\ndef deselect_by_keyword(items: list[Item], config: Config) -> None:\n    keywordexpr = config.option.keyword.lstrip()\n    if not keywordexpr:\n        return\n\n    expr = _parse_expression(keywordexpr, \"Wrong expression passed to '-k'\")\n\n    remaining = []\n    deselected = []\n    for colitem in items:\n        if not expr.evaluate(KeywordMatcher.from_item(colitem)):\n            deselected.append(colitem)\n        else:\n            remaining.append(colitem)\n\n    if deselected:\n        config.hook.pytest_deselected(items=deselected)\n        items[:] = remaining\n\n\n@dataclasses.dataclass\nclass MarkMatcher:\n    \"\"\"A matcher for markers which are present.\n\n    Tries to match on any marker names, attached to the given colitem.\n    \"\"\"\n\n    __slots__ = (\"own_mark_name_mapping\",)\n\n    own_mark_name_mapping: dict[str, list[Mark]]\n\n    @classmethod\n    def from_markers(cls, markers: Iterable[Mark]) -> MarkMatcher:\n        mark_name_mapping = collections.defaultdict(list)\n        for mark in markers:\n            mark_name_mapping[mark.name].append(mark)\n        return cls(mark_name_mapping)\n\n    def __call__(self, name: str, /, **kwargs: str | int | bool | None) -> bool:\n        if not (matches := self.own_mark_name_mapping.get(name, [])):\n            return False\n\n        for mark in matches:  # pylint: disable=consider-using-any-or-all\n            if all(mark.kwargs.get(k, NOTSET) == v for k, v in kwargs.items()):\n                return True\n        return False\n\n\ndef deselect_by_mark(items: list[Item], config: Config) -> None:\n    matchexpr = config.option.markexpr\n    if not matchexpr:\n        return\n\n    expr = _parse_expression(matchexpr, \"Wrong expression passed to '-m'\")\n    remaining: list[Item] = []\n    deselected: list[Item] = []\n    for item in items:\n        if expr.evaluate(MarkMatcher.from_markers(item.iter_markers())):\n            remaining.append(item)\n        else:\n            deselected.append(item)\n    if deselected:\n        config.hook.pytest_deselected(items=deselected)\n        items[:] = remaining\n\n\ndef _parse_expression(expr: str, exc_message: str) -> Expression:\n    try:\n        return Expression.compile(expr)\n    except SyntaxError as e:\n        raise UsageError(\n            f\"{exc_message}: {e.text}: at column {e.offset}: {e.msg}\"\n        ) from None\n\n\ndef pytest_collection_modifyitems(items: list[Item], config: Config) -> None:\n    deselect_by_keyword(items, config)\n    deselect_by_mark(items, config)\n\n\ndef pytest_configure(config: Config) -> None:\n    config.stash[old_mark_config_key] = MARK_GEN._config\n    MARK_GEN._config = config\n\n    empty_parameterset = config.getini(EMPTY_PARAMETERSET_OPTION)\n\n    if empty_parameterset not in (\"skip\", \"xfail\", \"fail_at_collect\", None, \"\"):\n        raise UsageError(\n            f\"{EMPTY_PARAMETERSET_OPTION!s} must be one of skip, xfail or fail_at_collect\"\n            f\" but it is {empty_parameterset!r}\"\n        )\n\n\ndef pytest_unconfigure(config: Config) -> None:\n    MARK_GEN._config = config.stash.get(old_mark_config_key, None)\n"
  },
  {
    "path": "src/_pytest/mark/expression.py",
    "content": "r\"\"\"Evaluate match expressions, as used by `-k` and `-m`.\n\nThe grammar is:\n\nexpression: expr? EOF\nexpr:       and_expr ('or' and_expr)*\nand_expr:   not_expr ('and' not_expr)*\nnot_expr:   'not' not_expr | '(' expr ')' | ident kwargs?\n\nident:      (\\w|:|\\+|-|\\.|\\[|\\]|\\\\|/)+\nkwargs:     ('(' name '=' value ( ', ' name '=' value )*  ')')\nname:       a valid ident, but not a reserved keyword\nvalue:      (unescaped) string literal | (-)?[0-9]+ | 'False' | 'True' | 'None'\n\nThe semantics are:\n\n- Empty expression evaluates to False.\n- ident evaluates to True or False according to a provided matcher function.\n- ident with parentheses and keyword arguments evaluates to True or False according to a provided matcher function.\n- or/and/not evaluate according to the usual boolean semantics.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport ast\nfrom collections.abc import Iterator\nfrom collections.abc import Mapping\nfrom collections.abc import Sequence\nimport dataclasses\nimport enum\nimport keyword\nimport re\nimport types\nfrom typing import Final\nfrom typing import final\nfrom typing import Literal\nfrom typing import NoReturn\nfrom typing import overload\nfrom typing import Protocol\n\n\n__all__ = [\n    \"Expression\",\n    \"ExpressionMatcher\",\n]\n\n\nFILE_NAME: Final = \"<pytest match expression>\"\n\n\nclass TokenType(enum.Enum):\n    LPAREN = \"left parenthesis\"\n    RPAREN = \"right parenthesis\"\n    OR = \"or\"\n    AND = \"and\"\n    NOT = \"not\"\n    IDENT = \"identifier\"\n    EOF = \"end of input\"\n    EQUAL = \"=\"\n    STRING = \"string literal\"\n    COMMA = \",\"\n\n\n@dataclasses.dataclass(frozen=True)\nclass Token:\n    __slots__ = (\"pos\", \"type\", \"value\")\n    type: TokenType\n    value: str\n    pos: int\n\n\nclass Scanner:\n    __slots__ = (\"current\", \"input\", \"tokens\")\n\n    def __init__(self, input: str) -> None:\n        self.input = input\n        self.tokens = self.lex(input)\n        self.current = next(self.tokens)\n\n    def lex(self, input: str) -> Iterator[Token]:\n        pos = 0\n        while pos < len(input):\n            if input[pos] in (\" \", \"\\t\"):\n                pos += 1\n            elif input[pos] == \"(\":\n                yield Token(TokenType.LPAREN, \"(\", pos)\n                pos += 1\n            elif input[pos] == \")\":\n                yield Token(TokenType.RPAREN, \")\", pos)\n                pos += 1\n            elif input[pos] == \"=\":\n                yield Token(TokenType.EQUAL, \"=\", pos)\n                pos += 1\n            elif input[pos] == \",\":\n                yield Token(TokenType.COMMA, \",\", pos)\n                pos += 1\n            elif (quote_char := input[pos]) in (\"'\", '\"'):\n                end_quote_pos = input.find(quote_char, pos + 1)\n                if end_quote_pos == -1:\n                    raise SyntaxError(\n                        f'closing quote \"{quote_char}\" is missing',\n                        (FILE_NAME, 1, pos + 1, input),\n                    )\n                value = input[pos : end_quote_pos + 1]\n                if (backslash_pos := input.find(\"\\\\\")) != -1:\n                    raise SyntaxError(\n                        r'escaping with \"\\\" not supported in marker expression',\n                        (FILE_NAME, 1, backslash_pos + 1, input),\n                    )\n                yield Token(TokenType.STRING, value, pos)\n                pos += len(value)\n            else:\n                match = re.match(r\"(:?\\w|:|\\+|-|\\.|\\[|\\]|\\\\|/)+\", input[pos:])\n                if match:\n                    value = match.group(0)\n                    if value == \"or\":\n                        yield Token(TokenType.OR, value, pos)\n                    elif value == \"and\":\n                        yield Token(TokenType.AND, value, pos)\n                    elif value == \"not\":\n                        yield Token(TokenType.NOT, value, pos)\n                    else:\n                        yield Token(TokenType.IDENT, value, pos)\n                    pos += len(value)\n                else:\n                    raise SyntaxError(\n                        f'unexpected character \"{input[pos]}\"',\n                        (FILE_NAME, 1, pos + 1, input),\n                    )\n        yield Token(TokenType.EOF, \"\", pos)\n\n    @overload\n    def accept(self, type: TokenType, *, reject: Literal[True]) -> Token: ...\n\n    @overload\n    def accept(\n        self, type: TokenType, *, reject: Literal[False] = False\n    ) -> Token | None: ...\n\n    def accept(self, type: TokenType, *, reject: bool = False) -> Token | None:\n        if self.current.type is type:\n            token = self.current\n            if token.type is not TokenType.EOF:\n                self.current = next(self.tokens)\n            return token\n        if reject:\n            self.reject((type,))\n        return None\n\n    def reject(self, expected: Sequence[TokenType]) -> NoReturn:\n        raise SyntaxError(\n            \"expected {}; got {}\".format(\n                \" OR \".join(type.value for type in expected),\n                self.current.type.value,\n            ),\n            (FILE_NAME, 1, self.current.pos + 1, self.input),\n        )\n\n\n# True, False and None are legal match expression identifiers,\n# but illegal as Python identifiers. To fix this, this prefix\n# is added to identifiers in the conversion to Python AST.\nIDENT_PREFIX = \"$\"\n\n\ndef expression(s: Scanner) -> ast.Expression:\n    if s.accept(TokenType.EOF):\n        ret: ast.expr = ast.Constant(False)\n    else:\n        ret = expr(s)\n        s.accept(TokenType.EOF, reject=True)\n    return ast.fix_missing_locations(ast.Expression(ret))\n\n\ndef expr(s: Scanner) -> ast.expr:\n    ret = and_expr(s)\n    while s.accept(TokenType.OR):\n        rhs = and_expr(s)\n        ret = ast.BoolOp(ast.Or(), [ret, rhs])\n    return ret\n\n\ndef and_expr(s: Scanner) -> ast.expr:\n    ret = not_expr(s)\n    while s.accept(TokenType.AND):\n        rhs = not_expr(s)\n        ret = ast.BoolOp(ast.And(), [ret, rhs])\n    return ret\n\n\ndef not_expr(s: Scanner) -> ast.expr:\n    if s.accept(TokenType.NOT):\n        return ast.UnaryOp(ast.Not(), not_expr(s))\n    if s.accept(TokenType.LPAREN):\n        ret = expr(s)\n        s.accept(TokenType.RPAREN, reject=True)\n        return ret\n    ident = s.accept(TokenType.IDENT)\n    if ident:\n        name = ast.Name(IDENT_PREFIX + ident.value, ast.Load())\n        if s.accept(TokenType.LPAREN):\n            ret = ast.Call(func=name, args=[], keywords=all_kwargs(s))\n            s.accept(TokenType.RPAREN, reject=True)\n        else:\n            ret = name\n        return ret\n\n    s.reject((TokenType.NOT, TokenType.LPAREN, TokenType.IDENT))\n\n\nBUILTIN_MATCHERS = {\"True\": True, \"False\": False, \"None\": None}\n\n\ndef single_kwarg(s: Scanner) -> ast.keyword:\n    keyword_name = s.accept(TokenType.IDENT, reject=True)\n    if not keyword_name.value.isidentifier():\n        raise SyntaxError(\n            f\"not a valid python identifier {keyword_name.value}\",\n            (FILE_NAME, 1, keyword_name.pos + 1, s.input),\n        )\n    if keyword.iskeyword(keyword_name.value):\n        raise SyntaxError(\n            f\"unexpected reserved python keyword `{keyword_name.value}`\",\n            (FILE_NAME, 1, keyword_name.pos + 1, s.input),\n        )\n    s.accept(TokenType.EQUAL, reject=True)\n\n    if value_token := s.accept(TokenType.STRING):\n        value: str | int | bool | None = value_token.value[1:-1]  # strip quotes\n    else:\n        value_token = s.accept(TokenType.IDENT, reject=True)\n        if (number := value_token.value).isdigit() or (\n            number.startswith(\"-\") and number[1:].isdigit()\n        ):\n            value = int(number)\n        elif value_token.value in BUILTIN_MATCHERS:\n            value = BUILTIN_MATCHERS[value_token.value]\n        else:\n            raise SyntaxError(\n                f'unexpected character/s \"{value_token.value}\"',\n                (FILE_NAME, 1, value_token.pos + 1, s.input),\n            )\n\n    ret = ast.keyword(keyword_name.value, ast.Constant(value))\n    return ret\n\n\ndef all_kwargs(s: Scanner) -> list[ast.keyword]:\n    ret = [single_kwarg(s)]\n    while s.accept(TokenType.COMMA):\n        ret.append(single_kwarg(s))\n    return ret\n\n\nclass ExpressionMatcher(Protocol):\n    \"\"\"A callable which, given an identifier and optional kwargs, should return\n    whether it matches in an :class:`Expression` evaluation.\n\n    Should be prepared to handle arbitrary strings as input.\n\n    If no kwargs are provided, the expression of the form `foo`.\n    If kwargs are provided, the expression is of the form `foo(1, b=True, \"s\")`.\n\n    If the expression is not supported (e.g. don't want to accept the kwargs\n    syntax variant), should raise :class:`~pytest.UsageError`.\n\n    Example::\n\n        def matcher(name: str, /, **kwargs: str | int | bool | None) -> bool:\n            # Match `cat`.\n            if name == \"cat\" and not kwargs:\n                return True\n            # Match `dog(barks=True)`.\n            if name == \"dog\" and kwargs == {\"barks\": False}:\n                return True\n            return False\n    \"\"\"\n\n    def __call__(self, name: str, /, **kwargs: str | int | bool | None) -> bool: ...\n\n\n@dataclasses.dataclass\nclass MatcherNameAdapter:\n    matcher: ExpressionMatcher\n    name: str\n\n    def __bool__(self) -> bool:\n        return self.matcher(self.name)\n\n    def __call__(self, **kwargs: str | int | bool | None) -> bool:\n        return self.matcher(self.name, **kwargs)\n\n\nclass MatcherAdapter(Mapping[str, MatcherNameAdapter]):\n    \"\"\"Adapts a matcher function to a locals mapping as required by eval().\"\"\"\n\n    def __init__(self, matcher: ExpressionMatcher) -> None:\n        self.matcher = matcher\n\n    def __getitem__(self, key: str) -> MatcherNameAdapter:\n        return MatcherNameAdapter(matcher=self.matcher, name=key[len(IDENT_PREFIX) :])\n\n    def __iter__(self) -> Iterator[str]:\n        raise NotImplementedError()\n\n    def __len__(self) -> int:\n        raise NotImplementedError()\n\n\n@final\nclass Expression:\n    \"\"\"A compiled match expression as used by -k and -m.\n\n    The expression can be evaluated against different matchers.\n    \"\"\"\n\n    __slots__ = (\"_code\", \"input\")\n\n    def __init__(self, input: str, code: types.CodeType) -> None:\n        #: The original input line, as a string.\n        self.input: Final = input\n        self._code: Final = code\n\n    @classmethod\n    def compile(cls, input: str) -> Expression:\n        \"\"\"Compile a match expression.\n\n        :param input: The input expression - one line.\n\n        :raises SyntaxError: If the expression is malformed.\n        \"\"\"\n        astexpr = expression(Scanner(input))\n        code = compile(\n            astexpr,\n            filename=\"<pytest match expression>\",\n            mode=\"eval\",\n        )\n        return Expression(input, code)\n\n    def evaluate(self, matcher: ExpressionMatcher) -> bool:\n        \"\"\"Evaluate the match expression.\n\n        :param matcher:\n            A callback which determines whether an identifier matches or not.\n            See the :class:`ExpressionMatcher` protocol for details and example.\n\n        :returns: Whether the expression matches or not.\n\n        :raises UsageError:\n            If the matcher doesn't support the expression. Cannot happen if the\n            matcher supports all expressions.\n        \"\"\"\n        return bool(eval(self._code, {\"__builtins__\": {}}, MatcherAdapter(matcher)))\n"
  },
  {
    "path": "src/_pytest/mark/structures.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport collections.abc\nfrom collections.abc import Callable\nfrom collections.abc import Collection\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nfrom collections.abc import Mapping\nfrom collections.abc import MutableMapping\nfrom collections.abc import Sequence\nimport dataclasses\nimport enum\nimport inspect\nfrom typing import Any\nfrom typing import final\nfrom typing import NamedTuple\nfrom typing import overload\nfrom typing import TYPE_CHECKING\nfrom typing import TypeVar\nimport warnings\n\nfrom .._code import getfslineno\nfrom ..compat import deprecated\nfrom ..compat import NOTSET\nfrom ..compat import NotSetType\nfrom _pytest.config import Config\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.deprecated import PARAMETRIZE_NON_COLLECTION_ITERABLE\nfrom _pytest.outcomes import fail\nfrom _pytest.raises import AbstractRaises\nfrom _pytest.scope import _ScopeName\nfrom _pytest.warning_types import PytestUnknownMarkWarning\n\n\nif TYPE_CHECKING:\n    from ..nodes import Node\n\n\nEMPTY_PARAMETERSET_OPTION = \"empty_parameter_set_mark\"\n\n\n# Singleton type for HIDDEN_PARAM, as described in:\n# https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions\nclass _HiddenParam(enum.Enum):\n    token = 0\n\n\n#: Can be used as a parameter set id to hide it from the test name.\nHIDDEN_PARAM = _HiddenParam.token\n\n\ndef istestfunc(func) -> bool:\n    return callable(func) and getattr(func, \"__name__\", \"<lambda>\") != \"<lambda>\"\n\n\ndef get_empty_parameterset_mark(\n    config: Config, argnames: Sequence[str], func\n) -> MarkDecorator:\n    from ..nodes import Collector\n\n    argslisting = \", \".join(argnames)\n\n    _fs, lineno = getfslineno(func)\n    reason = f\"got empty parameter set for ({argslisting})\"\n    requested_mark = config.getini(EMPTY_PARAMETERSET_OPTION)\n    if requested_mark in (\"\", None, \"skip\"):\n        mark = MARK_GEN.skip(reason=reason)\n    elif requested_mark == \"xfail\":\n        mark = MARK_GEN.xfail(reason=reason, run=False)\n    elif requested_mark == \"fail_at_collect\":\n        raise Collector.CollectError(\n            f\"Empty parameter set in '{func.__name__}' at line {lineno + 1}\"\n        )\n    else:\n        raise LookupError(requested_mark)\n    return mark\n\n\nclass ParameterSet(NamedTuple):\n    \"\"\"A set of values for a set of parameters along with associated marks and\n    an optional ID for the set.\n\n    Examples::\n\n        pytest.param(1, 2, 3)\n        # ParameterSet(values=(1, 2, 3), marks=(), id=None)\n\n        pytest.param(\"hello\", id=\"greeting\")\n        # ParameterSet(values=(\"hello\",), marks=(), id=\"greeting\")\n\n        # Parameter set with marks\n        pytest.param(42, marks=pytest.mark.xfail)\n        # ParameterSet(values=(42,), marks=(MarkDecorator(...),), id=None)\n\n        # From parametrize mark (parameter names + list of parameter sets)\n        pytest.mark.parametrize(\n            (\"a\", \"b\", \"expected\"),\n            [\n                (1, 2, 3),\n                pytest.param(40, 2, 42, id=\"everything\"),\n            ],\n        )\n        # ParameterSet(values=(1, 2, 3), marks=(), id=None)\n        # ParameterSet(values=(40, 2, 42), marks=(), id=\"everything\")\n    \"\"\"\n\n    values: Sequence[object | NotSetType]\n    marks: Collection[MarkDecorator | Mark]\n    id: str | _HiddenParam | None\n\n    @classmethod\n    def param(\n        cls,\n        *values: object,\n        marks: MarkDecorator | Collection[MarkDecorator | Mark] = (),\n        id: str | _HiddenParam | None = None,\n    ) -> ParameterSet:\n        if isinstance(marks, MarkDecorator):\n            marks = (marks,)\n        else:\n            assert isinstance(marks, collections.abc.Collection)\n        if any(i.name == \"usefixtures\" for i in marks):\n            raise ValueError(\n                \"pytest.param cannot add pytest.mark.usefixtures; see \"\n                \"https://docs.pytest.org/en/stable/reference/reference.html#pytest-param\"\n            )\n\n        if id is not None:\n            if not isinstance(id, str) and id is not HIDDEN_PARAM:\n                raise TypeError(\n                    \"Expected id to be a string or a `pytest.HIDDEN_PARAM` sentinel, \"\n                    f\"got {type(id)}: {id!r}\",\n                )\n        return cls(values, marks, id)\n\n    @classmethod\n    def extract_from(\n        cls,\n        parameterset: ParameterSet | Sequence[object] | object,\n        force_tuple: bool = False,\n    ) -> ParameterSet:\n        \"\"\"Extract from an object or objects.\n\n        :param parameterset:\n            A legacy style parameterset that may or may not be a tuple,\n            and may or may not be wrapped into a mess of mark objects.\n\n        :param force_tuple:\n            Enforce tuple wrapping so single argument tuple values\n            don't get decomposed and break tests.\n        \"\"\"\n        if isinstance(parameterset, cls):\n            return parameterset\n        if force_tuple:\n            return cls.param(parameterset)\n        else:\n            # TODO: Refactor to fix this type-ignore. Currently the following\n            # passes type-checking but crashes:\n            #\n            #   @pytest.mark.parametrize(('x', 'y'), [1, 2])\n            #   def test_foo(x, y): pass\n            return cls(parameterset, marks=[], id=None)  # type: ignore[arg-type]\n\n    @staticmethod\n    def _parse_parametrize_args(\n        argnames: str | Sequence[str],\n        argvalues: Iterable[ParameterSet | Sequence[object] | object],\n        *args,\n        **kwargs,\n    ) -> tuple[Sequence[str], bool]:\n        if isinstance(argnames, str):\n            # A trailing comma indicates tuple-style: \"arg,\" is equivalent to (\"arg\",)\n            # In this case, argvalues should be a list of tuples, not wrapped values.\n            # See https://github.com/pytest-dev/pytest/issues/719\n            has_trailing_comma = argnames.rstrip().endswith(\",\")\n            argnames = [x.strip() for x in argnames.split(\",\") if x.strip()]\n            force_tuple = len(argnames) == 1 and not has_trailing_comma\n        else:\n            force_tuple = False\n        return argnames, force_tuple\n\n    @staticmethod\n    def _parse_parametrize_parameters(\n        argvalues: Iterable[ParameterSet | Sequence[object] | object],\n        force_tuple: bool,\n    ) -> list[ParameterSet]:\n        return [\n            ParameterSet.extract_from(x, force_tuple=force_tuple) for x in argvalues\n        ]\n\n    @classmethod\n    def _for_parametrize(\n        cls,\n        argnames: str | Sequence[str],\n        argvalues: Iterable[ParameterSet | Sequence[object] | object],\n        func,\n        config: Config,\n        nodeid: str,\n    ) -> tuple[Sequence[str], list[ParameterSet]]:\n        if not isinstance(argvalues, Collection):\n            warnings.warn(\n                PARAMETRIZE_NON_COLLECTION_ITERABLE.format(\n                    nodeid=nodeid,\n                    type_name=type(argvalues).__name__,\n                ),\n                stacklevel=3,\n            )\n\n        argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)\n        parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)\n        del argvalues\n\n        if parameters:\n            # Check all parameter sets have the correct number of values.\n            for param in parameters:\n                if len(param.values) != len(argnames):\n                    msg = (\n                        '{nodeid}: in \"parametrize\" the number of names ({names_len}):\\n'\n                        \"  {names}\\n\"\n                        \"must be equal to the number of values ({values_len}):\\n\"\n                        \"  {values}\"\n                    )\n                    fail(\n                        msg.format(\n                            nodeid=nodeid,\n                            values=param.values,\n                            names=argnames,\n                            names_len=len(argnames),\n                            values_len=len(param.values),\n                        ),\n                        pytrace=False,\n                    )\n        else:\n            # Empty parameter set (likely computed at runtime): create a single\n            # parameter set with NOTSET values, with the \"empty parameter set\" mark applied to it.\n            mark = get_empty_parameterset_mark(config, argnames, func)\n            parameters.append(\n                ParameterSet(\n                    values=(NOTSET,) * len(argnames), marks=[mark], id=\"NOTSET\"\n                )\n            )\n        return argnames, parameters\n\n\n@final\n@dataclasses.dataclass(frozen=True)\nclass Mark:\n    \"\"\"A pytest mark.\"\"\"\n\n    #: Name of the mark.\n    name: str\n    #: Positional arguments of the mark decorator.\n    args: tuple[Any, ...]\n    #: Keyword arguments of the mark decorator.\n    kwargs: Mapping[str, Any]\n\n    #: Source Mark for ids with parametrize Marks.\n    _param_ids_from: Mark | None = dataclasses.field(default=None, repr=False)\n    #: Resolved/generated ids with parametrize Marks.\n    _param_ids_generated: Sequence[str] | None = dataclasses.field(\n        default=None, repr=False\n    )\n\n    def __init__(\n        self,\n        name: str,\n        args: tuple[Any, ...],\n        kwargs: Mapping[str, Any],\n        param_ids_from: Mark | None = None,\n        param_ids_generated: Sequence[str] | None = None,\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        \"\"\":meta private:\"\"\"\n        check_ispytest(_ispytest)\n        # Weirdness to bypass frozen=True.\n        object.__setattr__(self, \"name\", name)\n        object.__setattr__(self, \"args\", args)\n        object.__setattr__(self, \"kwargs\", kwargs)\n        object.__setattr__(self, \"_param_ids_from\", param_ids_from)\n        object.__setattr__(self, \"_param_ids_generated\", param_ids_generated)\n\n    def _has_param_ids(self) -> bool:\n        return \"ids\" in self.kwargs or len(self.args) >= 4\n\n    def combined_with(self, other: Mark) -> Mark:\n        \"\"\"Return a new Mark which is a combination of this\n        Mark and another Mark.\n\n        Combines by appending args and merging kwargs.\n\n        :param Mark other: The mark to combine with.\n        :rtype: Mark\n        \"\"\"\n        assert self.name == other.name\n\n        # Remember source of ids with parametrize Marks.\n        param_ids_from: Mark | None = None\n        if self.name == \"parametrize\":\n            if other._has_param_ids():\n                param_ids_from = other\n            elif self._has_param_ids():\n                param_ids_from = self\n\n        return Mark(\n            self.name,\n            self.args + other.args,\n            dict(self.kwargs, **other.kwargs),\n            param_ids_from=param_ids_from,\n            _ispytest=True,\n        )\n\n\n# A generic parameter designating an object to which a Mark may\n# be applied -- a test function (callable) or class.\n# Note: a lambda is not allowed, but this can't be represented.\nMarkable = TypeVar(\"Markable\", bound=Callable[..., object] | type)\n\n\n@dataclasses.dataclass\nclass MarkDecorator:\n    \"\"\"A decorator for applying a mark on test functions and classes.\n\n    ``MarkDecorators`` are created with ``pytest.mark``::\n\n        mark1 = pytest.mark.NAME  # Simple MarkDecorator\n        mark2 = pytest.mark.NAME(name1=value)  # Parametrized MarkDecorator\n\n    and can then be applied as decorators to test functions::\n\n        @mark2\n        def test_function():\n            pass\n\n    When a ``MarkDecorator`` is called, it does the following:\n\n    1. If called with a single class as its only positional argument and no\n       additional keyword arguments, it attaches the mark to the class so it\n       gets applied automatically to all test cases found in that class.\n\n    2. If called with a single function as its only positional argument and\n       no additional keyword arguments, it attaches the mark to the function,\n       containing all the arguments already stored internally in the\n       ``MarkDecorator``.\n\n    3. When called in any other case, it returns a new ``MarkDecorator``\n       instance with the original ``MarkDecorator``'s content updated with\n       the arguments passed to this call.\n\n    Note: The rules above prevent a ``MarkDecorator`` from storing only a\n    single function or class reference as its positional argument with no\n    additional keyword or positional arguments. You can work around this by\n    using `with_args()`.\n    \"\"\"\n\n    mark: Mark\n\n    def __init__(self, mark: Mark, *, _ispytest: bool = False) -> None:\n        \"\"\":meta private:\"\"\"\n        check_ispytest(_ispytest)\n        self.mark = mark\n\n    @property\n    def name(self) -> str:\n        \"\"\"Alias for mark.name.\"\"\"\n        return self.mark.name\n\n    @property\n    def args(self) -> tuple[Any, ...]:\n        \"\"\"Alias for mark.args.\"\"\"\n        return self.mark.args\n\n    @property\n    def kwargs(self) -> Mapping[str, Any]:\n        \"\"\"Alias for mark.kwargs.\"\"\"\n        return self.mark.kwargs\n\n    @property\n    def markname(self) -> str:\n        \"\"\":meta private:\"\"\"\n        return self.name  # for backward-compat (2.4.1 had this attr)\n\n    def with_args(self, *args: object, **kwargs: object) -> MarkDecorator:\n        \"\"\"Return a MarkDecorator with extra arguments added.\n\n        Unlike calling the MarkDecorator, with_args() can be used even\n        if the sole argument is a callable/class.\n        \"\"\"\n        mark = Mark(self.name, args, kwargs, _ispytest=True)\n        return MarkDecorator(self.mark.combined_with(mark), _ispytest=True)\n\n    # Type ignored because the overloads overlap with an incompatible\n    # return type. Not much we can do about that. Thankfully mypy picks\n    # the first match so it works out even if we break the rules.\n    @overload\n    def __call__(self, arg: Markable) -> Markable:  # type: ignore[overload-overlap]\n        pass\n\n    @overload\n    def __call__(self, *args: object, **kwargs: object) -> MarkDecorator:\n        pass\n\n    def __call__(self, *args: object, **kwargs: object):\n        \"\"\"Call the MarkDecorator.\"\"\"\n        if args and not kwargs:\n            func = args[0]\n            is_class = inspect.isclass(func)\n            # For staticmethods/classmethods, the marks are eventually fetched from the\n            # function object, not the descriptor, so unwrap.\n            unwrapped_func = func\n            if isinstance(func, staticmethod | classmethod):\n                unwrapped_func = func.__func__\n            if len(args) == 1 and (istestfunc(unwrapped_func) or is_class):\n                store_mark(unwrapped_func, self.mark)\n                return func\n        return self.with_args(*args, **kwargs)\n\n\ndef get_unpacked_marks(\n    obj: object | type,\n    *,\n    consider_mro: bool = True,\n) -> list[Mark]:\n    \"\"\"Obtain the unpacked marks that are stored on an object.\n\n    If obj is a class and consider_mro is true, return marks applied to\n    this class and all of its super-classes in MRO order. If consider_mro\n    is false, only return marks applied directly to this class.\n    \"\"\"\n    if isinstance(obj, type):\n        if not consider_mro:\n            mark_lists = [obj.__dict__.get(\"pytestmark\", [])]\n        else:\n            mark_lists = [\n                x.__dict__.get(\"pytestmark\", []) for x in reversed(obj.__mro__)\n            ]\n        mark_list = []\n        for item in mark_lists:\n            if isinstance(item, list):\n                mark_list.extend(item)\n            else:\n                mark_list.append(item)\n    else:\n        mark_attribute = getattr(obj, \"pytestmark\", [])\n        if isinstance(mark_attribute, list):\n            mark_list = mark_attribute\n        else:\n            mark_list = [mark_attribute]\n    return list(normalize_mark_list(mark_list))\n\n\ndef normalize_mark_list(\n    mark_list: Iterable[Mark | MarkDecorator],\n) -> Iterable[Mark]:\n    \"\"\"\n    Normalize an iterable of Mark or MarkDecorator objects into a list of marks\n    by retrieving the `mark` attribute on MarkDecorator instances.\n\n    :param mark_list: marks to normalize\n    :returns: A new list of the extracted Mark objects\n    \"\"\"\n    for mark in mark_list:\n        mark_obj = getattr(mark, \"mark\", mark)\n        if not isinstance(mark_obj, Mark):\n            raise TypeError(f\"got {mark_obj!r} instead of Mark\")\n        yield mark_obj\n\n\ndef store_mark(obj, mark: Mark) -> None:\n    \"\"\"Store a Mark on an object.\n\n    This is used to implement the Mark declarations/decorators correctly.\n    \"\"\"\n    assert isinstance(mark, Mark), mark\n\n    from ..fixtures import getfixturemarker\n\n    if getfixturemarker(obj) is not None:\n        fail(\n            \"Marks cannot be applied to fixtures.\\n\"\n            \"See docs: https://docs.pytest.org/en/stable/deprecations.html#applying-a-mark-to-a-fixture-function\"\n        )\n\n    # Always reassign name to avoid updating pytestmark in a reference that\n    # was only borrowed.\n    obj.pytestmark = [*get_unpacked_marks(obj, consider_mro=False), mark]\n\n\n# Typing for builtin pytest marks. This is cheating; it gives builtin marks\n# special privilege, and breaks modularity. But practicality beats purity...\nif TYPE_CHECKING:\n\n    class _SkipMarkDecorator(MarkDecorator):\n        @overload  # type: ignore[override,no-overload-impl]\n        def __call__(self, arg: Markable) -> Markable: ...\n\n        @overload\n        def __call__(self, reason: str = ...) -> MarkDecorator: ...\n\n    class _SkipifMarkDecorator(MarkDecorator):\n        def __call__(  # type: ignore[override]\n            self,\n            condition: str | bool = ...,\n            *conditions: str | bool,\n            reason: str = ...,\n        ) -> MarkDecorator: ...\n\n    class _XfailMarkDecorator(MarkDecorator):\n        @overload  # type: ignore[override,no-overload-impl]\n        def __call__(self, arg: Markable) -> Markable: ...\n\n        @overload\n        def __call__(\n            self,\n            condition: str | bool = True,\n            *conditions: str | bool,\n            reason: str = ...,\n            run: bool = ...,\n            raises: None\n            | type[BaseException]\n            | tuple[type[BaseException], ...]\n            | AbstractRaises[BaseException] = ...,\n            strict: bool = ...,\n        ) -> MarkDecorator: ...\n\n    class _ParametrizeMarkDecorator(MarkDecorator):\n        @overload  # type: ignore[override,no-overload-impl]\n        def __call__(\n            self,\n            argnames: str | Sequence[str],\n            argvalues: Collection[ParameterSet | Sequence[object] | object],\n            *,\n            indirect: bool | Sequence[str] = ...,\n            ids: Iterable[None | str | float | int | bool]\n            | Callable[[Any], object | None]\n            | None = ...,\n            scope: _ScopeName | None = ...,\n        ) -> MarkDecorator: ...\n\n        @overload\n        @deprecated(\n            \"Passing a non-Collection iterable to the 'argvalues' parameter of @pytest.mark.parametrize is deprecated. \"\n            \"Convert argvalues to a list or tuple.\",\n        )\n        def __call__(\n            self,\n            argnames: str | Sequence[str],\n            argvalues: Iterable[ParameterSet | Sequence[object] | object],\n            *,\n            indirect: bool | Sequence[str] = ...,\n            ids: Iterable[None | str | float | int | bool]\n            | Callable[[Any], object | None]\n            | None = ...,\n            scope: _ScopeName | None = ...,\n        ) -> MarkDecorator: ...\n\n    class _UsefixturesMarkDecorator(MarkDecorator):\n        def __call__(self, *fixtures: str) -> MarkDecorator:  # type: ignore[override]\n            ...\n\n    class _FilterwarningsMarkDecorator(MarkDecorator):\n        def __call__(self, *filters: str) -> MarkDecorator:  # type: ignore[override]\n            ...\n\n\n@final\nclass MarkGenerator:\n    \"\"\"Factory for :class:`MarkDecorator` objects - exposed as\n    a ``pytest.mark`` singleton instance.\n\n    Example::\n\n         import pytest\n\n\n         @pytest.mark.slowtest\n         def test_function():\n             pass\n\n    applies a 'slowtest' :class:`Mark` on ``test_function``.\n    \"\"\"\n\n    # See TYPE_CHECKING above.\n    if TYPE_CHECKING:\n        skip: _SkipMarkDecorator\n        skipif: _SkipifMarkDecorator\n        xfail: _XfailMarkDecorator\n        parametrize: _ParametrizeMarkDecorator\n        usefixtures: _UsefixturesMarkDecorator\n        filterwarnings: _FilterwarningsMarkDecorator\n\n    def __init__(self, *, _ispytest: bool = False) -> None:\n        check_ispytest(_ispytest)\n        self._config: Config | None = None\n        self._markers: set[str] = set()\n\n    def __getattr__(self, name: str) -> MarkDecorator:\n        \"\"\"Generate a new :class:`MarkDecorator` with the given name.\"\"\"\n        if name[0] == \"_\":\n            raise AttributeError(\"Marker name must NOT start with underscore\")\n\n        if self._config is not None:\n            # We store a set of markers as a performance optimisation - if a mark\n            # name is in the set we definitely know it, but a mark may be known and\n            # not in the set.  We therefore start by updating the set!\n            if name not in self._markers:\n                for line in self._config.getini(\"markers\"):\n                    # example lines: \"skipif(condition): skip the given test if...\"\n                    # or \"hypothesis: tests which use Hypothesis\", so to get the\n                    # marker name we split on both `:` and `(`.\n                    marker = line.split(\":\")[0].split(\"(\")[0].strip()\n                    self._markers.add(marker)\n\n            # If the name is not in the set of known marks after updating,\n            # then it really is time to issue a warning or an error.\n            if name not in self._markers:\n                # Raise a specific error for common misspellings of \"parametrize\".\n                if name in [\"parameterize\", \"parametrise\", \"parameterise\"]:\n                    __tracebackhide__ = True\n                    fail(f\"Unknown '{name}' mark, did you mean 'parametrize'?\")\n\n                strict_markers = self._config.getini(\"strict_markers\")\n                if strict_markers is None:\n                    strict_markers = self._config.getini(\"strict\")\n                if strict_markers:\n                    fail(\n                        f\"{name!r} not found in `markers` configuration option\",\n                        pytrace=False,\n                    )\n\n                warnings.warn(\n                    f\"Unknown pytest.mark.{name} - is this a typo?  You can register \"\n                    \"custom marks to avoid this warning - for details, see \"\n                    \"https://docs.pytest.org/en/stable/how-to/mark.html\",\n                    PytestUnknownMarkWarning,\n                    2,\n                )\n\n        return MarkDecorator(Mark(name, (), {}, _ispytest=True), _ispytest=True)\n\n\nMARK_GEN = MarkGenerator(_ispytest=True)\n\n\n@final\nclass NodeKeywords(MutableMapping[str, Any]):\n    __slots__ = (\"_markers\", \"node\", \"parent\")\n\n    def __init__(self, node: Node) -> None:\n        self.node = node\n        self.parent = node.parent\n        self._markers = {node.name: True}\n\n    def __getitem__(self, key: str) -> Any:\n        try:\n            return self._markers[key]\n        except KeyError:\n            if self.parent is None:\n                raise\n            return self.parent.keywords[key]\n\n    def __setitem__(self, key: str, value: Any) -> None:\n        self._markers[key] = value\n\n    # Note: we could've avoided explicitly implementing some of the methods\n    # below and use the collections.abc fallback, but that would be slow.\n\n    def __contains__(self, key: object) -> bool:\n        return key in self._markers or (\n            self.parent is not None and key in self.parent.keywords\n        )\n\n    def update(  # type: ignore[override]\n        self,\n        other: Mapping[str, Any] | Iterable[tuple[str, Any]] = (),\n        **kwds: Any,\n    ) -> None:\n        self._markers.update(other)\n        self._markers.update(kwds)\n\n    def __delitem__(self, key: str) -> None:\n        raise ValueError(\"cannot delete key in keywords dict\")\n\n    def __iter__(self) -> Iterator[str]:\n        # Doesn't need to be fast.\n        yield from self._markers\n        if self.parent is not None:\n            for keyword in self.parent.keywords:\n                # self._marks and self.parent.keywords can have duplicates.\n                if keyword not in self._markers:\n                    yield keyword\n\n    def __len__(self) -> int:\n        # Doesn't need to be fast.\n        return sum(1 for keyword in self)\n\n    def __repr__(self) -> str:\n        return f\"<NodeKeywords for node {self.node}>\"\n"
  },
  {
    "path": "src/_pytest/monkeypatch.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Monkeypatching and mocking functionality.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nfrom collections.abc import Mapping\nfrom collections.abc import MutableMapping\nfrom contextlib import contextmanager\nimport importlib\nimport os\nfrom pathlib import Path\nimport re\nimport sys\nfrom typing import Any\nfrom typing import final\nfrom typing import overload\nfrom typing import TypeVar\nimport warnings\n\nfrom _pytest.compat import NOTSET\nfrom _pytest.compat import NotSetType\nfrom _pytest.deprecated import MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES\nfrom _pytest.fixtures import fixture\nfrom _pytest.warning_types import PytestWarning\n\n\nRE_IMPORT_ERROR_NAME = re.compile(r\"^No module named (.*)$\")\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\n@fixture\ndef monkeypatch() -> Generator[MonkeyPatch]:\n    \"\"\"A convenient fixture for monkey-patching.\n\n    The fixture provides these methods to modify objects, dictionaries, or\n    :data:`os.environ`:\n\n    * :meth:`monkeypatch.setattr(obj, name, value, raising=True) <pytest.MonkeyPatch.setattr>`\n    * :meth:`monkeypatch.delattr(obj, name, raising=True) <pytest.MonkeyPatch.delattr>`\n    * :meth:`monkeypatch.setitem(mapping, name, value) <pytest.MonkeyPatch.setitem>`\n    * :meth:`monkeypatch.delitem(obj, name, raising=True) <pytest.MonkeyPatch.delitem>`\n    * :meth:`monkeypatch.setenv(name, value, prepend=None) <pytest.MonkeyPatch.setenv>`\n    * :meth:`monkeypatch.delenv(name, raising=True) <pytest.MonkeyPatch.delenv>`\n    * :meth:`monkeypatch.syspath_prepend(path) <pytest.MonkeyPatch.syspath_prepend>`\n    * :meth:`monkeypatch.chdir(path) <pytest.MonkeyPatch.chdir>`\n    * :meth:`monkeypatch.context() <pytest.MonkeyPatch.context>`\n\n    All modifications will be undone after the requesting test function or\n    fixture has finished. The ``raising`` parameter determines if a :class:`KeyError`\n    or :class:`AttributeError` will be raised if the set/deletion operation does not have the\n    specified target.\n\n    To undo modifications done by the fixture in a contained scope,\n    use :meth:`context() <pytest.MonkeyPatch.context>`.\n    \"\"\"\n    mpatch = MonkeyPatch()\n    yield mpatch\n    mpatch.undo()\n\n\ndef resolve(name: str) -> object:\n    # Simplified from zope.dottedname.\n    parts = name.split(\".\")\n\n    used = parts.pop(0)\n    found: object = importlib.import_module(used)\n    for part in parts:\n        used += \".\" + part\n        try:\n            found = getattr(found, part)\n        except AttributeError:\n            pass\n        else:\n            continue\n        # We use explicit un-nesting of the handling block in order\n        # to avoid nested exceptions.\n        try:\n            importlib.import_module(used)\n        except ImportError as ex:\n            expected = str(ex).split()[-1]\n            if expected == used:\n                raise\n            else:\n                raise ImportError(f\"import error in {used}: {ex}\") from ex\n        found = annotated_getattr(found, part, used)\n    return found\n\n\ndef annotated_getattr(obj: object, name: str, ann: str) -> object:\n    try:\n        obj = getattr(obj, name)\n    except AttributeError as e:\n        raise AttributeError(\n            f\"{type(obj).__name__!r} object at {ann} has no attribute {name!r}\"\n        ) from e\n    return obj\n\n\ndef derive_importpath(import_path: str, raising: bool) -> tuple[str, object]:\n    if not isinstance(import_path, str) or \".\" not in import_path:\n        raise TypeError(f\"must be absolute import path string, not {import_path!r}\")\n    module, attr = import_path.rsplit(\".\", 1)\n    target = resolve(module)\n    if raising:\n        annotated_getattr(target, attr, ann=module)\n    return attr, target\n\n\n@final\nclass MonkeyPatch:\n    \"\"\"Helper to conveniently monkeypatch attributes/items/environment\n    variables/syspath.\n\n    Returned by the :fixture:`monkeypatch` fixture.\n\n    .. versionchanged:: 6.2\n        Can now also be used directly as `pytest.MonkeyPatch()`, for when\n        the fixture is not available. In this case, use\n        :meth:`with MonkeyPatch.context() as mp: <context>` or remember to call\n        :meth:`undo` explicitly.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self._setattr: list[tuple[object, str, object]] = []\n        self._setitem: list[tuple[Mapping[Any, Any], object, object]] = []\n        self._cwd: str | None = None\n        self._savesyspath: list[str] | None = None\n\n    @classmethod\n    @contextmanager\n    def context(cls) -> Generator[MonkeyPatch]:\n        \"\"\"Context manager that returns a new :class:`MonkeyPatch` object\n        which undoes any patching done inside the ``with`` block upon exit.\n\n        Example:\n\n        .. code-block:: python\n\n            import functools\n\n\n            def test_partial(monkeypatch):\n                with monkeypatch.context() as m:\n                    m.setattr(functools, \"partial\", 3)\n\n        Useful in situations where it is desired to undo some patches before the test ends,\n        such as mocking ``stdlib`` functions that might break pytest itself if mocked (for examples\n        of this see :issue:`3290`).\n        \"\"\"\n        m = cls()\n        try:\n            yield m\n        finally:\n            m.undo()\n\n    @overload\n    def setattr(\n        self,\n        target: str,\n        name: object,\n        value: NotSetType = ...,\n        raising: bool = ...,\n    ) -> None: ...\n\n    @overload\n    def setattr(\n        self,\n        target: object,\n        name: str,\n        value: object,\n        raising: bool = ...,\n    ) -> None: ...\n\n    def setattr(\n        self,\n        target: str | object,\n        name: object | str,\n        value: object = NOTSET,\n        raising: bool = True,\n    ) -> None:\n        \"\"\"\n        Set attribute value on target, memorizing the old value.\n\n        For example:\n\n        .. code-block:: python\n\n            import os\n\n            monkeypatch.setattr(os, \"getcwd\", lambda: \"/\")\n\n        The code above replaces the :func:`os.getcwd` function by a ``lambda`` which\n        always returns ``\"/\"``.\n\n        For convenience, you can specify a string as ``target`` which\n        will be interpreted as a dotted import path, with the last part\n        being the attribute name:\n\n        .. code-block:: python\n\n            monkeypatch.setattr(\"os.getcwd\", lambda: \"/\")\n\n        Raises :class:`AttributeError` if the attribute does not exist, unless\n        ``raising`` is set to False.\n\n        **Where to patch**\n\n        ``monkeypatch.setattr`` works by (temporarily) changing the object that a name points to with another one.\n        There can be many names pointing to any individual object, so for patching to work you must ensure\n        that you patch the name used by the system under test.\n\n        See the section :ref:`Where to patch <python:where-to-patch>` in the :mod:`unittest.mock`\n        docs for a complete explanation, which is meant for :func:`unittest.mock.patch` but\n        applies to ``monkeypatch.setattr`` as well.\n        \"\"\"\n        __tracebackhide__ = True\n        import inspect\n\n        if value is NOTSET:\n            if not isinstance(target, str):\n                raise TypeError(\n                    \"use setattr(target, name, value) or \"\n                    \"setattr(target, value) with target being a dotted \"\n                    \"import string\"\n                )\n            value = name\n            name, target = derive_importpath(target, raising)\n        else:\n            if not isinstance(name, str):\n                raise TypeError(\n                    \"use setattr(target, name, value) with name being a string or \"\n                    \"setattr(target, value) with target being a dotted \"\n                    \"import string\"\n                )\n\n        oldval = getattr(target, name, NOTSET)\n        if raising and oldval is NOTSET:\n            raise AttributeError(f\"{target!r} has no attribute {name!r}\")\n\n        # avoid class descriptors like staticmethod/classmethod\n        if inspect.isclass(target):\n            oldval = target.__dict__.get(name, NOTSET)\n        self._setattr.append((target, name, oldval))\n        setattr(target, name, value)\n\n    def delattr(\n        self,\n        target: object | str,\n        name: str | NotSetType = NOTSET,\n        raising: bool = True,\n    ) -> None:\n        \"\"\"Delete attribute ``name`` from ``target``.\n\n        If no ``name`` is specified and ``target`` is a string\n        it will be interpreted as a dotted import path with the\n        last part being the attribute name.\n\n        Raises AttributeError it the attribute does not exist, unless\n        ``raising`` is set to False.\n        \"\"\"\n        __tracebackhide__ = True\n        import inspect\n\n        if name is NOTSET:\n            if not isinstance(target, str):\n                raise TypeError(\n                    \"use delattr(target, name) or \"\n                    \"delattr(target) with target being a dotted \"\n                    \"import string\"\n                )\n            name, target = derive_importpath(target, raising)\n\n        if not hasattr(target, name):\n            if raising:\n                raise AttributeError(name)\n        else:\n            oldval = getattr(target, name, NOTSET)\n            # Avoid class descriptors like staticmethod/classmethod.\n            if inspect.isclass(target):\n                oldval = target.__dict__.get(name, NOTSET)\n            self._setattr.append((target, name, oldval))\n            delattr(target, name)\n\n    def setitem(self, dic: Mapping[K, V], name: K, value: V) -> None:\n        \"\"\"Set dictionary entry ``name`` to value.\"\"\"\n        self._setitem.append((dic, name, dic.get(name, NOTSET)))\n        # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict\n        dic[name] = value  # type: ignore[index]\n\n    def delitem(self, dic: Mapping[K, V], name: K, raising: bool = True) -> None:\n        \"\"\"Delete ``name`` from dict.\n\n        Raises ``KeyError`` if it doesn't exist, unless ``raising`` is set to\n        False.\n        \"\"\"\n        if name not in dic:\n            if raising:\n                raise KeyError(name)\n        else:\n            self._setitem.append((dic, name, dic.get(name, NOTSET)))\n            # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict\n            del dic[name]  # type: ignore[attr-defined]\n\n    def setenv(self, name: str, value: str, prepend: str | None = None) -> None:\n        \"\"\"Set environment variable ``name`` to ``value``.\n\n        If ``prepend`` is a character, read the current environment variable\n        value and prepend the ``value`` adjoined with the ``prepend``\n        character.\n        \"\"\"\n        if not isinstance(value, str):\n            warnings.warn(  # type: ignore[unreachable]\n                PytestWarning(\n                    f\"Value of environment variable {name} type should be str, but got \"\n                    f\"{value!r} (type: {type(value).__name__}); converted to str implicitly\"\n                ),\n                stacklevel=2,\n            )\n            value = str(value)\n        if prepend and name in os.environ:\n            value = value + prepend + os.environ[name]\n        self.setitem(os.environ, name, value)\n\n    def delenv(self, name: str, raising: bool = True) -> None:\n        \"\"\"Delete ``name`` from the environment.\n\n        Raises ``KeyError`` if it does not exist, unless ``raising`` is set to\n        False.\n        \"\"\"\n        environ: MutableMapping[str, str] = os.environ\n        self.delitem(environ, name, raising=raising)\n\n    def syspath_prepend(self, path) -> None:\n        \"\"\"Prepend ``path`` to ``sys.path`` list of import locations.\"\"\"\n        if self._savesyspath is None:\n            self._savesyspath = sys.path[:]\n        sys.path.insert(0, str(path))\n\n        # https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171\n        # this is only needed when pkg_resources was already loaded by the namespace package\n        if \"pkg_resources\" in sys.modules:\n            import pkg_resources\n            from pkg_resources import fixup_namespace_packages\n\n            # Only issue deprecation warning if this call would actually have an\n            # effect for this specific path.\n            if (\n                hasattr(pkg_resources, \"_namespace_packages\")\n                and pkg_resources._namespace_packages\n            ):\n                path_obj = Path(str(path))\n                for ns_pkg in pkg_resources._namespace_packages:\n                    if ns_pkg is None:\n                        continue\n                    ns_pkg_path = path_obj / ns_pkg.replace(\".\", os.sep)\n                    if ns_pkg_path.is_dir():\n                        warnings.warn(\n                            MONKEYPATCH_LEGACY_NAMESPACE_PACKAGES, stacklevel=2\n                        )\n                        break\n\n            fixup_namespace_packages(str(path))\n\n        # A call to syspathinsert() usually means that the caller wants to\n        # import some dynamically created files, thus with python3 we\n        # invalidate its import caches.\n        # This is especially important when any namespace package is in use,\n        # since then the mtime based FileFinder cache (that gets created in\n        # this case already) gets not invalidated when writing the new files\n        # quickly afterwards.\n        from importlib import invalidate_caches\n\n        invalidate_caches()\n\n    def chdir(self, path: str | os.PathLike[str]) -> None:\n        \"\"\"Change the current working directory to the specified path.\n\n        :param path:\n            The path to change into.\n        \"\"\"\n        if self._cwd is None:\n            self._cwd = os.getcwd()\n        os.chdir(path)\n\n    def undo(self) -> None:\n        \"\"\"Undo previous changes.\n\n        This call consumes the undo stack. Calling it a second time has no\n        effect unless you do more monkeypatching after the undo call.\n\n        There is generally no need to call `undo()`, since it is\n        called automatically during tear-down.\n\n        .. note::\n            The same `monkeypatch` fixture is used across a\n            single test function invocation. If `monkeypatch` is used both by\n            the test function itself and one of the test fixtures,\n            calling `undo()` will undo all of the changes made in\n            both functions.\n\n            Prefer to use :meth:`context() <pytest.MonkeyPatch.context>` instead.\n        \"\"\"\n        for obj, name, value in reversed(self._setattr):\n            if value is not NOTSET:\n                setattr(obj, name, value)\n            else:\n                delattr(obj, name)\n        self._setattr[:] = []\n        for dictionary, key, value in reversed(self._setitem):\n            if value is NOTSET:\n                try:\n                    # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict\n                    del dictionary[key]  # type: ignore[attr-defined]\n                except KeyError:\n                    pass  # Was already deleted, so we have the desired state.\n            else:\n                # Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict\n                dictionary[key] = value  # type: ignore[index]\n        self._setitem[:] = []\n        if self._savesyspath is not None:\n            sys.path[:] = self._savesyspath\n            self._savesyspath = None\n\n        if self._cwd is not None:\n            os.chdir(self._cwd)\n            self._cwd = None\n"
  },
  {
    "path": "src/_pytest/nodes.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport abc\nfrom collections.abc import Callable\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nfrom collections.abc import MutableMapping\nfrom functools import cached_property\nfrom functools import lru_cache\nimport os\nimport pathlib\nfrom pathlib import Path\nfrom typing import Any\nfrom typing import cast\nfrom typing import NoReturn\nfrom typing import overload\nfrom typing import TYPE_CHECKING\nfrom typing import TypeVar\nimport warnings\n\nimport pluggy\n\nimport _pytest._code\nfrom _pytest._code import getfslineno\nfrom _pytest._code.code import ExceptionInfo\nfrom _pytest._code.code import TerminalRepr\nfrom _pytest._code.code import Traceback\nfrom _pytest._code.code import TracebackStyle\nfrom _pytest.compat import LEGACY_PATH\nfrom _pytest.compat import signature\nfrom _pytest.config import Config\nfrom _pytest.config import ConftestImportFailure\nfrom _pytest.mark.structures import Mark\nfrom _pytest.mark.structures import MarkDecorator\nfrom _pytest.mark.structures import NodeKeywords\nfrom _pytest.outcomes import fail\nfrom _pytest.pathlib import absolutepath\nfrom _pytest.stash import Stash\nfrom _pytest.warning_types import PytestWarning\n\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\n    # Imported here due to circular import.\n    from _pytest.main import Session\n\n\nSEP = \"/\"\n\n\ndef norm_sep(path: str | os.PathLike[str]) -> str:\n    \"\"\"Normalize path separators to forward slashes for nodeid compatibility.\n\n    Replaces backslashes with forward slashes. This handles both Windows native\n    paths and cross-platform data (e.g., Windows paths in serialized test reports\n    when running on Linux).\n\n    :param path: A path string or PathLike object.\n    :returns: String with all backslashes replaced by forward slashes.\n    \"\"\"\n    return os.fspath(path).replace(\"\\\\\", SEP)\n\n\ntracebackcutdir = Path(_pytest.__file__).parent\n\n\n_T = TypeVar(\"_T\")\n\n\n_NodeType = TypeVar(\"_NodeType\", bound=\"Node\")\n\n\nclass NodeMeta(abc.ABCMeta):\n    \"\"\"Metaclass used by :class:`Node` to enforce that direct construction raises\n    :class:`Failed`.\n\n    This behaviour supports the indirection introduced with :meth:`Node.from_parent`,\n    the named constructor to be used instead of direct construction. The design\n    decision to enforce indirection with :class:`NodeMeta` was made as a\n    temporary aid for refactoring the collection tree, which was diagnosed to\n    have :class:`Node` objects whose creational patterns were overly entangled.\n    Once the refactoring is complete, this metaclass can be removed.\n\n    See https://github.com/pytest-dev/pytest/projects/3 for an overview of the\n    progress on detangling the :class:`Node` classes.\n    \"\"\"\n\n    def __call__(cls, *k, **kw) -> NoReturn:\n        msg = (\n            \"Direct construction of {name} has been deprecated, please use {name}.from_parent.\\n\"\n            \"See \"\n            \"https://docs.pytest.org/en/stable/deprecations.html#node-construction-changed-to-node-from-parent\"\n            \" for more details.\"\n        ).format(name=f\"{cls.__module__}.{cls.__name__}\")\n        fail(msg, pytrace=False)\n\n    def _create(cls: type[_T], *k, **kw) -> _T:\n        try:\n            return super().__call__(*k, **kw)  # type: ignore[no-any-return,misc]\n        except TypeError:\n            sig = signature(getattr(cls, \"__init__\"))\n            known_kw = {k: v for k, v in kw.items() if k in sig.parameters}\n            from .warning_types import PytestDeprecationWarning\n\n            warnings.warn(\n                PytestDeprecationWarning(\n                    f\"{cls} is not using a cooperative constructor and only takes {set(known_kw)}.\\n\"\n                    \"See https://docs.pytest.org/en/stable/deprecations.html\"\n                    \"#constructors-of-custom-pytest-node-subclasses-should-take-kwargs \"\n                    \"for more details.\"\n                )\n            )\n\n            return super().__call__(*k, **known_kw)  # type: ignore[no-any-return,misc]\n\n\nclass Node(abc.ABC, metaclass=NodeMeta):\n    r\"\"\"Base class of :class:`Collector` and :class:`Item`, the components of\n    the test collection tree.\n\n    ``Collector``\\'s are the internal nodes of the tree, and ``Item``\\'s are the\n    leaf nodes.\n    \"\"\"\n\n    # Implemented in the legacypath plugin.\n    #: A ``LEGACY_PATH`` copy of the :attr:`path` attribute. Intended for usage\n    #: for methods not migrated to ``pathlib.Path`` yet, such as\n    #: :meth:`Item.reportinfo <pytest.Item.reportinfo>`. Will be deprecated in\n    #: a future release, prefer using :attr:`path` instead.\n    fspath: LEGACY_PATH\n\n    # Use __slots__ to make attribute access faster.\n    # Note that __dict__ is still available.\n    __slots__ = (\n        \"__dict__\",\n        \"_nodeid\",\n        \"_store\",\n        \"config\",\n        \"name\",\n        \"parent\",\n        \"path\",\n        \"session\",\n    )\n\n    def __init__(\n        self,\n        name: str,\n        parent: Node | None = None,\n        config: Config | None = None,\n        session: Session | None = None,\n        fspath: None = None,\n        path: Path | None = None,\n        nodeid: str | None = None,\n    ) -> None:\n        #: A unique name within the scope of the parent node.\n        self.name: str = name\n\n        #: The parent collector node.\n        self.parent = parent\n\n        if config:\n            #: The pytest config object.\n            self.config: Config = config\n        else:\n            if not parent:\n                raise TypeError(\"config or parent must be provided\")\n            self.config = parent.config\n\n        if session:\n            #: The pytest session this node is part of.\n            self.session: Session = session\n        else:\n            if not parent:\n                raise TypeError(\"session or parent must be provided\")\n            self.session = parent.session\n\n        if path is None:\n            assert parent is not None\n            path = parent.path\n        #: Filesystem path where this node was collected from.\n        self.path: pathlib.Path = path\n\n        # The explicit annotation is to avoid publicly exposing NodeKeywords.\n        #: Keywords/markers collected from all scopes.\n        self.keywords: MutableMapping[str, Any] = NodeKeywords(self)\n\n        #: The marker objects belonging to this node.\n        self.own_markers: list[Mark] = []\n\n        #: Allow adding of extra keywords to use for matching.\n        self.extra_keyword_matches: set[str] = set()\n\n        if nodeid is not None:\n            assert \"::()\" not in nodeid\n            self._nodeid = nodeid\n        else:\n            if not self.parent:\n                raise TypeError(\"nodeid or parent must be provided\")\n            self._nodeid = self.parent.nodeid + \"::\" + self.name\n\n        #: A place where plugins can store information on the node for their\n        #: own use.\n        self.stash: Stash = Stash()\n        # Deprecated alias. Was never public. Can be removed in a few releases.\n        self._store = self.stash\n\n    @classmethod\n    def from_parent(cls, parent: Node, **kw) -> Self:\n        \"\"\"Public constructor for Nodes.\n\n        This indirection got introduced in order to enable removing\n        the fragile logic from the node constructors.\n\n        Subclasses can use ``super().from_parent(...)`` when overriding the\n        construction.\n\n        :param parent: The parent node of this Node.\n        \"\"\"\n        if \"config\" in kw:\n            raise TypeError(\"config is not a valid argument for from_parent\")\n        if \"session\" in kw:\n            raise TypeError(\"session is not a valid argument for from_parent\")\n        return cls._create(parent=parent, **kw)\n\n    @property\n    def ihook(self) -> pluggy.HookRelay:\n        \"\"\"Path-sensitive hook proxy used to call pytest hooks.\"\"\"\n        return self.session.gethookproxy(self.path)\n\n    def __repr__(self) -> str:\n        return \"<{} {}>\".format(self.__class__.__name__, getattr(self, \"name\", None))\n\n    def warn(self, warning: Warning) -> None:\n        \"\"\"Issue a warning for this Node.\n\n        Warnings will be displayed after the test session, unless explicitly suppressed.\n\n        :param Warning warning:\n            The warning instance to issue.\n\n        :raises ValueError: If ``warning`` instance is not a subclass of Warning.\n\n        Example usage:\n\n        .. code-block:: python\n\n            node.warn(PytestWarning(\"some message\"))\n            node.warn(UserWarning(\"some message\"))\n\n        .. versionchanged:: 6.2\n            Any subclass of :class:`Warning` is now accepted, rather than only\n            :class:`PytestWarning <pytest.PytestWarning>` subclasses.\n        \"\"\"\n        # enforce type checks here to avoid getting a generic type error later otherwise.\n        if not isinstance(warning, Warning):\n            raise ValueError(\n                f\"warning must be an instance of Warning or subclass, got {warning!r}\"\n            )\n        path, lineno = get_fslocation_from_item(self)\n        assert lineno is not None\n        warnings.warn_explicit(\n            warning,\n            category=None,\n            filename=str(path),\n            lineno=lineno + 1,\n        )\n\n    # Methods for ordering nodes.\n\n    @property\n    def nodeid(self) -> str:\n        \"\"\"A ::-separated string denoting its collection tree address.\"\"\"\n        return self._nodeid\n\n    def __hash__(self) -> int:\n        return hash(self._nodeid)\n\n    def setup(self) -> None:\n        pass\n\n    def teardown(self) -> None:\n        pass\n\n    def iter_parents(self) -> Iterator[Node]:\n        \"\"\"Iterate over all parent collectors starting from and including self\n        up to the root of the collection tree.\n\n        .. versionadded:: 8.1\n        \"\"\"\n        parent: Node | None = self\n        while parent is not None:\n            yield parent\n            parent = parent.parent\n\n    def listchain(self) -> list[Node]:\n        \"\"\"Return a list of all parent collectors starting from the root of the\n        collection tree down to and including self.\"\"\"\n        chain = []\n        item: Node | None = self\n        while item is not None:\n            chain.append(item)\n            item = item.parent\n        chain.reverse()\n        return chain\n\n    def add_marker(self, marker: str | MarkDecorator, append: bool = True) -> None:\n        \"\"\"Dynamically add a marker object to the node.\n\n        :param marker:\n            The marker.\n        :param append:\n            Whether to append the marker, or prepend it.\n        \"\"\"\n        from _pytest.mark import MARK_GEN\n\n        if isinstance(marker, MarkDecorator):\n            marker_ = marker\n        elif isinstance(marker, str):\n            marker_ = getattr(MARK_GEN, marker)\n        else:\n            raise ValueError(\"is not a string or pytest.mark.* Marker\")\n        self.keywords[marker_.name] = marker_\n        if append:\n            self.own_markers.append(marker_.mark)\n        else:\n            self.own_markers.insert(0, marker_.mark)\n\n    def iter_markers(self, name: str | None = None) -> Iterator[Mark]:\n        \"\"\"Iterate over all markers of the node.\n\n        :param name: If given, filter the results by the name attribute.\n        :returns: An iterator of the markers of the node.\n        \"\"\"\n        return (x[1] for x in self.iter_markers_with_node(name=name))\n\n    def iter_markers_with_node(\n        self, name: str | None = None\n    ) -> Iterator[tuple[Node, Mark]]:\n        \"\"\"Iterate over all markers of the node.\n\n        :param name: If given, filter the results by the name attribute.\n        :returns: An iterator of (node, mark) tuples.\n        \"\"\"\n        for node in self.iter_parents():\n            for mark in node.own_markers:\n                if name is None or getattr(mark, \"name\", None) == name:\n                    yield node, mark\n\n    @overload\n    def get_closest_marker(self, name: str) -> Mark | None: ...\n\n    @overload\n    def get_closest_marker(self, name: str, default: Mark) -> Mark: ...\n\n    def get_closest_marker(self, name: str, default: Mark | None = None) -> Mark | None:\n        \"\"\"Return the first marker matching the name, from closest (for\n        example function) to farther level (for example module level).\n\n        :param default: Fallback return value if no marker was found.\n        :param name: Name to filter by.\n        \"\"\"\n        return next(self.iter_markers(name=name), default)\n\n    def listextrakeywords(self) -> set[str]:\n        \"\"\"Return a set of all extra keywords in self and any parents.\"\"\"\n        extra_keywords: set[str] = set()\n        for item in self.listchain():\n            extra_keywords.update(item.extra_keyword_matches)\n        return extra_keywords\n\n    def listnames(self) -> list[str]:\n        return [x.name for x in self.listchain()]\n\n    def addfinalizer(self, fin: Callable[[], object]) -> None:\n        \"\"\"Register a function to be called without arguments when this node is\n        finalized.\n\n        This method can only be called when this node is active\n        in a setup chain, for example during self.setup().\n        \"\"\"\n        self.session._setupstate.addfinalizer(fin, self)\n\n    def getparent(self, cls: type[_NodeType]) -> _NodeType | None:\n        \"\"\"Get the closest parent node (including self) which is an instance of\n        the given class.\n\n        :param cls: The node class to search for.\n        :returns: The node, if found.\n        \"\"\"\n        for node in self.iter_parents():\n            if isinstance(node, cls):\n                return node\n        return None\n\n    def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:\n        return excinfo.traceback\n\n    def _repr_failure_py(\n        self,\n        excinfo: ExceptionInfo[BaseException],\n        style: TracebackStyle | None = None,\n    ) -> TerminalRepr:\n        from _pytest.fixtures import FixtureLookupError\n\n        if isinstance(excinfo.value, ConftestImportFailure):\n            excinfo = ExceptionInfo.from_exception(excinfo.value.cause)\n        if isinstance(excinfo.value, fail.Exception):\n            if not excinfo.value.pytrace:\n                style = \"value\"\n        if isinstance(excinfo.value, FixtureLookupError):\n            return excinfo.value.formatrepr()\n\n        tbfilter: bool | Callable[[ExceptionInfo[BaseException]], Traceback]\n        if self.config.getoption(\"fulltrace\", False):\n            style = \"long\"\n            tbfilter = False\n        else:\n            tbfilter = self._traceback_filter\n            if style == \"auto\":\n                style = \"long\"\n        # XXX should excinfo.getrepr record all data and toterminal() process it?\n        if style is None:\n            if self.config.getoption(\"tbstyle\", \"auto\") == \"short\":\n                style = \"short\"\n            else:\n                style = \"long\"\n\n        if self.config.get_verbosity() > 1:\n            truncate_locals = False\n        else:\n            truncate_locals = True\n\n        truncate_args = False if self.config.get_verbosity() > 2 else True\n\n        # excinfo.getrepr() formats paths relative to the CWD if `abspath` is False.\n        # It is possible for a fixture/test to change the CWD while this code runs, which\n        # would then result in the user seeing confusing paths in the failure message.\n        # To fix this, if the CWD changed, always display the full absolute path.\n        # It will be better to just always display paths relative to invocation_dir, but\n        # this requires a lot of plumbing (#6428).\n        try:\n            abspath = Path(os.getcwd()) != self.config.invocation_params.dir\n        except OSError:\n            abspath = True\n\n        return excinfo.getrepr(\n            funcargs=True,\n            abspath=abspath,\n            showlocals=self.config.getoption(\"showlocals\", False),\n            style=style,\n            tbfilter=tbfilter,\n            truncate_locals=truncate_locals,\n            truncate_args=truncate_args,\n        )\n\n    def repr_failure(\n        self,\n        excinfo: ExceptionInfo[BaseException],\n        style: TracebackStyle | None = None,\n    ) -> str | TerminalRepr:\n        \"\"\"Return a representation of a collection or test failure.\n\n        .. seealso:: :ref:`non-python tests`\n\n        :param excinfo: Exception information for the failure.\n        \"\"\"\n        return self._repr_failure_py(excinfo, style)\n\n\ndef get_fslocation_from_item(node: Node) -> tuple[str | Path, int | None]:\n    \"\"\"Try to extract the actual location from a node, depending on available attributes:\n\n    * \"location\": a pair (path, lineno)\n    * \"obj\": a Python object that the node wraps.\n    * \"path\": just a path\n\n    :rtype: A tuple of (str|Path, int) with filename and 0-based line number.\n    \"\"\"\n    # See Item.location.\n    location: tuple[str, int | None, str] | None = getattr(node, \"location\", None)\n    if location is not None:\n        return location[:2]\n    obj = getattr(node, \"obj\", None)\n    if obj is not None:\n        return getfslineno(obj)\n    return getattr(node, \"path\", \"unknown location\"), -1\n\n\nclass Collector(Node, abc.ABC):\n    \"\"\"Base class of all collectors.\n\n    Collector create children through `collect()` and thus iteratively build\n    the collection tree.\n    \"\"\"\n\n    class CollectError(Exception):\n        \"\"\"An error during collection, contains a custom message.\"\"\"\n\n    @abc.abstractmethod\n    def collect(self) -> Iterable[Item | Collector]:\n        \"\"\"Collect children (items and collectors) for this collector.\"\"\"\n        raise NotImplementedError(\"abstract\")\n\n    # TODO: This omits the style= parameter which breaks Liskov Substitution.\n    def repr_failure(  # type: ignore[override]\n        self, excinfo: ExceptionInfo[BaseException]\n    ) -> str | TerminalRepr:\n        \"\"\"Return a representation of a collection failure.\n\n        :param excinfo: Exception information for the failure.\n        \"\"\"\n        if isinstance(excinfo.value, self.CollectError) and not self.config.getoption(\n            \"fulltrace\", False\n        ):\n            exc = excinfo.value\n            return str(exc.args[0])\n\n        # Respect explicit tbstyle option, but default to \"short\"\n        # (_repr_failure_py uses \"long\" with \"fulltrace\" option always).\n        tbstyle = self.config.getoption(\"tbstyle\", \"auto\")\n        if tbstyle == \"auto\":\n            tbstyle = \"short\"\n\n        return self._repr_failure_py(excinfo, style=tbstyle)\n\n    def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:\n        if hasattr(self, \"path\"):\n            traceback = excinfo.traceback\n            ntraceback = traceback.cut(path=self.path)\n            if ntraceback == traceback:\n                ntraceback = ntraceback.cut(excludepath=tracebackcutdir)\n            return ntraceback.filter(excinfo)\n        return excinfo.traceback\n\n\n@lru_cache(maxsize=1000)\ndef _check_initialpaths_for_relpath(\n    initial_paths: frozenset[Path], path: Path\n) -> str | None:\n    if path in initial_paths:\n        return \"\"\n\n    for parent in path.parents:\n        if parent in initial_paths:\n            return str(path.relative_to(parent))\n\n    return None\n\n\nclass FSCollector(Collector, abc.ABC):\n    \"\"\"Base class for filesystem collectors.\"\"\"\n\n    def __init__(\n        self,\n        fspath: None = None,\n        path_or_parent: Path | Node | None = None,\n        path: Path | None = None,\n        name: str | None = None,\n        parent: Node | None = None,\n        config: Config | None = None,\n        session: Session | None = None,\n        nodeid: str | None = None,\n    ) -> None:\n        if path_or_parent:\n            if isinstance(path_or_parent, Node):\n                assert parent is None\n                parent = cast(FSCollector, path_or_parent)\n            elif isinstance(path_or_parent, Path):\n                assert path is None\n                path = path_or_parent\n        assert path is not None\n\n        if name is None:\n            name = path.name\n            if parent is not None and parent.path != path:\n                try:\n                    rel = path.relative_to(parent.path)\n                except ValueError:\n                    pass\n                else:\n                    name = str(rel)\n                name = norm_sep(name)\n        self.path = path\n\n        if session is None:\n            assert parent is not None\n            session = parent.session\n\n        if nodeid is None:\n            try:\n                nodeid = str(self.path.relative_to(session.config.rootpath))\n            except ValueError:\n                nodeid = _check_initialpaths_for_relpath(session._initialpaths, path)\n\n            if nodeid:\n                nodeid = norm_sep(nodeid)\n\n        super().__init__(\n            name=name,\n            parent=parent,\n            config=config,\n            session=session,\n            nodeid=nodeid,\n            path=path,\n        )\n\n    @classmethod\n    def from_parent(\n        cls,\n        parent,\n        *,\n        fspath: None = None,\n        path: Path | None = None,\n        **kw,\n    ) -> Self:\n        \"\"\"The public constructor.\"\"\"\n        return super().from_parent(parent=parent, fspath=fspath, path=path, **kw)\n\n\nclass File(FSCollector, abc.ABC):\n    \"\"\"Base class for collecting tests from a file.\n\n    :ref:`non-python tests`.\n    \"\"\"\n\n\nclass Directory(FSCollector, abc.ABC):\n    \"\"\"Base class for collecting files from a directory.\n\n    A basic directory collector does the following: goes over the files and\n    sub-directories in the directory and creates collectors for them by calling\n    the hooks :hook:`pytest_collect_directory` and :hook:`pytest_collect_file`,\n    after checking that they are not ignored using\n    :hook:`pytest_ignore_collect`.\n\n    The default directory collectors are :class:`~pytest.Dir` and\n    :class:`~pytest.Package`.\n\n    .. versionadded:: 8.0\n\n    :ref:`custom directory collectors`.\n    \"\"\"\n\n\nclass Item(Node, abc.ABC):\n    \"\"\"Base class of all test invocation items.\n\n    Note that for a single function there might be multiple test invocation items.\n    \"\"\"\n\n    nextitem = None\n\n    def __init__(\n        self,\n        name,\n        parent=None,\n        config: Config | None = None,\n        session: Session | None = None,\n        nodeid: str | None = None,\n        **kw,\n    ) -> None:\n        # The first two arguments are intentionally passed positionally,\n        # to keep plugins who define a node type which inherits from\n        # (pytest.Item, pytest.File) working (see issue #8435).\n        # They can be made kwargs when the deprecation above is done.\n        super().__init__(\n            name,\n            parent,\n            config=config,\n            session=session,\n            nodeid=nodeid,\n            **kw,\n        )\n        self._report_sections: list[tuple[str, str, str]] = []\n\n        #: A list of tuples (name, value) that holds user defined properties\n        #: for this test.\n        self.user_properties: list[tuple[str, object]] = []\n\n        self._check_item_and_collector_diamond_inheritance()\n\n    def _check_item_and_collector_diamond_inheritance(self) -> None:\n        \"\"\"\n        Check if the current type inherits from both File and Collector\n        at the same time, emitting a warning accordingly (#8447).\n        \"\"\"\n        cls = type(self)\n\n        # We inject an attribute in the type to avoid issuing this warning\n        # for the same class more than once, which is not helpful.\n        # It is a hack, but was deemed acceptable in order to avoid\n        # flooding the user in the common case.\n        attr_name = \"_pytest_diamond_inheritance_warning_shown\"\n        if getattr(cls, attr_name, False):\n            return\n        setattr(cls, attr_name, True)\n\n        problems = \", \".join(\n            base.__name__ for base in cls.__bases__ if issubclass(base, Collector)\n        )\n        if problems:\n            warnings.warn(\n                f\"{cls.__name__} is an Item subclass and should not be a collector, \"\n                f\"however its bases {problems} are collectors.\\n\"\n                \"Please split the Collectors and the Item into separate node types.\\n\"\n                \"Pytest Doc example: https://docs.pytest.org/en/latest/example/nonpython.html\\n\"\n                \"example pull request on a plugin: https://github.com/asmeurer/pytest-flakes/pull/40/\",\n                PytestWarning,\n            )\n\n    @abc.abstractmethod\n    def runtest(self) -> None:\n        \"\"\"Run the test case for this item.\n\n        Must be implemented by subclasses.\n\n        .. seealso:: :ref:`non-python tests`\n        \"\"\"\n        raise NotImplementedError(\"runtest must be implemented by Item subclass\")\n\n    def add_report_section(self, when: str, key: str, content: str) -> None:\n        \"\"\"Add a new report section, similar to what's done internally to add\n        stdout and stderr captured output::\n\n            item.add_report_section(\"call\", \"stdout\", \"report section contents\")\n\n        :param str when:\n            One of the possible capture states, ``\"setup\"``, ``\"call\"``, ``\"teardown\"``.\n        :param str key:\n            Name of the section, can be customized at will. Pytest uses ``\"stdout\"`` and\n            ``\"stderr\"`` internally.\n        :param str content:\n            The full contents as a string.\n        \"\"\"\n        if content:\n            self._report_sections.append((when, key, content))\n\n    def reportinfo(self) -> tuple[os.PathLike[str] | str, int | None, str]:\n        \"\"\"Get location information for this item for test reports.\n\n        Returns a tuple with three elements:\n\n        - The path of the test (default ``self.path``)\n        - The 0-based line number of the test (default ``None``)\n        - A name of the test to be shown (default ``\"\"``)\n\n        .. seealso:: :ref:`non-python tests`\n        \"\"\"\n        return self.path, None, \"\"\n\n    @cached_property\n    def location(self) -> tuple[str, int | None, str]:\n        \"\"\"\n        Returns a tuple of ``(relfspath, lineno, testname)`` for this item\n        where ``relfspath`` is file path relative to ``config.rootpath``\n        and lineno is a 0-based line number.\n        \"\"\"\n        location = self.reportinfo()\n        path = absolutepath(location[0])\n        relfspath = self.session._node_location_to_relpath(path)\n        assert type(location[2]) is str\n        return (relfspath, location[1], location[2])\n"
  },
  {
    "path": "src/_pytest/outcomes.py",
    "content": "\"\"\"Exception classes and constants handling test outcomes as well as\nfunctions creating them.\"\"\"\n\nfrom __future__ import annotations\n\nimport importlib\nimport sys\nfrom typing import Any\nfrom typing import ClassVar\nfrom typing import NoReturn\n\n\nclass OutcomeException(BaseException):\n    \"\"\"OutcomeException and its subclass instances indicate and contain info\n    about test and collection outcomes.\"\"\"\n\n    def __init__(self, msg: str | None = None, pytrace: bool = True) -> None:\n        if msg is not None and not isinstance(msg, str):\n            error_msg = (  # type: ignore[unreachable]\n                \"{} expected string as 'msg' parameter, got '{}' instead.\\n\"\n                \"Perhaps you meant to use a mark?\"\n            )\n            raise TypeError(error_msg.format(type(self).__name__, type(msg).__name__))\n        super().__init__(msg)\n        self.msg = msg\n        self.pytrace = pytrace\n\n    def __repr__(self) -> str:\n        if self.msg is not None:\n            return self.msg\n        return f\"<{self.__class__.__name__} instance>\"\n\n    __str__ = __repr__\n\n\nTEST_OUTCOME = (OutcomeException, Exception)\n\n\nclass Skipped(OutcomeException):\n    # XXX hackish: on 3k we fake to live in the builtins\n    # in order to have Skipped exception printing shorter/nicer\n    __module__ = \"builtins\"\n\n    def __init__(\n        self,\n        msg: str | None = None,\n        pytrace: bool = True,\n        allow_module_level: bool = False,\n        *,\n        _use_item_location: bool = False,\n    ) -> None:\n        super().__init__(msg=msg, pytrace=pytrace)\n        self.allow_module_level = allow_module_level\n        # If true, the skip location is reported as the item's location,\n        # instead of the place that raises the exception/calls skip().\n        self._use_item_location = _use_item_location\n\n\nclass Failed(OutcomeException):\n    \"\"\"Raised from an explicit call to pytest.fail().\"\"\"\n\n    __module__ = \"builtins\"\n\n\nclass Exit(Exception):\n    \"\"\"Raised for immediate program exits (no tracebacks/summaries).\"\"\"\n\n    def __init__(\n        self, msg: str = \"unknown reason\", returncode: int | None = None\n    ) -> None:\n        self.msg = msg\n        self.returncode = returncode\n        super().__init__(msg)\n\n\nclass XFailed(Failed):\n    \"\"\"Raised from an explicit call to pytest.xfail().\"\"\"\n\n\nclass _Exit:\n    \"\"\"Exit testing process.\n\n    :param reason:\n        The message to show as the reason for exiting pytest.  reason has a default value\n        only because `msg` is deprecated.\n\n    :param returncode:\n        Return code to be used when exiting pytest. None means the same as ``0`` (no error),\n        same as :func:`sys.exit`.\n\n    :raises pytest.exit.Exception:\n        The exception that is raised.\n    \"\"\"\n\n    Exception: ClassVar[type[Exit]] = Exit\n\n    def __call__(self, reason: str = \"\", returncode: int | None = None) -> NoReturn:\n        __tracebackhide__ = True\n        raise Exit(msg=reason, returncode=returncode)\n\n\nexit: _Exit = _Exit()\n\n\nclass _Skip:\n    \"\"\"Skip an executing test with the given message.\n\n    This function should be called only during testing (setup, call or teardown) or\n    during collection by using the ``allow_module_level`` flag.  This function can\n    be called in doctests as well.\n\n    :param reason:\n        The message to show the user as reason for the skip.\n\n    :param allow_module_level:\n        Allows this function to be called at module level.\n        Raising the skip exception at module level will stop\n        the execution of the module and prevent the collection of all tests in the module,\n        even those defined before the `skip` call.\n\n        Defaults to False.\n\n    :raises pytest.skip.Exception:\n        The exception that is raised.\n\n    .. note::\n        It is better to use the :ref:`pytest.mark.skipif ref` marker when\n        possible to declare a test to be skipped under certain conditions\n        like mismatching platforms or dependencies.\n        Similarly, use the ``# doctest: +SKIP`` directive (see :py:data:`doctest.SKIP`)\n        to skip a doctest statically.\n    \"\"\"\n\n    Exception: ClassVar[type[Skipped]] = Skipped\n\n    def __call__(self, reason: str = \"\", allow_module_level: bool = False) -> NoReturn:\n        __tracebackhide__ = True\n        raise Skipped(msg=reason, allow_module_level=allow_module_level)\n\n\nskip: _Skip = _Skip()\n\n\nclass _Fail:\n    \"\"\"Explicitly fail an executing test with the given message.\n\n    :param reason:\n        The message to show the user as reason for the failure.\n\n    :param pytrace:\n        If False, msg represents the full failure information and no\n        python traceback will be reported.\n\n    :raises pytest.fail.Exception:\n        The exception that is raised.\n    \"\"\"\n\n    Exception: ClassVar[type[Failed]] = Failed\n\n    def __call__(self, reason: str = \"\", pytrace: bool = True) -> NoReturn:\n        __tracebackhide__ = True\n        raise Failed(msg=reason, pytrace=pytrace)\n\n\nfail: _Fail = _Fail()\n\n\nclass _XFail:\n    \"\"\"Imperatively xfail an executing test or setup function with the given reason.\n\n    This function should be called only during testing (setup, call or teardown).\n\n    No other code is executed after using ``xfail()`` (it is implemented\n    internally by raising an exception).\n\n    :param reason:\n        The message to show the user as reason for the xfail.\n\n    .. note::\n        It is better to use the :ref:`pytest.mark.xfail ref` marker when\n        possible to declare a test to be xfailed under certain conditions\n        like known bugs or missing features.\n\n    :raises pytest.xfail.Exception:\n        The exception that is raised.\n    \"\"\"\n\n    Exception: ClassVar[type[XFailed]] = XFailed\n\n    def __call__(self, reason: str = \"\") -> NoReturn:\n        __tracebackhide__ = True\n        raise XFailed(msg=reason)\n\n\nxfail: _XFail = _XFail()\n\n\ndef importorskip(\n    modname: str,\n    minversion: str | None = None,\n    reason: str | None = None,\n    *,\n    exc_type: type[ImportError] | None = None,\n) -> Any:\n    \"\"\"Import and return the requested module ``modname``, or skip the\n    current test if the module cannot be imported.\n\n    :param modname:\n        The name of the module to import.\n    :param minversion:\n        If given, the imported module's ``__version__`` attribute must be at\n        least this minimal version, otherwise the test is still skipped.\n    :param reason:\n        If given, this reason is shown as the message when the module cannot\n        be imported.\n    :param exc_type:\n        The exception that should be captured in order to skip modules.\n        Must be :py:class:`ImportError` or a subclass.\n\n        Defaults to :class:`ModuleNotFoundError` when not given, which means\n        the module must be missing for the test to be skipped.\n        Pass ``exc_type=ImportError`` to also skip modules that raise\n        :class:`ImportError` during import.\n\n        See :ref:`import-or-skip-import-error` for details.\n\n\n    :returns:\n        The imported module. This should be assigned to its canonical name.\n\n    :raises pytest.skip.Exception:\n        If the module cannot be imported.\n\n    Example::\n\n        docutils = pytest.importorskip(\"docutils\")\n\n    .. versionadded:: 8.2\n\n        The ``exc_type`` parameter.\n\n    .. versionchanged:: 9.1\n\n        The default for ``exc_type`` is now :class:`ModuleNotFoundError`.\n    \"\"\"\n    import warnings\n\n    __tracebackhide__ = True\n    compile(modname, \"\", \"eval\")  # to catch syntaxerrors\n\n    # Keep the public signature compatible while using the pytest 9.1 default behavior.\n    if exc_type is None:\n        exc_type = ModuleNotFoundError\n\n    skipped: Skipped | None = None\n\n    with warnings.catch_warnings():\n        # Make sure to ignore ImportWarnings that might happen because\n        # of existing directories with the same name we're trying to\n        # import but without a __init__.py file.\n        warnings.simplefilter(\"ignore\")\n\n        try:\n            importlib.import_module(modname)\n        except exc_type as exc:\n            # Do not raise or issue warnings inside the catch_warnings() block.\n            if reason is None:\n                reason = f\"could not import {modname!r}: {exc}\"\n            skipped = Skipped(reason, allow_module_level=True)\n    if skipped:\n        raise skipped\n\n    mod = sys.modules[modname]\n    if minversion is None:\n        return mod\n    verattr = getattr(mod, \"__version__\", None)\n    if minversion is not None:\n        # Imported lazily to improve start-up time.\n        from packaging.version import Version\n\n        if verattr is None or Version(verattr) < Version(minversion):\n            raise Skipped(\n                f\"module {modname!r} has __version__ {verattr!r}, required is: {minversion!r}\",\n                allow_module_level=True,\n            )\n    return mod\n"
  },
  {
    "path": "src/_pytest/pastebin.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Submit failure or test session information to a pastebin service.\"\"\"\n\nfrom __future__ import annotations\n\nfrom io import StringIO\nimport tempfile\nfrom typing import IO\n\nfrom _pytest.config import Config\nfrom _pytest.config import create_terminal_writer\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.stash import StashKey\nfrom _pytest.terminal import TerminalReporter\nimport pytest\n\n\npastebinfile_key = StashKey[IO[bytes]]()\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"terminal reporting\")\n    group.addoption(\n        \"--pastebin\",\n        metavar=\"mode\",\n        action=\"store\",\n        dest=\"pastebin\",\n        default=None,\n        choices=[\"failed\", \"all\"],\n        help=\"Send failed|all info to bpaste.net pastebin service\",\n    )\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_configure(config: Config) -> None:\n    if config.option.pastebin == \"all\":\n        tr = config.pluginmanager.getplugin(\"terminalreporter\")\n        # If no terminal reporter plugin is present, nothing we can do here;\n        # this can happen when this function executes in a worker node\n        # when using pytest-xdist, for example.\n        if tr is not None:\n            # pastebin file will be UTF-8 encoded binary file.\n            config.stash[pastebinfile_key] = tempfile.TemporaryFile(\"w+b\")\n            oldwrite = tr._tw.write\n\n            def tee_write(s, **kwargs):\n                oldwrite(s, **kwargs)\n                if isinstance(s, str):\n                    s = s.encode(\"utf-8\")\n                config.stash[pastebinfile_key].write(s)\n\n            tr._tw.write = tee_write\n\n\ndef pytest_unconfigure(config: Config) -> None:\n    if pastebinfile_key in config.stash:\n        pastebinfile = config.stash[pastebinfile_key]\n        # Get terminal contents and delete file.\n        pastebinfile.seek(0)\n        sessionlog = pastebinfile.read()\n        pastebinfile.close()\n        del config.stash[pastebinfile_key]\n        # Undo our patching in the terminal reporter.\n        tr = config.pluginmanager.getplugin(\"terminalreporter\")\n        del tr._tw.__dict__[\"write\"]\n        # Write summary.\n        tr.write_sep(\"=\", \"Sending information to Paste Service\")\n        pastebinurl = create_new_paste(sessionlog)\n        tr.write_line(f\"pastebin session-log: {pastebinurl}\\n\")\n\n\ndef create_new_paste(contents: str | bytes) -> str:\n    \"\"\"Create a new paste using the bpaste.net service.\n\n    :contents: Paste contents string.\n    :returns: URL to the pasted contents, or an error message.\n    \"\"\"\n    import re\n    from urllib.error import HTTPError\n    from urllib.parse import urlencode\n    from urllib.request import urlopen\n\n    params = {\"code\": contents, \"lexer\": \"text\", \"expiry\": \"1week\"}\n    url = \"https://bpa.st\"\n    try:\n        response: str = (\n            urlopen(url, data=urlencode(params).encode(\"ascii\")).read().decode(\"utf-8\")\n        )\n    except HTTPError as e:\n        with e:  # HTTPErrors are also http responses that must be closed!\n            return f\"bad response: {e}\"\n    except OSError as e:  # eg urllib.error.URLError\n        return f\"bad response: {e}\"\n    m = re.search(r'href=\"/raw/(\\w+)\"', response)\n    if m:\n        return f\"{url}/show/{m.group(1)}\"\n    else:\n        return \"bad response: invalid format ('\" + response + \"')\"\n\n\ndef pytest_terminal_summary(terminalreporter: TerminalReporter) -> None:\n    if terminalreporter.config.option.pastebin != \"failed\":\n        return\n    if \"failed\" in terminalreporter.stats:\n        terminalreporter.write_sep(\"=\", \"Sending information to Paste Service\")\n        for rep in terminalreporter.stats[\"failed\"]:\n            try:\n                msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc\n            except AttributeError:\n                msg = terminalreporter._getfailureheadline(rep)\n            file = StringIO()\n            tw = create_terminal_writer(terminalreporter.config, file)\n            rep.toterminal(tw)\n            s = file.getvalue()\n            assert len(s)\n            pastebinurl = create_new_paste(s)\n            terminalreporter.write_line(f\"{msg} --> {pastebinurl}\")\n"
  },
  {
    "path": "src/_pytest/pathlib.py",
    "content": "from __future__ import annotations\n\nimport atexit\nfrom collections.abc import Callable\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nimport contextlib\nfrom enum import Enum\nfrom errno import EBADF\nfrom errno import ELOOP\nfrom errno import ENOENT\nfrom errno import ENOTDIR\nimport fnmatch\nfrom functools import partial\nfrom importlib.machinery import ModuleSpec\nfrom importlib.machinery import PathFinder\nimport importlib.util\nimport itertools\nimport os\nfrom os.path import expanduser\nfrom os.path import expandvars\nfrom os.path import isabs\nfrom os.path import sep\nfrom pathlib import Path\nfrom pathlib import PurePath\nfrom posixpath import sep as posix_sep\nimport shutil\nimport sys\nimport types\nfrom types import ModuleType\nfrom typing import Any\nfrom typing import TypeVar\nimport uuid\nimport warnings\n\nfrom _pytest.compat import assert_never\nfrom _pytest.outcomes import skip\nfrom _pytest.warning_types import PytestWarning\n\n\nif sys.version_info < (3, 11):\n    from importlib._bootstrap_external import _NamespaceLoader as NamespaceLoader\nelse:\n    from importlib.machinery import NamespaceLoader\n\nLOCK_TIMEOUT = 60 * 60 * 24 * 3\n\n_AnyPurePath = TypeVar(\"_AnyPurePath\", bound=PurePath)\n\n# The following function, variables and comments were\n# copied from cpython 3.9 Lib/pathlib.py file.\n\n# EBADF - guard against macOS `stat` throwing EBADF\n_IGNORED_ERRORS = (ENOENT, ENOTDIR, EBADF, ELOOP)\n\n_IGNORED_WINERRORS = (\n    21,  # ERROR_NOT_READY - drive exists but is not accessible\n    1921,  # ERROR_CANT_RESOLVE_FILENAME - fix for broken symlink pointing to itself\n)\n\n\ndef _ignore_error(exception: Exception) -> bool:\n    return (\n        getattr(exception, \"errno\", None) in _IGNORED_ERRORS\n        or getattr(exception, \"winerror\", None) in _IGNORED_WINERRORS\n    )\n\n\ndef get_lock_path(path: _AnyPurePath) -> _AnyPurePath:\n    return path.joinpath(\".lock\")\n\n\ndef on_rm_rf_error(\n    func: Callable[..., Any] | None,\n    path: str,\n    excinfo: BaseException\n    | tuple[type[BaseException], BaseException, types.TracebackType | None],\n    *,\n    start_path: Path,\n) -> bool:\n    \"\"\"Handle known read-only errors during rmtree.\n\n    The returned value is used only by our own tests.\n    \"\"\"\n    if isinstance(excinfo, BaseException):\n        exc = excinfo\n    else:\n        exc = excinfo[1]\n\n    # Another process removed the file in the middle of the \"rm_rf\" (xdist for example).\n    # More context: https://github.com/pytest-dev/pytest/issues/5974#issuecomment-543799018\n    if isinstance(exc, FileNotFoundError):\n        return False\n\n    if not isinstance(exc, PermissionError):\n        warnings.warn(\n            PytestWarning(f\"(rm_rf) error removing {path}\\n{type(exc)}: {exc}\")\n        )\n        return False\n\n    if func not in (os.rmdir, os.remove, os.unlink):\n        if func not in (os.open,):\n            warnings.warn(\n                PytestWarning(\n                    f\"(rm_rf) unknown function {func} when removing {path}:\\n{type(exc)}: {exc}\"\n                )\n            )\n        return False\n\n    # Chmod + retry.\n    import stat\n\n    def chmod_rw(p: str) -> None:\n        mode = os.stat(p).st_mode\n        os.chmod(p, mode | stat.S_IRUSR | stat.S_IWUSR)\n\n    # For files, we need to recursively go upwards in the directories to\n    # ensure they all are also writable.\n    p = Path(path)\n    if p.is_file():\n        for parent in p.parents:\n            chmod_rw(str(parent))\n            # Stop when we reach the original path passed to rm_rf.\n            if parent == start_path:\n                break\n    chmod_rw(str(path))\n\n    func(path)\n    return True\n\n\ndef ensure_extended_length_path(path: Path) -> Path:\n    \"\"\"Get the extended-length version of a path (Windows).\n\n    On Windows, by default, the maximum length of a path (MAX_PATH) is 260\n    characters, and operations on paths longer than that fail. But it is possible\n    to overcome this by converting the path to \"extended-length\" form before\n    performing the operation:\n    https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation\n\n    On Windows, this function returns the extended-length absolute version of path.\n    On other platforms it returns path unchanged.\n    \"\"\"\n    if sys.platform.startswith(\"win32\"):\n        path = path.resolve()\n        path = Path(get_extended_length_path_str(str(path)))\n    return path\n\n\ndef get_extended_length_path_str(path: str) -> str:\n    \"\"\"Convert a path to a Windows extended length path.\"\"\"\n    long_path_prefix = \"\\\\\\\\?\\\\\"\n    unc_long_path_prefix = \"\\\\\\\\?\\\\UNC\\\\\"\n    if path.startswith((long_path_prefix, unc_long_path_prefix)):\n        return path\n    # UNC\n    if path.startswith(\"\\\\\\\\\"):\n        return unc_long_path_prefix + path[2:]\n    return long_path_prefix + path\n\n\ndef rm_rf(path: Path) -> None:\n    \"\"\"Remove the path contents recursively, even if some elements\n    are read-only.\"\"\"\n    path = ensure_extended_length_path(path)\n    onerror = partial(on_rm_rf_error, start_path=path)\n    if sys.version_info >= (3, 12):\n        shutil.rmtree(str(path), onexc=onerror)\n    else:\n        shutil.rmtree(str(path), onerror=onerror)\n\n\ndef find_prefixed(root: Path, prefix: str) -> Iterator[os.DirEntry[str]]:\n    \"\"\"Find all elements in root that begin with the prefix, case-insensitive.\"\"\"\n    l_prefix = prefix.lower()\n    for x in os.scandir(root):\n        if x.name.lower().startswith(l_prefix):\n            yield x\n\n\ndef extract_suffixes(iter: Iterable[os.DirEntry[str]], prefix: str) -> Iterator[str]:\n    \"\"\"Return the parts of the paths following the prefix.\n\n    :param iter: Iterator over path names.\n    :param prefix: Expected prefix of the path names.\n    \"\"\"\n    p_len = len(prefix)\n    for entry in iter:\n        yield entry.name[p_len:]\n\n\ndef find_suffixes(root: Path, prefix: str) -> Iterator[str]:\n    \"\"\"Combine find_prefixes and extract_suffixes.\"\"\"\n    return extract_suffixes(find_prefixed(root, prefix), prefix)\n\n\ndef parse_num(maybe_num: str) -> int:\n    \"\"\"Parse number path suffixes, returns -1 on error.\"\"\"\n    try:\n        return int(maybe_num)\n    except ValueError:\n        return -1\n\n\ndef _force_symlink(root: Path, target: str | PurePath, link_to: str | Path) -> None:\n    \"\"\"Helper to create the current symlink.\n\n    It's full of race conditions that are reasonably OK to ignore\n    for the context of best effort linking to the latest test run.\n\n    The presumption being that in case of much parallelism\n    the inaccuracy is going to be acceptable.\n    \"\"\"\n    current_symlink = root.joinpath(target)\n    try:\n        current_symlink.unlink()\n    except OSError:\n        pass\n    try:\n        current_symlink.symlink_to(link_to)\n    except Exception:\n        pass\n\n\ndef make_numbered_dir(root: Path, prefix: str, mode: int = 0o700) -> Path:\n    \"\"\"Create a directory with an increased number as suffix for the given prefix.\"\"\"\n    for i in range(10):\n        # try up to 10 times to create the directory\n        max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)\n        new_number = max_existing + 1\n        new_path = root.joinpath(f\"{prefix}{new_number}\")\n        try:\n            new_path.mkdir(mode=mode)\n        except Exception:\n            pass\n        else:\n            _force_symlink(root, prefix + \"current\", new_path)\n            return new_path\n    else:\n        raise OSError(\n            \"could not create numbered dir with prefix \"\n            f\"{prefix} in {root} after 10 tries\"\n        )\n\n\ndef create_cleanup_lock(p: Path) -> Path:\n    \"\"\"Create a lock to prevent premature directory cleanup.\"\"\"\n    lock_path = get_lock_path(p)\n    try:\n        fd = os.open(str(lock_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)\n    except FileExistsError as e:\n        raise OSError(f\"cannot create lockfile in {p}\") from e\n    else:\n        pid = os.getpid()\n        spid = str(pid).encode()\n        os.write(fd, spid)\n        os.close(fd)\n        if not lock_path.is_file():\n            raise OSError(\"lock path got renamed after successful creation\")\n        return lock_path\n\n\ndef register_cleanup_lock_removal(\n    lock_path: Path, register: Any = atexit.register\n) -> Any:\n    \"\"\"Register a cleanup function for removing a lock, by default on atexit.\"\"\"\n    pid = os.getpid()\n\n    def cleanup_on_exit(lock_path: Path = lock_path, original_pid: int = pid) -> None:\n        current_pid = os.getpid()\n        if current_pid != original_pid:\n            # fork\n            return\n        try:\n            lock_path.unlink()\n        except OSError:\n            pass\n\n    return register(cleanup_on_exit)\n\n\ndef maybe_delete_a_numbered_dir(path: Path) -> None:\n    \"\"\"Remove a numbered directory if its lock can be obtained and it does\n    not seem to be in use.\"\"\"\n    path = ensure_extended_length_path(path)\n    lock_path = None\n    try:\n        lock_path = create_cleanup_lock(path)\n        parent = path.parent\n\n        garbage = parent.joinpath(f\"garbage-{uuid.uuid4()}\")\n        path.rename(garbage)\n        rm_rf(garbage)\n    except OSError:\n        #  known races:\n        #  * other process did a cleanup at the same time\n        #  * deletable directory was found\n        #  * process cwd (Windows)\n        return\n    finally:\n        # If we created the lock, ensure we remove it even if we failed\n        # to properly remove the numbered dir.\n        if lock_path is not None:\n            try:\n                lock_path.unlink()\n            except OSError:\n                pass\n\n\ndef ensure_deletable(path: Path, consider_lock_dead_if_created_before: float) -> bool:\n    \"\"\"Check if `path` is deletable based on whether the lock file is expired.\"\"\"\n    if path.is_symlink():\n        return False\n    lock = get_lock_path(path)\n    try:\n        if not lock.is_file():\n            return True\n    except OSError:\n        # we might not have access to the lock file at all, in this case assume\n        # we don't have access to the entire directory (#7491).\n        return False\n    try:\n        lock_time = lock.stat().st_mtime\n    except Exception:\n        return False\n    else:\n        if lock_time < consider_lock_dead_if_created_before:\n            # We want to ignore any errors while trying to remove the lock such as:\n            # - PermissionDenied, like the file permissions have changed since the lock creation;\n            # - FileNotFoundError, in case another pytest process got here first;\n            # and any other cause of failure.\n            with contextlib.suppress(OSError):\n                lock.unlink()\n                return True\n        return False\n\n\ndef try_cleanup(path: Path, consider_lock_dead_if_created_before: float) -> None:\n    \"\"\"Try to cleanup a directory if we can ensure it's deletable.\"\"\"\n    if ensure_deletable(path, consider_lock_dead_if_created_before):\n        maybe_delete_a_numbered_dir(path)\n\n\ndef cleanup_candidates(root: Path, prefix: str, keep: int) -> Iterator[Path]:\n    \"\"\"List candidates for numbered directories to be removed - follows py.path.\"\"\"\n    max_existing = max(map(parse_num, find_suffixes(root, prefix)), default=-1)\n    max_delete = max_existing - keep\n    entries = find_prefixed(root, prefix)\n    entries, entries2 = itertools.tee(entries)\n    numbers = map(parse_num, extract_suffixes(entries2, prefix))\n    for entry, number in zip(entries, numbers, strict=True):\n        if number <= max_delete:\n            yield Path(entry)\n\n\ndef cleanup_dead_symlinks(root: Path) -> None:\n    for left_dir in root.iterdir():\n        if left_dir.is_symlink():\n            if not left_dir.resolve().exists():\n                left_dir.unlink()\n\n\ndef cleanup_numbered_dir(\n    root: Path, prefix: str, keep: int, consider_lock_dead_if_created_before: float\n) -> None:\n    \"\"\"Cleanup for lock driven numbered directories.\"\"\"\n    if not root.exists():\n        return\n    for path in cleanup_candidates(root, prefix, keep):\n        try_cleanup(path, consider_lock_dead_if_created_before)\n    for path in root.glob(\"garbage-*\"):\n        try_cleanup(path, consider_lock_dead_if_created_before)\n\n    cleanup_dead_symlinks(root)\n\n\ndef make_numbered_dir_with_cleanup(\n    root: Path,\n    prefix: str,\n    keep: int,\n    lock_timeout: float,\n    mode: int,\n) -> Path:\n    \"\"\"Create a numbered dir with a cleanup lock and remove old ones.\"\"\"\n    e = None\n    for i in range(10):\n        try:\n            p = make_numbered_dir(root, prefix, mode)\n            # Only lock the current dir when keep is not 0\n            if keep != 0:\n                lock_path = create_cleanup_lock(p)\n                register_cleanup_lock_removal(lock_path)\n        except Exception as exc:\n            e = exc\n        else:\n            consider_lock_dead_if_created_before = p.stat().st_mtime - lock_timeout\n            # Register a cleanup for program exit\n            atexit.register(\n                cleanup_numbered_dir,\n                root,\n                prefix,\n                keep,\n                consider_lock_dead_if_created_before,\n            )\n            return p\n    assert e is not None\n    raise e\n\n\ndef resolve_from_str(input: str, rootpath: Path) -> Path:\n    input = expanduser(input)\n    input = expandvars(input)\n    if isabs(input):\n        return Path(input)\n    else:\n        return rootpath.joinpath(input)\n\n\ndef fnmatch_ex(pattern: str, path: str | os.PathLike[str]) -> bool:\n    \"\"\"A port of FNMatcher from py.path.common which works with PurePath() instances.\n\n    The difference between this algorithm and PurePath.match() is that the\n    latter matches \"**\" glob expressions for each part of the path, while\n    this algorithm uses the whole path instead.\n\n    For example:\n        \"tests/foo/bar/doc/test_foo.py\" matches pattern \"tests/**/doc/test*.py\"\n        with this algorithm, but not with PurePath.match().\n\n    This algorithm was ported to keep backward-compatibility with existing\n    settings which assume paths match according this logic.\n\n    References:\n    * https://bugs.python.org/issue29249\n    * https://bugs.python.org/issue34731\n    \"\"\"\n    path = PurePath(path)\n    iswin32 = sys.platform.startswith(\"win\")\n\n    if iswin32 and sep not in pattern and posix_sep in pattern:\n        # Running on Windows, the pattern has no Windows path separators,\n        # and the pattern has one or more Posix path separators. Replace\n        # the Posix path separators with the Windows path separator.\n        pattern = pattern.replace(posix_sep, sep)\n\n    if sep not in pattern:\n        name = path.name\n    else:\n        name = str(path)\n        if path.is_absolute() and not os.path.isabs(pattern):\n            pattern = f\"*{os.sep}{pattern}\"\n    return fnmatch.fnmatch(name, pattern)\n\n\ndef parts(s: str) -> set[str]:\n    parts = s.split(sep)\n    return {sep.join(parts[: i + 1]) or sep for i in range(len(parts))}\n\n\ndef symlink_or_skip(\n    src: os.PathLike[str] | str,\n    dst: os.PathLike[str] | str,\n    **kwargs: Any,\n) -> None:\n    \"\"\"Make a symlink, or skip the test in case symlinks are not supported.\"\"\"\n    try:\n        os.symlink(src, dst, **kwargs)\n    except OSError as e:\n        skip(f\"symlinks not supported: {e}\")\n\n\nclass ImportMode(Enum):\n    \"\"\"Possible values for `mode` parameter of `import_path`.\"\"\"\n\n    prepend = \"prepend\"\n    append = \"append\"\n    importlib = \"importlib\"\n\n\nclass ImportPathMismatchError(ImportError):\n    \"\"\"Raised on import_path() if there is a mismatch of __file__'s.\n\n    This can happen when `import_path` is called multiple times with different filenames that has\n    the same basename but reside in packages\n    (for example \"/tests1/test_foo.py\" and \"/tests2/test_foo.py\").\n    \"\"\"\n\n\ndef import_path(\n    path: str | os.PathLike[str],\n    *,\n    mode: str | ImportMode = ImportMode.prepend,\n    root: Path,\n    consider_namespace_packages: bool,\n) -> ModuleType:\n    \"\"\"\n    Import and return a module from the given path, which can be a file (a module) or\n    a directory (a package).\n\n    :param path:\n        Path to the file to import.\n\n    :param mode:\n        Controls the underlying import mechanism that will be used:\n\n        * ImportMode.prepend: the directory containing the module (or package, taking\n          `__init__.py` files into account) will be put at the *start* of `sys.path` before\n          being imported with `importlib.import_module`.\n\n        * ImportMode.append: same as `prepend`, but the directory will be appended\n          to the end of `sys.path`, if not already in `sys.path`.\n\n        * ImportMode.importlib: uses more fine control mechanisms provided by `importlib`\n          to import the module, which avoids having to muck with `sys.path` at all. It effectively\n          allows having same-named test modules in different places.\n\n    :param root:\n        Used as an anchor when mode == ImportMode.importlib to obtain\n        a unique name for the module being imported so it can safely be stored\n        into ``sys.modules``.\n\n    :param consider_namespace_packages:\n        If True, consider namespace packages when resolving module names.\n\n    :raises ImportPathMismatchError:\n        If after importing the given `path` and the module `__file__`\n        are different. Only raised in `prepend` and `append` modes.\n    \"\"\"\n    path = Path(path)\n    mode = ImportMode(mode)\n\n    if not path.exists():\n        raise ImportError(path)\n\n    if mode is ImportMode.importlib:\n        # Try to import this module using the standard import mechanisms, but\n        # without touching sys.path.\n        try:\n            pkg_root, module_name = resolve_pkg_root_and_module_name(\n                path, consider_namespace_packages=consider_namespace_packages\n            )\n        except CouldNotResolvePathError:\n            pass\n        else:\n            # If the given module name is already in sys.modules, do not import it again.\n            with contextlib.suppress(KeyError):\n                return sys.modules[module_name]\n\n            mod = _import_module_using_spec(\n                module_name, path, pkg_root, insert_modules=False\n            )\n            if mod is not None:\n                return mod\n\n        # Could not import the module with the current sys.path, so we fall back\n        # to importing the file as a single module, not being a part of a package.\n        module_name = module_name_from_path(path, root)\n        with contextlib.suppress(KeyError):\n            return sys.modules[module_name]\n\n        mod = _import_module_using_spec(\n            module_name, path, path.parent, insert_modules=True\n        )\n        if mod is None:\n            raise ImportError(f\"Can't find module {module_name} at location {path}\")\n        return mod\n\n    try:\n        pkg_root, module_name = resolve_pkg_root_and_module_name(\n            path, consider_namespace_packages=consider_namespace_packages\n        )\n    except CouldNotResolvePathError:\n        pkg_root, module_name = path.parent, path.stem\n\n    # Change sys.path permanently: restoring it at the end of this function would cause surprising\n    # problems because of delayed imports: for example, a conftest.py file imported by this function\n    # might have local imports, which would fail at runtime if we restored sys.path.\n    if mode is ImportMode.append:\n        if str(pkg_root) not in sys.path:\n            sys.path.append(str(pkg_root))\n    elif mode is ImportMode.prepend:\n        if str(pkg_root) != sys.path[0]:\n            sys.path.insert(0, str(pkg_root))\n    else:\n        assert_never(mode)\n\n    importlib.import_module(module_name)\n\n    mod = sys.modules[module_name]\n    if path.name == \"__init__.py\":\n        return mod\n\n    ignore = os.environ.get(\"PY_IGNORE_IMPORTMISMATCH\", \"\")\n    if ignore != \"1\":\n        module_file = mod.__file__\n        if module_file is None:\n            raise ImportPathMismatchError(module_name, module_file, path)\n\n        if module_file.endswith((\".pyc\", \".pyo\")):\n            module_file = module_file[:-1]\n        if module_file.endswith(os.sep + \"__init__.py\"):\n            module_file = module_file[: -(len(os.sep + \"__init__.py\"))]\n\n        try:\n            is_same = _is_same(str(path), module_file)\n        except FileNotFoundError:\n            is_same = False\n\n        if not is_same:\n            raise ImportPathMismatchError(module_name, module_file, path)\n\n    return mod\n\n\ndef _import_module_using_spec(\n    module_name: str, module_path: Path, module_location: Path, *, insert_modules: bool\n) -> ModuleType | None:\n    \"\"\"\n    Tries to import a module by its canonical name, path, and its parent location.\n\n    :param module_name:\n        The expected module name, will become the key of `sys.modules`.\n\n    :param module_path:\n        The file path of the module, for example `/foo/bar/test_demo.py`.\n        If module is a package, pass the path to the  `__init__.py` of the package.\n        If module is a namespace package, pass directory path.\n\n    :param module_location:\n        The parent location of the module.\n        If module is a package, pass the directory containing the `__init__.py` file.\n\n    :param insert_modules:\n        If True, will call `insert_missing_modules` to create empty intermediate modules\n        with made-up module names (when importing test files not reachable from `sys.path`).\n\n    Example 1 of parent_module_*:\n\n        module_name:        \"a.b.c.demo\"\n        module_path:        Path(\"a/b/c/demo.py\")\n        module_location:    Path(\"a/b/c/\")\n        if \"a.b.c\" is package (\"a/b/c/__init__.py\" exists), then\n            parent_module_name:         \"a.b.c\"\n            parent_module_path:         Path(\"a/b/c/__init__.py\")\n            parent_module_location:     Path(\"a/b/c/\")\n        else:\n            parent_module_name:         \"a.b.c\"\n            parent_module_path:         Path(\"a/b/c\")\n            parent_module_location:     Path(\"a/b/\")\n\n    Example 2 of parent_module_*:\n\n        module_name:        \"a.b.c\"\n        module_path:        Path(\"a/b/c/__init__.py\")\n        module_location:    Path(\"a/b/c/\")\n        if  \"a.b\" is package (\"a/b/__init__.py\" exists), then\n            parent_module_name:         \"a.b\"\n            parent_module_path:         Path(\"a/b/__init__.py\")\n            parent_module_location:     Path(\"a/b/\")\n        else:\n            parent_module_name:         \"a.b\"\n            parent_module_path:         Path(\"a/b/\")\n            parent_module_location:     Path(\"a/\")\n    \"\"\"\n    # Attempt to import the parent module, seems is our responsibility:\n    # https://github.com/python/cpython/blob/73906d5c908c1e0b73c5436faeff7d93698fc074/Lib/importlib/_bootstrap.py#L1308-L1311\n    parent_module_name, _, name = module_name.rpartition(\".\")\n    parent_module: ModuleType | None = None\n    if parent_module_name:\n        parent_module = sys.modules.get(parent_module_name)\n        # If the parent_module lacks the `__path__` attribute, AttributeError when finding a submodule's spec,\n        # requiring re-import according to the path.\n        need_reimport = not hasattr(parent_module, \"__path__\")\n        if parent_module is None or need_reimport:\n            # Get parent_location based on location, get parent_path based on path.\n            if module_path.name == \"__init__.py\":\n                # If the current module is in a package,\n                # need to leave the package first and then enter the parent module.\n                parent_module_path = module_path.parent.parent\n            else:\n                parent_module_path = module_path.parent\n\n            if (parent_module_path / \"__init__.py\").is_file():\n                # If the parent module is a package, loading by  __init__.py file.\n                parent_module_path = parent_module_path / \"__init__.py\"\n\n            parent_module = _import_module_using_spec(\n                parent_module_name,\n                parent_module_path,\n                parent_module_path.parent,\n                insert_modules=insert_modules,\n            )\n\n    # Checking with sys.meta_path first in case one of its hooks can import this module,\n    # such as our own assertion-rewrite hook.\n    for meta_importer in sys.meta_path:\n        module_name_of_meta = getattr(meta_importer.__class__, \"__module__\", \"\")\n        if module_name_of_meta == \"_pytest.assertion.rewrite\" and module_path.is_file():\n            # Import modules in subdirectories by module_path\n            # to ensure assertion rewrites are not missed (#12659).\n            find_spec_path = [str(module_location), str(module_path)]\n        else:\n            find_spec_path = [str(module_location)]\n\n        spec = meta_importer.find_spec(module_name, find_spec_path)\n\n        if spec_matches_module_path(spec, module_path):\n            break\n    else:\n        loader = None\n        if module_path.is_dir():\n            # The `spec_from_file_location` matches a loader based on the file extension by default.\n            # For a namespace package, need to manually specify a loader.\n            loader = NamespaceLoader(name, module_path, PathFinder())  # type: ignore[arg-type]\n\n        spec = importlib.util.spec_from_file_location(\n            module_name, str(module_path), loader=loader\n        )\n\n    if spec_matches_module_path(spec, module_path):\n        assert spec is not None\n        # Find spec and import this module.\n        mod = importlib.util.module_from_spec(spec)\n        sys.modules[module_name] = mod\n        spec.loader.exec_module(mod)  # type: ignore[union-attr]\n\n        # Set this module as an attribute of the parent module (#12194).\n        if parent_module is not None:\n            setattr(parent_module, name, mod)\n\n        if insert_modules:\n            insert_missing_modules(sys.modules, module_name)\n        return mod\n\n    return None\n\n\ndef spec_matches_module_path(module_spec: ModuleSpec | None, module_path: Path) -> bool:\n    \"\"\"Return true if the given ModuleSpec can be used to import the given module path.\"\"\"\n    if module_spec is None:\n        return False\n\n    if module_spec.origin:\n        return Path(module_spec.origin) == module_path\n\n    # Compare the path with the `module_spec.submodule_Search_Locations` in case\n    # the module is part of a namespace package.\n    # https://docs.python.org/3/library/importlib.html#importlib.machinery.ModuleSpec.submodule_search_locations\n    if module_spec.submodule_search_locations:  # can be None.\n        for path in module_spec.submodule_search_locations:\n            if Path(path) == module_path:\n                return True\n\n    return False\n\n\n# Implement a special _is_same function on Windows which returns True if the two filenames\n# compare equal, to circumvent os.path.samefile returning False for mounts in UNC (#7678).\nif sys.platform.startswith(\"win\"):\n\n    def _is_same(f1: str, f2: str) -> bool:\n        return Path(f1) == Path(f2) or os.path.samefile(f1, f2)\n\nelse:\n\n    def _is_same(f1: str, f2: str) -> bool:\n        return os.path.samefile(f1, f2)\n\n\ndef module_name_from_path(path: Path, root: Path) -> str:\n    \"\"\"\n    Return a dotted module name based on the given path, anchored on root.\n\n    For example: path=\"projects/src/tests/test_foo.py\" and root=\"/projects\", the\n    resulting module name will be \"src.tests.test_foo\".\n    \"\"\"\n    path = path.with_suffix(\"\")\n    try:\n        relative_path = path.relative_to(root)\n    except ValueError:\n        # If we can't get a relative path to root, use the full path, except\n        # for the first part (\"d:\\\\\" or \"/\" depending on the platform, for example).\n        path_parts = path.parts[1:]\n    else:\n        # Use the parts for the relative path to the root path.\n        path_parts = relative_path.parts\n\n    # Module name for packages do not contain the __init__ file, unless\n    # the `__init__.py` file is at the root.\n    if len(path_parts) >= 2 and path_parts[-1] == \"__init__\":\n        path_parts = path_parts[:-1]\n\n    # Module names cannot contain \".\", normalize them to \"_\". This prevents\n    # a directory having a \".\" in the name (\".env.310\" for example) causing extra intermediate modules.\n    # Also, important to replace \".\" at the start of paths, as those are considered relative imports.\n    path_parts = tuple(x.replace(\".\", \"_\") for x in path_parts)\n\n    return \".\".join(path_parts)\n\n\ndef insert_missing_modules(modules: dict[str, ModuleType], module_name: str) -> None:\n    \"\"\"\n    Used by ``import_path`` to create intermediate modules when using mode=importlib.\n\n    When we want to import a module as \"src.tests.test_foo\" for example, we need\n    to create empty modules \"src\" and \"src.tests\" after inserting \"src.tests.test_foo\",\n    otherwise \"src.tests.test_foo\" is not importable by ``__import__``.\n    \"\"\"\n    module_parts = module_name.split(\".\")\n    while module_name:\n        parent_module_name, _, child_name = module_name.rpartition(\".\")\n        if parent_module_name:\n            parent_module = modules.get(parent_module_name)\n            if parent_module is None:\n                try:\n                    # If sys.meta_path is empty, calling import_module will issue\n                    # a warning and raise ModuleNotFoundError. To avoid the\n                    # warning, we check sys.meta_path explicitly and raise the error\n                    # ourselves to fall back to creating a dummy module.\n                    if not sys.meta_path:\n                        raise ModuleNotFoundError\n                    parent_module = importlib.import_module(parent_module_name)\n                except ModuleNotFoundError:\n                    parent_module = ModuleType(\n                        module_name,\n                        doc=\"Empty module created by pytest's importmode=importlib.\",\n                    )\n                modules[parent_module_name] = parent_module\n\n            # Add child attribute to the parent that can reference the child\n            # modules.\n            if not hasattr(parent_module, child_name):\n                setattr(parent_module, child_name, modules[module_name])\n\n        module_parts.pop(-1)\n        module_name = \".\".join(module_parts)\n\n\ndef resolve_package_path(path: Path) -> Path | None:\n    \"\"\"Return the Python package path by looking for the last\n    directory upwards which still contains an __init__.py.\n\n    Returns None if it cannot be determined.\n    \"\"\"\n    result = None\n    for parent in itertools.chain((path,), path.parents):\n        if parent.is_dir():\n            if not (parent / \"__init__.py\").is_file():\n                break\n            if not parent.name.isidentifier():\n                break\n            result = parent\n    return result\n\n\ndef resolve_pkg_root_and_module_name(\n    path: Path, *, consider_namespace_packages: bool = False\n) -> tuple[Path, str]:\n    \"\"\"\n    Return the path to the directory of the root package that contains the\n    given Python file, and its module name:\n\n        src/\n            app/\n                __init__.py\n                core/\n                    __init__.py\n                    models.py\n\n    Passing the full path to `models.py` will yield Path(\"src\") and \"app.core.models\".\n\n    If consider_namespace_packages is True, then we additionally check upwards in the hierarchy\n    for namespace packages:\n\n    https://packaging.python.org/en/latest/guides/packaging-namespace-packages\n\n    Raises CouldNotResolvePathError if the given path does not belong to a package (missing any __init__.py files).\n    \"\"\"\n    pkg_root: Path | None = None\n    pkg_path = resolve_package_path(path)\n    if pkg_path is not None:\n        pkg_root = pkg_path.parent\n    if consider_namespace_packages:\n        start = pkg_root if pkg_root is not None else path.parent\n        for candidate in (start, *start.parents):\n            module_name = compute_module_name(candidate, path)\n            if module_name and is_importable(module_name, path):\n                # Point the pkg_root to the root of the namespace package.\n                pkg_root = candidate\n                break\n\n    if pkg_root is not None:\n        module_name = compute_module_name(pkg_root, path)\n        if module_name:\n            return pkg_root, module_name\n\n    raise CouldNotResolvePathError(f\"Could not resolve for {path}\")\n\n\ndef is_importable(module_name: str, module_path: Path) -> bool:\n    \"\"\"\n    Return if the given module path could be imported normally by Python, akin to the user\n    entering the REPL and importing the corresponding module name directly, and corresponds\n    to the module_path specified.\n\n    :param module_name:\n        Full module name that we want to check if is importable.\n        For example, \"app.models\".\n\n    :param module_path:\n        Full path to the python module/package we want to check if is importable.\n        For example, \"/projects/src/app/models.py\".\n    \"\"\"\n    try:\n        # Note this is different from what we do in ``_import_module_using_spec``, where we explicitly search through\n        # sys.meta_path to be able to pass the path of the module that we want to import (``meta_importer.find_spec``).\n        # Using importlib.util.find_spec() is different, it gives the same results as trying to import\n        # the module normally in the REPL.\n        spec = importlib.util.find_spec(module_name)\n    except (ImportError, ValueError, ImportWarning):\n        return False\n    else:\n        return spec_matches_module_path(spec, module_path)\n\n\ndef compute_module_name(root: Path, module_path: Path) -> str | None:\n    \"\"\"Compute a module name based on a path and a root anchor.\"\"\"\n    try:\n        path_without_suffix = module_path.with_suffix(\"\")\n    except ValueError:\n        # Empty paths (such as Path.cwd()) might break meta_path hooks (like our own assertion rewriter).\n        return None\n\n    try:\n        relative = path_without_suffix.relative_to(root)\n    except ValueError:  # pragma: no cover\n        return None\n    names = list(relative.parts)\n    if not names:\n        return None\n    if names[-1] == \"__init__\":\n        names.pop()\n    return \".\".join(names)\n\n\nclass CouldNotResolvePathError(Exception):\n    \"\"\"Custom exception raised by resolve_pkg_root_and_module_name.\"\"\"\n\n\ndef scandir(\n    path: str | os.PathLike[str],\n    sort_key: Callable[[os.DirEntry[str]], object] = lambda entry: entry.name,\n) -> list[os.DirEntry[str]]:\n    \"\"\"Scan a directory recursively, in breadth-first order.\n\n    The returned entries are sorted according to the given key.\n    The default is to sort by name.\n    If the directory does not exist, return an empty list.\n    \"\"\"\n    entries = []\n    # Attempt to create a scandir iterator for the given path.\n    try:\n        scandir_iter = os.scandir(path)\n    except FileNotFoundError:\n        # If the directory does not exist, return an empty list.\n        return []\n    # Use the scandir iterator in a context manager to ensure it is properly closed.\n    with scandir_iter as s:\n        for entry in s:\n            try:\n                entry.is_file()\n            except OSError as err:\n                if _ignore_error(err):\n                    continue\n                # Reraise non-ignorable errors to avoid hiding issues.\n                raise\n            entries.append(entry)\n    entries.sort(key=sort_key)  # type: ignore[arg-type]\n    return entries\n\n\ndef visit(\n    path: str | os.PathLike[str], recurse: Callable[[os.DirEntry[str]], bool]\n) -> Iterator[os.DirEntry[str]]:\n    \"\"\"Walk a directory recursively, in breadth-first order.\n\n    The `recurse` predicate determines whether a directory is recursed.\n\n    Entries at each directory level are sorted.\n    \"\"\"\n    entries = scandir(path)\n    yield from entries\n    for entry in entries:\n        if entry.is_dir() and recurse(entry):\n            yield from visit(entry.path, recurse)\n\n\ndef absolutepath(path: str | os.PathLike[str]) -> Path:\n    \"\"\"Convert a path to an absolute path using os.path.abspath.\n\n    Prefer this over Path.resolve() (see #6523).\n    Prefer this over Path.absolute() (not public, doesn't normalize).\n    \"\"\"\n    return Path(os.path.abspath(path))\n\n\ndef commonpath(path1: Path, path2: Path) -> Path | None:\n    \"\"\"Return the common part shared with the other path, or None if there is\n    no common part.\n\n    If one path is relative and one is absolute, returns None.\n    \"\"\"\n    try:\n        return Path(os.path.commonpath((str(path1), str(path2))))\n    except ValueError:\n        return None\n\n\ndef bestrelpath(directory: Path, dest: Path) -> str:\n    \"\"\"Return a string which is a relative path from directory to dest such\n    that directory/bestrelpath == dest.\n\n    The paths must be either both absolute or both relative.\n\n    If no such path can be determined, returns dest.\n    \"\"\"\n    assert isinstance(directory, Path)\n    assert isinstance(dest, Path)\n    if dest == directory:\n        return os.curdir\n    # Find the longest common directory.\n    base = commonpath(directory, dest)\n    # Can be the case on Windows for two absolute paths on different drives.\n    # Can be the case for two relative paths without common prefix.\n    # Can be the case for a relative path and an absolute path.\n    if not base:\n        return str(dest)\n    reldirectory = directory.relative_to(base)\n    reldest = dest.relative_to(base)\n    return os.path.join(\n        # Back from directory to base.\n        *([os.pardir] * len(reldirectory.parts)),\n        # Forward from base to dest.\n        *reldest.parts,\n    )\n\n\ndef safe_exists(p: Path) -> bool:\n    \"\"\"Like Path.exists(), but account for input arguments that might be too long (#11394).\"\"\"\n    try:\n        return p.exists()\n    except (ValueError, OSError):\n        # ValueError: stat: path too long for Windows\n        # OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect\n        return False\n\n\ndef samefile_nofollow(p1: Path, p2: Path) -> bool:\n    \"\"\"Test whether two paths reference the same actual file or directory.\n\n    Unlike Path.samefile(), does not resolve symlinks.\n    \"\"\"\n    return os.path.samestat(p1.lstat(), p2.lstat())\n"
  },
  {
    "path": "src/_pytest/py.typed",
    "content": ""
  },
  {
    "path": "src/_pytest/pytester.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"(Disabled by default) support for testing pytest and pytest plugins.\n\nPYTEST_DONT_REWRITE\n\"\"\"\n\nfrom __future__ import annotations\n\nimport collections.abc\nfrom collections.abc import Callable\nfrom collections.abc import Generator\nfrom collections.abc import Iterable\nfrom collections.abc import Sequence\nimport contextlib\nfrom fnmatch import fnmatch\nimport gc\nimport importlib\nfrom io import StringIO\nimport locale\nimport os\nfrom pathlib import Path\nimport platform\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport traceback\nfrom typing import Any\nfrom typing import Final\nfrom typing import final\nfrom typing import IO\nfrom typing import Literal\nfrom typing import overload\nfrom typing import TextIO\nfrom typing import TYPE_CHECKING\nfrom weakref import WeakKeyDictionary\n\nfrom iniconfig import IniConfig\nfrom iniconfig import SectionWrapper\n\nfrom _pytest import timing\nfrom _pytest._code import Source\nfrom _pytest.capture import _get_multicapture\nfrom _pytest.compat import NOTSET\nfrom _pytest.compat import NotSetType\nfrom _pytest.config import _PluggyPlugin\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.config import hookimpl\nfrom _pytest.config import main\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.fixtures import fixture\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.main import Session\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import Item\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import importorskip\nfrom _pytest.outcomes import skip\nfrom _pytest.pathlib import bestrelpath\nfrom _pytest.pathlib import make_numbered_dir\nfrom _pytest.reports import CollectReport\nfrom _pytest.reports import TestReport\nfrom _pytest.tmpdir import TempPathFactory\nfrom _pytest.warning_types import PytestFDWarning\n\n\nif TYPE_CHECKING:\n    import pexpect\n\n\npytest_plugins = [\"pytester_assertions\"]\n\n\nIGNORE_PAM = [  # filenames added when obtaining details about the current user\n    \"/var/lib/sss/mc/passwd\"\n]\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    parser.addoption(\n        \"--lsof\",\n        action=\"store_true\",\n        dest=\"lsof\",\n        default=False,\n        help=\"Run FD checks if lsof is available\",\n    )\n\n    parser.addoption(\n        \"--runpytest\",\n        default=\"inprocess\",\n        dest=\"runpytest\",\n        choices=(\"inprocess\", \"subprocess\"),\n        help=(\n            \"Run pytest sub runs in tests using an 'inprocess' \"\n            \"or 'subprocess' (python -m main) method\"\n        ),\n    )\n\n    parser.addini(\n        \"pytester_example_dir\", help=\"Directory to take the pytester example files from\"\n    )\n\n\ndef pytest_configure(config: Config) -> None:\n    if config.getvalue(\"lsof\"):\n        checker = LsofFdLeakChecker()\n        if checker.matching_platform():\n            config.pluginmanager.register(checker)\n\n    config.addinivalue_line(\n        \"markers\",\n        \"pytester_example_path(*path_segments): join the given path \"\n        \"segments to `pytester_example_dir` for this test.\",\n    )\n\n\nclass LsofFdLeakChecker:\n    def get_open_files(self) -> list[tuple[str, str]]:\n        if sys.version_info >= (3, 11):\n            # New in Python 3.11, ignores utf-8 mode\n            encoding = locale.getencoding()\n        else:\n            encoding = locale.getpreferredencoding(False)\n        out = subprocess.run(\n            (\"lsof\", \"-Ffn0\", \"-p\", str(os.getpid())),\n            stdout=subprocess.PIPE,\n            stderr=subprocess.DEVNULL,\n            check=True,\n            text=True,\n            encoding=encoding,\n        ).stdout\n\n        def isopen(line: str) -> bool:\n            return line.startswith(\"f\") and (\n                \"deleted\" not in line\n                and \"mem\" not in line\n                and \"txt\" not in line\n                and \"cwd\" not in line\n            )\n\n        open_files = []\n\n        for line in out.split(\"\\n\"):\n            if isopen(line):\n                fields = line.split(\"\\0\")\n                fd = fields[0][1:]\n                filename = fields[1][1:]\n                if filename in IGNORE_PAM:\n                    continue\n                if filename.startswith(\"/\"):\n                    open_files.append((fd, filename))\n\n        return open_files\n\n    def matching_platform(self) -> bool:\n        try:\n            subprocess.run((\"lsof\", \"-v\"), check=True)\n        except (OSError, subprocess.CalledProcessError):\n            return False\n        else:\n            return True\n\n    @hookimpl(wrapper=True, tryfirst=True)\n    def pytest_runtest_protocol(self, item: Item) -> Generator[None, object, object]:\n        lines1 = self.get_open_files()\n        try:\n            return (yield)\n        finally:\n            if hasattr(sys, \"pypy_version_info\"):\n                gc.collect()\n            lines2 = self.get_open_files()\n\n            new_fds = {t[0] for t in lines2} - {t[0] for t in lines1}\n            leaked_files = [t for t in lines2 if t[0] in new_fds]\n            if leaked_files:\n                error = [\n                    f\"***** {len(leaked_files)} FD leakage detected\",\n                    *(str(f) for f in leaked_files),\n                    \"*** Before:\",\n                    *(str(f) for f in lines1),\n                    \"*** After:\",\n                    *(str(f) for f in lines2),\n                    f\"***** {len(leaked_files)} FD leakage detected\",\n                    \"*** function {}:{}: {} \".format(*item.location),\n                    \"See issue #2366\",\n                ]\n                item.warn(PytestFDWarning(\"\\n\".join(error)))\n\n\n# used at least by pytest-xdist plugin\n\n\n@fixture\ndef _pytest(request: FixtureRequest) -> PytestArg:\n    \"\"\"Return a helper which offers a gethookrecorder(hook) method which\n    returns a HookRecorder instance which helps to make assertions about called\n    hooks.\"\"\"\n    return PytestArg(request)\n\n\nclass PytestArg:\n    def __init__(self, request: FixtureRequest) -> None:\n        self._request = request\n\n    def gethookrecorder(self, hook) -> HookRecorder:\n        hookrecorder = HookRecorder(hook._pm)\n        self._request.addfinalizer(hookrecorder.finish_recording)\n        return hookrecorder\n\n\ndef get_public_names(values: Iterable[str]) -> list[str]:\n    \"\"\"Only return names from iterator values without a leading underscore.\"\"\"\n    return [x for x in values if x[0] != \"_\"]\n\n\n@final\nclass RecordedHookCall:\n    \"\"\"A recorded call to a hook.\n\n    The arguments to the hook call are set as attributes.\n    For example:\n\n    .. code-block:: python\n\n        calls = hook_recorder.getcalls(\"pytest_runtest_setup\")\n        # Suppose pytest_runtest_setup was called once with `item=an_item`.\n        assert calls[0].item is an_item\n    \"\"\"\n\n    def __init__(self, name: str, kwargs) -> None:\n        self.__dict__.update(kwargs)\n        self._name = name\n\n    def __repr__(self) -> str:\n        d = self.__dict__.copy()\n        del d[\"_name\"]\n        return f\"<RecordedHookCall {self._name!r}(**{d!r})>\"\n\n    if TYPE_CHECKING:\n        # The class has undetermined attributes, this tells mypy about it.\n        def __getattr__(self, key: str): ...\n\n\n@final\nclass HookRecorder:\n    \"\"\"Record all hooks called in a plugin manager.\n\n    Hook recorders are created by :class:`Pytester`.\n\n    This wraps all the hook calls in the plugin manager, recording each call\n    before propagating the normal calls.\n    \"\"\"\n\n    def __init__(\n        self, pluginmanager: PytestPluginManager, *, _ispytest: bool = False\n    ) -> None:\n        check_ispytest(_ispytest)\n\n        self._pluginmanager = pluginmanager\n        self.calls: list[RecordedHookCall] = []\n        self.ret: int | ExitCode | None = None\n\n        def before(hook_name: str, hook_impls, kwargs) -> None:\n            self.calls.append(RecordedHookCall(hook_name, kwargs))\n\n        def after(outcome, hook_name: str, hook_impls, kwargs) -> None:\n            pass\n\n        self._undo_wrapping = pluginmanager.add_hookcall_monitoring(before, after)\n\n    def finish_recording(self) -> None:\n        self._undo_wrapping()\n\n    def getcalls(self, names: str | Iterable[str]) -> list[RecordedHookCall]:\n        \"\"\"Get all recorded calls to hooks with the given names (or name).\"\"\"\n        if isinstance(names, str):\n            names = names.split()\n        return [call for call in self.calls if call._name in names]\n\n    def assert_contains(self, entries: Sequence[tuple[str, str]]) -> None:\n        __tracebackhide__ = True\n        i = 0\n        entries = list(entries)\n        # Since Python 3.13, f_locals is not a dict, but eval requires a dict.\n        backlocals = dict(sys._getframe(1).f_locals)\n        while entries:\n            name, check = entries.pop(0)\n            for ind, call in enumerate(self.calls[i:]):\n                if call._name == name:\n                    print(\"NAMEMATCH\", name, call)\n                    if eval(check, backlocals, call.__dict__):\n                        print(\"CHECKERMATCH\", repr(check), \"->\", call)\n                    else:\n                        print(\"NOCHECKERMATCH\", repr(check), \"-\", call)\n                        continue\n                    i += ind + 1\n                    break\n                print(\"NONAMEMATCH\", name, \"with\", call)\n            else:\n                fail(f\"could not find {name!r} check {check!r}\")\n\n    def popcall(self, name: str) -> RecordedHookCall:\n        __tracebackhide__ = True\n        for i, call in enumerate(self.calls):\n            if call._name == name:\n                del self.calls[i]\n                return call\n        lines = [f\"could not find call {name!r}, in:\"]\n        lines.extend([f\"  {x}\" for x in self.calls])\n        fail(\"\\n\".join(lines))\n\n    def getcall(self, name: str) -> RecordedHookCall:\n        values = self.getcalls(name)\n        assert len(values) == 1, (name, values)\n        return values[0]\n\n    # functionality for test reports\n\n    @overload\n    def getreports(\n        self,\n        names: Literal[\"pytest_collectreport\"],\n    ) -> Sequence[CollectReport]: ...\n\n    @overload\n    def getreports(\n        self,\n        names: Literal[\"pytest_runtest_logreport\"],\n    ) -> Sequence[TestReport]: ...\n\n    @overload\n    def getreports(\n        self,\n        names: str | Iterable[str] = (\n            \"pytest_collectreport\",\n            \"pytest_runtest_logreport\",\n        ),\n    ) -> Sequence[CollectReport | TestReport]: ...\n\n    def getreports(\n        self,\n        names: str | Iterable[str] = (\n            \"pytest_collectreport\",\n            \"pytest_runtest_logreport\",\n        ),\n    ) -> Sequence[CollectReport | TestReport]:\n        return [x.report for x in self.getcalls(names)]\n\n    def matchreport(\n        self,\n        inamepart: str = \"\",\n        names: str | Iterable[str] = (\n            \"pytest_runtest_logreport\",\n            \"pytest_collectreport\",\n        ),\n        when: str | None = None,\n    ) -> CollectReport | TestReport:\n        \"\"\"Return a testreport whose dotted import path matches.\"\"\"\n        values = []\n        for rep in self.getreports(names=names):\n            if not when and rep.when != \"call\" and rep.passed:\n                # setup/teardown passing reports - let's ignore those\n                continue\n            if when and rep.when != when:\n                continue\n            if not inamepart or inamepart in rep.nodeid.split(\"::\"):\n                values.append(rep)\n        if not values:\n            raise ValueError(\n                f\"could not find test report matching {inamepart!r}: \"\n                \"no test reports at all!\"\n            )\n        if len(values) > 1:\n            raise ValueError(\n                f\"found 2 or more testreports matching {inamepart!r}: {values}\"\n            )\n        return values[0]\n\n    @overload\n    def getfailures(\n        self,\n        names: Literal[\"pytest_collectreport\"],\n    ) -> Sequence[CollectReport]: ...\n\n    @overload\n    def getfailures(\n        self,\n        names: Literal[\"pytest_runtest_logreport\"],\n    ) -> Sequence[TestReport]: ...\n\n    @overload\n    def getfailures(\n        self,\n        names: str | Iterable[str] = (\n            \"pytest_collectreport\",\n            \"pytest_runtest_logreport\",\n        ),\n    ) -> Sequence[CollectReport | TestReport]: ...\n\n    def getfailures(\n        self,\n        names: str | Iterable[str] = (\n            \"pytest_collectreport\",\n            \"pytest_runtest_logreport\",\n        ),\n    ) -> Sequence[CollectReport | TestReport]:\n        return [rep for rep in self.getreports(names) if rep.failed]\n\n    def getfailedcollections(self) -> Sequence[CollectReport]:\n        return self.getfailures(\"pytest_collectreport\")\n\n    def listoutcomes(\n        self,\n    ) -> tuple[\n        Sequence[TestReport],\n        Sequence[CollectReport | TestReport],\n        Sequence[CollectReport | TestReport],\n    ]:\n        passed = []\n        skipped = []\n        failed = []\n        for rep in self.getreports(\n            (\"pytest_collectreport\", \"pytest_runtest_logreport\")\n        ):\n            if rep.passed:\n                if rep.when == \"call\":\n                    assert isinstance(rep, TestReport)\n                    passed.append(rep)\n            elif rep.skipped:\n                skipped.append(rep)\n            else:\n                assert rep.failed, f\"Unexpected outcome: {rep!r}\"\n                failed.append(rep)\n        return passed, skipped, failed\n\n    def countoutcomes(self) -> list[int]:\n        return [len(x) for x in self.listoutcomes()]\n\n    def assertoutcome(self, passed: int = 0, skipped: int = 0, failed: int = 0) -> None:\n        __tracebackhide__ = True\n        from _pytest.pytester_assertions import assertoutcome\n\n        outcomes = self.listoutcomes()\n        assertoutcome(\n            outcomes,\n            passed=passed,\n            skipped=skipped,\n            failed=failed,\n        )\n\n    def clear(self) -> None:\n        self.calls[:] = []\n\n\n@fixture\ndef linecomp() -> LineComp:\n    \"\"\"A :class: `LineComp` instance for checking that an input linearly\n    contains a sequence of strings.\"\"\"\n    return LineComp()\n\n\n@fixture(name=\"LineMatcher\")\ndef LineMatcher_fixture(request: FixtureRequest) -> type[LineMatcher]:\n    \"\"\"A reference to the :class: `LineMatcher`.\n\n    This is instantiable with a list of lines (without their trailing newlines).\n    This is useful for testing large texts, such as the output of commands.\n    \"\"\"\n    return LineMatcher\n\n\n@fixture\ndef pytester(\n    request: FixtureRequest, tmp_path_factory: TempPathFactory, monkeypatch: MonkeyPatch\n) -> Pytester:\n    \"\"\"\n    Facilities to write tests/configuration files, execute pytest in isolation, and match\n    against expected output, perfect for black-box testing of pytest plugins.\n\n    It attempts to isolate the test run from external factors as much as possible, modifying\n    the current working directory to ``path`` and environment variables during initialization.\n\n    It is particularly useful for testing plugins. It is similar to the :fixture:`tmp_path`\n    fixture but provides methods which aid in testing pytest itself.\n    \"\"\"\n    return Pytester(request, tmp_path_factory, monkeypatch, _ispytest=True)\n\n\n@fixture\ndef _sys_snapshot() -> Generator[None]:\n    snappaths = SysPathsSnapshot()\n    snapmods = SysModulesSnapshot()\n    yield\n    snapmods.restore()\n    snappaths.restore()\n\n\n@fixture\ndef _config_for_test() -> Generator[Config]:\n    from _pytest.config import get_config\n\n    config = get_config()\n    yield config\n    config._ensure_unconfigure()  # cleanup, e.g. capman closing tmpfiles.\n\n\n# Regex to match the session duration string in the summary: \"74.34s\".\nrex_session_duration = re.compile(r\"\\d+\\.\\d\\ds\")\n# Regex to match all the counts and phrases in the summary line: \"34 passed, 111 skipped\".\nrex_outcome = re.compile(r\"(\\d+) (\\w+)\")\n\n\n@final\nclass RunResult:\n    \"\"\"The result of running a command from :class:`~pytest.Pytester`.\"\"\"\n\n    def __init__(\n        self,\n        ret: int | ExitCode,\n        outlines: list[str],\n        errlines: list[str],\n        duration: float,\n    ) -> None:\n        try:\n            self.ret: int | ExitCode = ExitCode(ret)\n            \"\"\"The return value.\"\"\"\n        except ValueError:\n            self.ret = ret\n        self.outlines = outlines\n        \"\"\"List of lines captured from stdout.\"\"\"\n        self.errlines = errlines\n        \"\"\"List of lines captured from stderr.\"\"\"\n        self.stdout = LineMatcher(outlines)\n        \"\"\":class:`~pytest.LineMatcher` of stdout.\n\n        Use e.g. :func:`str(stdout) <pytest.LineMatcher.__str__()>` to reconstruct stdout, or the commonly used\n        :func:`stdout.fnmatch_lines() <pytest.LineMatcher.fnmatch_lines()>` method.\n        \"\"\"\n        self.stderr = LineMatcher(errlines)\n        \"\"\":class:`~pytest.LineMatcher` of stderr.\"\"\"\n        self.duration = duration\n        \"\"\"Duration in seconds.\"\"\"\n\n    def __repr__(self) -> str:\n        return (\n            f\"<RunResult ret={self.ret!s} \"\n            f\"len(stdout.lines)={len(self.stdout.lines)} \"\n            f\"len(stderr.lines)={len(self.stderr.lines)} \"\n            f\"duration={self.duration:.2f}s>\"\n        )\n\n    def parseoutcomes(self) -> dict[str, int]:\n        \"\"\"Return a dictionary of outcome noun -> count from parsing the terminal\n        output that the test process produced.\n\n        The returned nouns will always be in plural form::\n\n            ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====\n\n        Will return ``{\"failed\": 1, \"passed\": 1, \"warnings\": 1, \"errors\": 1}``.\n        \"\"\"\n        return self.parse_summary_nouns(self.outlines)\n\n    @classmethod\n    def parse_summary_nouns(cls, lines) -> dict[str, int]:\n        \"\"\"Extract the nouns from a pytest terminal summary line.\n\n        It always returns the plural noun for consistency::\n\n            ======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====\n\n        Will return ``{\"failed\": 1, \"passed\": 1, \"warnings\": 1, \"errors\": 1}``.\n        \"\"\"\n        for line in reversed(lines):\n            if rex_session_duration.search(line):\n                outcomes = rex_outcome.findall(line)\n                ret = {noun: int(count) for (count, noun) in outcomes}\n                break\n        else:\n            raise ValueError(\"Pytest terminal summary report not found\")\n\n        to_plural = {\n            \"warning\": \"warnings\",\n            \"error\": \"errors\",\n        }\n        return {to_plural.get(k, k): v for k, v in ret.items()}\n\n    def assert_outcomes(\n        self,\n        passed: int = 0,\n        skipped: int = 0,\n        failed: int = 0,\n        errors: int = 0,\n        xpassed: int = 0,\n        xfailed: int = 0,\n        warnings: int | None = None,\n        deselected: int | None = None,\n    ) -> None:\n        \"\"\"\n        Assert that the specified outcomes appear with the respective\n        numbers (0 means it didn't occur) in the text output from a test run.\n\n        ``warnings`` and ``deselected`` are only checked if not None.\n        \"\"\"\n        __tracebackhide__ = True\n        from _pytest.pytester_assertions import assert_outcomes\n\n        outcomes = self.parseoutcomes()\n        assert_outcomes(\n            outcomes,\n            passed=passed,\n            skipped=skipped,\n            failed=failed,\n            errors=errors,\n            xpassed=xpassed,\n            xfailed=xfailed,\n            warnings=warnings,\n            deselected=deselected,\n        )\n\n\nclass SysModulesSnapshot:\n    def __init__(self, preserve: Callable[[str], bool] | None = None) -> None:\n        self.__preserve = preserve\n        self.__saved = dict(sys.modules)\n\n    def restore(self) -> None:\n        if self.__preserve:\n            self.__saved.update(\n                (k, m) for k, m in sys.modules.items() if self.__preserve(k)\n            )\n        sys.modules.clear()\n        sys.modules.update(self.__saved)\n\n\nclass SysPathsSnapshot:\n    def __init__(self) -> None:\n        self.__saved = list(sys.path), list(sys.meta_path)\n\n    def restore(self) -> None:\n        sys.path[:], sys.meta_path[:] = self.__saved\n\n\n@final\nclass Pytester:\n    \"\"\"\n    Facilities to write tests/configuration files, execute pytest in isolation, and match\n    against expected output, perfect for black-box testing of pytest plugins.\n\n    It attempts to isolate the test run from external factors as much as possible, modifying\n    the current working directory to :attr:`path` and environment variables during initialization.\n    \"\"\"\n\n    __test__ = False\n\n    CLOSE_STDIN: Final = NOTSET\n\n    class TimeoutExpired(Exception):\n        pass\n\n    def __init__(\n        self,\n        request: FixtureRequest,\n        tmp_path_factory: TempPathFactory,\n        monkeypatch: MonkeyPatch,\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        self._request = request\n        self._mod_collections: WeakKeyDictionary[Collector, list[Item | Collector]] = (\n            WeakKeyDictionary()\n        )\n        if request.function:\n            name: str = request.function.__name__\n        else:\n            name = request.node.name\n        self._name = name\n        self._path: Path = tmp_path_factory.mktemp(name, numbered=True)\n        #: A list of plugins to use with :py:meth:`parseconfig` and\n        #: :py:meth:`runpytest`. Initially this is an empty list but plugins can\n        #: be added to the list.\n        #:\n        #: When running in subprocess mode, specify plugins by name (str) - adding\n        #: plugin objects directly is not supported.\n        self.plugins: list[str | _PluggyPlugin] = []\n        self._sys_path_snapshot = SysPathsSnapshot()\n        self._sys_modules_snapshot = self.__take_sys_modules_snapshot()\n        self._request.addfinalizer(self._finalize)\n        self._method = self._request.config.getoption(\"--runpytest\")\n        self._test_tmproot = tmp_path_factory.mktemp(f\"tmp-{name}\", numbered=True)\n\n        self._monkeypatch = mp = monkeypatch\n        self.chdir()\n        mp.setenv(\"PYTEST_DEBUG_TEMPROOT\", str(self._test_tmproot))\n        # Ensure no unexpected caching via tox.\n        mp.delenv(\"TOX_ENV_DIR\", raising=False)\n        # Discard outer pytest options.\n        mp.delenv(\"PYTEST_ADDOPTS\", raising=False)\n        # Ensure no user config is used.\n        tmphome = str(self.path)\n        mp.setenv(\"HOME\", tmphome)\n        mp.setenv(\"USERPROFILE\", tmphome)\n        # Do not use colors for inner runs by default.\n        mp.setenv(\"PY_COLORS\", \"0\")\n\n    @property\n    def path(self) -> Path:\n        \"\"\"Temporary directory path used to create files/run tests from, etc.\"\"\"\n        return self._path\n\n    def __repr__(self) -> str:\n        return f\"<Pytester {self.path!r}>\"\n\n    def _finalize(self) -> None:\n        \"\"\"\n        Clean up global state artifacts.\n\n        Some methods modify the global interpreter state and this tries to\n        clean this up. It does not remove the temporary directory however so\n        it can be looked at after the test run has finished.\n        \"\"\"\n        self._sys_modules_snapshot.restore()\n        self._sys_path_snapshot.restore()\n\n    def __take_sys_modules_snapshot(self) -> SysModulesSnapshot:\n        # Some zope modules used by twisted-related tests keep internal state\n        # and can't be deleted; we had some trouble in the past with\n        # `zope.interface` for example.\n        #\n        # Preserve readline due to https://bugs.python.org/issue41033.\n        # pexpect issues a SIGWINCH.\n        def preserve_module(name):\n            return name.startswith((\"zope\", \"readline\"))\n\n        return SysModulesSnapshot(preserve=preserve_module)\n\n    def make_hook_recorder(self, pluginmanager: PytestPluginManager) -> HookRecorder:\n        \"\"\"Create a new :class:`HookRecorder` for a :class:`PytestPluginManager`.\"\"\"\n        pluginmanager.reprec = reprec = HookRecorder(pluginmanager, _ispytest=True)  # type: ignore[attr-defined]\n        self._request.addfinalizer(reprec.finish_recording)\n        return reprec\n\n    def chdir(self) -> None:\n        \"\"\"Cd into the temporary directory.\n\n        This is done automatically upon instantiation.\n        \"\"\"\n        self._monkeypatch.chdir(self.path)\n\n    def _makefile(\n        self,\n        ext: str,\n        lines: Sequence[Any | bytes],\n        files: dict[str, str],\n        encoding: str = \"utf-8\",\n    ) -> Path:\n        items = list(files.items())\n\n        if ext is None:\n            raise TypeError(\"ext must not be None\")\n\n        if ext and not ext.startswith(\".\"):\n            raise ValueError(\n                f\"pytester.makefile expects a file extension, try .{ext} instead of {ext}\"\n            )\n\n        def to_text(s: Any | bytes) -> str:\n            return s.decode(encoding) if isinstance(s, bytes) else str(s)\n\n        if lines:\n            source = \"\\n\".join(to_text(x) for x in lines)\n            basename = self._name\n            items.insert(0, (basename, source))\n\n        ret = None\n        for basename, value in items:\n            p = self.path.joinpath(basename).with_suffix(ext)\n            p.parent.mkdir(parents=True, exist_ok=True)\n            source_ = Source(value)\n            source = \"\\n\".join(to_text(line) for line in source_.lines)\n            p.write_text(source.strip(), encoding=encoding)\n            if ret is None:\n                ret = p\n        assert ret is not None\n        return ret\n\n    def makefile(self, ext: str, *args: str, **kwargs: str) -> Path:\n        r\"\"\"Create new text file(s) in the test directory.\n\n        :param ext:\n            The extension the file(s) should use, including the dot, e.g. `.py`.\n        :param args:\n            All args are treated as strings and joined using newlines.\n            The result is written as contents to the file.  The name of the\n            file is based on the test function requesting this fixture.\n        :param kwargs:\n            Each keyword is the name of a file, while the value of it will\n            be written as contents of the file.\n        :returns:\n            The first created file.\n\n        Examples:\n\n        .. code-block:: python\n\n            pytester.makefile(\".txt\", \"line1\", \"line2\")\n\n            pytester.makefile(\".ini\", pytest=\"[pytest]\\naddopts=-rs\\n\")\n\n        To create binary files, use :meth:`pathlib.Path.write_bytes` directly:\n\n        .. code-block:: python\n\n            filename = pytester.path.joinpath(\"foo.bin\")\n            filename.write_bytes(b\"...\")\n        \"\"\"\n        return self._makefile(ext, args, kwargs)\n\n    def makeconftest(self, source: str) -> Path:\n        \"\"\"Write a conftest.py file.\n\n        :param source: The contents.\n        :returns: The conftest.py file.\n        \"\"\"\n        return self.makepyfile(conftest=source)\n\n    def makeini(self, source: str) -> Path:\n        \"\"\"Write a tox.ini file.\n\n        :param source: The contents.\n        :returns: The tox.ini file.\n        \"\"\"\n        return self.makefile(\".ini\", tox=source)\n\n    def maketoml(self, source: str) -> Path:\n        \"\"\"Write a pytest.toml file.\n\n        :param source: The contents.\n        :returns: The pytest.toml file.\n\n        .. versionadded:: 9.0\n        \"\"\"\n        return self.makefile(\".toml\", pytest=source)\n\n    def getinicfg(self, source: str) -> SectionWrapper:\n        \"\"\"Return the pytest section from the tox.ini config file.\"\"\"\n        p = self.makeini(source)\n        return IniConfig(str(p))[\"pytest\"]\n\n    def makepyprojecttoml(self, source: str) -> Path:\n        \"\"\"Write a pyproject.toml file.\n\n        :param source: The contents.\n        :returns: The pyproject.ini file.\n\n        .. versionadded:: 6.0\n        \"\"\"\n        return self.makefile(\".toml\", pyproject=source)\n\n    def makepyfile(self, *args, **kwargs) -> Path:\n        r\"\"\"Shortcut for .makefile() with a .py extension.\n\n        Defaults to the test name with a '.py' extension, e.g test_foobar.py, overwriting\n        existing files.\n\n        Examples:\n\n        .. code-block:: python\n\n            def test_something(pytester):\n                # Initial file is created test_something.py.\n                pytester.makepyfile(\"foobar\")\n                # To create multiple files, pass kwargs accordingly.\n                pytester.makepyfile(custom=\"foobar\")\n                # At this point, both 'test_something.py' & 'custom.py' exist in the test directory.\n\n        \"\"\"\n        return self._makefile(\".py\", args, kwargs)\n\n    def maketxtfile(self, *args, **kwargs) -> Path:\n        r\"\"\"Shortcut for .makefile() with a .txt extension.\n\n        Defaults to the test name with a '.txt' extension, e.g test_foobar.txt, overwriting\n        existing files.\n\n        Examples:\n\n        .. code-block:: python\n\n            def test_something(pytester):\n                # Initial file is created test_something.txt.\n                pytester.maketxtfile(\"foobar\")\n                # To create multiple files, pass kwargs accordingly.\n                pytester.maketxtfile(custom=\"foobar\")\n                # At this point, both 'test_something.txt' & 'custom.txt' exist in the test directory.\n\n        \"\"\"\n        return self._makefile(\".txt\", args, kwargs)\n\n    def syspathinsert(self, path: str | os.PathLike[str] | None = None) -> None:\n        \"\"\"Prepend a directory to sys.path, defaults to :attr:`path`.\n\n        This is undone automatically when this object dies at the end of each\n        test.\n\n        :param path:\n            The path.\n        \"\"\"\n        if path is None:\n            path = self.path\n\n        self._monkeypatch.syspath_prepend(str(path))\n\n    def mkdir(self, name: str | os.PathLike[str]) -> Path:\n        \"\"\"Create a new (sub)directory.\n\n        :param name:\n            The name of the directory, relative to the pytester path.\n        :returns:\n            The created directory.\n        :rtype: pathlib.Path\n        \"\"\"\n        p = self.path / name\n        p.mkdir()\n        return p\n\n    def mkpydir(self, name: str | os.PathLike[str]) -> Path:\n        \"\"\"Create a new python package.\n\n        This creates a (sub)directory with an empty ``__init__.py`` file so it\n        gets recognised as a Python package.\n        \"\"\"\n        p = self.path / name\n        p.mkdir()\n        p.joinpath(\"__init__.py\").touch()\n        return p\n\n    def copy_example(self, name: str | None = None) -> Path:\n        \"\"\"Copy file from project's directory into the testdir.\n\n        :param name:\n            The name of the file to copy.\n        :return:\n            Path to the copied directory (inside ``self.path``).\n        :rtype: pathlib.Path\n        \"\"\"\n        example_dir_ = self._request.config.getini(\"pytester_example_dir\")\n        if example_dir_ is None:\n            raise ValueError(\"pytester_example_dir is unset, can't copy examples\")\n        example_dir: Path = self._request.config.rootpath / example_dir_\n\n        for extra_element in self._request.node.iter_markers(\"pytester_example_path\"):\n            assert extra_element.args\n            example_dir = example_dir.joinpath(*extra_element.args)\n\n        if name is None:\n            func_name = self._name\n            maybe_dir = example_dir / func_name\n            maybe_file = example_dir / (func_name + \".py\")\n\n            if maybe_dir.is_dir():\n                example_path = maybe_dir\n            elif maybe_file.is_file():\n                example_path = maybe_file\n            else:\n                raise LookupError(\n                    f\"{func_name} can't be found as module or package in {example_dir}\"\n                )\n        else:\n            example_path = example_dir.joinpath(name)\n\n        if example_path.is_dir() and not example_path.joinpath(\"__init__.py\").is_file():\n            shutil.copytree(example_path, self.path, symlinks=True, dirs_exist_ok=True)\n            return self.path\n        elif example_path.is_file():\n            result = self.path.joinpath(example_path.name)\n            shutil.copy(example_path, result)\n            return result\n        else:\n            raise LookupError(\n                f'example \"{example_path}\" is not found as a file or directory'\n            )\n\n    def getnode(self, config: Config, arg: str | os.PathLike[str]) -> Collector | Item:\n        \"\"\"Get the collection node of a file.\n\n        :param config:\n           A pytest config.\n           See :py:meth:`parseconfig` and :py:meth:`parseconfigure` for creating it.\n        :param arg:\n            Path to the file.\n        :returns:\n            The node.\n        \"\"\"\n        session = Session.from_config(config)\n        assert \"::\" not in str(arg)\n        p = Path(os.path.abspath(arg))\n        config.hook.pytest_sessionstart(session=session)\n        res = session.perform_collect([str(p)], genitems=False)[0]\n        config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)\n        return res\n\n    def getpathnode(self, path: str | os.PathLike[str]) -> Collector | Item:\n        \"\"\"Return the collection node of a file.\n\n        This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to\n        create the (configured) pytest Config instance.\n\n        :param path:\n            Path to the file.\n        :returns:\n            The node.\n        \"\"\"\n        path = Path(path)\n        config = self.parseconfigure(path)\n        session = Session.from_config(config)\n        x = bestrelpath(session.path, path)\n        config.hook.pytest_sessionstart(session=session)\n        res = session.perform_collect([x], genitems=False)[0]\n        config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)\n        return res\n\n    def genitems(self, colitems: Sequence[Item | Collector]) -> list[Item]:\n        \"\"\"Generate all test items from a collection node.\n\n        This recurses into the collection node and returns a list of all the\n        test items contained within.\n\n        :param colitems:\n            The collection nodes.\n        :returns:\n            The collected items.\n        \"\"\"\n        session = colitems[0].session\n        result: list[Item] = []\n        for colitem in colitems:\n            result.extend(session.genitems(colitem))\n        return result\n\n    def runitem(self, source: str) -> Any:\n        \"\"\"Run the \"test_func\" Item.\n\n        The calling test instance (class containing the test method) must\n        provide a ``.getrunner()`` method which should return a runner which\n        can run the test protocol for a single item, e.g.\n        ``_pytest.runner.runtestprotocol``.\n        \"\"\"\n        # used from runner functional tests\n        item = self.getitem(source)\n        # the test class where we are called from wants to provide the runner\n        testclassinstance = self._request.instance\n        runner = testclassinstance.getrunner()\n        return runner(item)\n\n    def inline_runsource(self, source: str, *cmdlineargs) -> HookRecorder:\n        \"\"\"Run a test module in process using ``pytest.main()``.\n\n        This run writes \"source\" into a temporary file and runs\n        ``pytest.main()`` on it, returning a :py:class:`HookRecorder` instance\n        for the result.\n\n        :param source: The source code of the test module.\n        :param cmdlineargs: Any extra command line arguments to use.\n        \"\"\"\n        p = self.makepyfile(source)\n        values = [*list(cmdlineargs), p]\n        return self.inline_run(*values)\n\n    def inline_genitems(self, *args) -> tuple[list[Item], HookRecorder]:\n        \"\"\"Run ``pytest.main(['--collect-only'])`` in-process.\n\n        Runs the :py:func:`pytest.main` function to run all of pytest inside\n        the test process itself like :py:meth:`inline_run`, but returns a\n        tuple of the collected items and a :py:class:`HookRecorder` instance.\n        \"\"\"\n        rec = self.inline_run(\"--collect-only\", *args)\n        items = [x.item for x in rec.getcalls(\"pytest_itemcollected\")]\n        return items, rec\n\n    def inline_run(\n        self,\n        *args: str | os.PathLike[str],\n        plugins=(),\n        no_reraise_ctrlc: bool = False,\n    ) -> HookRecorder:\n        \"\"\"Run ``pytest.main()`` in-process, returning a HookRecorder.\n\n        Runs the :py:func:`pytest.main` function to run all of pytest inside\n        the test process itself.  This means it can return a\n        :py:class:`HookRecorder` instance which gives more detailed results\n        from that run than can be done by matching stdout/stderr from\n        :py:meth:`runpytest`.\n\n        :param args:\n            Command line arguments to pass to :py:func:`pytest.main`.\n        :param plugins:\n            Extra plugin instances the ``pytest.main()`` instance should use.\n        :param no_reraise_ctrlc:\n            Typically we reraise keyboard interrupts from the child run. If\n            True, the KeyboardInterrupt exception is captured.\n        \"\"\"\n        from _pytest.unraisableexception import gc_collect_iterations_key\n\n        # (maybe a cpython bug?) the importlib cache sometimes isn't updated\n        # properly between file creation and inline_run (especially if imports\n        # are interspersed with file creation)\n        importlib.invalidate_caches()\n\n        plugins = list(plugins)\n        finalizers = []\n        try:\n            # Any sys.module or sys.path changes done while running pytest\n            # inline should be reverted after the test run completes to avoid\n            # clashing with later inline tests run within the same pytest test,\n            # e.g. just because they use matching test module names.\n            finalizers.append(self.__take_sys_modules_snapshot().restore)\n            finalizers.append(SysPathsSnapshot().restore)\n\n            # Important note:\n            # - our tests should not leave any other references/registrations\n            #   laying around other than possibly loaded test modules\n            #   referenced from sys.modules, as nothing will clean those up\n            #   automatically\n\n            rec = []\n\n            class PytesterHelperPlugin:\n                @staticmethod\n                def pytest_configure(config: Config) -> None:\n                    rec.append(self.make_hook_recorder(config.pluginmanager))\n\n                    # The unraisable plugin GC collect slows down inline\n                    # pytester runs too much.\n                    config.stash[gc_collect_iterations_key] = 0\n\n            plugins.append(PytesterHelperPlugin())\n            ret = main([str(x) for x in args], plugins=plugins)\n            if len(rec) == 1:\n                reprec = rec.pop()\n            else:\n\n                class reprec:  # type: ignore\n                    pass\n\n            reprec.ret = ret\n\n            # Typically we reraise keyboard interrupts from the child run\n            # because it's our user requesting interruption of the testing.\n            if ret == ExitCode.INTERRUPTED and not no_reraise_ctrlc:\n                calls = reprec.getcalls(\"pytest_keyboard_interrupt\")\n                if calls and calls[-1].excinfo.type == KeyboardInterrupt:\n                    raise KeyboardInterrupt()\n            return reprec\n        finally:\n            for finalizer in finalizers:\n                finalizer()\n\n    def runpytest_inprocess(\n        self, *args: str | os.PathLike[str], **kwargs: Any\n    ) -> RunResult:\n        \"\"\"Return result of running pytest in-process, providing a similar\n        interface to what self.runpytest() provides.\"\"\"\n        syspathinsert = kwargs.pop(\"syspathinsert\", False)\n\n        if syspathinsert:\n            self.syspathinsert()\n        instant = timing.Instant()\n        capture = _get_multicapture(\"sys\")\n        capture.start_capturing()\n        try:\n            try:\n                reprec = self.inline_run(*args, **kwargs)\n            except SystemExit as e:\n                ret = e.args[0]\n                try:\n                    ret = ExitCode(e.args[0])\n                except ValueError:\n                    pass\n\n                class reprec:  # type: ignore\n                    ret = ret\n\n            except Exception:\n                traceback.print_exc()\n\n                class reprec:  # type: ignore\n                    ret = ExitCode(3)\n\n        finally:\n            out, err = capture.readouterr()\n            capture.stop_capturing()\n            sys.stdout.write(out)\n            sys.stderr.write(err)\n\n        assert reprec.ret is not None\n        res = RunResult(\n            reprec.ret, out.splitlines(), err.splitlines(), instant.elapsed().seconds\n        )\n        res.reprec = reprec  # type: ignore\n        return res\n\n    def runpytest(self, *args: str | os.PathLike[str], **kwargs: Any) -> RunResult:\n        \"\"\"Run pytest inline or in a subprocess, depending on the command line\n        option \"--runpytest\" and return a :py:class:`~pytest.RunResult`.\"\"\"\n        new_args = self._ensure_basetemp(args)\n        if self._method == \"inprocess\":\n            return self.runpytest_inprocess(*new_args, **kwargs)\n        elif self._method == \"subprocess\":\n            return self.runpytest_subprocess(*new_args, **kwargs)\n        raise RuntimeError(f\"Unrecognized runpytest option: {self._method}\")\n\n    def _ensure_basetemp(\n        self, args: Sequence[str | os.PathLike[str]]\n    ) -> list[str | os.PathLike[str]]:\n        new_args = list(args)\n        for x in new_args:\n            if str(x).startswith(\"--basetemp\"):\n                break\n        else:\n            new_args.append(\n                \"--basetemp={}\".format(self.path.parent.joinpath(\"basetemp\"))\n            )\n        return new_args\n\n    def parseconfig(self, *args: str | os.PathLike[str]) -> Config:\n        \"\"\"Return a new pytest :class:`pytest.Config` instance from given\n        commandline args.\n\n        This invokes the pytest bootstrapping code in _pytest.config to create a\n        new :py:class:`pytest.PytestPluginManager` and call the\n        :hook:`pytest_cmdline_parse` hook to create a new :class:`pytest.Config`\n        instance.\n\n        If :attr:`plugins` has been populated they should be plugin modules\n        to be registered with the plugin manager.\n        \"\"\"\n        import _pytest.config\n\n        new_args = [str(x) for x in self._ensure_basetemp(args)]\n\n        config = _pytest.config._prepareconfig(new_args, self.plugins)\n        # we don't know what the test will do with this half-setup config\n        # object and thus we make sure it gets unconfigured properly in any\n        # case (otherwise capturing could still be active, for example)\n        self._request.addfinalizer(config._ensure_unconfigure)\n        return config\n\n    def parseconfigure(self, *args: str | os.PathLike[str]) -> Config:\n        \"\"\"Return a new pytest configured Config instance.\n\n        Returns a new :py:class:`pytest.Config` instance like\n        :py:meth:`parseconfig`, but also calls the :hook:`pytest_configure`\n        hook.\n        \"\"\"\n        config = self.parseconfig(*args)\n        config._do_configure()\n        return config\n\n    def getitem(\n        self, source: str | os.PathLike[str], funcname: str = \"test_func\"\n    ) -> Item:\n        \"\"\"Return the test item for a test function.\n\n        Writes the source to a python file and runs pytest's collection on\n        the resulting module, returning the test item for the requested\n        function name.\n\n        :param source:\n            The module source.\n        :param funcname:\n            The name of the test function for which to return a test item.\n        :returns:\n            The test item.\n        \"\"\"\n        items = self.getitems(source)\n        for item in items:\n            if item.name == funcname:\n                return item\n        assert 0, f\"{funcname!r} item not found in module:\\n{source}\\nitems: {items}\"\n\n    def getitems(self, source: str | os.PathLike[str]) -> list[Item]:\n        \"\"\"Return all test items collected from the module.\n\n        Writes the source to a Python file and runs pytest's collection on\n        the resulting module, returning all test items contained within.\n        \"\"\"\n        modcol = self.getmodulecol(source)\n        return self.genitems([modcol])\n\n    def getmodulecol(\n        self,\n        source: str | os.PathLike[str],\n        configargs=(),\n        *,\n        withinit: bool = False,\n    ):\n        \"\"\"Return the module collection node for ``source``.\n\n        Writes ``source`` to a file using :py:meth:`makepyfile` and then\n        runs the pytest collection on it, returning the collection node for the\n        test module.\n\n        :param source:\n            The source code of the module to collect.\n\n        :param configargs:\n            Any extra arguments to pass to :py:meth:`parseconfigure`.\n\n        :param withinit:\n            Whether to also write an ``__init__.py`` file to the same\n            directory to ensure it is a package.\n        \"\"\"\n        if isinstance(source, os.PathLike):\n            path = self.path.joinpath(source)\n            assert not withinit, \"not supported for paths\"\n        else:\n            kw = {self._name: str(source)}\n            path = self.makepyfile(**kw)\n        if withinit:\n            self.makepyfile(__init__=\"#\")\n        self.config = config = self.parseconfigure(path, *configargs)\n        return self.getnode(config, path)\n\n    def collect_by_name(self, modcol: Collector, name: str) -> Item | Collector | None:\n        \"\"\"Return the collection node for name from the module collection.\n\n        Searches a module collection node for a collection node matching the\n        given name.\n\n        :param modcol: A module collection node; see :py:meth:`getmodulecol`.\n        :param name: The name of the node to return.\n        \"\"\"\n        if modcol not in self._mod_collections:\n            self._mod_collections[modcol] = list(modcol.collect())\n        for colitem in self._mod_collections[modcol]:\n            if colitem.name == name:\n                return colitem\n        return None\n\n    def popen(\n        self,\n        cmdargs: Sequence[str | os.PathLike[str]],\n        stdout: int | TextIO = subprocess.PIPE,\n        stderr: int | TextIO = subprocess.PIPE,\n        stdin: NotSetType | bytes | IO[Any] | int = CLOSE_STDIN,\n        **kw,\n    ):\n        \"\"\"Invoke :py:class:`subprocess.Popen`.\n\n        Calls :py:class:`subprocess.Popen` making sure the current working\n        directory is in ``PYTHONPATH``.\n\n        You probably want to use :py:meth:`run` instead.\n        \"\"\"\n        env = os.environ.copy()\n        env[\"PYTHONPATH\"] = os.pathsep.join(\n            filter(None, [os.getcwd(), env.get(\"PYTHONPATH\", \"\")])\n        )\n        kw[\"env\"] = env\n\n        if stdin is self.CLOSE_STDIN:\n            kw[\"stdin\"] = subprocess.PIPE\n        elif isinstance(stdin, bytes):\n            kw[\"stdin\"] = subprocess.PIPE\n        else:\n            kw[\"stdin\"] = stdin\n\n        popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)\n        if stdin is self.CLOSE_STDIN:\n            assert popen.stdin is not None\n            popen.stdin.close()\n        elif isinstance(stdin, bytes):\n            assert popen.stdin is not None\n            popen.stdin.write(stdin)\n\n        return popen\n\n    def run(\n        self,\n        *cmdargs: str | os.PathLike[str],\n        timeout: float | None = None,\n        stdin: NotSetType | bytes | IO[Any] | int = CLOSE_STDIN,\n    ) -> RunResult:\n        \"\"\"Run a command with arguments.\n\n        Run a process using :py:class:`subprocess.Popen` saving the stdout and\n        stderr.\n\n        :param cmdargs:\n            The sequence of arguments to pass to :py:class:`subprocess.Popen`,\n            with path-like objects being converted to :py:class:`str`\n            automatically.\n        :param timeout:\n            The period in seconds after which to timeout and raise\n            :py:class:`Pytester.TimeoutExpired`.\n        :param stdin:\n            Optional standard input.\n\n            - If it is ``CLOSE_STDIN`` (Default), then this method calls\n              :py:class:`subprocess.Popen` with ``stdin=subprocess.PIPE``, and\n              the standard input is closed immediately after the new command is\n              started.\n\n            - If it is of type :py:class:`bytes`, these bytes are sent to the\n              standard input of the command.\n\n            - Otherwise, it is passed through to :py:class:`subprocess.Popen`.\n              For further information in this case, consult the document of the\n              ``stdin`` parameter in :py:class:`subprocess.Popen`.\n        :type stdin: _pytest.compat.NotSetType | bytes | IO[Any] | int\n        :returns:\n            The result.\n\n        \"\"\"\n        __tracebackhide__ = True\n\n        cmdargs = tuple(os.fspath(arg) for arg in cmdargs)\n        p1 = self.path.joinpath(\"stdout\")\n        p2 = self.path.joinpath(\"stderr\")\n        print(\"running:\", *cmdargs)\n        print(\"     in:\", Path.cwd())\n\n        with p1.open(\"w\", encoding=\"utf8\") as f1, p2.open(\"w\", encoding=\"utf8\") as f2:\n            instant = timing.Instant()\n            popen = self.popen(\n                cmdargs,\n                stdin=stdin,\n                stdout=f1,\n                stderr=f2,\n            )\n            if popen.stdin is not None:\n                popen.stdin.close()\n\n            def handle_timeout() -> None:\n                __tracebackhide__ = True\n\n                timeout_message = f\"{timeout} second timeout expired running: {cmdargs}\"\n\n                popen.kill()\n                popen.wait()\n                raise self.TimeoutExpired(timeout_message)\n\n            if timeout is None:\n                ret = popen.wait()\n            else:\n                try:\n                    ret = popen.wait(timeout)\n                except subprocess.TimeoutExpired:\n                    handle_timeout()\n            f1.flush()\n            f2.flush()\n\n        with p1.open(encoding=\"utf8\") as f1, p2.open(encoding=\"utf8\") as f2:\n            out = f1.read().splitlines()\n            err = f2.read().splitlines()\n\n        self._dump_lines(out, sys.stdout)\n        self._dump_lines(err, sys.stderr)\n\n        with contextlib.suppress(ValueError):\n            ret = ExitCode(ret)\n        return RunResult(ret, out, err, instant.elapsed().seconds)\n\n    def _dump_lines(self, lines, fp):\n        try:\n            for line in lines:\n                print(line, file=fp)\n        except UnicodeEncodeError:\n            print(f\"couldn't print to {fp} because of encoding\")\n\n    def _getpytestargs(self) -> tuple[str, ...]:\n        return sys.executable, \"-mpytest\"\n\n    def runpython(self, script: os.PathLike[str]) -> RunResult:\n        \"\"\"Run a python script using sys.executable as interpreter.\"\"\"\n        return self.run(sys.executable, script)\n\n    def runpython_c(self, command: str) -> RunResult:\n        \"\"\"Run ``python -c \"command\"``.\"\"\"\n        return self.run(sys.executable, \"-c\", command)\n\n    def runpytest_subprocess(\n        self, *args: str | os.PathLike[str], timeout: float | None = None\n    ) -> RunResult:\n        \"\"\"Run pytest as a subprocess with given arguments.\n\n        Any plugins added to the :py:attr:`plugins` list will be added using the\n        ``-p`` command line option.  Additionally ``--basetemp`` is used to put\n        any temporary files and directories in a numbered directory prefixed\n        with \"runpytest-\" to not conflict with the normal numbered pytest\n        location for temporary files and directories.\n\n        :param args:\n            The sequence of arguments to pass to the pytest subprocess.\n        :param timeout:\n            The period in seconds after which to timeout and raise\n            :py:class:`Pytester.TimeoutExpired`.\n        :returns:\n            The result.\n        \"\"\"\n        __tracebackhide__ = True\n        p = make_numbered_dir(root=self.path, prefix=\"runpytest-\", mode=0o700)\n        args = (f\"--basetemp={p}\", *args)\n        for plugin in self.plugins:\n            if not isinstance(plugin, str):\n                raise ValueError(\n                    f\"Specifying plugins as objects is not supported in pytester subprocess mode; \"\n                    f\"specify by name instead: {plugin}\"\n                )\n            args = (\"-p\", plugin, *args)\n        args = self._getpytestargs() + args\n        return self.run(*args, timeout=timeout)\n\n    def spawn_pytest(self, string: str, expect_timeout: float = 10.0) -> pexpect.spawn:\n        \"\"\"Run pytest using pexpect.\n\n        This makes sure to use the right pytest and sets up the temporary\n        directory locations.\n\n        The pexpect child is returned.\n        \"\"\"\n        basetemp = self.path / \"temp-pexpect\"\n        basetemp.mkdir(mode=0o700)\n        invoke = \" \".join(map(str, self._getpytestargs()))\n        cmd = f\"{invoke} --basetemp={basetemp} {string}\"\n        return self.spawn(cmd, expect_timeout=expect_timeout)\n\n    def spawn(self, cmd: str, expect_timeout: float = 10.0) -> pexpect.spawn:\n        \"\"\"Run a command using pexpect.\n\n        The pexpect child is returned.\n        \"\"\"\n        pexpect = importorskip(\"pexpect\", \"3.0\")\n        if hasattr(sys, \"pypy_version_info\") and \"64\" in platform.machine():\n            skip(\"pypy-64 bit not supported\")\n        if not hasattr(pexpect, \"spawn\"):\n            skip(\"pexpect.spawn not available\")\n        logfile = self.path.joinpath(\"spawn.out\").open(\"wb\")\n\n        child = pexpect.spawn(cmd, logfile=logfile, timeout=expect_timeout)\n        self._request.addfinalizer(logfile.close)\n        return child\n\n\nclass LineComp:\n    def __init__(self) -> None:\n        self.stringio = StringIO()\n        \"\"\":class:`python:io.StringIO()` instance used for input.\"\"\"\n\n    def assert_contains_lines(self, lines2: Sequence[str]) -> None:\n        \"\"\"Assert that ``lines2`` are contained (linearly) in :attr:`stringio`'s value.\n\n        Lines are matched using :func:`LineMatcher.fnmatch_lines <pytest.LineMatcher.fnmatch_lines>`.\n        \"\"\"\n        __tracebackhide__ = True\n        val = self.stringio.getvalue()\n        self.stringio.truncate(0)\n        self.stringio.seek(0)\n        lines1 = val.split(\"\\n\")\n        LineMatcher(lines1).fnmatch_lines(lines2)\n\n\nclass LineMatcher:\n    \"\"\"Flexible matching of text.\n\n    This is a convenience class to test large texts like the output of\n    commands.\n\n    The constructor takes a list of lines without their trailing newlines, i.e.\n    ``text.splitlines()``.\n    \"\"\"\n\n    def __init__(self, lines: list[str]) -> None:\n        self.lines = lines\n        self._log_output: list[str] = []\n\n    def __str__(self) -> str:\n        \"\"\"Return the entire original text.\n\n        .. versionadded:: 6.2\n            You can use :meth:`str` in older versions.\n        \"\"\"\n        return \"\\n\".join(self.lines)\n\n    def _getlines(self, lines2: str | Sequence[str] | Source) -> Sequence[str]:\n        if isinstance(lines2, str):\n            lines2 = Source(lines2)\n        if isinstance(lines2, Source):\n            lines2 = lines2.strip().lines\n        return lines2\n\n    def fnmatch_lines_random(self, lines2: Sequence[str]) -> None:\n        \"\"\"Check lines exist in the output in any order (using :func:`python:fnmatch.fnmatch`).\"\"\"\n        __tracebackhide__ = True\n        self._match_lines_random(lines2, fnmatch)\n\n    def re_match_lines_random(self, lines2: Sequence[str]) -> None:\n        \"\"\"Check lines exist in the output in any order (using :func:`python:re.match`).\"\"\"\n        __tracebackhide__ = True\n        self._match_lines_random(lines2, lambda name, pat: bool(re.match(pat, name)))\n\n    def _match_lines_random(\n        self, lines2: Sequence[str], match_func: Callable[[str, str], bool]\n    ) -> None:\n        __tracebackhide__ = True\n        lines2 = self._getlines(lines2)\n        for line in lines2:\n            for x in self.lines:\n                if line == x or match_func(x, line):\n                    self._log(\"matched: \", repr(line))\n                    break\n            else:\n                msg = f\"line {line!r} not found in output\"\n                self._log(msg)\n                self._fail(msg)\n\n    def get_lines_after(self, fnline: str) -> Sequence[str]:\n        \"\"\"Return all lines following the given line in the text.\n\n        The given line can contain glob wildcards.\n        \"\"\"\n        for i, line in enumerate(self.lines):\n            if fnline == line or fnmatch(line, fnline):\n                return self.lines[i + 1 :]\n        raise ValueError(f\"line {fnline!r} not found in output\")\n\n    def _log(self, *args) -> None:\n        self._log_output.append(\" \".join(str(x) for x in args))\n\n    @property\n    def _log_text(self) -> str:\n        return \"\\n\".join(self._log_output)\n\n    def fnmatch_lines(\n        self, lines2: Sequence[str], *, consecutive: bool = False\n    ) -> None:\n        \"\"\"Check lines exist in the output (using :func:`python:fnmatch.fnmatch`).\n\n        The argument is a list of lines which have to match and can use glob\n        wildcards.  If they do not match a pytest.fail() is called.  The\n        matches and non-matches are also shown as part of the error message.\n\n        :param lines2: String patterns to match.\n        :param consecutive: Match lines consecutively?\n        \"\"\"\n        __tracebackhide__ = True\n        self._match_lines(lines2, fnmatch, \"fnmatch\", consecutive=consecutive)\n\n    def re_match_lines(\n        self, lines2: Sequence[str], *, consecutive: bool = False\n    ) -> None:\n        \"\"\"Check lines exist in the output (using :func:`python:re.match`).\n\n        The argument is a list of lines which have to match using ``re.match``.\n        If they do not match a pytest.fail() is called.\n\n        The matches and non-matches are also shown as part of the error message.\n\n        :param lines2: string patterns to match.\n        :param consecutive: match lines consecutively?\n        \"\"\"\n        __tracebackhide__ = True\n        self._match_lines(\n            lines2,\n            lambda name, pat: bool(re.match(pat, name)),\n            \"re.match\",\n            consecutive=consecutive,\n        )\n\n    def _match_lines(\n        self,\n        lines2: Sequence[str],\n        match_func: Callable[[str, str], bool],\n        match_nickname: str,\n        *,\n        consecutive: bool = False,\n    ) -> None:\n        \"\"\"Underlying implementation of ``fnmatch_lines`` and ``re_match_lines``.\n\n        :param Sequence[str] lines2:\n            List of string patterns to match. The actual format depends on\n            ``match_func``.\n        :param match_func:\n            A callable ``match_func(line, pattern)`` where line is the\n            captured line from stdout/stderr and pattern is the matching\n            pattern.\n        :param str match_nickname:\n            The nickname for the match function that will be logged to stdout\n            when a match occurs.\n        :param consecutive:\n            Match lines consecutively?\n        \"\"\"\n        if not isinstance(lines2, collections.abc.Sequence):\n            raise TypeError(f\"invalid type for lines2: {type(lines2).__name__}\")\n        lines2 = self._getlines(lines2)\n        lines1 = self.lines[:]\n        extralines = []\n        __tracebackhide__ = True\n        wnick = len(match_nickname) + 1\n        started = False\n        for line in lines2:\n            nomatchprinted = False\n            while lines1:\n                nextline = lines1.pop(0)\n                if line == nextline:\n                    self._log(\"exact match:\", repr(line))\n                    started = True\n                    break\n                elif match_func(nextline, line):\n                    self._log(f\"{match_nickname}:\", repr(line))\n                    self._log(\n                        \"{:>{width}}\".format(\"with:\", width=wnick), repr(nextline)\n                    )\n                    started = True\n                    break\n                else:\n                    if consecutive and started:\n                        msg = f\"no consecutive match: {line!r}\"\n                        self._log(msg)\n                        self._log(\n                            \"{:>{width}}\".format(\"with:\", width=wnick), repr(nextline)\n                        )\n                        self._fail(msg)\n                    if not nomatchprinted:\n                        self._log(\n                            \"{:>{width}}\".format(\"nomatch:\", width=wnick), repr(line)\n                        )\n                        nomatchprinted = True\n                    self._log(\"{:>{width}}\".format(\"and:\", width=wnick), repr(nextline))\n                extralines.append(nextline)\n            else:\n                msg = f\"remains unmatched: {line!r}\"\n                self._log(msg)\n                self._fail(msg)\n        self._log_output = []\n\n    def no_fnmatch_line(self, pat: str) -> None:\n        \"\"\"Ensure captured lines do not match the given pattern, using ``fnmatch.fnmatch``.\n\n        :param str pat: The pattern to match lines.\n        \"\"\"\n        __tracebackhide__ = True\n        self._no_match_line(pat, fnmatch, \"fnmatch\")\n\n    def no_re_match_line(self, pat: str) -> None:\n        \"\"\"Ensure captured lines do not match the given pattern, using ``re.match``.\n\n        :param str pat: The regular expression to match lines.\n        \"\"\"\n        __tracebackhide__ = True\n        self._no_match_line(\n            pat, lambda name, pat: bool(re.match(pat, name)), \"re.match\"\n        )\n\n    def _no_match_line(\n        self, pat: str, match_func: Callable[[str, str], bool], match_nickname: str\n    ) -> None:\n        \"\"\"Ensure captured lines does not have a the given pattern, using ``fnmatch.fnmatch``.\n\n        :param str pat: The pattern to match lines.\n        \"\"\"\n        __tracebackhide__ = True\n        nomatch_printed = False\n        wnick = len(match_nickname) + 1\n        for line in self.lines:\n            if match_func(line, pat):\n                msg = f\"{match_nickname}: {pat!r}\"\n                self._log(msg)\n                self._log(\"{:>{width}}\".format(\"with:\", width=wnick), repr(line))\n                self._fail(msg)\n            else:\n                if not nomatch_printed:\n                    self._log(\"{:>{width}}\".format(\"nomatch:\", width=wnick), repr(pat))\n                    nomatch_printed = True\n                self._log(\"{:>{width}}\".format(\"and:\", width=wnick), repr(line))\n        self._log_output = []\n\n    def _fail(self, msg: str) -> None:\n        __tracebackhide__ = True\n        log_text = self._log_text\n        self._log_output = []\n        fail(log_text)\n\n    def str(self) -> str:\n        \"\"\"Return the entire original text.\"\"\"\n        return str(self)\n"
  },
  {
    "path": "src/_pytest/pytester_assertions.py",
    "content": "\"\"\"Helper plugin for pytester; should not be loaded on its own.\"\"\"\n\n# This plugin contains assertions used by pytester. pytester cannot\n# contain them itself, since it is imported by the `pytest` module,\n# hence cannot be subject to assertion rewriting, which requires a\n# module to not be already imported.\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\n\nfrom _pytest.reports import CollectReport\nfrom _pytest.reports import TestReport\n\n\ndef assertoutcome(\n    outcomes: tuple[\n        Sequence[TestReport],\n        Sequence[CollectReport | TestReport],\n        Sequence[CollectReport | TestReport],\n    ],\n    passed: int = 0,\n    skipped: int = 0,\n    failed: int = 0,\n) -> None:\n    __tracebackhide__ = True\n\n    realpassed, realskipped, realfailed = outcomes\n    obtained = {\n        \"failed\": len(realfailed),\n        \"passed\": len(realpassed),\n        \"skipped\": len(realskipped),\n    }\n    expected = {\"failed\": failed, \"passed\": passed, \"skipped\": skipped}\n    assert obtained == expected, outcomes\n\n\ndef assert_outcomes(\n    outcomes: dict[str, int],\n    passed: int = 0,\n    skipped: int = 0,\n    failed: int = 0,\n    errors: int = 0,\n    xpassed: int = 0,\n    xfailed: int = 0,\n    warnings: int | None = None,\n    deselected: int | None = None,\n) -> None:\n    \"\"\"Assert that the specified outcomes appear with the respective\n    numbers (0 means it didn't occur) in the text output from a test run.\"\"\"\n    __tracebackhide__ = True\n\n    obtained = {\n        \"passed\": outcomes.get(\"passed\", 0),\n        \"skipped\": outcomes.get(\"skipped\", 0),\n        \"failed\": outcomes.get(\"failed\", 0),\n        \"errors\": outcomes.get(\"errors\", 0),\n        \"xpassed\": outcomes.get(\"xpassed\", 0),\n        \"xfailed\": outcomes.get(\"xfailed\", 0),\n    }\n    expected = {\n        \"passed\": passed,\n        \"skipped\": skipped,\n        \"failed\": failed,\n        \"errors\": errors,\n        \"xpassed\": xpassed,\n        \"xfailed\": xfailed,\n    }\n    if warnings is not None:\n        obtained[\"warnings\"] = outcomes.get(\"warnings\", 0)\n        expected[\"warnings\"] = warnings\n    if deselected is not None:\n        obtained[\"deselected\"] = outcomes.get(\"deselected\", 0)\n        expected[\"deselected\"] = deselected\n    assert obtained == expected\n"
  },
  {
    "path": "src/_pytest/python.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Python test discovery, setup and run of test functions.\"\"\"\n\nfrom __future__ import annotations\n\nimport abc\nfrom collections import Counter\nfrom collections import defaultdict\nfrom collections.abc import Callable\nfrom collections.abc import Generator\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nfrom collections.abc import Mapping\nfrom collections.abc import Sequence\nimport dataclasses\nimport enum\nimport fnmatch\nfrom functools import partial\nimport inspect\nimport itertools\nimport os\nfrom pathlib import Path\nimport re\nimport textwrap\nimport types\nfrom typing import Any\nfrom typing import cast\nfrom typing import final\nfrom typing import Literal\nfrom typing import NoReturn\nfrom typing import TYPE_CHECKING\nimport warnings\n\nimport _pytest\nfrom _pytest import fixtures\nfrom _pytest import nodes\nfrom _pytest._code import filter_traceback\nfrom _pytest._code import getfslineno\nfrom _pytest._code.code import ExceptionInfo\nfrom _pytest._code.code import TerminalRepr\nfrom _pytest._code.code import Traceback\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest.compat import ascii_escaped\nfrom _pytest.compat import get_default_arg_names\nfrom _pytest.compat import get_real_func\nfrom _pytest.compat import getimfunc\nfrom _pytest.compat import is_async_function\nfrom _pytest.compat import NOTSET\nfrom _pytest.compat import safe_getattr\nfrom _pytest.compat import safe_isclass\nfrom _pytest.config import Config\nfrom _pytest.config import hookimpl\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.fixtures import _resolve_args_directness\nfrom _pytest.fixtures import FixtureDef\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.fixtures import FuncFixtureInfo\nfrom _pytest.fixtures import get_scope_node\nfrom _pytest.main import Session\nfrom _pytest.mark import ParameterSet\nfrom _pytest.mark.structures import _HiddenParam\nfrom _pytest.mark.structures import get_unpacked_marks\nfrom _pytest.mark.structures import HIDDEN_PARAM\nfrom _pytest.mark.structures import Mark\nfrom _pytest.mark.structures import MarkDecorator\nfrom _pytest.mark.structures import normalize_mark_list\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import skip\nfrom _pytest.pathlib import fnmatch_ex\nfrom _pytest.pathlib import import_path\nfrom _pytest.pathlib import ImportPathMismatchError\nfrom _pytest.pathlib import scandir\nfrom _pytest.scope import _ScopeName\nfrom _pytest.scope import Scope\nfrom _pytest.stash import StashKey\nfrom _pytest.warning_types import PytestCollectionWarning\nfrom _pytest.warning_types import PytestReturnNotNoneWarning\n\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    parser.addini(\n        \"python_files\",\n        type=\"args\",\n        # NOTE: default is also used in AssertionRewritingHook.\n        default=[\"test_*.py\", \"*_test.py\"],\n        help=\"Glob-style file patterns for Python test module discovery\",\n    )\n    parser.addini(\n        \"python_classes\",\n        type=\"args\",\n        default=[\"Test\"],\n        help=\"Prefixes or glob names for Python test class discovery\",\n    )\n    parser.addini(\n        \"python_functions\",\n        type=\"args\",\n        default=[\"test\"],\n        help=\"Prefixes or glob names for Python test function and method discovery\",\n    )\n    parser.addini(\n        \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\",\n        type=\"bool\",\n        default=False,\n        help=\"Disable string escape non-ASCII characters, might cause unwanted \"\n        \"side effects(use at your own risk)\",\n    )\n    parser.addini(\n        \"strict_parametrization_ids\",\n        type=\"bool\",\n        # None => fallback to `strict`.\n        default=None,\n        help=\"Emit an error if non-unique parameter set IDs are detected\",\n    )\n\n\ndef pytest_generate_tests(metafunc: Metafunc) -> None:\n    for marker in metafunc.definition.iter_markers(name=\"parametrize\"):\n        metafunc.parametrize(*marker.args, **marker.kwargs, _param_mark=marker)\n\n\ndef pytest_configure(config: Config) -> None:\n    config.addinivalue_line(\n        \"markers\",\n        \"parametrize(argnames, argvalues): call a test function multiple \"\n        \"times passing in different arguments in turn. argvalues generally \"\n        \"needs to be a list of values if argnames specifies only one name \"\n        \"or a list of tuples of values if argnames specifies multiple names. \"\n        \"Example: @parametrize('arg1', [1,2]) would lead to two calls of the \"\n        \"decorated test function, one with arg1=1 and another with arg1=2.\"\n        \"see https://docs.pytest.org/en/stable/how-to/parametrize.html for more info \"\n        \"and examples.\",\n    )\n    config.addinivalue_line(\n        \"markers\",\n        \"usefixtures(fixturename1, fixturename2, ...): mark tests as needing \"\n        \"all of the specified fixtures. see \"\n        \"https://docs.pytest.org/en/stable/explanation/fixtures.html#usefixtures \",\n    )\n\n\ndef async_fail(nodeid: str) -> None:\n    msg = (\n        \"async def functions are not natively supported.\\n\"\n        \"You need to install a suitable plugin for your async framework, for example:\\n\"\n        \"  - anyio\\n\"\n        \"  - pytest-asyncio\\n\"\n        \"  - pytest-tornasync\\n\"\n        \"  - pytest-trio\\n\"\n        \"  - pytest-twisted\"\n    )\n    fail(msg, pytrace=False)\n\n\n@hookimpl(trylast=True)\ndef pytest_pyfunc_call(pyfuncitem: Function) -> object | None:\n    testfunction = pyfuncitem.obj\n    if is_async_function(testfunction):\n        async_fail(pyfuncitem.nodeid)\n    funcargs = pyfuncitem.funcargs\n    testargs = {arg: funcargs[arg] for arg in pyfuncitem._fixtureinfo.argnames}\n    result = testfunction(**testargs)\n    if hasattr(result, \"__await__\") or hasattr(result, \"__aiter__\"):\n        async_fail(pyfuncitem.nodeid)\n    elif result is not None:\n        warnings.warn(\n            PytestReturnNotNoneWarning(\n                f\"Test functions should return None, but {pyfuncitem.nodeid} returned {type(result)!r}.\\n\"\n                \"Did you mean to use `assert` instead of `return`?\\n\"\n                \"See https://docs.pytest.org/en/stable/how-to/assert.html#return-not-none for more information.\"\n            )\n        )\n    return True\n\n\ndef pytest_collect_directory(\n    path: Path, parent: nodes.Collector\n) -> nodes.Collector | None:\n    pkginit = path / \"__init__.py\"\n    try:\n        has_pkginit = pkginit.is_file()\n    except PermissionError:\n        # See https://github.com/pytest-dev/pytest/issues/12120#issuecomment-2106349096.\n        return None\n    if has_pkginit:\n        return Package.from_parent(parent, path=path)\n    return None\n\n\ndef pytest_collect_file(file_path: Path, parent: nodes.Collector) -> Module | None:\n    if file_path.suffix == \".py\":\n        if not parent.session.isinitpath(file_path):\n            if not path_matches_patterns(\n                file_path, parent.config.getini(\"python_files\")\n            ):\n                return None\n        ihook = parent.session.gethookproxy(file_path)\n        module: Module = ihook.pytest_pycollect_makemodule(\n            module_path=file_path, parent=parent\n        )\n        return module\n    return None\n\n\ndef path_matches_patterns(path: Path, patterns: Iterable[str]) -> bool:\n    \"\"\"Return whether path matches any of the patterns in the list of globs given.\"\"\"\n    return any(fnmatch_ex(pattern, path) for pattern in patterns)\n\n\ndef pytest_pycollect_makemodule(module_path: Path, parent) -> Module:\n    return Module.from_parent(parent, path=module_path)\n\n\n@hookimpl(trylast=True)\ndef pytest_pycollect_makeitem(\n    collector: Module | Class, name: str, obj: object\n) -> None | nodes.Item | nodes.Collector | list[nodes.Item | nodes.Collector]:\n    assert isinstance(collector, Class | Module), type(collector)\n    # Nothing was collected elsewhere, let's do it here.\n    if safe_isclass(obj):\n        if collector.istestclass(obj, name):\n            return Class.from_parent(collector, name=name, obj=obj)\n    elif collector.istestfunction(obj, name):\n        # mock seems to store unbound methods (issue473), normalize it.\n        obj = getattr(obj, \"__func__\", obj)\n        # We need to try and unwrap the function if it's a functools.partial\n        # or a functools.wrapped.\n        # We mustn't if it's been wrapped with mock.patch (python 2 only).\n        if not (inspect.isfunction(obj) or inspect.isfunction(get_real_func(obj))):\n            filename, lineno = getfslineno(obj)\n            warnings.warn_explicit(\n                message=PytestCollectionWarning(\n                    f\"cannot collect {name!r} because it is not a function.\"\n                ),\n                category=None,\n                filename=str(filename),\n                lineno=lineno + 1,\n            )\n        elif getattr(obj, \"__test__\", True):\n            if inspect.isgeneratorfunction(obj):\n                fail(\n                    f\"'yield' keyword is allowed in fixtures, but not in tests ({name})\",\n                    pytrace=False,\n                )\n            return list(collector._genfunctions(name, obj))\n        return None\n    return None\n\n\nclass PyobjMixin(nodes.Node):\n    \"\"\"this mix-in inherits from Node to carry over the typing information\n\n    as its intended to always mix in before a node\n    its position in the mro is unaffected\"\"\"\n\n    _ALLOW_MARKERS = True\n\n    @property\n    def module(self):\n        \"\"\"Python module object this node was collected from (can be None).\"\"\"\n        node = self.getparent(Module)\n        return node.obj if node is not None else None\n\n    @property\n    def cls(self):\n        \"\"\"Python class object this node was collected from (can be None).\"\"\"\n        node = self.getparent(Class)\n        return node.obj if node is not None else None\n\n    @property\n    def instance(self):\n        \"\"\"Python instance object the function is bound to.\n\n        Returns None if not a test method, e.g. for a standalone test function,\n        a class or a module.\n        \"\"\"\n        # Overridden by Function.\n        return None\n\n    @property\n    def obj(self):\n        \"\"\"Underlying Python object.\"\"\"\n        obj = getattr(self, \"_obj\", None)\n        if obj is None:\n            self._obj = obj = self._getobj()\n            # XXX evil hack\n            # used to avoid Function marker duplication\n            if self._ALLOW_MARKERS:\n                self.own_markers.extend(get_unpacked_marks(self.obj))\n                # This assumes that `obj` is called before there is a chance\n                # to add custom keys to `self.keywords`, so no fear of overriding.\n                self.keywords.update((mark.name, mark) for mark in self.own_markers)\n        return obj\n\n    @obj.setter\n    def obj(self, value):\n        self._obj = value\n\n    def _getobj(self):\n        \"\"\"Get the underlying Python object. May be overwritten by subclasses.\"\"\"\n        # TODO: Improve the type of `parent` such that assert/ignore aren't needed.\n        assert self.parent is not None\n        obj = self.parent.obj  # type: ignore[attr-defined]\n        return getattr(obj, self.name)\n\n    def getmodpath(self, stopatmodule: bool = True, includemodule: bool = False) -> str:\n        \"\"\"Return Python path relative to the containing module.\"\"\"\n        parts = []\n        for node in self.iter_parents():\n            name = node.name\n            if isinstance(node, Module):\n                name = os.path.splitext(name)[0]\n                if stopatmodule:\n                    if includemodule:\n                        parts.append(name)\n                    break\n            parts.append(name)\n        parts.reverse()\n        return \".\".join(parts)\n\n    def reportinfo(self) -> tuple[os.PathLike[str] | str, int | None, str]:\n        # XXX caching?\n        path, lineno = getfslineno(self.obj)\n        modpath = self.getmodpath()\n        return path, lineno, modpath\n\n\n# As an optimization, these builtin attribute names are pre-ignored when\n# iterating over an object during collection -- the pytest_pycollect_makeitem\n# hook is not called for them.\n# fmt: off\nclass _EmptyClass: pass  # noqa: E701\nIGNORED_ATTRIBUTES = frozenset.union(\n    frozenset(),\n    # Module.\n    dir(types.ModuleType(\"empty_module\")),\n    # Some extra module attributes the above doesn't catch.\n    {\"__builtins__\", \"__file__\", \"__cached__\"},\n    # Class.\n    dir(_EmptyClass),\n    # Instance.\n    dir(_EmptyClass()),\n)\ndel _EmptyClass\n# fmt: on\n\n\nclass PyCollector(PyobjMixin, nodes.Collector, abc.ABC):\n    def funcnamefilter(self, name: str) -> bool:\n        return self._matches_prefix_or_glob_option(\"python_functions\", name)\n\n    def isnosetest(self, obj: object) -> bool:\n        \"\"\"Look for the __test__ attribute, which is applied by the\n        @nose.tools.istest decorator.\n        \"\"\"\n        # We explicitly check for \"is True\" here to not mistakenly treat\n        # classes with a custom __getattr__ returning something truthy (like a\n        # function) as test classes.\n        return safe_getattr(obj, \"__test__\", False) is True\n\n    def classnamefilter(self, name: str) -> bool:\n        return self._matches_prefix_or_glob_option(\"python_classes\", name)\n\n    def istestfunction(self, obj: object, name: str) -> bool:\n        if self.funcnamefilter(name) or self.isnosetest(obj):\n            if isinstance(obj, staticmethod | classmethod):\n                # staticmethods and classmethods need to be unwrapped.\n                obj = safe_getattr(obj, \"__func__\", False)\n            return callable(obj) and fixtures.getfixturemarker(obj) is None\n        else:\n            return False\n\n    def istestclass(self, obj: object, name: str) -> bool:\n        if not (self.classnamefilter(name) or self.isnosetest(obj)):\n            return False\n        if inspect.isabstract(obj):\n            return False\n        return True\n\n    def _matches_prefix_or_glob_option(self, option_name: str, name: str) -> bool:\n        \"\"\"Check if the given name matches the prefix or glob-pattern defined\n        in configuration.\"\"\"\n        for option in self.config.getini(option_name):\n            if name.startswith(option):\n                return True\n            # Check that name looks like a glob-string before calling fnmatch\n            # because this is called for every name in each collected module,\n            # and fnmatch is somewhat expensive to call.\n            elif (\"*\" in option or \"?\" in option or \"[\" in option) and fnmatch.fnmatch(\n                name, option\n            ):\n                return True\n        return False\n\n    def collect(self) -> Iterable[nodes.Item | nodes.Collector]:\n        if not getattr(self.obj, \"__test__\", True):\n            return []\n\n        # Avoid random getattrs and peek in the __dict__ instead.\n        dicts = [getattr(self.obj, \"__dict__\", {})]\n        if isinstance(self.obj, type):\n            for basecls in self.obj.__mro__:\n                dicts.append(basecls.__dict__)\n\n        # In each class, nodes should be definition ordered.\n        # __dict__ is definition ordered.\n        seen: set[str] = set()\n        dict_values: list[list[nodes.Item | nodes.Collector]] = []\n        collect_imported_tests = self.session.config.getini(\"collect_imported_tests\")\n        ihook = self.ihook\n        for dic in dicts:\n            values: list[nodes.Item | nodes.Collector] = []\n            # Note: seems like the dict can change during iteration -\n            # be careful not to remove the list() without consideration.\n            for name, obj in list(dic.items()):\n                if name in IGNORED_ATTRIBUTES:\n                    continue\n                if name in seen:\n                    continue\n                seen.add(name)\n\n                if not collect_imported_tests and isinstance(self, Module):\n                    # Do not collect functions and classes from other modules.\n                    if inspect.isfunction(obj) or inspect.isclass(obj):\n                        if obj.__module__ != self._getobj().__name__:\n                            continue\n\n                res = ihook.pytest_pycollect_makeitem(\n                    collector=self, name=name, obj=obj\n                )\n                if res is None:\n                    continue\n                elif isinstance(res, list):\n                    values.extend(res)\n                else:\n                    values.append(res)\n            dict_values.append(values)\n\n        # Between classes in the class hierarchy, reverse-MRO order -- nodes\n        # inherited from base classes should come before subclasses.\n        result = []\n        for values in reversed(dict_values):\n            result.extend(values)\n        return result\n\n    def _genfunctions(self, name: str, funcobj) -> Iterator[Function]:\n        modulecol = self.getparent(Module)\n        assert modulecol is not None\n        module = modulecol.obj\n        clscol = self.getparent(Class)\n        cls = (clscol and clscol.obj) or None\n\n        definition = FunctionDefinition.from_parent(self, name=name, callobj=funcobj)\n        fixtureinfo = definition._fixtureinfo\n\n        # pytest_generate_tests impls call metafunc.parametrize() which fills\n        # metafunc._calls, the outcome of the hook.\n        metafunc = Metafunc(\n            definition=definition,\n            fixtureinfo=fixtureinfo,\n            config=self.config,\n            cls=cls,\n            module=module,\n            _ispytest=True,\n        )\n        methods = []\n        if hasattr(module, \"pytest_generate_tests\"):\n            methods.append(module.pytest_generate_tests)\n        if cls is not None and hasattr(cls, \"pytest_generate_tests\"):\n            methods.append(cls().pytest_generate_tests)\n        self.ihook.pytest_generate_tests.call_extra(methods, dict(metafunc=metafunc))\n\n        if not metafunc._calls:\n            yield Function.from_parent(self, name=name, fixtureinfo=fixtureinfo)\n        else:\n            metafunc._recompute_direct_params_indices()\n            # Direct parametrizations taking place in module/class-specific\n            # `metafunc.parametrize` calls may have shadowed some fixtures, so make sure\n            # we update what the function really needs a.k.a its fixture closure. Note that\n            # direct parametrizations using `@pytest.mark.parametrize` have already been considered\n            # into making the closure using `ignore_args` arg to `getfixtureclosure`.\n            fixtureinfo.prune_dependency_tree()\n\n            for callspec in metafunc._calls:\n                subname = f\"{name}[{callspec.id}]\" if callspec._idlist else name\n                yield Function.from_parent(\n                    self,\n                    name=subname,\n                    callspec=callspec,\n                    fixtureinfo=fixtureinfo,\n                    keywords={callspec.id: True},\n                    originalname=name,\n                )\n\n\ndef importtestmodule(\n    path: Path,\n    config: Config,\n):\n    # We assume we are only called once per module.\n    importmode = config.getoption(\"--import-mode\")\n    try:\n        mod = import_path(\n            path,\n            mode=importmode,\n            root=config.rootpath,\n            consider_namespace_packages=config.getini(\"consider_namespace_packages\"),\n        )\n    except SyntaxError as e:\n        raise nodes.Collector.CollectError(\n            ExceptionInfo.from_current().getrepr(style=\"short\")\n        ) from e\n    except ImportPathMismatchError as e:\n        raise nodes.Collector.CollectError(\n            \"import file mismatch:\\n\"\n            \"imported module {!r} has this __file__ attribute:\\n\"\n            \"  {}\\n\"\n            \"which is not the same as the test file we want to collect:\\n\"\n            \"  {}\\n\"\n            \"HINT: remove __pycache__ / .pyc files and/or use a \"\n            \"unique basename for your test file modules\".format(*e.args)\n        ) from e\n    except ImportError as e:\n        exc_info = ExceptionInfo.from_current()\n        if config.get_verbosity() < 2:\n            exc_info.traceback = exc_info.traceback.filter(filter_traceback)\n        exc_repr = (\n            exc_info.getrepr(style=\"short\")\n            if exc_info.traceback\n            else exc_info.exconly()\n        )\n        formatted_tb = str(exc_repr)\n        raise nodes.Collector.CollectError(\n            f\"ImportError while importing test module '{path}'.\\n\"\n            \"Hint: make sure your test modules/packages have valid Python names.\\n\"\n            \"Traceback:\\n\"\n            f\"{formatted_tb}\"\n        ) from e\n    except skip.Exception as e:\n        if e.allow_module_level:\n            raise\n        raise nodes.Collector.CollectError(\n            \"Using pytest.skip outside of a test will skip the entire module. \"\n            \"If that's your intention, pass `allow_module_level=True`. \"\n            \"If you want to skip a specific test or an entire class, \"\n            \"use the @pytest.mark.skip or @pytest.mark.skipif decorators.\"\n        ) from e\n    config.pluginmanager.consider_module(mod)\n    return mod\n\n\nclass Module(nodes.File, PyCollector):\n    \"\"\"Collector for test classes and functions in a Python module.\"\"\"\n\n    def _getobj(self):\n        return importtestmodule(self.path, self.config)\n\n    def collect(self) -> Iterable[nodes.Item | nodes.Collector]:\n        self._register_setup_module_fixture()\n        self._register_setup_function_fixture()\n        self.session._fixturemanager.parsefactories(self)\n        return super().collect()\n\n    def _register_setup_module_fixture(self) -> None:\n        \"\"\"Register an autouse, module-scoped fixture for the collected module object\n        that invokes setUpModule/tearDownModule if either or both are available.\n\n        Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n        other fixtures (#517).\n        \"\"\"\n        setup_module = _get_first_non_fixture_func(\n            self.obj, (\"setUpModule\", \"setup_module\")\n        )\n        teardown_module = _get_first_non_fixture_func(\n            self.obj, (\"tearDownModule\", \"teardown_module\")\n        )\n\n        if setup_module is None and teardown_module is None:\n            return\n\n        def xunit_setup_module_fixture(request) -> Generator[None]:\n            module = request.module\n            if setup_module is not None:\n                _call_with_optional_argument(setup_module, module)\n            yield\n            if teardown_module is not None:\n                _call_with_optional_argument(teardown_module, module)\n\n        self.session._fixturemanager._register_fixture(\n            # Use a unique name to speed up lookup.\n            name=f\"_xunit_setup_module_fixture_{self.obj.__name__}\",\n            func=xunit_setup_module_fixture,\n            nodeid=self.nodeid,\n            scope=\"module\",\n            autouse=True,\n        )\n\n    def _register_setup_function_fixture(self) -> None:\n        \"\"\"Register an autouse, function-scoped fixture for the collected module object\n        that invokes setup_function/teardown_function if either or both are available.\n\n        Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n        other fixtures (#517).\n        \"\"\"\n        setup_function = _get_first_non_fixture_func(self.obj, (\"setup_function\",))\n        teardown_function = _get_first_non_fixture_func(\n            self.obj, (\"teardown_function\",)\n        )\n        if setup_function is None and teardown_function is None:\n            return\n\n        def xunit_setup_function_fixture(request) -> Generator[None]:\n            if request.instance is not None:\n                # in this case we are bound to an instance, so we need to let\n                # setup_method handle this\n                yield\n                return\n            function = request.function\n            if setup_function is not None:\n                _call_with_optional_argument(setup_function, function)\n            yield\n            if teardown_function is not None:\n                _call_with_optional_argument(teardown_function, function)\n\n        self.session._fixturemanager._register_fixture(\n            # Use a unique name to speed up lookup.\n            name=f\"_xunit_setup_function_fixture_{self.obj.__name__}\",\n            func=xunit_setup_function_fixture,\n            nodeid=self.nodeid,\n            scope=\"function\",\n            autouse=True,\n        )\n\n\nclass Package(nodes.Directory):\n    \"\"\"Collector for files and directories in a Python packages -- directories\n    with an `__init__.py` file.\n\n    .. note::\n\n        Directories without an `__init__.py` file are instead collected by\n        :class:`~pytest.Dir` by default. Both are :class:`~pytest.Directory`\n        collectors.\n\n    .. versionchanged:: 8.0\n\n        Now inherits from :class:`~pytest.Directory`.\n    \"\"\"\n\n    def __init__(\n        self,\n        fspath: None,\n        parent: nodes.Collector,\n        # NOTE: following args are unused:\n        config=None,\n        session=None,\n        nodeid=None,\n        path: Path | None = None,\n    ) -> None:\n        # NOTE: Could be just the following, but kept as-is for compat.\n        # super().__init__(self, fspath, parent=parent)\n        session = parent.session\n        super().__init__(\n            fspath=fspath,\n            path=path,\n            parent=parent,\n            config=config,\n            session=session,\n            nodeid=nodeid,\n        )\n\n    def setup(self) -> None:\n        init_mod = importtestmodule(self.path / \"__init__.py\", self.config)\n\n        # Not using fixtures to call setup_module here because autouse fixtures\n        # from packages are not called automatically (#4085).\n        setup_module = _get_first_non_fixture_func(\n            init_mod, (\"setUpModule\", \"setup_module\")\n        )\n        if setup_module is not None:\n            _call_with_optional_argument(setup_module, init_mod)\n\n        teardown_module = _get_first_non_fixture_func(\n            init_mod, (\"tearDownModule\", \"teardown_module\")\n        )\n        if teardown_module is not None:\n            func = partial(_call_with_optional_argument, teardown_module, init_mod)\n            self.addfinalizer(func)\n\n    def collect(self) -> Iterable[nodes.Item | nodes.Collector]:\n        # Always collect __init__.py first.\n        def sort_key(entry: os.DirEntry[str]) -> object:\n            return (entry.name != \"__init__.py\", entry.name)\n\n        config = self.config\n        col: nodes.Collector | None\n        cols: Sequence[nodes.Collector]\n        ihook = self.ihook\n        for direntry in scandir(self.path, sort_key):\n            if direntry.is_dir():\n                path = Path(direntry.path)\n                if not self.session.isinitpath(path, with_parents=True):\n                    if ihook.pytest_ignore_collect(collection_path=path, config=config):\n                        continue\n                col = ihook.pytest_collect_directory(path=path, parent=self)\n                if col is not None:\n                    yield col\n\n            elif direntry.is_file():\n                path = Path(direntry.path)\n                if not self.session.isinitpath(path):\n                    if ihook.pytest_ignore_collect(collection_path=path, config=config):\n                        continue\n                cols = ihook.pytest_collect_file(file_path=path, parent=self)\n                yield from cols\n\n\ndef _call_with_optional_argument(func, arg) -> None:\n    \"\"\"Call the given function with the given argument if func accepts one argument, otherwise\n    calls func without arguments.\"\"\"\n    arg_count = func.__code__.co_argcount\n    if inspect.ismethod(func):\n        arg_count -= 1\n    if arg_count:\n        func(arg)\n    else:\n        func()\n\n\ndef _get_first_non_fixture_func(obj: object, names: Iterable[str]) -> object | None:\n    \"\"\"Return the attribute from the given object to be used as a setup/teardown\n    xunit-style function, but only if not marked as a fixture to avoid calling it twice.\n    \"\"\"\n    for name in names:\n        meth: object | None = getattr(obj, name, None)\n        if meth is not None and fixtures.getfixturemarker(meth) is None:\n            return meth\n    return None\n\n\nclass Class(PyCollector):\n    \"\"\"Collector for test methods (and nested classes) in a Python class.\"\"\"\n\n    @classmethod\n    def from_parent(cls, parent, *, name, obj=None, **kw) -> Self:  # type: ignore[override]\n        \"\"\"The public constructor.\"\"\"\n        return super().from_parent(name=name, parent=parent, **kw)\n\n    def newinstance(self):\n        return self.obj()\n\n    def collect(self) -> Iterable[nodes.Item | nodes.Collector]:\n        if not safe_getattr(self.obj, \"__test__\", True):\n            return []\n        if hasinit(self.obj):\n            assert self.parent is not None\n            self.warn(\n                PytestCollectionWarning(\n                    f\"cannot collect test class {self.obj.__name__!r} because it has a \"\n                    f\"__init__ constructor (from: {self.parent.nodeid})\"\n                )\n            )\n            return []\n        elif hasnew(self.obj):\n            assert self.parent is not None\n            self.warn(\n                PytestCollectionWarning(\n                    f\"cannot collect test class {self.obj.__name__!r} because it has a \"\n                    f\"__new__ constructor (from: {self.parent.nodeid})\"\n                )\n            )\n            return []\n\n        self._register_setup_class_fixture()\n        self._register_setup_method_fixture()\n\n        self.session._fixturemanager.parsefactories(self.newinstance(), self.nodeid)\n\n        return super().collect()\n\n    def _register_setup_class_fixture(self) -> None:\n        \"\"\"Register an autouse, class scoped fixture into the collected class object\n        that invokes setup_class/teardown_class if either or both are available.\n\n        Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with\n        other fixtures (#517).\n        \"\"\"\n        setup_class = _get_first_non_fixture_func(self.obj, (\"setup_class\",))\n        teardown_class = _get_first_non_fixture_func(self.obj, (\"teardown_class\",))\n        if setup_class is None and teardown_class is None:\n            return\n\n        def xunit_setup_class_fixture(request) -> Generator[None]:\n            cls = request.cls\n            if setup_class is not None:\n                func = getimfunc(setup_class)\n                _call_with_optional_argument(func, cls)\n            yield\n            if teardown_class is not None:\n                func = getimfunc(teardown_class)\n                _call_with_optional_argument(func, cls)\n\n        self.session._fixturemanager._register_fixture(\n            # Use a unique name to speed up lookup.\n            name=f\"_xunit_setup_class_fixture_{self.obj.__qualname__}\",\n            func=xunit_setup_class_fixture,\n            nodeid=self.nodeid,\n            scope=\"class\",\n            autouse=True,\n        )\n\n    def _register_setup_method_fixture(self) -> None:\n        \"\"\"Register an autouse, function scoped fixture into the collected class object\n        that invokes setup_method/teardown_method if either or both are available.\n\n        Using a fixture to invoke these methods ensures we play nicely and unsurprisingly with\n        other fixtures (#517).\n        \"\"\"\n        setup_name = \"setup_method\"\n        setup_method = _get_first_non_fixture_func(self.obj, (setup_name,))\n        teardown_name = \"teardown_method\"\n        teardown_method = _get_first_non_fixture_func(self.obj, (teardown_name,))\n        if setup_method is None and teardown_method is None:\n            return\n\n        def xunit_setup_method_fixture(request) -> Generator[None]:\n            instance = request.instance\n            method = request.function\n            if setup_method is not None:\n                func = getattr(instance, setup_name)\n                _call_with_optional_argument(func, method)\n            yield\n            if teardown_method is not None:\n                func = getattr(instance, teardown_name)\n                _call_with_optional_argument(func, method)\n\n        self.session._fixturemanager._register_fixture(\n            # Use a unique name to speed up lookup.\n            name=f\"_xunit_setup_method_fixture_{self.obj.__qualname__}\",\n            func=xunit_setup_method_fixture,\n            nodeid=self.nodeid,\n            scope=\"function\",\n            autouse=True,\n        )\n\n\ndef hasinit(obj: object) -> bool:\n    init: object = getattr(obj, \"__init__\", None)\n    if init:\n        return init != object.__init__\n    return False\n\n\ndef hasnew(obj: object) -> bool:\n    new: object = getattr(obj, \"__new__\", None)\n    if new:\n        return new != object.__new__\n    return False\n\n\n@final\n@dataclasses.dataclass(frozen=True)\nclass IdMaker:\n    \"\"\"Make IDs for a parametrization.\"\"\"\n\n    __slots__ = (\n        \"argnames\",\n        \"config\",\n        \"idfn\",\n        \"ids\",\n        \"nodeid\",\n        \"parametersets\",\n    )\n\n    # The argnames of the parametrization.\n    argnames: Sequence[str]\n    # The ParameterSets of the parametrization.\n    parametersets: Sequence[ParameterSet]\n    # Optionally, a user-provided callable to make IDs for parameters in a\n    # ParameterSet.\n    idfn: Callable[[Any], object | None] | None\n    # Optionally, explicit IDs for ParameterSets by index.\n    ids: Sequence[object | None] | None\n    # Optionally, the pytest config.\n    # Used for controlling ASCII escaping, determining parametrization ID\n    # strictness, and for calling the :hook:`pytest_make_parametrize_id` hook.\n    config: Config | None\n    # Optionally, the ID of the node being parametrized.\n    # Used only for clearer error messages.\n    nodeid: str | None\n\n    def make_unique_parameterset_ids(self) -> list[str | _HiddenParam]:\n        \"\"\"Make a unique identifier for each ParameterSet, that may be used to\n        identify the parametrization in a node ID.\n\n        If strict_parametrization_ids is enabled, and duplicates are detected,\n        raises CollectError. Otherwise makes the IDs unique as follows:\n\n        Format is <prm_1_token>-...-<prm_n_token>[counter], where prm_x_token is\n        - user-provided id, if given\n        - else an id derived from the value, applicable for certain types\n        - else <argname><parameterset index>\n        The counter suffix is appended only in case a string wouldn't be unique\n        otherwise.\n        \"\"\"\n        resolved_ids = list(self._resolve_ids())\n        # All IDs must be unique!\n        if len(resolved_ids) != len(set(resolved_ids)):\n            # Record the number of occurrences of each ID.\n            id_counts = Counter(resolved_ids)\n\n            if self._strict_parametrization_ids_enabled():\n                parameters = \", \".join(self.argnames)\n                parametersets = \", \".join(\n                    [saferepr(list(param.values)) for param in self.parametersets]\n                )\n                ids = \", \".join(\n                    id if id is not HIDDEN_PARAM else \"<hidden>\" for id in resolved_ids\n                )\n                duplicates = \", \".join(\n                    id if id is not HIDDEN_PARAM else \"<hidden>\"\n                    for id, count in id_counts.items()\n                    if count > 1\n                )\n                msg = textwrap.dedent(f\"\"\"\n                    Duplicate parametrization IDs detected, but strict_parametrization_ids is set.\n\n                    Test name:      {self.nodeid}\n                    Parameters:     {parameters}\n                    Parameter sets: {parametersets}\n                    IDs:            {ids}\n                    Duplicates:     {duplicates}\n\n                    You can fix this problem using `@pytest.mark.parametrize(..., ids=...)` or `pytest.param(..., id=...)`.\n                \"\"\").strip()  # noqa: E501\n                raise nodes.Collector.CollectError(msg)\n\n            # Map the ID to its next suffix.\n            id_suffixes: dict[str, int] = defaultdict(int)\n            # Suffix non-unique IDs to make them unique.\n            for index, id in enumerate(resolved_ids):\n                if id_counts[id] > 1:\n                    if id is HIDDEN_PARAM:\n                        self._complain_multiple_hidden_parameter_sets()\n                    suffix = \"\"\n                    if id and id[-1].isdigit():\n                        suffix = \"_\"\n                    new_id = f\"{id}{suffix}{id_suffixes[id]}\"\n                    while new_id in set(resolved_ids):\n                        id_suffixes[id] += 1\n                        new_id = f\"{id}{suffix}{id_suffixes[id]}\"\n                    resolved_ids[index] = new_id\n                    id_suffixes[id] += 1\n        assert len(resolved_ids) == len(set(resolved_ids)), (\n            f\"Internal error: {resolved_ids=}\"\n        )\n        return resolved_ids\n\n    def _strict_parametrization_ids_enabled(self) -> bool:\n        if self.config is None:\n            return False\n        strict_parametrization_ids = self.config.getini(\"strict_parametrization_ids\")\n        if strict_parametrization_ids is None:\n            strict_parametrization_ids = self.config.getini(\"strict\")\n        return cast(bool, strict_parametrization_ids)\n\n    def _resolve_ids(self) -> Iterable[str | _HiddenParam]:\n        \"\"\"Resolve IDs for all ParameterSets (may contain duplicates).\"\"\"\n        for idx, parameterset in enumerate(self.parametersets):\n            if parameterset.id is not None:\n                # ID provided directly - pytest.param(..., id=\"...\")\n                if parameterset.id is HIDDEN_PARAM:\n                    yield HIDDEN_PARAM\n                else:\n                    yield _ascii_escaped_by_config(parameterset.id, self.config)\n            elif self.ids and idx < len(self.ids) and self.ids[idx] is not None:\n                # ID provided in the IDs list - parametrize(..., ids=[...]).\n                if self.ids[idx] is HIDDEN_PARAM:\n                    yield HIDDEN_PARAM\n                else:\n                    yield self._idval_from_value_required(self.ids[idx], idx)\n            else:\n                # ID not provided - generate it.\n                yield \"-\".join(\n                    self._idval(val, argname, idx)\n                    for val, argname in zip(\n                        parameterset.values, self.argnames, strict=True\n                    )\n                )\n\n    def _idval(self, val: object, argname: str, idx: int) -> str:\n        \"\"\"Make an ID for a parameter in a ParameterSet.\"\"\"\n        idval = self._idval_from_function(val, argname, idx)\n        if idval is not None:\n            return idval\n        idval = self._idval_from_hook(val, argname)\n        if idval is not None:\n            return idval\n        idval = self._idval_from_value(val)\n        if idval is not None:\n            return idval\n        return self._idval_from_argname(argname, idx)\n\n    def _idval_from_function(self, val: object, argname: str, idx: int) -> str | None:\n        \"\"\"Try to make an ID for a parameter in a ParameterSet using the\n        user-provided id callable, if given.\"\"\"\n        if self.idfn is None:\n            return None\n        try:\n            id = self.idfn(val)\n        except Exception as e:\n            prefix = f\"{self.nodeid}: \" if self.nodeid is not None else \"\"\n            msg = \"error raised while trying to determine id of parameter '{}' at position {}\"\n            msg = prefix + msg.format(argname, idx)\n            raise ValueError(msg) from e\n        if id is None:\n            return None\n        return self._idval_from_value(id)\n\n    def _idval_from_hook(self, val: object, argname: str) -> str | None:\n        \"\"\"Try to make an ID for a parameter in a ParameterSet by calling the\n        :hook:`pytest_make_parametrize_id` hook.\"\"\"\n        if self.config:\n            id: str | None = self.config.hook.pytest_make_parametrize_id(\n                config=self.config, val=val, argname=argname\n            )\n            return id\n        return None\n\n    def _idval_from_value(self, val: object) -> str | None:\n        \"\"\"Try to make an ID for a parameter in a ParameterSet from its value,\n        if the value type is supported.\"\"\"\n        if isinstance(val, str | bytes):\n            return _ascii_escaped_by_config(val, self.config)\n        elif val is None or isinstance(val, float | int | bool | complex):\n            return str(val)\n        elif isinstance(val, re.Pattern):\n            return ascii_escaped(val.pattern)\n        elif val is NOTSET:\n            # Fallback to default. Note that NOTSET is an enum.Enum.\n            pass\n        elif isinstance(val, enum.Enum):\n            return str(val)\n        elif isinstance(getattr(val, \"__name__\", None), str):\n            # Name of a class, function, module, etc.\n            name: str = getattr(val, \"__name__\")\n            return name\n        return None\n\n    def _idval_from_value_required(self, val: object, idx: int) -> str:\n        \"\"\"Like _idval_from_value(), but fails if the type is not supported.\"\"\"\n        id = self._idval_from_value(val)\n        if id is not None:\n            return id\n\n        # Fail.\n        prefix = self._make_error_prefix()\n        msg = (\n            f\"{prefix}ids contains unsupported value {saferepr(val)} (type: {type(val)!r}) at index {idx}. \"\n            \"Supported types are: str, bytes, int, float, complex, bool, enum, regex or anything with a __name__.\"\n        )\n        fail(msg, pytrace=False)\n\n    @staticmethod\n    def _idval_from_argname(argname: str, idx: int) -> str:\n        \"\"\"Make an ID for a parameter in a ParameterSet from the argument name\n        and the index of the ParameterSet.\"\"\"\n        return str(argname) + str(idx)\n\n    def _complain_multiple_hidden_parameter_sets(self) -> NoReturn:\n        fail(\n            f\"{self._make_error_prefix()}multiple instances of HIDDEN_PARAM \"\n            \"cannot be used in the same parametrize call, \"\n            \"because the tests names need to be unique.\"\n        )\n\n    def _make_error_prefix(self) -> str:\n        if self.nodeid is not None:\n            return f\"In {self.nodeid}: \"\n        else:\n            return \"\"\n\n\n@final\n@dataclasses.dataclass(frozen=True)\nclass CallSpec2:\n    \"\"\"A planned parameterized invocation of a test function.\n\n    Calculated during collection for a given test function's Metafunc.\n    Once collection is over, each callspec is turned into a single Item\n    and stored in item.callspec.\n    \"\"\"\n\n    # arg name -> arg value which will be passed to a fixture or pseudo-fixture\n    # of the same name. (indirect or direct parametrization respectively)\n    params: dict[str, object] = dataclasses.field(default_factory=dict)\n    # arg name -> arg index.\n    indices: dict[str, int] = dataclasses.field(default_factory=dict)\n    # arg name -> parameter scope.\n    # Used for sorting parametrized resources.\n    _arg2scope: Mapping[str, Scope] = dataclasses.field(default_factory=dict)\n    # Parts which will be added to the item's name in `[..]` separated by \"-\".\n    _idlist: Sequence[str] = dataclasses.field(default_factory=tuple)\n    # Marks which will be applied to the item.\n    marks: list[Mark] = dataclasses.field(default_factory=list)\n\n    def setmulti(\n        self,\n        *,\n        argnames: Iterable[str],\n        valset: Iterable[object],\n        id: str | _HiddenParam,\n        marks: Iterable[Mark | MarkDecorator],\n        scope: Scope,\n        param_index: int,\n        nodeid: str,\n    ) -> CallSpec2:\n        params = self.params.copy()\n        indices = self.indices.copy()\n        arg2scope = dict(self._arg2scope)\n        for arg, val in zip(argnames, valset, strict=True):\n            if arg in params:\n                raise nodes.Collector.CollectError(\n                    f\"{nodeid}: duplicate parametrization of {arg!r}\"\n                )\n            params[arg] = val\n            indices[arg] = param_index\n            arg2scope[arg] = scope\n        return CallSpec2(\n            params=params,\n            indices=indices,\n            _arg2scope=arg2scope,\n            _idlist=self._idlist if id is HIDDEN_PARAM else [*self._idlist, id],\n            marks=[*self.marks, *normalize_mark_list(marks)],\n        )\n\n    def getparam(self, name: str) -> object:\n        try:\n            return self.params[name]\n        except KeyError as e:\n            raise ValueError(name) from e\n\n    @property\n    def id(self) -> str:\n        return \"-\".join(self._idlist)\n\n\ndef get_direct_param_fixture_func(request: FixtureRequest) -> Any:\n    return request.param\n\n\n# Used for storing pseudo fixturedefs for direct parametrization.\nname2pseudofixturedef_key = StashKey[dict[str, FixtureDef[Any]]]()\n\n\n@final\nclass Metafunc:\n    \"\"\"Objects passed to the :hook:`pytest_generate_tests` hook.\n\n    They help to inspect a test function and to generate tests according to\n    test configuration or values specified in the class or module where a\n    test function is defined.\n    \"\"\"\n\n    def __init__(\n        self,\n        definition: FunctionDefinition,\n        fixtureinfo: fixtures.FuncFixtureInfo,\n        config: Config,\n        cls=None,\n        module=None,\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n\n        #: Access to the underlying :class:`_pytest.python.FunctionDefinition`.\n        self.definition = definition\n\n        #: Access to the :class:`pytest.Config` object for the test session.\n        self.config = config\n\n        #: The module object where the test function is defined in.\n        self.module = module\n\n        #: Underlying Python test function.\n        self.function = definition.obj\n\n        #: Set of fixture names required by the test function.\n        self.fixturenames = fixtureinfo.names_closure\n\n        #: Class object where the test function is defined in or ``None``.\n        self.cls = cls\n\n        self._arg2fixturedefs = fixtureinfo.name2fixturedefs\n\n        # Result of parametrize().\n        self._calls: list[CallSpec2] = []\n\n        self._params_directness: dict[str, Literal[\"indirect\", \"direct\"]] = {}\n\n    def parametrize(\n        self,\n        argnames: str | Sequence[str],\n        argvalues: Iterable[ParameterSet | Sequence[object] | object],\n        indirect: bool | Sequence[str] = False,\n        ids: Iterable[object | None] | Callable[[Any], object | None] | None = None,\n        scope: _ScopeName | None = None,\n        *,\n        _param_mark: Mark | None = None,\n    ) -> None:\n        \"\"\"Add new invocations to the underlying test function using the list\n        of argvalues for the given argnames. Parametrization is performed\n        during the collection phase. If you need to setup expensive resources\n        see about setting ``indirect`` to do it at test setup time instead.\n\n        Can be called multiple times per test function (but only on different\n        argument names), in which case each call parametrizes all previous\n        parametrizations, e.g.\n\n        ::\n\n            unparametrized:         t\n            parametrize [\"x\", \"y\"]: t[x], t[y]\n            parametrize [1, 2]:     t[x-1], t[x-2], t[y-1], t[y-2]\n\n        :param argnames:\n            A comma-separated string denoting one or more argument names, or\n            a list/tuple of argument strings.\n\n        :param argvalues:\n            The list of argvalues determines how often a test is invoked with\n            different argument values.\n\n            If only one argname was specified argvalues is a list of values.\n            If N argnames were specified, argvalues must be a list of\n            N-tuples, where each tuple-element specifies a value for its\n            respective argname.\n\n            .. versionchanged:: 9.1\n\n                Passing a non-:class:`~collections.abc.Collection` iterable\n                (such as a generator or iterator) is deprecated. See\n                :ref:`parametrize-iterators` for details.\n\n        :param indirect:\n            A list of arguments' names (subset of argnames) or a boolean.\n            If True the list contains all names from the argnames. Each\n            argvalue corresponding to an argname in this list will\n            be passed as request.param to its respective argname fixture\n            function so that it can perform more expensive setups during the\n            setup phase of a test rather than at collection time.\n\n        :param ids:\n            Sequence of (or generator for) ids for ``argvalues``,\n            or a callable to return part of the id for each argvalue.\n\n            With sequences (and generators like ``itertools.count()``) the\n            returned ids should be of type ``string``, ``int``, ``float``,\n            ``bool``, or ``None``.\n            They are mapped to the corresponding index in ``argvalues``.\n            ``None`` means to use the auto-generated id.\n\n            .. versionadded:: 8.4\n                :ref:`hidden-param` means to hide the parameter set\n                from the test name. Can only be used at most 1 time, as\n                test names need to be unique.\n\n            If it is a callable it will be called for each entry in\n            ``argvalues``, and the return value is used as part of the\n            auto-generated id for the whole set (where parts are joined with\n            dashes (\"-\")).\n            This is useful to provide more specific ids for certain items, e.g.\n            dates.  Returning ``None`` will use an auto-generated id.\n\n            If no ids are provided they will be generated automatically from\n            the argvalues.\n\n        :param scope:\n            If specified it denotes the scope of the parameters.\n            The scope is used for grouping tests by parameter instances.\n            It will also override any fixture-function defined scope, allowing\n            to set a dynamic scope using test context or configuration.\n        \"\"\"\n        nodeid = self.definition.nodeid\n\n        argnames, parametersets = ParameterSet._for_parametrize(\n            argnames,\n            argvalues,\n            self.function,\n            self.config,\n            nodeid=self.definition.nodeid,\n        )\n        del argvalues\n\n        if \"request\" in argnames:\n            fail(\n                f\"{nodeid}: 'request' is a reserved name and cannot be used in @pytest.mark.parametrize\",\n                pytrace=False,\n            )\n\n        if scope is not None:\n            scope_ = Scope.from_user(\n                scope, descr=f\"parametrize() call in {self.function.__name__}\"\n            )\n        else:\n            scope_ = _find_parametrized_scope(argnames, self._arg2fixturedefs, indirect)\n\n        self._validate_if_using_arg_names(argnames, indirect)\n\n        # Use any already (possibly) generated ids with parametrize Marks.\n        if _param_mark and _param_mark._param_ids_from:\n            generated_ids = _param_mark._param_ids_from._param_ids_generated\n            if generated_ids is not None:\n                ids = generated_ids\n\n        ids = self._resolve_parameter_set_ids(\n            argnames, ids, parametersets, nodeid=self.definition.nodeid\n        )\n\n        # Store used (possibly generated) ids with parametrize Marks.\n        if _param_mark and _param_mark._param_ids_from and generated_ids is None:\n            object.__setattr__(_param_mark._param_ids_from, \"_param_ids_generated\", ids)\n\n        # Calculate directness.\n        arg_directness = _resolve_args_directness(\n            argnames, indirect, self.definition.nodeid\n        )\n        self._params_directness.update(arg_directness)\n\n        # Add direct parametrizations as fixturedefs to arg2fixturedefs by\n        # registering artificial \"pseudo\" FixtureDef's such that later at test\n        # setup time we can rely on FixtureDefs to exist for all argnames.\n        node = None\n        # For scopes higher than function, a \"pseudo\" FixtureDef might have\n        # already been created for the scope. We thus store and cache the\n        # FixtureDef on the node related to the scope.\n        if scope_ is Scope.Function:\n            name2pseudofixturedef = None\n        else:\n            collector = self.definition.parent\n            assert collector is not None\n            node = get_scope_node(collector, scope_)\n            if node is None:\n                # If used class scope and there is no class, use module-level\n                # collector (for now).\n                if scope_ is Scope.Class:\n                    assert isinstance(collector, Module)\n                    node = collector\n                # If used package scope and there is no package, use session\n                # (for now).\n                elif scope_ is Scope.Package:\n                    node = collector.session\n                else:\n                    assert False, f\"Unhandled missing scope: {scope}\"\n            default: dict[str, FixtureDef[Any]] = {}\n            name2pseudofixturedef = node.stash.setdefault(\n                name2pseudofixturedef_key, default\n            )\n        for argname in argnames:\n            if arg_directness[argname] == \"indirect\":\n                continue\n            if name2pseudofixturedef is not None and argname in name2pseudofixturedef:\n                fixturedef = name2pseudofixturedef[argname]\n            else:\n                fixturedef = FixtureDef(\n                    config=self.config,\n                    baseid=\"\",\n                    argname=argname,\n                    func=get_direct_param_fixture_func,\n                    scope=scope_,\n                    params=None,\n                    ids=None,\n                    _ispytest=True,\n                )\n                if name2pseudofixturedef is not None:\n                    name2pseudofixturedef[argname] = fixturedef\n            self._arg2fixturedefs[argname] = [fixturedef]\n\n        # Create the new calls: if we are parametrize() multiple times (by applying the decorator\n        # more than once) then we accumulate those calls generating the cartesian product\n        # of all calls.\n        newcalls = []\n        for callspec in self._calls or [CallSpec2()]:\n            for param_index, (param_id, param_set) in enumerate(\n                zip(ids, parametersets, strict=True)\n            ):\n                newcallspec = callspec.setmulti(\n                    argnames=argnames,\n                    valset=param_set.values,\n                    id=param_id,\n                    marks=param_set.marks,\n                    scope=scope_,\n                    param_index=param_index,\n                    nodeid=nodeid,\n                )\n                newcalls.append(newcallspec)\n        self._calls = newcalls\n\n    def _resolve_parameter_set_ids(\n        self,\n        argnames: Sequence[str],\n        ids: Iterable[object | None] | Callable[[Any], object | None] | None,\n        parametersets: Sequence[ParameterSet],\n        nodeid: str,\n    ) -> list[str | _HiddenParam]:\n        \"\"\"Resolve the actual ids for the given parameter sets.\n\n        :param argnames:\n            Argument names passed to ``parametrize()``.\n        :param ids:\n            The `ids` parameter of the ``parametrize()`` call (see docs).\n        :param parametersets:\n            The parameter sets, each containing a set of values corresponding\n            to ``argnames``.\n        :param nodeid str:\n            The nodeid of the definition item that generated this\n            parametrization.\n        :returns:\n            List with ids for each parameter set given.\n        \"\"\"\n        if ids is None:\n            idfn = None\n            ids_ = None\n        elif callable(ids):\n            idfn = ids\n            ids_ = None\n        else:\n            idfn = None\n            ids_ = self._validate_ids(ids, parametersets)\n        id_maker = IdMaker(\n            argnames,\n            parametersets,\n            idfn,\n            ids_,\n            self.config,\n            nodeid=nodeid,\n        )\n        return id_maker.make_unique_parameterset_ids()\n\n    def _validate_ids(\n        self,\n        ids: Iterable[object | None],\n        parametersets: Sequence[ParameterSet],\n    ) -> list[object | None]:\n        try:\n            num_ids = len(ids)  # type: ignore[arg-type]\n        except TypeError:\n            try:\n                iter(ids)\n            except TypeError as e:\n                raise TypeError(\"ids must be a callable or an iterable\") from e\n            num_ids = len(parametersets)\n\n        # num_ids == 0 is a special case: https://github.com/pytest-dev/pytest/issues/1849\n        if num_ids != len(parametersets) and num_ids != 0:\n            nodeid = self.definition.nodeid\n            fail(\n                f\"In {nodeid}: {len(parametersets)} parameter sets specified, with different number of ids: {num_ids}\",\n                pytrace=False,\n            )\n\n        return list(itertools.islice(ids, num_ids))\n\n    def _validate_if_using_arg_names(\n        self,\n        argnames: Sequence[str],\n        indirect: bool | Sequence[str],\n    ) -> None:\n        \"\"\"Check if all argnames are being used, by default values, or directly/indirectly.\n\n        :param List[str] argnames: List of argument names passed to ``parametrize()``.\n        :param indirect: Same as the ``indirect`` parameter of ``parametrize()``.\n        :raises ValueError: If validation fails.\n        \"\"\"\n        default_arg_names = set(get_default_arg_names(self.function))\n        nodeid = self.definition.nodeid\n        for arg in argnames:\n            if arg not in self.fixturenames:\n                if arg in default_arg_names:\n                    fail(\n                        f\"In {nodeid}: function already takes an argument '{arg}' with a default value\",\n                        pytrace=False,\n                    )\n                else:\n                    if isinstance(indirect, Sequence):\n                        name = \"fixture\" if arg in indirect else \"argument\"\n                    else:\n                        name = \"fixture\" if indirect else \"argument\"\n                    fail(\n                        f\"In {nodeid}: function uses no {name} '{arg}'\",\n                        pytrace=False,\n                    )\n\n    def _recompute_direct_params_indices(self) -> None:\n        for argname, param_type in self._params_directness.items():\n            if param_type == \"direct\":\n                for i, callspec in enumerate(self._calls):\n                    callspec.indices[argname] = i\n\n\ndef _find_parametrized_scope(\n    argnames: Sequence[str],\n    arg2fixturedefs: Mapping[str, Sequence[fixtures.FixtureDef[object]]],\n    indirect: bool | Sequence[str],\n) -> Scope:\n    \"\"\"Find the most appropriate scope for a parametrized call based on its arguments.\n\n    When there's at least one direct argument, always use \"function\" scope.\n\n    When a test function is parametrized and all its arguments are indirect\n    (e.g. fixtures), return the most narrow scope based on the fixtures used.\n\n    Related to issue #1832, based on code posted by @Kingdread.\n    \"\"\"\n    if isinstance(indirect, Sequence):\n        all_arguments_are_fixtures = len(indirect) == len(argnames)\n    else:\n        all_arguments_are_fixtures = bool(indirect)\n\n    if all_arguments_are_fixtures:\n        fixturedefs = arg2fixturedefs or {}\n        used_scopes = [\n            fixturedef[-1]._scope\n            for name, fixturedef in fixturedefs.items()\n            if name in argnames\n        ]\n        # Takes the most narrow scope from used fixtures.\n        return min(used_scopes, default=Scope.Function)\n\n    return Scope.Function\n\n\ndef _ascii_escaped_by_config(val: str | bytes, config: Config | None) -> str:\n    if config is None:\n        escape_option = False\n    else:\n        escape_option = config.getini(\n            \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n        )\n    # TODO: If escaping is turned off and the user passes bytes,\n    #       will return a bytes. For now we ignore this but the\n    #       code *probably* doesn't handle this case.\n    return val if escape_option else ascii_escaped(val)  # type: ignore\n\n\nclass Function(PyobjMixin, nodes.Item):\n    \"\"\"Item responsible for setting up and executing a Python test function.\n\n    :param name:\n        The full function name, including any decorations like those\n        added by parametrization (``my_func[my_param]``).\n    :param parent:\n        The parent Node.\n    :param config:\n        The pytest Config object.\n    :param callspec:\n        If given, this function has been parametrized and the callspec contains\n        meta information about the parametrization.\n    :param callobj:\n        If given, the object which will be called when the Function is invoked,\n        otherwise the callobj will be obtained from ``parent`` using ``originalname``.\n    :param keywords:\n        Keywords bound to the function object for \"-k\" matching.\n    :param session:\n        The pytest Session object.\n    :param fixtureinfo:\n        Fixture information already resolved at this fixture node..\n    :param originalname:\n        The attribute name to use for accessing the underlying function object.\n        Defaults to ``name``. Set this if name is different from the original name,\n        for example when it contains decorations like those added by parametrization\n        (``my_func[my_param]``).\n    \"\"\"\n\n    # Disable since functions handle it themselves.\n    _ALLOW_MARKERS = False\n\n    def __init__(\n        self,\n        name: str,\n        parent,\n        config: Config | None = None,\n        callspec: CallSpec2 | None = None,\n        callobj=NOTSET,\n        keywords: Mapping[str, Any] | None = None,\n        session: Session | None = None,\n        fixtureinfo: FuncFixtureInfo | None = None,\n        originalname: str | None = None,\n    ) -> None:\n        super().__init__(name, parent, config=config, session=session)\n\n        if callobj is not NOTSET:\n            self._obj = callobj\n            self._instance = getattr(callobj, \"__self__\", None)\n\n        #: Original function name, without any decorations (for example\n        #: parametrization adds a ``\"[...]\"`` suffix to function names), used to access\n        #: the underlying function object from ``parent`` (in case ``callobj`` is not given\n        #: explicitly).\n        #:\n        #: .. versionadded:: 3.0\n        self.originalname = originalname or name\n\n        # Note: when FunctionDefinition is introduced, we should change ``originalname``\n        # to a readonly property that returns FunctionDefinition.name.\n\n        self.own_markers.extend(get_unpacked_marks(self.obj))\n        if callspec:\n            self.callspec = callspec\n            self.own_markers.extend(callspec.marks)\n\n        # todo: this is a hell of a hack\n        # https://github.com/pytest-dev/pytest/issues/4569\n        # Note: the order of the updates is important here; indicates what\n        # takes priority (ctor argument over function attributes over markers).\n        # Take own_markers only; NodeKeywords handles parent traversal on its own.\n        self.keywords.update((mark.name, mark) for mark in self.own_markers)\n        self.keywords.update(self.obj.__dict__)\n        if keywords:\n            self.keywords.update(keywords)\n\n        if fixtureinfo is None:\n            fm = self.session._fixturemanager\n            fixtureinfo = fm.getfixtureinfo(self, self.obj, self.cls)\n        self._fixtureinfo: FuncFixtureInfo = fixtureinfo\n        self.fixturenames = fixtureinfo.names_closure\n        self._initrequest()\n\n    # todo: determine sound type limitations\n    @classmethod\n    def from_parent(cls, parent, **kw) -> Self:\n        \"\"\"The public constructor.\"\"\"\n        return super().from_parent(parent=parent, **kw)\n\n    def _initrequest(self) -> None:\n        self.funcargs: dict[str, object] = {}\n        self._request = fixtures.TopRequest(self, _ispytest=True)\n\n    @property\n    def function(self):\n        \"\"\"Underlying python 'function' object.\"\"\"\n        return getimfunc(self.obj)\n\n    @property\n    def instance(self):\n        try:\n            return self._instance\n        except AttributeError:\n            if isinstance(self.parent, Class):\n                # Each Function gets a fresh class instance.\n                self._instance = self._getinstance()\n            else:\n                self._instance = None\n        return self._instance\n\n    def _getinstance(self):\n        if isinstance(self.parent, Class):\n            # Each Function gets a fresh class instance.\n            return self.parent.newinstance()\n        else:\n            return None\n\n    def _getobj(self):\n        instance = self.instance\n        if instance is not None:\n            parent_obj = instance\n        else:\n            assert self.parent is not None\n            parent_obj = self.parent.obj  # type: ignore[attr-defined]\n        return getattr(parent_obj, self.originalname)\n\n    @property\n    def _pyfuncitem(self):\n        \"\"\"(compatonly) for code expecting pytest-2.2 style request objects.\"\"\"\n        return self\n\n    def runtest(self) -> None:\n        \"\"\"Execute the underlying test function.\"\"\"\n        self.ihook.pytest_pyfunc_call(pyfuncitem=self)\n\n    def setup(self) -> None:\n        self._request._fillfixtures()\n\n    def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:\n        if hasattr(self, \"_obj\") and not self.config.getoption(\"fulltrace\", False):\n            code = _pytest._code.Code.from_function(get_real_func(self.obj))\n            path, firstlineno = code.path, code.firstlineno\n            traceback = excinfo.traceback\n            ntraceback = traceback.cut(path=path, firstlineno=firstlineno)\n            if ntraceback == traceback:\n                ntraceback = ntraceback.cut(path=path)\n                if ntraceback == traceback:\n                    ntraceback = ntraceback.filter(filter_traceback)\n                    if not ntraceback:\n                        ntraceback = traceback\n            ntraceback = ntraceback.filter(excinfo)\n\n            # issue364: mark all but first and last frames to\n            # only show a single-line message for each frame.\n            if self.config.getoption(\"tbstyle\", \"auto\") == \"auto\":\n                if len(ntraceback) > 2:\n                    ntraceback = Traceback(\n                        (\n                            ntraceback[0],\n                            *(t.with_repr_style(\"short\") for t in ntraceback[1:-1]),\n                            ntraceback[-1],\n                        )\n                    )\n\n            return ntraceback\n        return excinfo.traceback\n\n    # TODO: Type ignored -- breaks Liskov Substitution.\n    def repr_failure(  # type: ignore[override]\n        self,\n        excinfo: ExceptionInfo[BaseException],\n    ) -> str | TerminalRepr:\n        style = self.config.getoption(\"tbstyle\", \"auto\")\n        if style == \"auto\":\n            style = \"long\"\n        return self._repr_failure_py(excinfo, style=style)\n\n\nclass FunctionDefinition(Function):\n    \"\"\"This class is a stop gap solution until we evolve to have actual function\n    definition nodes and manage to get rid of ``metafunc``.\"\"\"\n\n    def runtest(self) -> None:\n        raise RuntimeError(\"function definitions are not supposed to be run as tests\")\n\n    setup = runtest\n"
  },
  {
    "path": "src/_pytest/python_api.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Collection\nfrom collections.abc import Mapping\nfrom collections.abc import Sequence\nfrom collections.abc import Sized\nfrom decimal import Decimal\nimport math\nfrom numbers import Complex\nimport pprint\nimport sys\nfrom typing import Any\nfrom typing import TYPE_CHECKING\n\n\nif TYPE_CHECKING:\n    from numpy import ndarray\n\n\ndef _compare_approx(\n    full_object: object,\n    message_data: Sequence[tuple[str, str, str]],\n    number_of_elements: int,\n    different_ids: Sequence[object],\n    max_abs_diff: float,\n    max_rel_diff: float,\n) -> list[str]:\n    message_list = list(message_data)\n    message_list.insert(0, (\"Index\", \"Obtained\", \"Expected\"))\n    max_sizes = [0, 0, 0]\n    for index, obtained, expected in message_list:\n        max_sizes[0] = max(max_sizes[0], len(index))\n        max_sizes[1] = max(max_sizes[1], len(obtained))\n        max_sizes[2] = max(max_sizes[2], len(expected))\n    explanation = [\n        f\"comparison failed. Mismatched elements: {len(different_ids)} / {number_of_elements}:\",\n        f\"Max absolute difference: {max_abs_diff}\",\n        f\"Max relative difference: {max_rel_diff}\",\n    ] + [\n        f\"{indexes:<{max_sizes[0]}} | {obtained:<{max_sizes[1]}} | {expected:<{max_sizes[2]}}\"\n        for indexes, obtained, expected in message_list\n    ]\n    return explanation\n\n\n# builtin pytest.approx helper\n\n\nclass ApproxBase:\n    \"\"\"Provide shared utilities for making approximate comparisons between\n    numbers or sequences of numbers.\"\"\"\n\n    # Tell numpy to use our `__eq__` operator instead of its.\n    __array_ufunc__ = None\n    __array_priority__ = 100\n\n    def __init__(self, expected, rel=None, abs=None, nan_ok: bool = False) -> None:\n        __tracebackhide__ = True\n        self.expected = expected\n        self.abs = abs\n        self.rel = rel\n        self.nan_ok = nan_ok\n        self._check_type()\n\n    def __repr__(self) -> str:\n        raise NotImplementedError\n\n    def _repr_compare(self, other_side: Any) -> list[str]:\n        return [\n            \"comparison failed\",\n            f\"Obtained: {other_side}\",\n            f\"Expected: {self}\",\n        ]\n\n    def __eq__(self, actual) -> bool:\n        return all(\n            a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)\n        )\n\n    def __bool__(self):\n        __tracebackhide__ = True\n        raise AssertionError(\n            \"approx() is not supported in a boolean context.\\nDid you mean: `assert a == approx(b)`?\"\n        )\n\n    # Ignore type because of https://github.com/python/mypy/issues/4266.\n    __hash__ = None  # type: ignore\n\n    def __ne__(self, actual) -> bool:\n        return not (actual == self)\n\n    def _approx_scalar(self, x) -> ApproxScalar:\n        if isinstance(x, Decimal):\n            return ApproxDecimal(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)\n        return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)\n\n    def _yield_comparisons(self, actual):\n        \"\"\"Yield all the pairs of numbers to be compared.\n\n        This is used to implement the `__eq__` method.\n        \"\"\"\n        raise NotImplementedError\n\n    def _check_type(self) -> None:\n        \"\"\"Raise a TypeError if the expected value is not a valid type.\"\"\"\n        # This is only a concern if the expected value is a sequence.  In every\n        # other case, the approx() function ensures that the expected value has\n        # a numeric type.  For this reason, the default is to do nothing.  The\n        # classes that deal with sequences should reimplement this method to\n        # raise if there are any non-numeric elements in the sequence.\n\n\ndef _recursive_sequence_map(f, x):\n    \"\"\"Recursively map a function over a sequence of arbitrary depth\"\"\"\n    if isinstance(x, list | tuple):\n        seq_type = type(x)\n        return seq_type(_recursive_sequence_map(f, xi) for xi in x)\n    elif _is_sequence_like(x):\n        return [_recursive_sequence_map(f, xi) for xi in x]\n    else:\n        return f(x)\n\n\nclass ApproxNumpy(ApproxBase):\n    \"\"\"Perform approximate comparisons where the expected value is numpy array.\"\"\"\n\n    def __repr__(self) -> str:\n        list_scalars = _recursive_sequence_map(\n            self._approx_scalar, self.expected.tolist()\n        )\n        return f\"approx({list_scalars!r})\"\n\n    def _repr_compare(self, other_side: ndarray | list[Any]) -> list[str]:\n        import itertools\n        import math\n\n        def get_value_from_nested_list(\n            nested_list: list[Any], nd_index: tuple[Any, ...]\n        ) -> Any:\n            \"\"\"\n            Helper function to get the value out of a nested list, given an n-dimensional index.\n            This mimics numpy's indexing, but for raw nested python lists.\n            \"\"\"\n            value: Any = nested_list\n            for i in nd_index:\n                value = value[i]\n            return value\n\n        np_array_shape = self.expected.shape\n        approx_side_as_seq = _recursive_sequence_map(\n            self._approx_scalar, self.expected.tolist()\n        )\n\n        # convert other_side to numpy array to ensure shape attribute is available\n        other_side_as_array = _as_numpy_array(other_side)\n        assert other_side_as_array is not None\n\n        if np_array_shape != other_side_as_array.shape:\n            return [\n                \"Impossible to compare arrays with different shapes.\",\n                f\"Shapes: {np_array_shape} and {other_side_as_array.shape}\",\n            ]\n\n        number_of_elements = self.expected.size\n        max_abs_diff = -math.inf\n        max_rel_diff = -math.inf\n        different_ids = []\n        for index in itertools.product(*(range(i) for i in np_array_shape)):\n            approx_value = get_value_from_nested_list(approx_side_as_seq, index)\n            other_value = get_value_from_nested_list(other_side_as_array, index)\n            if approx_value != other_value:\n                abs_diff = abs(approx_value.expected - other_value)\n                max_abs_diff = max(max_abs_diff, abs_diff)\n                if other_value == 0.0:\n                    max_rel_diff = math.inf\n                else:\n                    max_rel_diff = max(max_rel_diff, abs_diff / abs(other_value))\n                different_ids.append(index)\n\n        message_data = [\n            (\n                str(index),\n                str(get_value_from_nested_list(other_side_as_array, index)),\n                str(get_value_from_nested_list(approx_side_as_seq, index)),\n            )\n            for index in different_ids\n        ]\n        return _compare_approx(\n            self.expected,\n            message_data,\n            number_of_elements,\n            different_ids,\n            max_abs_diff,\n            max_rel_diff,\n        )\n\n    def __eq__(self, actual) -> bool:\n        import numpy as np\n\n        # self.expected is supposed to always be an array here.\n\n        if not np.isscalar(actual):\n            try:\n                actual = np.asarray(actual)\n            except Exception as e:\n                raise TypeError(f\"cannot compare '{actual}' to numpy.ndarray\") from e\n\n        if not np.isscalar(actual) and actual.shape != self.expected.shape:\n            return False\n\n        return super().__eq__(actual)\n\n    def _yield_comparisons(self, actual):\n        import numpy as np\n\n        # `actual` can either be a numpy array or a scalar, it is treated in\n        # `__eq__` before being passed to `ApproxBase.__eq__`, which is the\n        # only method that calls this one.\n\n        if np.isscalar(actual):\n            for i in np.ndindex(self.expected.shape):\n                yield actual, self.expected[i].item()\n        else:\n            for i in np.ndindex(self.expected.shape):\n                yield actual[i].item(), self.expected[i].item()\n\n\nclass ApproxMapping(ApproxBase):\n    \"\"\"Perform approximate comparisons where the expected value is a mapping\n    with numeric values (the keys can be anything).\"\"\"\n\n    def __repr__(self) -> str:\n        return f\"approx({ ({k: self._approx_scalar(v) for k, v in self.expected.items()})!r})\"\n\n    def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]:\n        import math\n\n        if len(self.expected) != len(other_side):\n            return [\n                \"Impossible to compare mappings with different sizes.\",\n                f\"Lengths: {len(self.expected)} and {len(other_side)}\",\n            ]\n\n        if self.expected.keys() != other_side.keys():\n            return [\n                \"comparison failed.\",\n                f\"Mappings has different keys: expected {self.expected.keys()} but got {other_side.keys()}\",\n            ]\n\n        approx_side_as_map = {\n            k: self._approx_scalar(v) for k, v in self.expected.items()\n        }\n\n        number_of_elements = len(approx_side_as_map)\n        max_abs_diff = -math.inf\n        max_rel_diff = -math.inf\n        different_ids = []\n        for approx_key, approx_value in approx_side_as_map.items():\n            other_value = other_side[approx_key]\n            if approx_value != other_value:\n                if approx_value.expected is not None and other_value is not None:\n                    try:\n                        max_abs_diff = max(\n                            max_abs_diff, abs(approx_value.expected - other_value)\n                        )\n                        if approx_value.expected == 0.0:\n                            max_rel_diff = math.inf\n                        else:\n                            max_rel_diff = max(\n                                max_rel_diff,\n                                abs(\n                                    (approx_value.expected - other_value)\n                                    / approx_value.expected\n                                ),\n                            )\n                    except ZeroDivisionError:\n                        pass\n                different_ids.append(approx_key)\n\n        message_data = [\n            (str(key), str(other_side[key]), str(approx_side_as_map[key]))\n            for key in different_ids\n        ]\n\n        return _compare_approx(\n            self.expected,\n            message_data,\n            number_of_elements,\n            different_ids,\n            max_abs_diff,\n            max_rel_diff,\n        )\n\n    def __eq__(self, actual) -> bool:\n        try:\n            if set(actual.keys()) != set(self.expected.keys()):\n                return False\n        except AttributeError:\n            return False\n\n        return super().__eq__(actual)\n\n    def _yield_comparisons(self, actual):\n        for k in self.expected.keys():\n            yield actual[k], self.expected[k]\n\n    def _check_type(self) -> None:\n        __tracebackhide__ = True\n        for key, value in self.expected.items():\n            if isinstance(value, type(self.expected)):\n                msg = \"pytest.approx() does not support nested dictionaries: key={!r} value={!r}\\n  full mapping={}\"\n                raise TypeError(msg.format(key, value, pprint.pformat(self.expected)))\n\n\nclass ApproxSequenceLike(ApproxBase):\n    \"\"\"Perform approximate comparisons where the expected value is a sequence of numbers.\"\"\"\n\n    def __repr__(self) -> str:\n        seq_type = type(self.expected)\n        if seq_type not in (tuple, list):\n            seq_type = list\n        return f\"approx({seq_type(self._approx_scalar(x) for x in self.expected)!r})\"\n\n    def _repr_compare(self, other_side: Sequence[float]) -> list[str]:\n        import math\n\n        if len(self.expected) != len(other_side):\n            return [\n                \"Impossible to compare lists with different sizes.\",\n                f\"Lengths: {len(self.expected)} and {len(other_side)}\",\n            ]\n\n        approx_side_as_map = _recursive_sequence_map(self._approx_scalar, self.expected)\n\n        number_of_elements = len(approx_side_as_map)\n        max_abs_diff = -math.inf\n        max_rel_diff = -math.inf\n        different_ids = []\n        for i, (approx_value, other_value) in enumerate(\n            zip(approx_side_as_map, other_side, strict=True)\n        ):\n            if approx_value != other_value:\n                try:\n                    abs_diff = abs(approx_value.expected - other_value)\n                    max_abs_diff = max(max_abs_diff, abs_diff)\n                # Ignore non-numbers for the diff calculations (#13012).\n                except TypeError:\n                    pass\n                else:\n                    if other_value == 0.0:\n                        max_rel_diff = math.inf\n                    else:\n                        max_rel_diff = max(max_rel_diff, abs_diff / abs(other_value))\n                different_ids.append(i)\n        message_data = [\n            (str(i), str(other_side[i]), str(approx_side_as_map[i]))\n            for i in different_ids\n        ]\n\n        return _compare_approx(\n            self.expected,\n            message_data,\n            number_of_elements,\n            different_ids,\n            max_abs_diff,\n            max_rel_diff,\n        )\n\n    def __eq__(self, actual) -> bool:\n        try:\n            if len(actual) != len(self.expected):\n                return False\n        except TypeError:\n            return False\n        return super().__eq__(actual)\n\n    def _yield_comparisons(self, actual):\n        return zip(actual, self.expected, strict=True)\n\n    def _check_type(self) -> None:\n        __tracebackhide__ = True\n        for index, x in enumerate(self.expected):\n            if isinstance(x, type(self.expected)):\n                msg = \"pytest.approx() does not support nested data structures: {!r} at index {}\\n  full sequence: {}\"\n                raise TypeError(msg.format(x, index, pprint.pformat(self.expected)))\n\n\nclass ApproxScalar(ApproxBase):\n    \"\"\"Perform approximate comparisons where the expected value is a single number.\"\"\"\n\n    # Using Real should be better than this Union, but not possible yet:\n    # https://github.com/python/typeshed/pull/3108\n    DEFAULT_ABSOLUTE_TOLERANCE: float | Decimal = 1e-12\n    DEFAULT_RELATIVE_TOLERANCE: float | Decimal = 1e-6\n\n    def __repr__(self) -> str:\n        \"\"\"Return a string communicating both the expected value and the\n        tolerance for the comparison being made.\n\n        For example, ``1.0 ± 1e-6``, ``(3+4j) ± 5e-6 ∠ ±180°``.\n        \"\"\"\n        # Don't show a tolerance for values that aren't compared using\n        # tolerances, i.e. non-numerics and infinities. Need to call abs to\n        # handle complex numbers, e.g. (inf + 1j).\n        if (\n            isinstance(self.expected, bool)\n            or (not isinstance(self.expected, Complex | Decimal))\n            or math.isinf(abs(self.expected) or isinstance(self.expected, bool))\n        ):\n            return str(self.expected)\n\n        # If a sensible tolerance can't be calculated, self.tolerance will\n        # raise a ValueError.  In this case, display '???'.\n        try:\n            if 1e-3 <= self.tolerance < 1e3:\n                vetted_tolerance = f\"{self.tolerance:n}\"\n            else:\n                vetted_tolerance = f\"{self.tolerance:.1e}\"\n\n            if (\n                isinstance(self.expected, Complex)\n                and self.expected.imag\n                and not math.isinf(self.tolerance)\n            ):\n                vetted_tolerance += \" ∠ ±180°\"\n        except ValueError:\n            vetted_tolerance = \"???\"\n\n        return f\"{self.expected} ± {vetted_tolerance}\"\n\n    def __eq__(self, actual) -> bool:\n        \"\"\"Return whether the given value is equal to the expected value\n        within the pre-specified tolerance.\"\"\"\n\n        def is_bool(val: Any) -> bool:\n            # Check if `val` is a native bool or numpy bool.\n            if isinstance(val, bool):\n                return True\n            if np := sys.modules.get(\"numpy\"):\n                return isinstance(val, np.bool_)\n            return False\n\n        asarray = _as_numpy_array(actual)\n        if asarray is not None:\n            # Call ``__eq__()`` manually to prevent infinite-recursion with\n            # numpy<1.13.  See #3748.\n            return all(self.__eq__(a) for a in asarray.flat)\n\n        # Short-circuit exact equality, except for bool and np.bool_\n        if is_bool(self.expected) and not is_bool(actual):\n            return False\n        elif actual == self.expected:\n            return True\n\n        # If either type is non-numeric, fall back to strict equality.\n        # NB: we need Complex, rather than just Number, to ensure that __abs__,\n        # __sub__, and __float__ are defined. Also, consider bool to be\n        # non-numeric, even though it has the required arithmetic.\n        if is_bool(self.expected) or not (\n            isinstance(self.expected, Complex | Decimal)\n            and isinstance(actual, Complex | Decimal)\n        ):\n            return False\n\n        # Allow the user to control whether NaNs are considered equal to each\n        # other or not.  The abs() calls are for compatibility with complex\n        # numbers.\n        if math.isnan(abs(self.expected)):\n            return self.nan_ok and math.isnan(abs(actual))\n\n        # Infinity shouldn't be approximately equal to anything but itself, but\n        # if there's a relative tolerance, it will be infinite and infinity\n        # will seem approximately equal to everything.  The equal-to-itself\n        # case would have been short circuited above, so here we can just\n        # return false if the expected value is infinite.  The abs() call is\n        # for compatibility with complex numbers.\n        if math.isinf(abs(self.expected)):\n            return False\n\n        # Return true if the two numbers are within the tolerance.\n        result: bool = abs(self.expected - actual) <= self.tolerance\n        return result\n\n    __hash__ = None\n\n    @property\n    def tolerance(self):\n        \"\"\"Return the tolerance for the comparison.\n\n        This could be either an absolute tolerance or a relative tolerance,\n        depending on what the user specified or which would be larger.\n        \"\"\"\n\n        def set_default(x, default):\n            return x if x is not None else default\n\n        # Figure out what the absolute tolerance should be.  ``self.abs`` is\n        # either None or a value specified by the user.\n        absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE)\n\n        if absolute_tolerance < 0:\n            raise ValueError(\n                f\"absolute tolerance can't be negative: {absolute_tolerance}\"\n            )\n        if math.isnan(absolute_tolerance):\n            raise ValueError(\"absolute tolerance can't be NaN.\")\n\n        # If the user specified an absolute tolerance but not a relative one,\n        # just return the absolute tolerance.\n        if self.rel is None:\n            if self.abs is not None:\n                return absolute_tolerance\n\n        # Figure out what the relative tolerance should be.  ``self.rel`` is\n        # either None or a value specified by the user.  This is done after\n        # we've made sure the user didn't ask for an absolute tolerance only,\n        # because we don't want to raise errors about the relative tolerance if\n        # we aren't even going to use it.\n        relative_tolerance = set_default(\n            self.rel, self.DEFAULT_RELATIVE_TOLERANCE\n        ) * abs(self.expected)\n\n        if relative_tolerance < 0:\n            raise ValueError(\n                f\"relative tolerance can't be negative: {relative_tolerance}\"\n            )\n        if math.isnan(relative_tolerance):\n            raise ValueError(\"relative tolerance can't be NaN.\")\n\n        # Return the larger of the relative and absolute tolerances.\n        return max(relative_tolerance, absolute_tolerance)\n\n\nclass ApproxDecimal(ApproxScalar):\n    \"\"\"Perform approximate comparisons where the expected value is a Decimal.\"\"\"\n\n    DEFAULT_ABSOLUTE_TOLERANCE = Decimal(\"1e-12\")\n    DEFAULT_RELATIVE_TOLERANCE = Decimal(\"1e-6\")\n\n    def __repr__(self) -> str:\n        if isinstance(self.rel, float):\n            rel = Decimal.from_float(self.rel)\n        else:\n            rel = self.rel\n\n        if isinstance(self.abs, float):\n            abs_ = Decimal.from_float(self.abs)\n        else:\n            abs_ = self.abs\n\n        tol_str = \"???\"\n        if rel is not None and Decimal(\"1e-3\") <= rel <= Decimal(\"1e3\"):\n            tol_str = f\"{rel:.1e}\"\n        elif abs_ is not None:\n            tol_str = f\"{abs_:.1e}\"\n\n        return f\"{self.expected} ± {tol_str}\"\n\n\ndef approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:\n    \"\"\"Assert that two numbers (or two ordered sequences of numbers) are equal to each other\n    within some tolerance.\n\n    Due to the :doc:`python:tutorial/floatingpoint`, numbers that we\n    would intuitively expect to be equal are not always so::\n\n        >>> 0.1 + 0.2 == 0.3\n        False\n\n    This problem is commonly encountered when writing tests, e.g. when making\n    sure that floating-point values are what you expect them to be.  One way to\n    deal with this problem is to assert that two floating-point numbers are\n    equal to within some appropriate tolerance::\n\n        >>> abs((0.1 + 0.2) - 0.3) < 1e-6\n        True\n\n    However, comparisons like this are tedious to write and difficult to\n    understand.  Furthermore, absolute comparisons like the one above are\n    usually discouraged because there's no tolerance that works well for all\n    situations.  ``1e-6`` is good for numbers around ``1``, but too small for\n    very big numbers and too big for very small ones.  It's better to express\n    the tolerance as a fraction of the expected value, but relative comparisons\n    like that are even more difficult to write correctly and concisely.\n\n    The ``approx`` class performs floating-point comparisons using a syntax\n    that's as intuitive as possible::\n\n        >>> from pytest import approx\n        >>> 0.1 + 0.2 == approx(0.3)\n        True\n\n    The same syntax also works for ordered sequences of numbers::\n\n        >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))\n        True\n\n    ``numpy`` arrays::\n\n        >>> import numpy as np                                                          # doctest: +SKIP\n        >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP\n        True\n\n    And for a ``numpy`` array against a scalar::\n\n        >>> import numpy as np                                         # doctest: +SKIP\n        >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP\n        True\n\n    Only ordered sequences are supported, because ``approx`` needs\n    to infer the relative position of the sequences without ambiguity. This means\n    ``sets`` and other unordered sequences are not supported.\n\n    Finally, dictionary *values* can also be compared::\n\n        >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})\n        True\n\n    The comparison will be true if both mappings have the same keys and their\n    respective values match the expected tolerances.\n\n    **Tolerances**\n\n    By default, ``approx`` considers numbers within a relative tolerance of\n    ``1e-6`` (i.e. one part in a million) of its expected value to be equal.\n    This treatment would lead to surprising results if the expected value was\n    ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.\n    To handle this case less surprisingly, ``approx`` also considers numbers\n    within an absolute tolerance of ``1e-12`` of its expected value to be\n    equal.  Infinity and NaN are special cases.  Infinity is only considered\n    equal to itself, regardless of the relative tolerance.  NaN is not\n    considered equal to anything by default, but you can make it be equal to\n    itself by setting the ``nan_ok`` argument to True.  (This is meant to\n    facilitate comparing arrays that use NaN to mean \"no data\".)\n\n    Both the relative and absolute tolerances can be changed by passing\n    arguments to the ``approx`` constructor::\n\n        >>> 1.0001 == approx(1)\n        False\n        >>> 1.0001 == approx(1, rel=1e-3)\n        True\n        >>> 1.0001 == approx(1, abs=1e-3)\n        True\n\n    If you specify ``abs`` but not ``rel``, the comparison will not consider\n    the relative tolerance at all.  In other words, two numbers that are within\n    the default relative tolerance of ``1e-6`` will still be considered unequal\n    if they exceed the specified absolute tolerance.  If you specify both\n    ``abs`` and ``rel``, the numbers will be considered equal if either\n    tolerance is met::\n\n        >>> 1 + 1e-8 == approx(1)\n        True\n        >>> 1 + 1e-8 == approx(1, abs=1e-12)\n        False\n        >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)\n        True\n\n    **Non-numeric types**\n\n    You can also use ``approx`` to compare non-numeric types, or dicts and\n    sequences containing non-numeric types, in which case it falls back to\n    strict equality. This can be useful for comparing dicts and sequences that\n    can contain optional values::\n\n        >>> {\"required\": 1.0000005, \"optional\": None} == approx({\"required\": 1, \"optional\": None})\n        True\n        >>> [None, 1.0000005] == approx([None,1])\n        True\n        >>> [\"foo\", 1.0000005] == approx([None,1])\n        False\n\n    If you're thinking about using ``approx``, then you might want to know how\n    it compares to other good ways of comparing floating-point numbers.  All of\n    these algorithms are based on relative and absolute tolerances and should\n    agree for the most part, but they do have meaningful differences:\n\n    - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``:  True if the relative\n      tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute\n      tolerance is met.  Because the relative tolerance is calculated w.r.t.\n      both ``a`` and ``b``, this test is symmetric (i.e.  neither ``a`` nor\n      ``b`` is a \"reference value\").  You have to specify an absolute tolerance\n      if you want to compare to ``0.0`` because there is no tolerance by\n      default.  More information: :py:func:`math.isclose`.\n\n    - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference\n      between ``a`` and ``b`` is less that the sum of the relative tolerance\n      w.r.t. ``b`` and the absolute tolerance.  Because the relative tolerance\n      is only calculated w.r.t. ``b``, this test is asymmetric and you can\n      think of ``b`` as the reference value.  Support for comparing sequences\n      is provided by :py:func:`numpy.allclose`.  More information:\n      :std:doc:`numpy:reference/generated/numpy.isclose`.\n\n    - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``\n      are within an absolute tolerance of ``1e-7``.  No relative tolerance is\n      considered , so this function is not appropriate for very large or very\n      small numbers.  Also, it's only available in subclasses of ``unittest.TestCase``\n      and it's ugly because it doesn't follow PEP8.  More information:\n      :py:meth:`unittest.TestCase.assertAlmostEqual`.\n\n    - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative\n      tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.\n      Because the relative tolerance is only calculated w.r.t. ``b``, this test\n      is asymmetric and you can think of ``b`` as the reference value.  In the\n      special case that you explicitly specify an absolute tolerance but not a\n      relative tolerance, only the absolute tolerance is considered.\n\n    .. note::\n\n        ``approx`` can handle numpy arrays, but we recommend the\n        specialised test helpers in :std:doc:`numpy:reference/routines.testing`\n        if you need support for comparisons, NaNs, or ULP-based tolerances.\n\n        To match strings using regex, you can use\n        `Matches <https://github.com/asottile/re-assert#re_assertmatchespattern-str-args-kwargs>`_\n        from the\n        `re_assert package <https://github.com/asottile/re-assert>`_.\n\n\n    .. note::\n\n        Unlike built-in equality, this function considers\n        booleans unequal to numeric zero or one. For example::\n\n           >>> 1 == approx(True)\n           False\n\n    .. warning::\n\n       .. versionchanged:: 3.2\n\n       In order to avoid inconsistent behavior, :py:exc:`TypeError` is\n       raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.\n       The example below illustrates the problem::\n\n           assert approx(0.1) > 0.1 + 1e-10  # calls approx(0.1).__gt__(0.1 + 1e-10)\n           assert 0.1 + 1e-10 > approx(0.1)  # calls approx(0.1).__lt__(0.1 + 1e-10)\n\n       In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``\n       to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to\n       comparison. This is because the call hierarchy of rich comparisons\n       follows a fixed behavior. More information: :py:meth:`object.__ge__`\n\n    .. versionchanged:: 3.7.1\n       ``approx`` raises ``TypeError`` when it encounters a dict value or\n       sequence element of non-numeric type.\n\n    .. versionchanged:: 6.1.0\n       ``approx`` falls back to strict equality for non-numeric types instead\n       of raising ``TypeError``.\n    \"\"\"\n    # Delegate the comparison to a class that knows how to deal with the type\n    # of the expected value (e.g. int, float, list, dict, numpy.array, etc).\n    #\n    # The primary responsibility of these classes is to implement ``__eq__()``\n    # and ``__repr__()``.  The former is used to actually check if some\n    # \"actual\" value is equivalent to the given expected value within the\n    # allowed tolerance.  The latter is used to show the user the expected\n    # value and tolerance, in the case that a test failed.\n    #\n    # The actual logic for making approximate comparisons can be found in\n    # ApproxScalar, which is used to compare individual numbers.  All of the\n    # other Approx classes eventually delegate to this class.  The ApproxBase\n    # class provides some convenient methods and overloads, but isn't really\n    # essential.\n\n    __tracebackhide__ = True\n\n    if isinstance(expected, Decimal):\n        cls: type[ApproxBase] = ApproxDecimal\n    elif isinstance(expected, Mapping):\n        cls = ApproxMapping\n    elif _is_numpy_array(expected):\n        expected = _as_numpy_array(expected)\n        cls = ApproxNumpy\n    elif _is_sequence_like(expected):\n        cls = ApproxSequenceLike\n    elif isinstance(expected, Collection) and not isinstance(expected, str | bytes):\n        msg = f\"pytest.approx() only supports ordered sequences, but got: {expected!r}\"\n        raise TypeError(msg)\n    else:\n        cls = ApproxScalar\n\n    return cls(expected, rel, abs, nan_ok)\n\n\ndef _is_sequence_like(expected: object) -> bool:\n    return (\n        hasattr(expected, \"__getitem__\")\n        and isinstance(expected, Sized)\n        and not isinstance(expected, str | bytes)\n    )\n\n\ndef _is_numpy_array(obj: object) -> bool:\n    \"\"\"\n    Return true if the given object is implicitly convertible to ndarray,\n    and numpy is already imported.\n    \"\"\"\n    return _as_numpy_array(obj) is not None\n\n\ndef _as_numpy_array(obj: object) -> ndarray | None:\n    \"\"\"\n    Return an ndarray if the given object is implicitly convertible to ndarray,\n    and numpy is already imported, otherwise None.\n    \"\"\"\n    np: Any = sys.modules.get(\"numpy\")\n    if np is not None:\n        # avoid infinite recursion on numpy scalars, which have __array__\n        if np.isscalar(obj):\n            return None\n        elif isinstance(obj, np.ndarray):\n            return obj\n        elif hasattr(obj, \"__array__\") or hasattr(\"obj\", \"__array_interface__\"):\n            return np.asarray(obj)\n    return None\n"
  },
  {
    "path": "src/_pytest/raises.py",
    "content": "from __future__ import annotations\n\nfrom abc import ABC\nfrom abc import abstractmethod\nimport re\nfrom re import Pattern\nimport sys\nfrom textwrap import indent\nfrom typing import Any\nfrom typing import cast\nfrom typing import final\nfrom typing import Generic\nfrom typing import get_args\nfrom typing import get_origin\nfrom typing import Literal\nfrom typing import overload\nfrom typing import TYPE_CHECKING\nimport warnings\n\nfrom _pytest._code import ExceptionInfo\nfrom _pytest._code.code import stringify_exception\nfrom _pytest.outcomes import fail\nfrom _pytest.warning_types import PytestWarning\n\n\nif TYPE_CHECKING:\n    from collections.abc import Callable\n    from collections.abc import Sequence\n\n    # for some reason Sphinx does not play well with 'from types import TracebackType'\n    import types\n    from typing import TypeGuard\n\n    from typing_extensions import ParamSpec\n    from typing_extensions import TypeVar\n\n    P = ParamSpec(\"P\")\n\n    # this conditional definition is because we want to allow a TypeVar default\n    BaseExcT_co_default = TypeVar(\n        \"BaseExcT_co_default\",\n        bound=BaseException,\n        default=BaseException,\n        covariant=True,\n    )\n\n    # Use short name because it shows up in docs.\n    E = TypeVar(\"E\", bound=BaseException, default=BaseException)\nelse:\n    from typing import TypeVar\n\n    BaseExcT_co_default = TypeVar(\n        \"BaseExcT_co_default\", bound=BaseException, covariant=True\n    )\n\n# RaisesGroup doesn't work with a default.\nBaseExcT_co = TypeVar(\"BaseExcT_co\", bound=BaseException, covariant=True)\nBaseExcT_1 = TypeVar(\"BaseExcT_1\", bound=BaseException)\nBaseExcT_2 = TypeVar(\"BaseExcT_2\", bound=BaseException)\nExcT_1 = TypeVar(\"ExcT_1\", bound=Exception)\nExcT_2 = TypeVar(\"ExcT_2\", bound=Exception)\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import BaseExceptionGroup\n    from exceptiongroup import ExceptionGroup\n\n\n# String patterns default to including the unicode flag.\n_REGEX_NO_FLAGS = re.compile(r\"\").flags\n\n\n# pytest.raises helper\n@overload\ndef raises(\n    expected_exception: type[E] | tuple[type[E], ...],\n    *,\n    match: str | re.Pattern[str] | None = ...,\n    check: Callable[[E], bool] = ...,\n) -> RaisesExc[E]: ...\n\n\n@overload\ndef raises(\n    *,\n    match: str | re.Pattern[str],\n    # If exception_type is not provided, check() must do any typechecks itself.\n    check: Callable[[BaseException], bool] = ...,\n) -> RaisesExc[BaseException]: ...\n\n\n@overload\ndef raises(*, check: Callable[[BaseException], bool]) -> RaisesExc[BaseException]: ...\n\n\n@overload\ndef raises(\n    expected_exception: type[E] | tuple[type[E], ...],\n    func: Callable[..., Any],\n    *args: Any,\n    **kwargs: Any,\n) -> ExceptionInfo[E]: ...\n\n\ndef raises(\n    expected_exception: type[E] | tuple[type[E], ...] | None = None,\n    *args: Any,\n    **kwargs: Any,\n) -> RaisesExc[BaseException] | ExceptionInfo[E]:\n    r\"\"\"Assert that a code block/function call raises an exception type, or one of its subclasses.\n\n    :param expected_exception:\n        The expected exception type, or a tuple if one of multiple possible\n        exception types are expected. Note that subclasses of the passed exceptions\n        will also match.\n\n        This is not a required parameter, you may opt to only use ``match`` and/or\n        ``check`` for verifying the raised exception.\n\n    :kwparam str | re.Pattern[str] | None match:\n        If specified, a string containing a regular expression,\n        or a regular expression object, that is tested against the string\n        representation of the exception and its :pep:`678` `__notes__`\n        using :func:`re.search`.\n\n        To match a literal string that may contain :ref:`special characters\n        <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.\n\n        (This is only used when ``pytest.raises`` is used as a context manager,\n        and passed through to the function otherwise.\n        When using ``pytest.raises`` as a function, you can use:\n        ``pytest.raises(Exc, func, match=\"passed on\").match(\"my pattern\")``.)\n\n    :kwparam Callable[[BaseException], bool] check:\n\n        .. versionadded:: 8.4\n\n        If specified, a callable that will be called with the exception as a parameter\n        after checking the type and the match regex if specified.\n        If it returns ``True`` it will be considered a match, if not it will\n        be considered a failed match.\n\n\n    Use ``pytest.raises`` as a context manager, which will capture the exception of the given\n    type, or any of its subclasses::\n\n        >>> import pytest\n        >>> with pytest.raises(ZeroDivisionError):\n        ...    1/0\n\n    If the code block does not raise the expected exception (:class:`ZeroDivisionError` in the example\n    above), or no exception at all, the check will fail instead.\n\n    You can also use the keyword argument ``match`` to assert that the\n    exception matches a text or regex::\n\n        >>> with pytest.raises(ValueError, match='must be 0 or None'):\n        ...     raise ValueError(\"value must be 0 or None\")\n\n        >>> with pytest.raises(ValueError, match=r'must be \\d+$'):\n        ...     raise ValueError(\"value must be 42\")\n\n    The ``match`` argument searches the formatted exception string, which includes any\n    `PEP-678 <https://peps.python.org/pep-0678/>`__ ``__notes__``:\n\n        >>> with pytest.raises(ValueError, match=r\"had a note added\"):  # doctest: +SKIP\n        ...     e = ValueError(\"value must be 42\")\n        ...     e.add_note(\"had a note added\")\n        ...     raise e\n\n    The ``check`` argument, if provided, must return True when passed the raised exception\n    for the match to be successful, otherwise an :exc:`AssertionError` is raised.\n\n        >>> import errno\n        >>> with pytest.raises(OSError, check=lambda e: e.errno == errno.EACCES):\n        ...     raise OSError(errno.EACCES, \"no permission to view\")\n\n    The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the\n    details of the captured exception::\n\n        >>> with pytest.raises(ValueError) as exc_info:\n        ...     raise ValueError(\"value must be 42\")\n        >>> assert exc_info.type is ValueError\n        >>> assert exc_info.value.args[0] == \"value must be 42\"\n\n    .. warning::\n\n       Given that ``pytest.raises`` matches subclasses, be wary of using it to match :class:`Exception` like this::\n\n           # Careful, this will catch ANY exception raised.\n           with pytest.raises(Exception):\n               some_function()\n\n       Because :class:`Exception` is the base class of almost all exceptions, it is easy for this to hide\n       real bugs, where the user wrote this expecting a specific exception, but some other exception is being\n       raised due to a bug introduced during a refactoring.\n\n       Avoid using ``pytest.raises`` to catch :class:`Exception` unless certain that you really want to catch\n       **any** exception raised.\n\n    .. note::\n\n       When using ``pytest.raises`` as a context manager, it's worthwhile to\n       note that normal context manager rules apply and that the exception\n       raised *must* be the final line in the scope of the context manager.\n       Lines of code after that, within the scope of the context manager will\n       not be executed. For example::\n\n           >>> value = 15\n           >>> with pytest.raises(ValueError) as exc_info:\n           ...     if value > 10:\n           ...         raise ValueError(\"value must be <= 10\")\n           ...     assert exc_info.type is ValueError  # This will not execute.\n\n       Instead, the following approach must be taken (note the difference in\n       scope)::\n\n           >>> with pytest.raises(ValueError) as exc_info:\n           ...     if value > 10:\n           ...         raise ValueError(\"value must be <= 10\")\n           ...\n           >>> assert exc_info.type is ValueError\n\n    **Expecting exception groups**\n\n    When expecting exceptions wrapped in :exc:`BaseExceptionGroup` or\n    :exc:`ExceptionGroup`, you should instead use :class:`pytest.RaisesGroup`.\n\n    **Using with** ``pytest.mark.parametrize``\n\n    When using :ref:`pytest.mark.parametrize ref`\n    it is possible to parametrize tests such that\n    some runs raise an exception and others do not.\n\n    See :ref:`parametrizing_conditional_raising` for an example.\n\n    .. seealso::\n\n        :ref:`assertraises` for more examples and detailed discussion.\n\n    **Legacy form**\n\n    It is possible to specify a callable by passing a to-be-called lambda::\n\n        >>> raises(ZeroDivisionError, lambda: 1/0)\n        <ExceptionInfo ...>\n\n    or you can specify an arbitrary callable with arguments::\n\n        >>> def f(x): return 1/x\n        ...\n        >>> raises(ZeroDivisionError, f, 0)\n        <ExceptionInfo ...>\n        >>> raises(ZeroDivisionError, f, x=0)\n        <ExceptionInfo ...>\n\n    The form above is fully supported but discouraged for new code because the\n    context manager form is regarded as more readable and less error-prone.\n\n    .. note::\n        Similar to caught exception objects in Python, explicitly clearing\n        local references to returned ``ExceptionInfo`` objects can\n        help the Python interpreter speed up its garbage collection.\n\n        Clearing those references breaks a reference cycle\n        (``ExceptionInfo`` --> caught exception --> frame stack raising\n        the exception --> current frame stack --> local variables -->\n        ``ExceptionInfo``) which makes Python keep all objects referenced\n        from that cycle (including all local variables in the current\n        frame) alive until the next cyclic garbage collection run.\n        More detailed information can be found in the official Python\n        documentation for :ref:`the try statement <python:try>`.\n    \"\"\"\n    __tracebackhide__ = True\n\n    if not args:\n        if set(kwargs) - {\"match\", \"check\", \"expected_exception\"}:\n            msg = \"Unexpected keyword arguments passed to pytest.raises: \"\n            msg += \", \".join(sorted(kwargs))\n            msg += \"\\nUse context-manager form instead?\"\n            raise TypeError(msg)\n\n        if expected_exception is None:\n            return RaisesExc(**kwargs)\n        return RaisesExc(expected_exception, **kwargs)\n\n    if not expected_exception:\n        raise ValueError(\n            f\"Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. \"\n            f\"Raising exceptions is already understood as failing the test, so you don't need \"\n            f\"any special code to say 'this should never raise an exception'.\"\n        )\n    func = args[0]\n    if not callable(func):\n        raise TypeError(f\"{func!r} object (type: {type(func)}) must be callable\")\n    with RaisesExc(expected_exception) as excinfo:\n        func(*args[1:], **kwargs)\n    try:\n        return excinfo\n    finally:\n        del excinfo\n\n\n# note: RaisesExc/RaisesGroup uses fail() internally, so this alias\n#  indicates (to [internal] plugins?) that `pytest.raises` will\n#  raise `_pytest.outcomes.Failed`, where\n#  `outcomes.Failed is outcomes.fail.Exception is raises.Exception`\n# note: this is *not* the same as `_pytest.main.Failed`\n# note: mypy does not recognize this attribute, and it's not possible\n#  to use a protocol/decorator like the others in outcomes due to\n#  https://github.com/python/mypy/issues/18715\nraises.Exception = fail.Exception  # type: ignore[attr-defined]\n\n\ndef _match_pattern(match: Pattern[str]) -> str | Pattern[str]:\n    \"\"\"Helper function to remove redundant `re.compile` calls when printing regex\"\"\"\n    return match.pattern if match.flags == _REGEX_NO_FLAGS else match\n\n\ndef repr_callable(fun: Callable[[BaseExcT_1], bool]) -> str:\n    \"\"\"Get the repr of a ``check`` parameter.\n\n    Split out so it can be monkeypatched (e.g. by hypothesis)\n    \"\"\"\n    return repr(fun)\n\n\ndef backquote(s: str) -> str:\n    return \"`\" + s + \"`\"\n\n\ndef _exception_type_name(\n    e: type[BaseException] | tuple[type[BaseException], ...],\n) -> str:\n    if isinstance(e, type):\n        return e.__name__\n    if len(e) == 1:\n        return e[0].__name__\n    return \"(\" + \", \".join(ee.__name__ for ee in e) + \")\"\n\n\ndef _check_raw_type(\n    expected_type: type[BaseException] | tuple[type[BaseException], ...] | None,\n    exception: BaseException,\n) -> str | None:\n    if expected_type is None or expected_type == ():\n        return None\n\n    if not isinstance(\n        exception,\n        expected_type,\n    ):\n        actual_type_str = backquote(_exception_type_name(type(exception)) + \"()\")\n        expected_type_str = backquote(_exception_type_name(expected_type))\n        if (\n            isinstance(exception, BaseExceptionGroup)\n            and isinstance(expected_type, type)\n            and not issubclass(expected_type, BaseExceptionGroup)\n        ):\n            return f\"Unexpected nested {actual_type_str}, expected {expected_type_str}\"\n        return f\"{actual_type_str} is not an instance of {expected_type_str}\"\n    return None\n\n\ndef is_fully_escaped(s: str) -> bool:\n    # we know we won't compile with re.VERBOSE, so whitespace doesn't need to be escaped\n    metacharacters = \"{}()+.*?^$[]|\"\n    return not any(\n        c in metacharacters and (i == 0 or s[i - 1] != \"\\\\\") for (i, c) in enumerate(s)\n    )\n\n\ndef unescape(s: str) -> str:\n    return re.sub(r\"\\\\([{}()+-.*?^$\\[\\]\\s\\\\|])\", r\"\\1\", s)\n\n\n# These classes conceptually differ from ExceptionInfo in that ExceptionInfo is tied, and\n# constructed from, a particular exception - whereas these are constructed with expected\n# exceptions, and later allow matching towards particular exceptions.\n# But there's overlap in `ExceptionInfo.match` and `AbstractRaises._check_match`, as with\n# `AbstractRaises.matches` and `ExceptionInfo.errisinstance`+`ExceptionInfo.group_contains`.\n# The interaction between these classes should perhaps be improved.\nclass AbstractRaises(ABC, Generic[BaseExcT_co]):\n    \"\"\"ABC with common functionality shared between RaisesExc and RaisesGroup\"\"\"\n\n    def __init__(\n        self,\n        *,\n        match: str | Pattern[str] | None,\n        check: Callable[[BaseExcT_co], bool] | None,\n    ) -> None:\n        if isinstance(match, str):\n            # juggle error in order to avoid context to fail (necessary?)\n            re_error = None\n            try:\n                self.match: Pattern[str] | None = re.compile(match)\n            except re.error as e:\n                re_error = e\n            if re_error is not None:\n                fail(f\"Invalid regex pattern provided to 'match': {re_error}\")\n            if match == \"\":\n                warnings.warn(\n                    PytestWarning(\n                        \"matching against an empty string will *always* pass. If you want \"\n                        \"to check for an empty message you need to pass '^$'. If you don't \"\n                        \"want to match you should pass `None` or leave out the parameter.\"\n                    ),\n                    stacklevel=2,\n                )\n        else:\n            self.match = match\n\n        # check if this is a fully escaped regex and has ^$ to match fully\n        # in which case we can do a proper diff on error\n        self.rawmatch: str | None = None\n        if isinstance(match, str) or (\n            isinstance(match, Pattern) and match.flags == _REGEX_NO_FLAGS\n        ):\n            if isinstance(match, Pattern):\n                match = match.pattern\n            if (\n                match\n                and match[0] == \"^\"\n                and match[-1] == \"$\"\n                and is_fully_escaped(match[1:-1])\n            ):\n                self.rawmatch = unescape(match[1:-1])\n\n        self.check = check\n        self._fail_reason: str | None = None\n\n        # used to suppress repeated printing of `repr(self.check)`\n        self._nested: bool = False\n\n        # set in self._parse_exc\n        self.is_baseexception = False\n\n    def _parse_exc(\n        self, exc: type[BaseExcT_1] | types.GenericAlias, expected: str\n    ) -> type[BaseExcT_1]:\n        if isinstance(exc, type) and issubclass(exc, BaseException):\n            if not issubclass(exc, Exception):\n                self.is_baseexception = True\n            return exc\n        # because RaisesGroup does not support variable number of exceptions there's\n        # still a use for RaisesExc(ExceptionGroup[Exception]).\n        origin_exc: type[BaseException] | None = get_origin(exc)\n        if origin_exc and issubclass(origin_exc, BaseExceptionGroup):\n            exc_type = get_args(exc)[0]\n            if (\n                issubclass(origin_exc, ExceptionGroup) and exc_type in (Exception, Any)\n            ) or (\n                issubclass(origin_exc, BaseExceptionGroup)\n                and exc_type in (BaseException, Any)\n            ):\n                if not issubclass(origin_exc, ExceptionGroup):\n                    self.is_baseexception = True\n                return cast(type[BaseExcT_1], origin_exc)\n            else:\n                raise ValueError(\n                    f\"Only `ExceptionGroup[Exception]` or `BaseExceptionGroup[BaseException]` \"\n                    f\"are accepted as generic types but got `{exc}`. \"\n                    f\"As `raises` will catch all instances of the specified group regardless of the \"\n                    f\"generic argument specific nested exceptions has to be checked \"\n                    f\"with `RaisesGroup`.\"\n                )\n        # unclear if the Type/ValueError distinction is even helpful here\n        msg = f\"Expected {expected}, but got \"\n        if isinstance(exc, type):  # type: ignore[unreachable]\n            raise ValueError(msg + f\"{exc.__name__!r}\")\n        if isinstance(exc, BaseException):  # type: ignore[unreachable]\n            raise TypeError(msg + f\"an exception instance: {type(exc).__name__}\")\n        raise TypeError(msg + repr(type(exc).__name__))\n\n    @property\n    def fail_reason(self) -> str | None:\n        \"\"\"Set after a call to :meth:`matches` to give a human-readable reason for why the match failed.\n        When used as a context manager the string will be printed as the reason for the\n        test failing.\"\"\"\n        return self._fail_reason\n\n    def _check_check(\n        self: AbstractRaises[BaseExcT_1],\n        exception: BaseExcT_1,\n    ) -> bool:\n        if self.check is None:\n            return True\n\n        if self.check(exception):\n            return True\n\n        check_repr = \"\" if self._nested else \" \" + repr_callable(self.check)\n        self._fail_reason = f\"check{check_repr} did not return True\"\n        return False\n\n    # TODO: harmonize with ExceptionInfo.match\n    def _check_match(self, e: BaseException) -> bool:\n        if self.match is None or re.search(\n            self.match,\n            stringified_exception := stringify_exception(\n                e, include_subexception_msg=False\n            ),\n        ):\n            return True\n\n        # if we're matching a group, make sure we're explicit to reduce confusion\n        # if they're trying to match an exception contained within the group\n        maybe_specify_type = (\n            f\" the `{_exception_type_name(type(e))}()`\"\n            if isinstance(e, BaseExceptionGroup)\n            else \"\"\n        )\n        if isinstance(self.rawmatch, str):\n            # TODO: it instructs to use `-v` to print leading text, but that doesn't work\n            # I also don't know if this is the proper entry point, or tool to use at all\n            from _pytest.assertion.util import _diff_text\n            from _pytest.assertion.util import dummy_highlighter\n\n            diff = _diff_text(self.rawmatch, stringified_exception, dummy_highlighter)\n            self._fail_reason = (\"\\n\" if diff[0][0] == \"-\" else \"\") + \"\\n\".join(diff)\n            return False\n\n        self._fail_reason = (\n            f\"Regex pattern did not match{maybe_specify_type}.\\n\"\n            f\"  Expected regex: {_match_pattern(self.match)!r}\\n\"\n            f\"  Actual message: {stringified_exception!r}\"\n        )\n        if _match_pattern(self.match) == stringified_exception:\n            self._fail_reason += \"\\n Did you mean to `re.escape()` the regex?\"\n        return False\n\n    @abstractmethod\n    def matches(\n        self: AbstractRaises[BaseExcT_1], exception: BaseException\n    ) -> TypeGuard[BaseExcT_1]:\n        \"\"\"Check if an exception matches the requirements of this AbstractRaises.\n        If it fails, :meth:`AbstractRaises.fail_reason` should be set.\n        \"\"\"\n\n\n@final\nclass RaisesExc(AbstractRaises[BaseExcT_co_default]):\n    \"\"\"\n    .. versionadded:: 8.4\n\n\n    This is the class constructed when calling :func:`pytest.raises`, but may be used\n    directly as a helper class with :class:`RaisesGroup` when you want to specify\n    requirements on sub-exceptions.\n\n    You don't need this if you only want to specify the type, since :class:`RaisesGroup`\n    accepts ``type[BaseException]``.\n\n    :param type[BaseException] | tuple[type[BaseException]] | None expected_exception:\n        The expected type, or one of several possible types.\n        May be ``None`` in order to only make use of ``match`` and/or ``check``\n\n        The type is checked with :func:`isinstance`, and does not need to be an exact match.\n        If that is wanted you can use the ``check`` parameter.\n\n    :kwparam str | Pattern[str] match:\n        A regex to match.\n\n    :kwparam Callable[[BaseException], bool] check:\n        If specified, a callable that will be called with the exception as a parameter\n        after checking the type and the match regex if specified.\n        If it returns ``True`` it will be considered a match, if not it will\n        be considered a failed match.\n\n    :meth:`RaisesExc.matches` can also be used standalone to check individual exceptions.\n\n    Examples::\n\n        with RaisesGroup(RaisesExc(ValueError, match=\"string\"))\n            ...\n        with RaisesGroup(RaisesExc(check=lambda x: x.args == (3, \"hello\"))):\n            ...\n        with RaisesGroup(RaisesExc(check=lambda x: type(x) is ValueError)):\n            ...\n    \"\"\"\n\n    # Trio bundled hypothesis monkeypatching, we will probably instead assume that\n    # hypothesis will handle that in their pytest plugin by the time this is released.\n    # Alternatively we could add a version of get_pretty_function_description ourselves\n    # https://github.com/HypothesisWorks/hypothesis/blob/8ced2f59f5c7bea3344e35d2d53e1f8f8eb9fcd8/hypothesis-python/src/hypothesis/internal/reflection.py#L439\n\n    # At least one of the three parameters must be passed.\n    @overload\n    def __init__(\n        self,\n        expected_exception: (\n            type[BaseExcT_co_default] | tuple[type[BaseExcT_co_default], ...]\n        ),\n        /,\n        *,\n        match: str | Pattern[str] | None = ...,\n        check: Callable[[BaseExcT_co_default], bool] | None = ...,\n    ) -> None: ...\n\n    @overload\n    def __init__(\n        self: RaisesExc[BaseException],  # Give E a value.\n        /,\n        *,\n        match: str | Pattern[str] | None,\n        # If exception_type is not provided, check() must do any typechecks itself.\n        check: Callable[[BaseException], bool] | None = ...,\n    ) -> None: ...\n\n    @overload\n    def __init__(self, /, *, check: Callable[[BaseException], bool]) -> None: ...\n\n    def __init__(\n        self,\n        expected_exception: (\n            type[BaseExcT_co_default] | tuple[type[BaseExcT_co_default], ...] | None\n        ) = None,\n        /,\n        *,\n        match: str | Pattern[str] | None = None,\n        check: Callable[[BaseExcT_co_default], bool] | None = None,\n    ):\n        super().__init__(match=match, check=check)\n        if isinstance(expected_exception, tuple):\n            expected_exceptions = expected_exception\n        elif expected_exception is None:\n            expected_exceptions = ()\n        else:\n            expected_exceptions = (expected_exception,)\n\n        if (expected_exceptions == ()) and match is None and check is None:\n            raise ValueError(\"You must specify at least one parameter to match on.\")\n\n        self.expected_exceptions = tuple(\n            self._parse_exc(e, expected=\"a BaseException type\")\n            for e in expected_exceptions\n        )\n\n        self._just_propagate = False\n\n    def matches(\n        self,\n        exception: BaseException | None,\n    ) -> TypeGuard[BaseExcT_co_default]:\n        \"\"\"Check if an exception matches the requirements of this :class:`RaisesExc`.\n        If it fails, :attr:`RaisesExc.fail_reason` will be set.\n\n        Examples::\n\n            assert RaisesExc(ValueError).matches(my_exception):\n            # is equivalent to\n            assert isinstance(my_exception, ValueError)\n\n            # this can be useful when checking e.g. the ``__cause__`` of an exception.\n            with pytest.raises(ValueError) as excinfo:\n                ...\n            assert RaisesExc(SyntaxError, match=\"foo\").matches(excinfo.value.__cause__)\n            # above line is equivalent to\n            assert isinstance(excinfo.value.__cause__, SyntaxError)\n            assert re.search(\"foo\", str(excinfo.value.__cause__)\n\n        \"\"\"\n        self._just_propagate = False\n        if exception is None:\n            self._fail_reason = \"exception is None\"\n            return False\n        if not self._check_type(exception):\n            self._just_propagate = True\n            return False\n\n        if not self._check_match(exception):\n            return False\n\n        return self._check_check(exception)\n\n    def __repr__(self) -> str:\n        parameters = []\n        if self.expected_exceptions:\n            parameters.append(_exception_type_name(self.expected_exceptions))\n        if self.match is not None:\n            # If no flags were specified, discard the redundant re.compile() here.\n            parameters.append(\n                f\"match={_match_pattern(self.match)!r}\",\n            )\n        if self.check is not None:\n            parameters.append(f\"check={repr_callable(self.check)}\")\n        return f\"RaisesExc({', '.join(parameters)})\"\n\n    def _check_type(self, exception: BaseException) -> TypeGuard[BaseExcT_co_default]:\n        self._fail_reason = _check_raw_type(self.expected_exceptions, exception)\n        return self._fail_reason is None\n\n    def __enter__(self) -> ExceptionInfo[BaseExcT_co_default]:\n        self.excinfo: ExceptionInfo[BaseExcT_co_default] = ExceptionInfo.for_later()\n        return self.excinfo\n\n    # TODO: move common code into superclass\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: types.TracebackType | None,\n    ) -> bool:\n        __tracebackhide__ = True\n        if exc_type is None:\n            if not self.expected_exceptions:\n                fail(\"DID NOT RAISE any exception\")\n            if len(self.expected_exceptions) > 1:\n                fail(f\"DID NOT RAISE any of {self.expected_exceptions!r}\")\n\n            fail(f\"DID NOT RAISE {self.expected_exceptions[0]!r}\")\n\n        assert self.excinfo is not None, (\n            \"Internal error - should have been constructed in __enter__\"\n        )\n\n        if not self.matches(exc_val):\n            if self._just_propagate:\n                return False\n            raise AssertionError(self._fail_reason)\n\n        # Cast to narrow the exception type now that it's verified....\n        # even though the TypeGuard in self.matches should be narrowing\n        exc_info = cast(\n            \"tuple[type[BaseExcT_co_default], BaseExcT_co_default, types.TracebackType]\",\n            (exc_type, exc_val, exc_tb),\n        )\n        self.excinfo.fill_unfilled(exc_info)\n        return True\n\n\n@final\nclass RaisesGroup(AbstractRaises[BaseExceptionGroup[BaseExcT_co]]):\n    \"\"\"\n    .. versionadded:: 8.4\n\n    Contextmanager for checking for an expected :exc:`ExceptionGroup`.\n    This works similar to :func:`pytest.raises`, but allows for specifying the structure of an :exc:`ExceptionGroup`.\n    :meth:`ExceptionInfo.group_contains` also tries to handle exception groups,\n    but it is very bad at checking that you *didn't* get unexpected exceptions.\n\n    The catching behaviour differs from :ref:`except* <except_star>`, being much\n    stricter about the structure by default.\n    By using ``allow_unwrapped=True`` and ``flatten_subgroups=True`` you can match\n    :ref:`except* <except_star>` fully when expecting a single exception.\n\n    :param args:\n        Any number of exception types, :class:`RaisesGroup` or :class:`RaisesExc`\n        to specify the exceptions contained in this exception.\n        All specified exceptions must be present in the raised group, *and no others*.\n\n        If you expect a variable number of exceptions you need to use\n        :func:`pytest.raises(ExceptionGroup) <pytest.raises>` and manually check\n        the contained exceptions. Consider making use of :meth:`RaisesExc.matches`.\n\n        It does not care about the order of the exceptions, so\n        ``RaisesGroup(ValueError, TypeError)``\n        is equivalent to\n        ``RaisesGroup(TypeError, ValueError)``.\n    :kwparam str | re.Pattern[str] | None match:\n        If specified, a string containing a regular expression,\n        or a regular expression object, that is tested against the string\n        representation of the exception group and its :pep:`678` `__notes__`\n        using :func:`re.search`.\n\n        To match a literal string that may contain :ref:`special characters\n        <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.\n\n        Note that \" (5 subgroups)\" will be stripped from the ``repr`` before matching.\n    :kwparam Callable[[E], bool] check:\n        If specified, a callable that will be called with the group as a parameter\n        after successfully matching the expected exceptions. If it returns ``True``\n        it will be considered a match, if not it will be considered a failed match.\n    :kwparam bool allow_unwrapped:\n        If expecting a single exception or :class:`RaisesExc` it will match even\n        if the exception is not inside an exceptiongroup.\n\n        Using this together with ``match``, ``check`` or expecting multiple exceptions\n        will raise an error.\n    :kwparam bool flatten_subgroups:\n        \"flatten\" any groups inside the raised exception group, extracting all exceptions\n        inside any nested groups, before matching. Without this it expects you to\n        fully specify the nesting structure by passing :class:`RaisesGroup` as expected\n        parameter.\n\n    Examples::\n\n        with RaisesGroup(ValueError):\n            raise ExceptionGroup(\"\", (ValueError(),))\n        # match\n        with RaisesGroup(\n            ValueError,\n            ValueError,\n            RaisesExc(TypeError, match=\"^expected int$\"),\n            match=\"^my group$\",\n        ):\n            raise ExceptionGroup(\n                \"my group\",\n                [\n                    ValueError(),\n                    TypeError(\"expected int\"),\n                    ValueError(),\n                ],\n            )\n        # check\n        with RaisesGroup(\n            KeyboardInterrupt,\n            match=\"^hello$\",\n            check=lambda x: isinstance(x.__cause__, ValueError),\n        ):\n            raise BaseExceptionGroup(\"hello\", [KeyboardInterrupt()]) from ValueError\n        # nested groups\n        with RaisesGroup(RaisesGroup(ValueError)):\n            raise ExceptionGroup(\"\", (ExceptionGroup(\"\", (ValueError(),)),))\n\n        # flatten_subgroups\n        with RaisesGroup(ValueError, flatten_subgroups=True):\n            raise ExceptionGroup(\"\", (ExceptionGroup(\"\", (ValueError(),)),))\n\n        # allow_unwrapped\n        with RaisesGroup(ValueError, allow_unwrapped=True):\n            raise ValueError\n\n\n    :meth:`RaisesGroup.matches` can also be used directly to check a standalone exception group.\n\n\n    The matching algorithm is greedy, which means cases such as this may fail::\n\n        with RaisesGroup(ValueError, RaisesExc(ValueError, match=\"hello\")):\n            raise ExceptionGroup(\"\", (ValueError(\"hello\"), ValueError(\"goodbye\")))\n\n    even though it generally does not care about the order of the exceptions in the group.\n    To avoid the above you should specify the first :exc:`ValueError` with a :class:`RaisesExc` as well.\n\n    .. note::\n        When raised exceptions don't match the expected ones, you'll get a detailed error\n        message explaining why. This includes ``repr(check)`` if set, which in Python can be\n        overly verbose, showing memory locations etc etc.\n\n        If installed and imported (in e.g. ``conftest.py``), the ``hypothesis`` library will\n        monkeypatch this output to provide shorter & more readable repr's.\n    \"\"\"\n\n    # allow_unwrapped=True requires: singular exception, exception not being\n    # RaisesGroup instance, match is None, check is None\n    @overload\n    def __init__(\n        self,\n        expected_exception: type[BaseExcT_co] | RaisesExc[BaseExcT_co],\n        /,\n        *,\n        allow_unwrapped: Literal[True],\n        flatten_subgroups: bool = False,\n    ) -> None: ...\n\n    # flatten_subgroups = True also requires no nested RaisesGroup\n    @overload\n    def __init__(\n        self,\n        expected_exception: type[BaseExcT_co] | RaisesExc[BaseExcT_co],\n        /,\n        *other_exceptions: type[BaseExcT_co] | RaisesExc[BaseExcT_co],\n        flatten_subgroups: Literal[True],\n        match: str | Pattern[str] | None = None,\n        check: Callable[[BaseExceptionGroup[BaseExcT_co]], bool] | None = None,\n    ) -> None: ...\n\n    # simplify the typevars if possible (the following 3 are equivalent but go simpler->complicated)\n    # ... the first handles RaisesGroup[ValueError], the second RaisesGroup[ExceptionGroup[ValueError]],\n    #     the third RaisesGroup[ValueError | ExceptionGroup[ValueError]].\n    # ... otherwise, we will get results like RaisesGroup[ValueError | ExceptionGroup[Never]] (I think)\n    #     (technically correct but misleading)\n    @overload\n    def __init__(\n        self: RaisesGroup[ExcT_1],\n        expected_exception: type[ExcT_1] | RaisesExc[ExcT_1],\n        /,\n        *other_exceptions: type[ExcT_1] | RaisesExc[ExcT_1],\n        match: str | Pattern[str] | None = None,\n        check: Callable[[ExceptionGroup[ExcT_1]], bool] | None = None,\n    ) -> None: ...\n\n    @overload\n    def __init__(\n        self: RaisesGroup[ExceptionGroup[ExcT_2]],\n        expected_exception: RaisesGroup[ExcT_2],\n        /,\n        *other_exceptions: RaisesGroup[ExcT_2],\n        match: str | Pattern[str] | None = None,\n        check: Callable[[ExceptionGroup[ExceptionGroup[ExcT_2]]], bool] | None = None,\n    ) -> None: ...\n\n    @overload\n    def __init__(\n        self: RaisesGroup[ExcT_1 | ExceptionGroup[ExcT_2]],\n        expected_exception: type[ExcT_1] | RaisesExc[ExcT_1] | RaisesGroup[ExcT_2],\n        /,\n        *other_exceptions: type[ExcT_1] | RaisesExc[ExcT_1] | RaisesGroup[ExcT_2],\n        match: str | Pattern[str] | None = None,\n        check: (\n            Callable[[ExceptionGroup[ExcT_1 | ExceptionGroup[ExcT_2]]], bool] | None\n        ) = None,\n    ) -> None: ...\n\n    # same as the above 3 but handling BaseException\n    @overload\n    def __init__(\n        self: RaisesGroup[BaseExcT_1],\n        expected_exception: type[BaseExcT_1] | RaisesExc[BaseExcT_1],\n        /,\n        *other_exceptions: type[BaseExcT_1] | RaisesExc[BaseExcT_1],\n        match: str | Pattern[str] | None = None,\n        check: Callable[[BaseExceptionGroup[BaseExcT_1]], bool] | None = None,\n    ) -> None: ...\n\n    @overload\n    def __init__(\n        self: RaisesGroup[BaseExceptionGroup[BaseExcT_2]],\n        expected_exception: RaisesGroup[BaseExcT_2],\n        /,\n        *other_exceptions: RaisesGroup[BaseExcT_2],\n        match: str | Pattern[str] | None = None,\n        check: (\n            Callable[[BaseExceptionGroup[BaseExceptionGroup[BaseExcT_2]]], bool] | None\n        ) = None,\n    ) -> None: ...\n\n    @overload\n    def __init__(\n        self: RaisesGroup[BaseExcT_1 | BaseExceptionGroup[BaseExcT_2]],\n        expected_exception: type[BaseExcT_1]\n        | RaisesExc[BaseExcT_1]\n        | RaisesGroup[BaseExcT_2],\n        /,\n        *other_exceptions: type[BaseExcT_1]\n        | RaisesExc[BaseExcT_1]\n        | RaisesGroup[BaseExcT_2],\n        match: str | Pattern[str] | None = None,\n        check: (\n            Callable[\n                [BaseExceptionGroup[BaseExcT_1 | BaseExceptionGroup[BaseExcT_2]]],\n                bool,\n            ]\n            | None\n        ) = None,\n    ) -> None: ...\n\n    def __init__(\n        self: RaisesGroup[ExcT_1 | BaseExcT_1 | BaseExceptionGroup[BaseExcT_2]],\n        expected_exception: type[BaseExcT_1]\n        | RaisesExc[BaseExcT_1]\n        | RaisesGroup[BaseExcT_2],\n        /,\n        *other_exceptions: type[BaseExcT_1]\n        | RaisesExc[BaseExcT_1]\n        | RaisesGroup[BaseExcT_2],\n        allow_unwrapped: bool = False,\n        flatten_subgroups: bool = False,\n        match: str | Pattern[str] | None = None,\n        check: (\n            Callable[[BaseExceptionGroup[BaseExcT_1]], bool]\n            | Callable[[ExceptionGroup[ExcT_1]], bool]\n            | None\n        ) = None,\n    ):\n        # The type hint on the `self` and `check` parameters uses different formats\n        # that are *very* hard to reconcile while adhering to the overloads, so we cast\n        # it to avoid an error when passing it to super().__init__\n        check = cast(\n            \"Callable[[BaseExceptionGroup[ExcT_1|BaseExcT_1|BaseExceptionGroup[BaseExcT_2]]], bool]\",\n            check,\n        )\n        super().__init__(match=match, check=check)\n        self.allow_unwrapped = allow_unwrapped\n        self.flatten_subgroups: bool = flatten_subgroups\n        self.is_baseexception = False\n\n        if allow_unwrapped and other_exceptions:\n            raise ValueError(\n                \"You cannot specify multiple exceptions with `allow_unwrapped=True.`\"\n                \" If you want to match one of multiple possible exceptions you should\"\n                \" use a `RaisesExc`.\"\n                \" E.g. `RaisesExc(check=lambda e: isinstance(e, (...)))`\",\n            )\n        if allow_unwrapped and isinstance(expected_exception, RaisesGroup):\n            raise ValueError(\n                \"`allow_unwrapped=True` has no effect when expecting a `RaisesGroup`.\"\n                \" You might want it in the expected `RaisesGroup`, or\"\n                \" `flatten_subgroups=True` if you don't care about the structure.\",\n            )\n        if allow_unwrapped and (match is not None or check is not None):\n            raise ValueError(\n                \"`allow_unwrapped=True` bypasses the `match` and `check` parameters\"\n                \" if the exception is unwrapped. If you intended to match/check the\"\n                \" exception you should use a `RaisesExc` object. If you want to match/check\"\n                \" the exceptiongroup when the exception *is* wrapped you need to\"\n                \" do e.g. `if isinstance(exc.value, ExceptionGroup):\"\n                \" assert RaisesGroup(...).matches(exc.value)` afterwards.\",\n            )\n\n        self.expected_exceptions: tuple[\n            type[BaseExcT_co] | RaisesExc[BaseExcT_co] | RaisesGroup[BaseException], ...\n        ] = tuple(\n            self._parse_excgroup(e, \"a BaseException type, RaisesExc, or RaisesGroup\")\n            for e in (\n                expected_exception,\n                *other_exceptions,\n            )\n        )\n\n    def _parse_excgroup(\n        self,\n        exc: (\n            type[BaseExcT_co]\n            | types.GenericAlias\n            | RaisesExc[BaseExcT_1]\n            | RaisesGroup[BaseExcT_2]\n        ),\n        expected: str,\n    ) -> type[BaseExcT_co] | RaisesExc[BaseExcT_1] | RaisesGroup[BaseExcT_2]:\n        # verify exception type and set `self.is_baseexception`\n        if isinstance(exc, RaisesGroup):\n            if self.flatten_subgroups:\n                raise ValueError(\n                    \"You cannot specify a nested structure inside a RaisesGroup with\"\n                    \" `flatten_subgroups=True`. The parameter will flatten subgroups\"\n                    \" in the raised exceptiongroup before matching, which would never\"\n                    \" match a nested structure.\",\n                )\n            self.is_baseexception |= exc.is_baseexception\n            exc._nested = True\n            return exc\n        elif isinstance(exc, RaisesExc):\n            self.is_baseexception |= exc.is_baseexception\n            exc._nested = True\n            return exc\n        elif isinstance(exc, tuple):\n            raise TypeError(\n                f\"Expected {expected}, but got {type(exc).__name__!r}.\\n\"\n                \"RaisesGroup does not support tuples of exception types when expecting one of \"\n                \"several possible exception types like RaisesExc.\\n\"\n                \"If you meant to expect a group with multiple exceptions, list them as separate arguments.\"\n            )\n        else:\n            return super()._parse_exc(exc, expected)\n\n    @overload\n    def __enter__(\n        self: RaisesGroup[ExcT_1],\n    ) -> ExceptionInfo[ExceptionGroup[ExcT_1]]: ...\n    @overload\n    def __enter__(\n        self: RaisesGroup[BaseExcT_1],\n    ) -> ExceptionInfo[BaseExceptionGroup[BaseExcT_1]]: ...\n\n    def __enter__(self) -> ExceptionInfo[BaseExceptionGroup[BaseException]]:\n        self.excinfo: ExceptionInfo[BaseExceptionGroup[BaseExcT_co]] = (\n            ExceptionInfo.for_later()\n        )\n        return self.excinfo\n\n    def __repr__(self) -> str:\n        reqs = [\n            e.__name__ if isinstance(e, type) else repr(e)\n            for e in self.expected_exceptions\n        ]\n        if self.allow_unwrapped:\n            reqs.append(f\"allow_unwrapped={self.allow_unwrapped}\")\n        if self.flatten_subgroups:\n            reqs.append(f\"flatten_subgroups={self.flatten_subgroups}\")\n        if self.match is not None:\n            # If no flags were specified, discard the redundant re.compile() here.\n            reqs.append(f\"match={_match_pattern(self.match)!r}\")\n        if self.check is not None:\n            reqs.append(f\"check={repr_callable(self.check)}\")\n        return f\"RaisesGroup({', '.join(reqs)})\"\n\n    def _unroll_exceptions(\n        self,\n        exceptions: Sequence[BaseException],\n    ) -> Sequence[BaseException]:\n        \"\"\"Used if `flatten_subgroups=True`.\"\"\"\n        res: list[BaseException] = []\n        for exc in exceptions:\n            if isinstance(exc, BaseExceptionGroup):\n                res.extend(self._unroll_exceptions(exc.exceptions))\n\n            else:\n                res.append(exc)\n        return res\n\n    @overload\n    def matches(\n        self: RaisesGroup[ExcT_1],\n        exception: BaseException | None,\n    ) -> TypeGuard[ExceptionGroup[ExcT_1]]: ...\n    @overload\n    def matches(\n        self: RaisesGroup[BaseExcT_1],\n        exception: BaseException | None,\n    ) -> TypeGuard[BaseExceptionGroup[BaseExcT_1]]: ...\n\n    def matches(\n        self,\n        exception: BaseException | None,\n    ) -> bool:\n        \"\"\"Check if an exception matches the requirements of this RaisesGroup.\n        If it fails, `RaisesGroup.fail_reason` will be set.\n\n        Example::\n\n            with pytest.raises(TypeError) as excinfo:\n                ...\n            assert RaisesGroup(ValueError).matches(excinfo.value.__cause__)\n            # the above line is equivalent to\n            myexc = excinfo.value.__cause\n            assert isinstance(myexc, BaseExceptionGroup)\n            assert len(myexc.exceptions) == 1\n            assert isinstance(myexc.exceptions[0], ValueError)\n        \"\"\"\n        self._fail_reason = None\n        if exception is None:\n            self._fail_reason = \"exception is None\"\n            return False\n        if not isinstance(exception, BaseExceptionGroup):\n            # we opt to only print type of the exception here, as the repr would\n            # likely be quite long\n            not_group_msg = f\"`{type(exception).__name__}()` is not an exception group\"\n            if len(self.expected_exceptions) > 1:\n                self._fail_reason = not_group_msg\n                return False\n            # if we have 1 expected exception, check if it would work even if\n            # allow_unwrapped is not set\n            res = self._check_expected(self.expected_exceptions[0], exception)\n            if res is None and self.allow_unwrapped:\n                return True\n\n            if res is None:\n                self._fail_reason = (\n                    f\"{not_group_msg}, but would match with `allow_unwrapped=True`\"\n                )\n            elif self.allow_unwrapped:\n                self._fail_reason = res\n            else:\n                self._fail_reason = not_group_msg\n            return False\n\n        actual_exceptions: Sequence[BaseException] = exception.exceptions\n        if self.flatten_subgroups:\n            actual_exceptions = self._unroll_exceptions(actual_exceptions)\n\n        if not self._check_match(exception):\n            self._fail_reason = cast(str, self._fail_reason)\n            old_reason = self._fail_reason\n            if (\n                len(actual_exceptions) == len(self.expected_exceptions) == 1\n                and isinstance(expected := self.expected_exceptions[0], type)\n                and isinstance(actual := actual_exceptions[0], expected)\n                and self._check_match(actual)\n            ):\n                assert self.match is not None, \"can't be None if _check_match failed\"\n                assert self._fail_reason is old_reason is not None\n                self._fail_reason += (\n                    f\"\\n\"\n                    f\" but matched the expected `{self._repr_expected(expected)}`.\\n\"\n                    f\" You might want \"\n                    f\"`RaisesGroup(RaisesExc({expected.__name__}, match={_match_pattern(self.match)!r}))`\"\n                )\n            else:\n                self._fail_reason = old_reason\n            return False\n\n        # do the full check on expected exceptions\n        if not self._check_exceptions(\n            exception,\n            actual_exceptions,\n        ):\n            self._fail_reason = cast(str, self._fail_reason)\n            assert self._fail_reason is not None\n            old_reason = self._fail_reason\n            # if we're not expecting a nested structure, and there is one, do a second\n            # pass where we try flattening it\n            if (\n                not self.flatten_subgroups\n                and not any(\n                    isinstance(e, RaisesGroup) for e in self.expected_exceptions\n                )\n                and any(isinstance(e, BaseExceptionGroup) for e in actual_exceptions)\n                and self._check_exceptions(\n                    exception,\n                    self._unroll_exceptions(exception.exceptions),\n                )\n            ):\n                # only indent if it's a single-line reason. In a multi-line there's already\n                # indented lines that this does not belong to.\n                indent = \"  \" if \"\\n\" not in self._fail_reason else \"\"\n                self._fail_reason = (\n                    old_reason\n                    + f\"\\n{indent}Did you mean to use `flatten_subgroups=True`?\"\n                )\n            else:\n                self._fail_reason = old_reason\n            return False\n\n        # Only run `self.check` once we know `exception` is of the correct type.\n        if not self._check_check(exception):\n            reason = (\n                cast(str, self._fail_reason) + f\" on the {type(exception).__name__}\"\n            )\n            if (\n                len(actual_exceptions) == len(self.expected_exceptions) == 1\n                and isinstance(expected := self.expected_exceptions[0], type)\n                # we explicitly break typing here :)\n                and self._check_check(actual_exceptions[0])  # type: ignore[arg-type]\n            ):\n                self._fail_reason = reason + (\n                    f\", but did return True for the expected {self._repr_expected(expected)}.\"\n                    f\" You might want RaisesGroup(RaisesExc({expected.__name__}, check=<...>))\"\n                )\n            else:\n                self._fail_reason = reason\n            return False\n\n        return True\n\n    @staticmethod\n    def _check_expected(\n        expected_type: (\n            type[BaseException] | RaisesExc[BaseException] | RaisesGroup[BaseException]\n        ),\n        exception: BaseException,\n    ) -> str | None:\n        \"\"\"Helper method for `RaisesGroup.matches` and `RaisesGroup._check_exceptions`\n        to check one of potentially several expected exceptions.\"\"\"\n        if isinstance(expected_type, type):\n            return _check_raw_type(expected_type, exception)\n        res = expected_type.matches(exception)\n        if res:\n            return None\n        assert expected_type.fail_reason is not None\n        if expected_type.fail_reason.startswith(\"\\n\"):\n            return f\"\\n{expected_type!r}: {indent(expected_type.fail_reason, '  ')}\"\n        return f\"{expected_type!r}: {expected_type.fail_reason}\"\n\n    @staticmethod\n    def _repr_expected(e: type[BaseException] | AbstractRaises[BaseException]) -> str:\n        \"\"\"Get the repr of an expected type/RaisesExc/RaisesGroup, but we only want\n        the name if it's a type\"\"\"\n        if isinstance(e, type):\n            return _exception_type_name(e)\n        return repr(e)\n\n    @overload\n    def _check_exceptions(\n        self: RaisesGroup[ExcT_1],\n        _exception: Exception,\n        actual_exceptions: Sequence[Exception],\n    ) -> TypeGuard[ExceptionGroup[ExcT_1]]: ...\n    @overload\n    def _check_exceptions(\n        self: RaisesGroup[BaseExcT_1],\n        _exception: BaseException,\n        actual_exceptions: Sequence[BaseException],\n    ) -> TypeGuard[BaseExceptionGroup[BaseExcT_1]]: ...\n\n    def _check_exceptions(\n        self,\n        _exception: BaseException,\n        actual_exceptions: Sequence[BaseException],\n    ) -> bool:\n        \"\"\"Helper method for RaisesGroup.matches that attempts to pair up expected and actual exceptions\"\"\"\n        # The _exception parameter is not used, but necessary for the TypeGuard\n\n        # full table with all results\n        results = ResultHolder(self.expected_exceptions, actual_exceptions)\n\n        # (indexes of) raised exceptions that haven't (yet) found an expected\n        remaining_actual = list(range(len(actual_exceptions)))\n        # (indexes of) expected exceptions that haven't found a matching raised\n        failed_expected: list[int] = []\n        # successful greedy matches\n        matches: dict[int, int] = {}\n\n        # loop over expected exceptions first to get a more predictable result\n        for i_exp, expected in enumerate(self.expected_exceptions):\n            for i_rem in remaining_actual:\n                res = self._check_expected(expected, actual_exceptions[i_rem])\n                results.set_result(i_exp, i_rem, res)\n                if res is None:\n                    remaining_actual.remove(i_rem)\n                    matches[i_exp] = i_rem\n                    break\n            else:\n                failed_expected.append(i_exp)\n\n        # All exceptions matched up successfully\n        if not remaining_actual and not failed_expected:\n            return True\n\n        # in case of a single expected and single raised we simplify the output\n        if 1 == len(actual_exceptions) == len(self.expected_exceptions):\n            assert not matches\n            self._fail_reason = res\n            return False\n\n        # The test case is failing, so we can do a slow and exhaustive check to find\n        # duplicate matches etc that will be helpful in debugging\n        for i_exp, expected in enumerate(self.expected_exceptions):\n            for i_actual, actual in enumerate(actual_exceptions):\n                if results.has_result(i_exp, i_actual):\n                    continue\n                results.set_result(\n                    i_exp, i_actual, self._check_expected(expected, actual)\n                )\n\n        successful_str = (\n            f\"{len(matches)} matched exception{'s' if len(matches) > 1 else ''}. \"\n            if matches\n            else \"\"\n        )\n\n        # all expected were found\n        if not failed_expected and results.no_match_for_actual(remaining_actual):\n            self._fail_reason = (\n                f\"{successful_str}Unexpected exception(s):\"\n                f\" {[actual_exceptions[i] for i in remaining_actual]!r}\"\n            )\n            return False\n        # all raised exceptions were expected\n        if not remaining_actual and results.no_match_for_expected(failed_expected):\n            no_match_for_str = \", \".join(\n                self._repr_expected(self.expected_exceptions[i])\n                for i in failed_expected\n            )\n            self._fail_reason = f\"{successful_str}Too few exceptions raised, found no match for: [{no_match_for_str}]\"\n            return False\n\n        # if there's only one remaining and one failed, and the unmatched didn't match anything else,\n        # we elect to only print why the remaining and the failed didn't match.\n        if (\n            1 == len(remaining_actual) == len(failed_expected)\n            and results.no_match_for_actual(remaining_actual)\n            and results.no_match_for_expected(failed_expected)\n        ):\n            self._fail_reason = f\"{successful_str}{results.get_result(failed_expected[0], remaining_actual[0])}\"\n            return False\n\n        # there's both expected and raised exceptions without matches\n        s = \"\"\n        if matches:\n            s += f\"\\n{successful_str}\"\n        indent_1 = \" \" * 2\n        indent_2 = \" \" * 4\n\n        if not remaining_actual:\n            s += \"\\nToo few exceptions raised!\"\n        elif not failed_expected:\n            s += \"\\nUnexpected exception(s)!\"\n\n        if failed_expected:\n            s += \"\\nThe following expected exceptions did not find a match:\"\n            rev_matches = {v: k for k, v in matches.items()}\n        for i_failed in failed_expected:\n            s += (\n                f\"\\n{indent_1}{self._repr_expected(self.expected_exceptions[i_failed])}\"\n            )\n            for i_actual, actual in enumerate(actual_exceptions):\n                if results.get_result(i_exp, i_actual) is None:\n                    # we print full repr of match target\n                    s += (\n                        f\"\\n{indent_2}It matches {backquote(repr(actual))} which was paired with \"\n                        + backquote(\n                            self._repr_expected(\n                                self.expected_exceptions[rev_matches[i_actual]]\n                            )\n                        )\n                    )\n\n        if remaining_actual:\n            s += \"\\nThe following raised exceptions did not find a match\"\n        for i_actual in remaining_actual:\n            s += f\"\\n{indent_1}{actual_exceptions[i_actual]!r}:\"\n            for i_exp, expected in enumerate(self.expected_exceptions):\n                res = results.get_result(i_exp, i_actual)\n                if i_exp in failed_expected:\n                    assert res is not None\n                    if res[0] != \"\\n\":\n                        s += \"\\n\"\n                    s += indent(res, indent_2)\n                if res is None:\n                    # we print full repr of match target\n                    s += (\n                        f\"\\n{indent_2}It matches {backquote(self._repr_expected(expected))} \"\n                        f\"which was paired with {backquote(repr(actual_exceptions[matches[i_exp]]))}\"\n                    )\n\n        if len(self.expected_exceptions) == len(actual_exceptions) and possible_match(\n            results\n        ):\n            s += (\n                \"\\nThere exist a possible match when attempting an exhaustive check,\"\n                \" but RaisesGroup uses a greedy algorithm. \"\n                \"Please make your expected exceptions more stringent with `RaisesExc` etc\"\n                \" so the greedy algorithm can function.\"\n            )\n        self._fail_reason = s\n        return False\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: types.TracebackType | None,\n    ) -> bool:\n        __tracebackhide__ = True\n        if exc_type is None:\n            fail(f\"DID NOT RAISE any exception, expected `{self.expected_type()}`\")\n\n        assert self.excinfo is not None, (\n            \"Internal error - should have been constructed in __enter__\"\n        )\n\n        # group_str is the only thing that differs between RaisesExc and RaisesGroup...\n        # I might just scrap it? Or make it part of fail_reason\n        group_str = (\n            \"(group)\"\n            if self.allow_unwrapped and not issubclass(exc_type, BaseExceptionGroup)\n            else \"group\"\n        )\n\n        if not self.matches(exc_val):\n            fail(f\"Raised exception {group_str} did not match: {self._fail_reason}\")\n\n        # Cast to narrow the exception type now that it's verified....\n        # even though the TypeGuard in self.matches should be narrowing\n        exc_info = cast(\n            \"tuple[type[BaseExceptionGroup[BaseExcT_co]], BaseExceptionGroup[BaseExcT_co], types.TracebackType]\",\n            (exc_type, exc_val, exc_tb),\n        )\n        self.excinfo.fill_unfilled(exc_info)\n        return True\n\n    def expected_type(self) -> str:\n        subexcs = []\n        for e in self.expected_exceptions:\n            if isinstance(e, RaisesExc):\n                subexcs.append(repr(e))\n            elif isinstance(e, RaisesGroup):\n                subexcs.append(e.expected_type())\n            elif isinstance(e, type):\n                subexcs.append(e.__name__)\n            else:  # pragma: no cover\n                raise AssertionError(\"unknown type\")\n        group_type = \"Base\" if self.is_baseexception else \"\"\n        return f\"{group_type}ExceptionGroup({', '.join(subexcs)})\"\n\n\n@final\nclass NotChecked:\n    \"\"\"Singleton for unchecked values in ResultHolder\"\"\"\n\n\nclass ResultHolder:\n    \"\"\"Container for results of checking exceptions.\n    Used in RaisesGroup._check_exceptions and possible_match.\n    \"\"\"\n\n    def __init__(\n        self,\n        expected_exceptions: tuple[\n            type[BaseException] | AbstractRaises[BaseException], ...\n        ],\n        actual_exceptions: Sequence[BaseException],\n    ) -> None:\n        self.results: list[list[str | type[NotChecked] | None]] = [\n            [NotChecked for _ in expected_exceptions] for _ in actual_exceptions\n        ]\n\n    def set_result(self, expected: int, actual: int, result: str | None) -> None:\n        self.results[actual][expected] = result\n\n    def get_result(self, expected: int, actual: int) -> str | None:\n        res = self.results[actual][expected]\n        assert res is not NotChecked\n        # mypy doesn't support identity checking against anything but None\n        return res  # type: ignore[return-value]\n\n    def has_result(self, expected: int, actual: int) -> bool:\n        return self.results[actual][expected] is not NotChecked\n\n    def no_match_for_expected(self, expected: list[int]) -> bool:\n        for i in expected:\n            for actual_results in self.results:\n                assert actual_results[i] is not NotChecked\n                if actual_results[i] is None:\n                    return False\n        return True\n\n    def no_match_for_actual(self, actual: list[int]) -> bool:\n        for i in actual:\n            for res in self.results[i]:\n                assert res is not NotChecked\n                if res is None:\n                    return False\n        return True\n\n\ndef possible_match(results: ResultHolder, used: set[int] | None = None) -> bool:\n    if used is None:\n        used = set()\n    curr_row = len(used)\n    if curr_row == len(results.results):\n        return True\n    return any(\n        val is None and i not in used and possible_match(results, used | {i})\n        for (i, val) in enumerate(results.results[curr_row])\n    )\n"
  },
  {
    "path": "src/_pytest/recwarn.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Record warnings during test function execution.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom collections.abc import Generator\nfrom collections.abc import Iterator\nfrom pprint import pformat\nimport re\nfrom types import TracebackType\nfrom typing import Any\nfrom typing import final\nfrom typing import overload\nfrom typing import TYPE_CHECKING\nfrom typing import TypeVar\n\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\nimport warnings\n\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.fixtures import fixture\nfrom _pytest.outcomes import Exit\nfrom _pytest.outcomes import fail\n\n\nT = TypeVar(\"T\")\n\n\n@fixture\ndef recwarn() -> Generator[WarningsRecorder]:\n    \"\"\"Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.\n\n    See :ref:`warnings` for information on warning categories.\n    \"\"\"\n    wrec = WarningsRecorder(_ispytest=True)\n    with wrec:\n        warnings.simplefilter(\"default\")\n        yield wrec\n\n\n@overload\ndef deprecated_call(\n    *, match: str | re.Pattern[str] | None = ...\n) -> WarningsRecorder: ...\n\n\n@overload\ndef deprecated_call(func: Callable[..., T], *args: Any, **kwargs: Any) -> T: ...\n\n\ndef deprecated_call(\n    func: Callable[..., Any] | None = None, *args: Any, **kwargs: Any\n) -> WarningsRecorder | Any:\n    \"\"\"Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning`` or ``FutureWarning``.\n\n    This function can be used as a context manager::\n\n        >>> import warnings\n        >>> def api_call_v2():\n        ...     warnings.warn('use v3 of this api', DeprecationWarning)\n        ...     return 200\n\n        >>> import pytest\n        >>> with pytest.deprecated_call():\n        ...    assert api_call_v2() == 200\n\n    It can also be used by passing a function and ``*args`` and ``**kwargs``,\n    in which case it will ensure calling ``func(*args, **kwargs)`` produces one of\n    the warnings types above. The return value is the return value of the function.\n\n    In the context manager form you may use the keyword argument ``match`` to assert\n    that the warning matches a text or regex.\n\n    The context manager produces a list of :class:`warnings.WarningMessage` objects,\n    one for each warning raised.\n    \"\"\"\n    __tracebackhide__ = True\n    if func is not None:\n        args = (func, *args)\n    return warns(\n        (DeprecationWarning, PendingDeprecationWarning, FutureWarning), *args, **kwargs\n    )\n\n\n@overload\ndef warns(\n    expected_warning: type[Warning] | tuple[type[Warning], ...] = ...,\n    *,\n    match: str | re.Pattern[str] | None = ...,\n) -> WarningsChecker: ...\n\n\n@overload\ndef warns(\n    expected_warning: type[Warning] | tuple[type[Warning], ...],\n    func: Callable[..., T],\n    *args: Any,\n    **kwargs: Any,\n) -> T: ...\n\n\ndef warns(\n    expected_warning: type[Warning] | tuple[type[Warning], ...] = Warning,\n    *args: Any,\n    match: str | re.Pattern[str] | None = None,\n    **kwargs: Any,\n) -> WarningsChecker | Any:\n    r\"\"\"Assert that code raises a particular class of warning.\n\n    Specifically, the parameter ``expected_warning`` can be a warning class or tuple\n    of warning classes, and the code inside the ``with`` block must issue at least one\n    warning of that class or classes.\n\n    This helper produces a list of :class:`warnings.WarningMessage` objects, one for\n    each warning emitted (regardless of whether it is an ``expected_warning`` or not).\n    Since pytest 8.0, unmatched warnings are also re-emitted when the context closes.\n\n    This function can be used as a context manager::\n\n        >>> import pytest\n        >>> with pytest.warns(RuntimeWarning):\n        ...    warnings.warn(\"my warning\", RuntimeWarning)\n\n    In the context manager form you may use the keyword argument ``match`` to assert\n    that the warning matches a text or regex::\n\n        >>> with pytest.warns(UserWarning, match='must be 0 or None'):\n        ...     warnings.warn(\"value must be 0 or None\", UserWarning)\n\n        >>> with pytest.warns(UserWarning, match=r'must be \\d+$'):\n        ...     warnings.warn(\"value must be 42\", UserWarning)\n\n        >>> with pytest.warns(UserWarning):  # catch re-emitted warning\n        ...     with pytest.warns(UserWarning, match=r'must be \\d+$'):\n        ...         warnings.warn(\"this is not here\", UserWarning)\n        Traceback (most recent call last):\n          ...\n        Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...\n\n    **Using with** ``pytest.mark.parametrize``\n\n    When using :ref:`pytest.mark.parametrize ref` it is possible to parametrize tests\n    such that some runs raise a warning and others do not.\n\n    This could be achieved in the same way as with exceptions, see\n    :ref:`parametrizing_conditional_raising` for an example.\n\n    \"\"\"\n    __tracebackhide__ = True\n    if not args:\n        if kwargs:\n            argnames = \", \".join(sorted(kwargs))\n            raise TypeError(\n                f\"Unexpected keyword arguments passed to pytest.warns: {argnames}\"\n                \"\\nUse context-manager form instead?\"\n            )\n        return WarningsChecker(expected_warning, match_expr=match, _ispytest=True)\n    else:\n        func = args[0]\n        if not callable(func):\n            raise TypeError(f\"{func!r} object (type: {type(func)}) must be callable\")\n        with WarningsChecker(expected_warning, _ispytest=True):\n            return func(*args[1:], **kwargs)\n\n\nclass WarningsRecorder(warnings.catch_warnings):\n    \"\"\"A context manager to record raised warnings.\n\n    Each recorded warning is an instance of :class:`warnings.WarningMessage`.\n\n    Adapted from `warnings.catch_warnings`.\n\n    .. note::\n        ``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated\n        differently; see :ref:`ensuring_function_triggers`.\n\n    \"\"\"\n\n    def __init__(self, *, _ispytest: bool = False) -> None:\n        check_ispytest(_ispytest)\n        super().__init__(record=True)\n        self._entered = False\n        self._list: list[warnings.WarningMessage] = []\n\n    @property\n    def list(self) -> list[warnings.WarningMessage]:\n        \"\"\"The list of recorded warnings.\"\"\"\n        return self._list\n\n    def __getitem__(self, i: int) -> warnings.WarningMessage:\n        \"\"\"Get a recorded warning by index.\"\"\"\n        return self._list[i]\n\n    def __iter__(self) -> Iterator[warnings.WarningMessage]:\n        \"\"\"Iterate through the recorded warnings.\"\"\"\n        return iter(self._list)\n\n    def __len__(self) -> int:\n        \"\"\"The number of recorded warnings.\"\"\"\n        return len(self._list)\n\n    def pop(self, cls: type[Warning] = Warning) -> warnings.WarningMessage:\n        \"\"\"Pop the first recorded warning which is an instance of ``cls``,\n        but not an instance of a child class of any other match.\n        Raises ``AssertionError`` if there is no match.\n        \"\"\"\n        best_idx: int | None = None\n        for i, w in enumerate(self._list):\n            if w.category == cls:\n                return self._list.pop(i)  # exact match, stop looking\n            if issubclass(w.category, cls) and (\n                best_idx is None\n                or not issubclass(w.category, self._list[best_idx].category)\n            ):\n                best_idx = i\n        if best_idx is not None:\n            return self._list.pop(best_idx)\n        __tracebackhide__ = True\n        raise AssertionError(f\"{cls!r} not found in warning list\")\n\n    def clear(self) -> None:\n        \"\"\"Clear the list of recorded warnings.\"\"\"\n        self._list[:] = []\n\n    # Type ignored because we basically want the `catch_warnings` generic type\n    # parameter to be ourselves but that is not possible(?).\n    def __enter__(self) -> Self:  # type: ignore[override]\n        if self._entered:\n            __tracebackhide__ = True\n            raise RuntimeError(f\"Cannot enter {self!r} twice\")\n        _list = super().__enter__()\n        # record=True means it's None.\n        assert _list is not None\n        self._list = _list\n        warnings.simplefilter(\"always\")\n        return self\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        if not self._entered:\n            __tracebackhide__ = True\n            raise RuntimeError(f\"Cannot exit {self!r} without entering first\")\n\n        super().__exit__(exc_type, exc_val, exc_tb)\n\n        # Built-in catch_warnings does not reset entered state so we do it\n        # manually here for this context manager to become reusable.\n        self._entered = False\n\n\n@final\nclass WarningsChecker(WarningsRecorder):\n    def __init__(\n        self,\n        expected_warning: type[Warning] | tuple[type[Warning], ...] = Warning,\n        match_expr: str | re.Pattern[str] | None = None,\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        super().__init__(_ispytest=True)\n\n        msg = \"exceptions must be derived from Warning, not %s\"\n        if isinstance(expected_warning, tuple):\n            for exc in expected_warning:\n                if not issubclass(exc, Warning):\n                    raise TypeError(msg % type(exc))\n            expected_warning_tup = expected_warning\n        elif isinstance(expected_warning, type) and issubclass(\n            expected_warning, Warning\n        ):\n            expected_warning_tup = (expected_warning,)\n        else:\n            raise TypeError(msg % type(expected_warning))\n\n        self.expected_warning = expected_warning_tup\n        self.match_expr = match_expr\n\n    def matches(self, warning: warnings.WarningMessage) -> bool:\n        assert self.expected_warning is not None\n        return issubclass(warning.category, self.expected_warning) and bool(\n            self.match_expr is None or re.search(self.match_expr, str(warning.message))\n        )\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> None:\n        super().__exit__(exc_type, exc_val, exc_tb)\n\n        __tracebackhide__ = True\n\n        # BaseExceptions like pytest.{skip,fail,xfail,exit} or Ctrl-C within\n        # pytest.warns should *not* trigger \"DID NOT WARN\" and get suppressed\n        # when the warning doesn't happen. Control-flow exceptions should always\n        # propagate.\n        if exc_val is not None and (\n            not isinstance(exc_val, Exception)\n            # Exit is an Exception, not a BaseException, for some reason.\n            or isinstance(exc_val, Exit)\n        ):\n            return\n\n        def found_str() -> str:\n            return pformat([record.message for record in self], indent=2)\n\n        try:\n            if not any(issubclass(w.category, self.expected_warning) for w in self):\n                fail(\n                    f\"DID NOT WARN. No warnings of type {self.expected_warning} were emitted.\\n\"\n                    f\" Emitted warnings: {found_str()}.\"\n                )\n            elif not any(self.matches(w) for w in self):\n                fail(\n                    f\"DID NOT WARN. No warnings of type {self.expected_warning} matching the regex were emitted.\\n\"\n                    f\" Regex: {self.match_expr}\\n\"\n                    f\" Emitted warnings: {found_str()}.\"\n                )\n        finally:\n            # Whether or not any warnings matched, we want to re-emit all unmatched warnings.\n            for w in self:\n                if not self.matches(w):\n                    warnings.warn_explicit(\n                        message=w.message,\n                        category=w.category,\n                        filename=w.filename,\n                        lineno=w.lineno,\n                        module=w.__module__,\n                        source=w.source,\n                    )\n\n            # Currently in Python it is possible to pass other types than an\n            # `str` message when creating `Warning` instances, however this\n            # causes an exception when :func:`warnings.filterwarnings` is used\n            # to filter those warnings. See\n            # https://github.com/python/cpython/issues/103577 for a discussion.\n            # While this can be considered a bug in CPython, we put guards in\n            # pytest as the error message produced without this check in place\n            # is confusing (#10865).\n            for w in self:\n                if type(w.message) is not UserWarning:\n                    # If the warning was of an incorrect type then `warnings.warn()`\n                    # creates a UserWarning. Any other warning must have been specified\n                    # explicitly.\n                    continue\n                if not w.message.args:\n                    # UserWarning() without arguments must have been specified explicitly.\n                    continue\n                msg = w.message.args[0]\n                if isinstance(msg, str):\n                    continue\n                # It's possible that UserWarning was explicitly specified, and\n                # its first argument was not a string. But that case can't be\n                # distinguished from an invalid type.\n                raise TypeError(\n                    f\"Warning must be str or Warning, got {msg!r} (type {type(msg).__name__})\"\n                )\n"
  },
  {
    "path": "src/_pytest/reports.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nfrom collections.abc import Mapping\nfrom collections.abc import Sequence\nimport dataclasses\nfrom io import StringIO\nimport os\nfrom pprint import pprint\nimport sys\nfrom typing import Any\nfrom typing import cast\nfrom typing import final\nfrom typing import Literal\nfrom typing import NoReturn\nfrom typing import TYPE_CHECKING\n\nfrom _pytest._code.code import ExceptionChainRepr\nfrom _pytest._code.code import ExceptionInfo\nfrom _pytest._code.code import ExceptionRepr\nfrom _pytest._code.code import ReprEntry\nfrom _pytest._code.code import ReprEntryNative\nfrom _pytest._code.code import ReprExceptionInfo\nfrom _pytest._code.code import ReprFileLocation\nfrom _pytest._code.code import ReprFuncArgs\nfrom _pytest._code.code import ReprLocals\nfrom _pytest._code.code import ReprTraceback\nfrom _pytest._code.code import TerminalRepr\nfrom _pytest._io import TerminalWriter\nfrom _pytest.config import Config\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import Item\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import skip\n\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import BaseExceptionGroup\n\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\n    from _pytest.runner import CallInfo\n\n\ndef getworkerinfoline(node):\n    try:\n        return node._workerinfocache\n    except AttributeError:\n        d = node.workerinfo\n        ver = \"{}.{}.{}\".format(*d[\"version_info\"][:3])\n        node._workerinfocache = s = \"[{}] {} -- Python {} {}\".format(\n            d[\"id\"], d[\"sysplatform\"], ver, d[\"executable\"]\n        )\n        return s\n\n\nclass BaseReport:\n    when: str | None\n    location: tuple[str, int | None, str] | None\n    longrepr: (\n        None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr\n    )\n    sections: list[tuple[str, str]]\n    nodeid: str\n    outcome: Literal[\"passed\", \"failed\", \"skipped\"]\n\n    def __init__(self, **kw: Any) -> None:\n        self.__dict__.update(kw)\n\n    if TYPE_CHECKING:\n        # Can have arbitrary fields given to __init__().\n        def __getattr__(self, key: str) -> Any: ...\n\n    def toterminal(self, out: TerminalWriter) -> None:\n        if hasattr(self, \"node\"):\n            worker_info = getworkerinfoline(self.node)\n            if worker_info:\n                out.line(worker_info)\n\n        longrepr = self.longrepr\n        if longrepr is None:\n            return\n\n        if hasattr(longrepr, \"toterminal\"):\n            longrepr_terminal = cast(TerminalRepr, longrepr)\n            longrepr_terminal.toterminal(out)\n        else:\n            try:\n                s = str(longrepr)\n            except UnicodeEncodeError:\n                s = \"<unprintable longrepr>\"\n            out.line(s)\n\n    def get_sections(self, prefix: str) -> Iterator[tuple[str, str]]:\n        for name, content in self.sections:\n            if name.startswith(prefix):\n                yield prefix, content\n\n    @property\n    def longreprtext(self) -> str:\n        \"\"\"Read-only property that returns the full string representation of\n        ``longrepr``.\n\n        .. versionadded:: 3.0\n        \"\"\"\n        file = StringIO()\n        tw = TerminalWriter(file)\n        tw.hasmarkup = False\n        self.toterminal(tw)\n        exc = file.getvalue()\n        return exc.strip()\n\n    @property\n    def caplog(self) -> str:\n        \"\"\"Return captured log lines, if log capturing is enabled.\n\n        .. versionadded:: 3.5\n        \"\"\"\n        return \"\\n\".join(\n            content for (prefix, content) in self.get_sections(\"Captured log\")\n        )\n\n    @property\n    def capstdout(self) -> str:\n        \"\"\"Return captured text from stdout, if capturing is enabled.\n\n        .. versionadded:: 3.0\n        \"\"\"\n        return \"\".join(\n            content for (prefix, content) in self.get_sections(\"Captured stdout\")\n        )\n\n    @property\n    def capstderr(self) -> str:\n        \"\"\"Return captured text from stderr, if capturing is enabled.\n\n        .. versionadded:: 3.0\n        \"\"\"\n        return \"\".join(\n            content for (prefix, content) in self.get_sections(\"Captured stderr\")\n        )\n\n    @property\n    def passed(self) -> bool:\n        \"\"\"Whether the outcome is passed.\"\"\"\n        return self.outcome == \"passed\"\n\n    @property\n    def failed(self) -> bool:\n        \"\"\"Whether the outcome is failed.\"\"\"\n        return self.outcome == \"failed\"\n\n    @property\n    def skipped(self) -> bool:\n        \"\"\"Whether the outcome is skipped.\"\"\"\n        return self.outcome == \"skipped\"\n\n    @property\n    def fspath(self) -> str:\n        \"\"\"The path portion of the reported node, as a string.\"\"\"\n        return self.nodeid.split(\"::\")[0]\n\n    @property\n    def count_towards_summary(self) -> bool:\n        \"\"\"**Experimental** Whether this report should be counted towards the\n        totals shown at the end of the test session: \"1 passed, 1 failure, etc\".\n\n        .. note::\n\n            This function is considered **experimental**, so beware that it is subject to changes\n            even in patch releases.\n        \"\"\"\n        return True\n\n    @property\n    def head_line(self) -> str | None:\n        \"\"\"**Experimental** The head line shown with longrepr output for this\n        report, more commonly during traceback representation during\n        failures::\n\n            ________ Test.foo ________\n\n\n        In the example above, the head_line is \"Test.foo\".\n\n        .. note::\n\n            This function is considered **experimental**, so beware that it is subject to changes\n            even in patch releases.\n        \"\"\"\n        if self.location is not None:\n            _fspath, _lineno, domain = self.location\n            return domain\n        return None\n\n    def _get_verbose_word_with_markup(\n        self, config: Config, default_markup: Mapping[str, bool]\n    ) -> tuple[str, Mapping[str, bool]]:\n        _category, _short, verbose = config.hook.pytest_report_teststatus(\n            report=self, config=config\n        )\n\n        if isinstance(verbose, str):\n            return verbose, default_markup\n\n        if isinstance(verbose, Sequence) and len(verbose) == 2:\n            word, markup = verbose\n            if isinstance(word, str) and isinstance(markup, Mapping):\n                return word, markup\n\n        fail(  # pragma: no cover\n            \"pytest_report_teststatus() hook (from a plugin) returned \"\n            f\"an invalid verbose value: {verbose!r}.\\nExpected either a string \"\n            \"or a tuple of (word, markup).\"\n        )\n\n    def _to_json(self) -> dict[str, Any]:\n        \"\"\"Return the contents of this report as a dict of builtin entries,\n        suitable for serialization.\n\n        This was originally the serialize_report() function from xdist (ca03269).\n\n        Experimental method.\n        \"\"\"\n        return _report_to_json(self)\n\n    @classmethod\n    def _from_json(cls, reportdict: dict[str, object]) -> Self:\n        \"\"\"Create either a TestReport or CollectReport, depending on the calling class.\n\n        It is the callers responsibility to know which class to pass here.\n\n        This was originally the serialize_report() function from xdist (ca03269).\n\n        Experimental method.\n        \"\"\"\n        kwargs = _report_kwargs_from_json(reportdict)\n        return cls(**kwargs)\n\n\ndef _report_unserialization_failure(\n    type_name: str, report_class: type[BaseReport], reportdict\n) -> NoReturn:\n    url = \"https://github.com/pytest-dev/pytest/issues\"\n    stream = StringIO()\n    pprint(\"-\" * 100, stream=stream)\n    pprint(f\"INTERNALERROR: Unknown entry type returned: {type_name}\", stream=stream)\n    pprint(f\"report_name: {report_class}\", stream=stream)\n    pprint(reportdict, stream=stream)\n    pprint(f\"Please report this bug at {url}\", stream=stream)\n    pprint(\"-\" * 100, stream=stream)\n    raise RuntimeError(stream.getvalue())\n\n\ndef _format_failed_longrepr(\n    item: Item, call: CallInfo[None], excinfo: ExceptionInfo[BaseException]\n):\n    if call.when == \"call\":\n        longrepr = item.repr_failure(excinfo)\n    else:\n        # Exception in setup or teardown.\n        longrepr = item._repr_failure_py(\n            excinfo, style=item.config.getoption(\"tbstyle\", \"auto\")\n        )\n    return longrepr\n\n\ndef _format_exception_group_all_skipped_longrepr(\n    item: Item,\n    excinfo: ExceptionInfo[BaseExceptionGroup[BaseException | BaseExceptionGroup]],\n) -> tuple[str, int, str]:\n    r = excinfo._getreprcrash()\n    assert r is not None, (\n        \"There should always be a traceback entry for skipping a test.\"\n    )\n    if all(\n        getattr(skip, \"_use_item_location\", False) for skip in excinfo.value.exceptions\n    ):\n        path, line = item.reportinfo()[:2]\n        assert line is not None\n        loc = (os.fspath(path), line + 1)\n        default_msg = \"skipped\"\n    else:\n        loc = (str(r.path), r.lineno)\n        default_msg = r.message\n\n    # Get all unique skip messages.\n    msgs: list[str] = []\n    for exception in excinfo.value.exceptions:\n        m = getattr(exception, \"msg\", None) or (\n            exception.args[0] if exception.args else None\n        )\n        if m and m not in msgs:\n            msgs.append(m)\n\n    reason = \"; \".join(msgs) if msgs else default_msg\n    longrepr = (*loc, reason)\n    return longrepr\n\n\nclass TestReport(BaseReport):\n    \"\"\"Basic test report object (also used for setup and teardown calls if\n    they fail).\n\n    Reports can contain arbitrary extra attributes.\n    \"\"\"\n\n    __test__ = False\n\n    # Defined by skipping plugin.\n    # xfail reason if xfailed, otherwise not defined. Use hasattr to distinguish.\n    wasxfail: str\n\n    def __init__(\n        self,\n        nodeid: str,\n        location: tuple[str, int | None, str],\n        keywords: Mapping[str, Any],\n        outcome: Literal[\"passed\", \"failed\", \"skipped\"],\n        longrepr: None\n        | ExceptionInfo[BaseException]\n        | tuple[str, int, str]\n        | str\n        | TerminalRepr,\n        when: Literal[\"setup\", \"call\", \"teardown\"],\n        sections: Iterable[tuple[str, str]] = (),\n        duration: float = 0,\n        start: float = 0,\n        stop: float = 0,\n        user_properties: Iterable[tuple[str, object]] | None = None,\n        **extra,\n    ) -> None:\n        #: Normalized collection nodeid.\n        self.nodeid = nodeid\n\n        #: A (filesystempath, lineno, domaininfo) tuple indicating the\n        #: actual location of a test item - it might be different from the\n        #: collected one e.g. if a method is inherited from a different module.\n        #: The filesystempath may be relative to ``config.rootdir``.\n        #: The line number is 0-based.\n        self.location: tuple[str, int | None, str] = location\n\n        #: A name -> value dictionary containing all keywords and\n        #: markers associated with a test invocation.\n        self.keywords: Mapping[str, Any] = keywords\n\n        #: Test outcome, always one of \"passed\", \"failed\", \"skipped\".\n        self.outcome = outcome\n\n        #: None or a failure representation.\n        self.longrepr = longrepr\n\n        #: One of 'setup', 'call', 'teardown' to indicate runtest phase.\n        self.when: Literal[\"setup\", \"call\", \"teardown\"] = when\n\n        #: User properties is a list of tuples (name, value) that holds user\n        #: defined properties of the test.\n        self.user_properties = list(user_properties or [])\n\n        #: Tuples of str ``(heading, content)`` with extra information\n        #: for the test report. Used by pytest to add text captured\n        #: from ``stdout``, ``stderr``, and intercepted logging events. May\n        #: be used by other plugins to add arbitrary information to reports.\n        self.sections = list(sections)\n\n        #: Time it took to run just the test.\n        self.duration: float = duration\n\n        #: The system time when the call started, in seconds since the epoch.\n        self.start: float = start\n        #: The system time when the call ended, in seconds since the epoch.\n        self.stop: float = stop\n\n        self.__dict__.update(extra)\n\n    def __repr__(self) -> str:\n        return f\"<{self.__class__.__name__} {self.nodeid!r} when={self.when!r} outcome={self.outcome!r}>\"\n\n    @classmethod\n    def from_item_and_call(cls, item: Item, call: CallInfo[None]) -> TestReport:\n        \"\"\"Create and fill a TestReport with standard item and call info.\n\n        :param item: The item.\n        :param call: The call info.\n        \"\"\"\n        when = call.when\n        # Remove \"collect\" from the Literal type -- only for collection calls.\n        assert when != \"collect\"\n        duration = call.duration\n        start = call.start\n        stop = call.stop\n        keywords = {x: 1 for x in item.keywords}\n        excinfo = call.excinfo\n        sections = []\n        if not call.excinfo:\n            outcome: Literal[\"passed\", \"failed\", \"skipped\"] = \"passed\"\n            longrepr: (\n                None\n                | ExceptionInfo[BaseException]\n                | tuple[str, int, str]\n                | str\n                | TerminalRepr\n            ) = None\n        else:\n            if not isinstance(excinfo, ExceptionInfo):\n                outcome = \"failed\"\n                longrepr = excinfo\n            elif isinstance(excinfo.value, skip.Exception):\n                outcome = \"skipped\"\n                r = excinfo._getreprcrash()\n                assert r is not None, (\n                    \"There should always be a traceback entry for skipping a test.\"\n                )\n                if excinfo.value._use_item_location:\n                    path, line = item.reportinfo()[:2]\n                    assert line is not None\n                    longrepr = (os.fspath(path), line + 1, r.message)\n                else:\n                    longrepr = (str(r.path), r.lineno, r.message)\n            elif isinstance(excinfo.value, BaseExceptionGroup) and (\n                excinfo.value.split(skip.Exception)[1] is None\n            ):\n                # All exceptions in the group are skip exceptions.\n                outcome = \"skipped\"\n                excinfo = cast(\n                    ExceptionInfo[\n                        BaseExceptionGroup[BaseException | BaseExceptionGroup]\n                    ],\n                    excinfo,\n                )\n                longrepr = _format_exception_group_all_skipped_longrepr(item, excinfo)\n            else:\n                outcome = \"failed\"\n                longrepr = _format_failed_longrepr(item, call, excinfo)\n        for rwhen, key, content in item._report_sections:\n            sections.append((f\"Captured {key} {rwhen}\", content))\n        return cls(\n            item.nodeid,\n            item.location,\n            keywords,\n            outcome,\n            longrepr,\n            when,\n            sections,\n            duration,\n            start,\n            stop,\n            user_properties=item.user_properties,\n        )\n\n\n@final\nclass CollectReport(BaseReport):\n    \"\"\"Collection report object.\n\n    Reports can contain arbitrary extra attributes.\n    \"\"\"\n\n    when = \"collect\"\n\n    def __init__(\n        self,\n        nodeid: str,\n        outcome: Literal[\"passed\", \"failed\", \"skipped\"],\n        longrepr: None\n        | ExceptionInfo[BaseException]\n        | tuple[str, int, str]\n        | str\n        | TerminalRepr,\n        result: list[Item | Collector] | None,\n        sections: Iterable[tuple[str, str]] = (),\n        **extra,\n    ) -> None:\n        #: Normalized collection nodeid.\n        self.nodeid = nodeid\n\n        #: Test outcome, always one of \"passed\", \"failed\", \"skipped\".\n        self.outcome = outcome\n\n        #: None or a failure representation.\n        self.longrepr = longrepr\n\n        #: The collected items and collection nodes.\n        self.result = result or []\n\n        #: Tuples of str ``(heading, content)`` with extra information\n        #: for the test report. Used by pytest to add text captured\n        #: from ``stdout``, ``stderr``, and intercepted logging events. May\n        #: be used by other plugins to add arbitrary information to reports.\n        self.sections = list(sections)\n\n        self.__dict__.update(extra)\n\n    @property\n    def location(  # type:ignore[override]\n        self,\n    ) -> tuple[str, int | None, str] | None:\n        return (self.fspath, None, self.fspath)\n\n    def __repr__(self) -> str:\n        return f\"<CollectReport {self.nodeid!r} lenresult={len(self.result)} outcome={self.outcome!r}>\"\n\n\nclass CollectErrorRepr(TerminalRepr):\n    def __init__(self, msg: str) -> None:\n        self.longrepr = msg\n\n    def toterminal(self, out: TerminalWriter) -> None:\n        out.line(self.longrepr, red=True)\n\n\ndef pytest_report_to_serializable(\n    report: CollectReport | TestReport,\n) -> dict[str, Any] | None:\n    if isinstance(report, TestReport | CollectReport):\n        data = report._to_json()\n        data[\"$report_type\"] = report.__class__.__name__\n        return data\n    # TODO: Check if this is actually reachable.\n    return None  # type: ignore[unreachable]\n\n\ndef pytest_report_from_serializable(\n    data: dict[str, Any],\n) -> CollectReport | TestReport | None:\n    if \"$report_type\" in data:\n        if data[\"$report_type\"] == \"TestReport\":\n            return TestReport._from_json(data)\n        elif data[\"$report_type\"] == \"CollectReport\":\n            return CollectReport._from_json(data)\n        assert False, \"Unknown report_type unserialize data: {}\".format(\n            data[\"$report_type\"]\n        )\n    return None\n\n\ndef _report_to_json(report: BaseReport) -> dict[str, Any]:\n    \"\"\"Return the contents of this report as a dict of builtin entries,\n    suitable for serialization.\n\n    This was originally the serialize_report() function from xdist (ca03269).\n    \"\"\"\n\n    def serialize_repr_entry(\n        entry: ReprEntry | ReprEntryNative,\n    ) -> dict[str, Any]:\n        data = dataclasses.asdict(entry)\n        for key, value in data.items():\n            if hasattr(value, \"__dict__\"):\n                data[key] = dataclasses.asdict(value)\n        entry_data = {\"type\": type(entry).__name__, \"data\": data}\n        return entry_data\n\n    def serialize_repr_traceback(reprtraceback: ReprTraceback) -> dict[str, Any]:\n        result = dataclasses.asdict(reprtraceback)\n        result[\"reprentries\"] = [\n            serialize_repr_entry(x) for x in reprtraceback.reprentries\n        ]\n        return result\n\n    def serialize_repr_crash(\n        reprcrash: ReprFileLocation | None,\n    ) -> dict[str, Any] | None:\n        if reprcrash is not None:\n            return dataclasses.asdict(reprcrash)\n        else:\n            return None\n\n    def serialize_exception_longrepr(rep: BaseReport) -> dict[str, Any]:\n        assert rep.longrepr is not None\n        # TODO: Investigate whether the duck typing is really necessary here.\n        longrepr = cast(ExceptionRepr, rep.longrepr)\n        result: dict[str, Any] = {\n            \"reprcrash\": serialize_repr_crash(longrepr.reprcrash),\n            \"reprtraceback\": serialize_repr_traceback(longrepr.reprtraceback),\n            \"sections\": longrepr.sections,\n        }\n        if isinstance(longrepr, ExceptionChainRepr):\n            result[\"chain\"] = []\n            for repr_traceback, repr_crash, description in longrepr.chain:\n                result[\"chain\"].append(\n                    (\n                        serialize_repr_traceback(repr_traceback),\n                        serialize_repr_crash(repr_crash),\n                        description,\n                    )\n                )\n        else:\n            result[\"chain\"] = None\n        return result\n\n    d = report.__dict__.copy()\n    if hasattr(report.longrepr, \"toterminal\"):\n        if hasattr(report.longrepr, \"reprtraceback\") and hasattr(\n            report.longrepr, \"reprcrash\"\n        ):\n            d[\"longrepr\"] = serialize_exception_longrepr(report)\n        else:\n            d[\"longrepr\"] = str(report.longrepr)\n    else:\n        d[\"longrepr\"] = report.longrepr\n    for name in d:\n        if isinstance(d[name], os.PathLike):\n            d[name] = os.fspath(d[name])\n        elif name == \"result\":\n            d[name] = None  # for now\n    return d\n\n\ndef _report_kwargs_from_json(reportdict: dict[str, Any]) -> dict[str, Any]:\n    \"\"\"Return **kwargs that can be used to construct a TestReport or\n    CollectReport instance.\n\n    This was originally the serialize_report() function from xdist (ca03269).\n    \"\"\"\n\n    def deserialize_repr_entry(entry_data):\n        data = entry_data[\"data\"]\n        entry_type = entry_data[\"type\"]\n        if entry_type == \"ReprEntry\":\n            reprfuncargs = None\n            reprfileloc = None\n            reprlocals = None\n            if data[\"reprfuncargs\"]:\n                reprfuncargs = ReprFuncArgs(**data[\"reprfuncargs\"])\n            if data[\"reprfileloc\"]:\n                reprfileloc = ReprFileLocation(**data[\"reprfileloc\"])\n            if data[\"reprlocals\"]:\n                reprlocals = ReprLocals(data[\"reprlocals\"][\"lines\"])\n\n            reprentry: ReprEntry | ReprEntryNative = ReprEntry(\n                lines=data[\"lines\"],\n                reprfuncargs=reprfuncargs,\n                reprlocals=reprlocals,\n                reprfileloc=reprfileloc,\n                style=data[\"style\"],\n            )\n        elif entry_type == \"ReprEntryNative\":\n            reprentry = ReprEntryNative(data[\"lines\"])\n        else:\n            _report_unserialization_failure(entry_type, TestReport, reportdict)\n        return reprentry\n\n    def deserialize_repr_traceback(repr_traceback_dict):\n        repr_traceback_dict[\"reprentries\"] = [\n            deserialize_repr_entry(x) for x in repr_traceback_dict[\"reprentries\"]\n        ]\n        return ReprTraceback(**repr_traceback_dict)\n\n    def deserialize_repr_crash(repr_crash_dict: dict[str, Any] | None):\n        if repr_crash_dict is not None:\n            return ReprFileLocation(**repr_crash_dict)\n        else:\n            return None\n\n    if (\n        reportdict[\"longrepr\"]\n        and \"reprcrash\" in reportdict[\"longrepr\"]\n        and \"reprtraceback\" in reportdict[\"longrepr\"]\n    ):\n        reprtraceback = deserialize_repr_traceback(\n            reportdict[\"longrepr\"][\"reprtraceback\"]\n        )\n        reprcrash = deserialize_repr_crash(reportdict[\"longrepr\"][\"reprcrash\"])\n        if reportdict[\"longrepr\"][\"chain\"]:\n            chain = []\n            for repr_traceback_data, repr_crash_data, description in reportdict[\n                \"longrepr\"\n            ][\"chain\"]:\n                chain.append(\n                    (\n                        deserialize_repr_traceback(repr_traceback_data),\n                        deserialize_repr_crash(repr_crash_data),\n                        description,\n                    )\n                )\n            exception_info: ExceptionChainRepr | ReprExceptionInfo = ExceptionChainRepr(\n                chain\n            )\n        else:\n            exception_info = ReprExceptionInfo(\n                reprtraceback=reprtraceback,\n                reprcrash=reprcrash,\n            )\n\n        for section in reportdict[\"longrepr\"][\"sections\"]:\n            exception_info.addsection(*section)\n        reportdict[\"longrepr\"] = exception_info\n\n    return reportdict\n"
  },
  {
    "path": "src/_pytest/runner.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Basic collect and runtest protocol implementations.\"\"\"\n\nfrom __future__ import annotations\n\nimport bdb\nfrom collections.abc import Callable\nimport dataclasses\nimport os\nimport sys\nimport types\nfrom typing import cast\nfrom typing import final\nfrom typing import Generic\nfrom typing import Literal\nfrom typing import TYPE_CHECKING\nfrom typing import TypeVar\n\nfrom .config import Config\nfrom .reports import BaseReport\nfrom .reports import CollectErrorRepr\nfrom .reports import CollectReport\nfrom .reports import TestReport\nfrom _pytest import timing\nfrom _pytest._code.code import ExceptionChainRepr\nfrom _pytest._code.code import ExceptionInfo\nfrom _pytest._code.code import TerminalRepr\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import Directory\nfrom _pytest.nodes import Item\nfrom _pytest.nodes import Node\nfrom _pytest.outcomes import Exit\nfrom _pytest.outcomes import OutcomeException\nfrom _pytest.outcomes import Skipped\nfrom _pytest.outcomes import TEST_OUTCOME\n\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import BaseExceptionGroup\n\nif TYPE_CHECKING:\n    from _pytest.main import Session\n    from _pytest.terminal import TerminalReporter\n\n#\n# pytest plugin hooks.\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"terminal reporting\", \"Reporting\", after=\"general\")\n    group.addoption(\n        \"--durations\",\n        action=\"store\",\n        type=int,\n        default=None,\n        metavar=\"N\",\n        help=\"Show N slowest setup/test durations (N=0 for all)\",\n    )\n    group.addoption(\n        \"--durations-min\",\n        action=\"store\",\n        type=float,\n        default=None,\n        metavar=\"N\",\n        help=\"Minimal duration in seconds for inclusion in slowest list. \"\n        \"Default: 0.005 (or 0.0 if -vv is given).\",\n    )\n\n\ndef pytest_terminal_summary(terminalreporter: TerminalReporter) -> None:\n    durations = terminalreporter.config.option.durations\n    durations_min = terminalreporter.config.option.durations_min\n    verbose = terminalreporter.config.get_verbosity()\n    if durations is None:\n        return\n    if durations_min is None:\n        durations_min = 0.005 if verbose < 2 else 0.0\n    tr = terminalreporter\n    dlist = []\n    for replist in tr.stats.values():\n        for rep in replist:\n            if hasattr(rep, \"duration\"):\n                dlist.append(rep)\n    if not dlist:\n        return\n    dlist.sort(key=lambda x: x.duration, reverse=True)\n    if not durations:\n        tr.write_sep(\"=\", \"slowest durations\")\n    else:\n        tr.write_sep(\"=\", f\"slowest {durations} durations\")\n        dlist = dlist[:durations]\n\n    for i, rep in enumerate(dlist):\n        if rep.duration < durations_min:\n            tr.write_line(\"\")\n            message = f\"({len(dlist) - i} durations < {durations_min:g}s hidden.\"\n            if terminalreporter.config.option.durations_min is None:\n                message += \"  Use -vv to show these durations.\"\n            message += \")\"\n            tr.write_line(message)\n            break\n        tr.write_line(f\"{rep.duration:02.2f}s {rep.when:<8} {rep.nodeid}\")\n\n\ndef pytest_sessionstart(session: Session) -> None:\n    session._setupstate = SetupState()\n\n\ndef pytest_sessionfinish(session: Session) -> None:\n    session._setupstate.teardown_exact(None)\n\n\ndef pytest_runtest_protocol(item: Item, nextitem: Item | None) -> bool:\n    ihook = item.ihook\n    ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)\n    runtestprotocol(item, nextitem=nextitem)\n    ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)\n    return True\n\n\ndef runtestprotocol(\n    item: Item, log: bool = True, nextitem: Item | None = None\n) -> list[TestReport]:\n    hasrequest = hasattr(item, \"_request\")\n    if hasrequest and not item._request:  # type: ignore[attr-defined]\n        # This only happens if the item is re-run, as is done by\n        # pytest-rerunfailures.\n        item._initrequest()  # type: ignore[attr-defined]\n    rep = call_and_report(item, \"setup\", log)\n    reports = [rep]\n    if rep.passed:\n        if item.config.getoption(\"setupshow\", False):\n            show_test_item(item)\n        if not item.config.getoption(\"setuponly\", False):\n            reports.append(call_and_report(item, \"call\", log))\n    # If the session is about to fail or stop, teardown everything - this is\n    # necessary to correctly report fixture teardown errors (see #11706)\n    if item.session.shouldfail or item.session.shouldstop:\n        nextitem = None\n    reports.append(call_and_report(item, \"teardown\", log, nextitem=nextitem))\n    # After all teardown hooks have been called\n    # want funcargs and request info to go away.\n    if hasrequest:\n        item._request = False  # type: ignore[attr-defined]\n        item.funcargs = None  # type: ignore[attr-defined]\n    return reports\n\n\ndef show_test_item(item: Item) -> None:\n    \"\"\"Show test function, parameters and the fixtures of the test item.\"\"\"\n    tw = item.config.get_terminal_writer()\n    tw.line()\n    tw.write(\" \" * 8)\n    tw.write(item.nodeid)\n    used_fixtures = sorted(getattr(item, \"fixturenames\", []))\n    if used_fixtures:\n        tw.write(\" (fixtures used: {})\".format(\", \".join(used_fixtures)))\n    tw.flush()\n\n\ndef pytest_runtest_setup(item: Item) -> None:\n    _update_current_test_var(item, \"setup\")\n    item.session._setupstate.setup(item)\n\n\ndef pytest_runtest_call(item: Item) -> None:\n    _update_current_test_var(item, \"call\")\n    try:\n        del sys.last_type\n        del sys.last_value\n        del sys.last_traceback\n        if sys.version_info >= (3, 12, 0):\n            del sys.last_exc  # type:ignore[attr-defined]\n    except AttributeError:\n        pass\n    try:\n        item.runtest()\n    except Exception as e:\n        # Store trace info to allow postmortem debugging\n        sys.last_type = type(e)\n        sys.last_value = e\n        if sys.version_info >= (3, 12, 0):\n            sys.last_exc = e  # type:ignore[attr-defined]\n        assert e.__traceback__ is not None\n        # Skip *this* frame\n        sys.last_traceback = e.__traceback__.tb_next\n        raise\n\n\ndef pytest_runtest_teardown(item: Item, nextitem: Item | None) -> None:\n    _update_current_test_var(item, \"teardown\")\n    item.session._setupstate.teardown_exact(nextitem)\n    _update_current_test_var(item, None)\n\n\ndef _update_current_test_var(\n    item: Item, when: Literal[\"setup\", \"call\", \"teardown\"] | None\n) -> None:\n    \"\"\"Update :envvar:`PYTEST_CURRENT_TEST` to reflect the current item and stage.\n\n    If ``when`` is None, delete ``PYTEST_CURRENT_TEST`` from the environment.\n    \"\"\"\n    var_name = \"PYTEST_CURRENT_TEST\"\n    if when:\n        value = f\"{item.nodeid} ({when})\"\n        # don't allow null bytes on environment variables (see #2644, #2957)\n        value = value.replace(\"\\x00\", \"(null)\")\n        os.environ[var_name] = value\n    else:\n        os.environ.pop(var_name)\n\n\ndef pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str] | None:\n    if report.when in (\"setup\", \"teardown\"):\n        if report.failed:\n            #      category, shortletter, verbose-word\n            return \"error\", \"E\", \"ERROR\"\n        elif report.skipped:\n            return \"skipped\", \"s\", \"SKIPPED\"\n        else:\n            return \"\", \"\", \"\"\n    return None\n\n\n#\n# Implementation\n\n\ndef call_and_report(\n    item: Item, when: Literal[\"setup\", \"call\", \"teardown\"], log: bool = True, **kwds\n) -> TestReport:\n    ihook = item.ihook\n    if when == \"setup\":\n        runtest_hook: Callable[..., None] = ihook.pytest_runtest_setup\n    elif when == \"call\":\n        runtest_hook = ihook.pytest_runtest_call\n    elif when == \"teardown\":\n        runtest_hook = ihook.pytest_runtest_teardown\n    else:\n        assert False, f\"Unhandled runtest hook case: {when}\"\n\n    call = CallInfo.from_call(\n        lambda: runtest_hook(item=item, **kwds),\n        when=when,\n        reraise=get_reraise_exceptions(item.config),\n    )\n    report: TestReport = ihook.pytest_runtest_makereport(item=item, call=call)\n    if log:\n        ihook.pytest_runtest_logreport(report=report)\n    if check_interactive_exception(call, report):\n        ihook.pytest_exception_interact(node=item, call=call, report=report)\n    return report\n\n\ndef get_reraise_exceptions(config: Config) -> tuple[type[BaseException], ...]:\n    \"\"\"Return exception types that should not be suppressed in general.\"\"\"\n    reraise: tuple[type[BaseException], ...] = (Exit,)\n    if not config.getoption(\"usepdb\", False):\n        reraise += (KeyboardInterrupt,)\n    return reraise\n\n\ndef check_interactive_exception(call: CallInfo[object], report: BaseReport) -> bool:\n    \"\"\"Check whether the call raised an exception that should be reported as\n    interactive.\"\"\"\n    if call.excinfo is None:\n        # Didn't raise.\n        return False\n    if hasattr(report, \"wasxfail\"):\n        # Exception was expected.\n        return False\n    unittest = sys.modules.get(\"unittest\")\n    if isinstance(call.excinfo.value, Skipped | bdb.BdbQuit) or (\n        unittest is not None and isinstance(call.excinfo.value, unittest.SkipTest)\n    ):\n        # Special control flow exception.\n        return False\n    return True\n\n\nTResult = TypeVar(\"TResult\", covariant=True)\n\n\n@final\n@dataclasses.dataclass\nclass CallInfo(Generic[TResult]):\n    \"\"\"Result/Exception info of a function invocation.\"\"\"\n\n    _result: TResult | None\n    #: The captured exception of the call, if it raised.\n    excinfo: ExceptionInfo[BaseException] | None\n    #: The system time when the call started, in seconds since the epoch.\n    start: float\n    #: The system time when the call ended, in seconds since the epoch.\n    stop: float\n    #: The call duration, in seconds.\n    duration: float\n    #: The context of invocation: \"collect\", \"setup\", \"call\" or \"teardown\".\n    when: Literal[\"collect\", \"setup\", \"call\", \"teardown\"]\n\n    def __init__(\n        self,\n        result: TResult | None,\n        excinfo: ExceptionInfo[BaseException] | None,\n        start: float,\n        stop: float,\n        duration: float,\n        when: Literal[\"collect\", \"setup\", \"call\", \"teardown\"],\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        self._result = result\n        self.excinfo = excinfo\n        self.start = start\n        self.stop = stop\n        self.duration = duration\n        self.when = when\n\n    @property\n    def result(self) -> TResult:\n        \"\"\"The return value of the call, if it didn't raise.\n\n        Can only be accessed if excinfo is None.\n        \"\"\"\n        if self.excinfo is not None:\n            raise AttributeError(f\"{self!r} has no valid result\")\n        # The cast is safe because an exception wasn't raised, hence\n        # _result has the expected function return type (which may be\n        #  None, that's why a cast and not an assert).\n        return cast(TResult, self._result)\n\n    @classmethod\n    def from_call(\n        cls,\n        func: Callable[[], TResult],\n        when: Literal[\"collect\", \"setup\", \"call\", \"teardown\"],\n        reraise: type[BaseException] | tuple[type[BaseException], ...] | None = None,\n    ) -> CallInfo[TResult]:\n        \"\"\"Call func, wrapping the result in a CallInfo.\n\n        :param func:\n            The function to call. Called without arguments.\n        :type func: Callable[[], _pytest.runner.TResult]\n        :param when:\n            The phase in which the function is called.\n        :param reraise:\n            Exception or exceptions that shall propagate if raised by the\n            function, instead of being wrapped in the CallInfo.\n        \"\"\"\n        excinfo = None\n        instant = timing.Instant()\n        try:\n            result: TResult | None = func()\n        except BaseException:\n            excinfo = ExceptionInfo.from_current()\n            if reraise is not None and isinstance(excinfo.value, reraise):\n                raise\n            result = None\n        duration = instant.elapsed()\n        return cls(\n            start=duration.start.time,\n            stop=duration.stop.time,\n            duration=duration.seconds,\n            when=when,\n            result=result,\n            excinfo=excinfo,\n            _ispytest=True,\n        )\n\n    def __repr__(self) -> str:\n        if self.excinfo is None:\n            return f\"<CallInfo when={self.when!r} result: {self._result!r}>\"\n        return f\"<CallInfo when={self.when!r} excinfo={self.excinfo!r}>\"\n\n\ndef pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> TestReport:\n    return TestReport.from_item_and_call(item, call)\n\n\ndef pytest_make_collect_report(collector: Collector) -> CollectReport:\n    def collect() -> list[Item | Collector]:\n        # Before collecting, if this is a Directory, load the conftests.\n        # If a conftest import fails to load, it is considered a collection\n        # error of the Directory collector. This is why it's done inside of the\n        # CallInfo wrapper.\n        #\n        # Note: initial conftests are loaded early, not here.\n        if isinstance(collector, Directory):\n            collector.config.pluginmanager._loadconftestmodules(\n                collector.path,\n                collector.config.getoption(\"importmode\"),\n                rootpath=collector.config.rootpath,\n                consider_namespace_packages=collector.config.getini(\n                    \"consider_namespace_packages\"\n                ),\n            )\n\n        return list(collector.collect())\n\n    call = CallInfo.from_call(\n        collect, \"collect\", reraise=(KeyboardInterrupt, SystemExit)\n    )\n    longrepr: None | tuple[str, int, str] | str | TerminalRepr = None\n    if not call.excinfo:\n        outcome: Literal[\"passed\", \"skipped\", \"failed\"] = \"passed\"\n    else:\n        skip_exceptions = [Skipped]\n        unittest = sys.modules.get(\"unittest\")\n        if unittest is not None:\n            skip_exceptions.append(unittest.SkipTest)\n        if isinstance(call.excinfo.value, tuple(skip_exceptions)):\n            outcome = \"skipped\"\n            r_ = collector._repr_failure_py(call.excinfo, \"line\")\n            assert isinstance(r_, ExceptionChainRepr), repr(r_)\n            r = r_.reprcrash\n            assert r\n            longrepr = (str(r.path), r.lineno, r.message)\n        else:\n            outcome = \"failed\"\n            errorinfo = collector.repr_failure(call.excinfo)\n            if not hasattr(errorinfo, \"toterminal\"):\n                assert isinstance(errorinfo, str)\n                errorinfo = CollectErrorRepr(errorinfo)\n            longrepr = errorinfo\n    result = call.result if not call.excinfo else None\n    rep = CollectReport(collector.nodeid, outcome, longrepr, result)\n    rep.call = call  # type: ignore # see collect_one_node\n    return rep\n\n\nclass SetupState:\n    \"\"\"Shared state for setting up/tearing down test items or collectors\n    in a session.\n\n    Suppose we have a collection tree as follows:\n\n    <Session session>\n        <Module mod1>\n            <Function item1>\n        <Module mod2>\n            <Function item2>\n\n    The SetupState maintains a stack. The stack starts out empty:\n\n        []\n\n    During the setup phase of item1, setup(item1) is called. What it does\n    is:\n\n        push session to stack, run session.setup()\n        push mod1 to stack, run mod1.setup()\n        push item1 to stack, run item1.setup()\n\n    The stack is:\n\n        [session, mod1, item1]\n\n    While the stack is in this shape, it is allowed to add finalizers to\n    each of session, mod1, item1 using addfinalizer().\n\n    During the teardown phase of item1, teardown_exact(item2) is called,\n    where item2 is the next item to item1. What it does is:\n\n        pop item1 from stack, run its teardowns\n        pop mod1 from stack, run its teardowns\n\n    mod1 was popped because it ended its purpose with item1. The stack is:\n\n        [session]\n\n    During the setup phase of item2, setup(item2) is called. What it does\n    is:\n\n        push mod2 to stack, run mod2.setup()\n        push item2 to stack, run item2.setup()\n\n    Stack:\n\n        [session, mod2, item2]\n\n    During the teardown phase of item2, teardown_exact(None) is called,\n    because item2 is the last item. What it does is:\n\n        pop item2 from stack, run its teardowns\n        pop mod2 from stack, run its teardowns\n        pop session from stack, run its teardowns\n\n    Stack:\n\n        []\n\n    The end!\n    \"\"\"\n\n    def __init__(self) -> None:\n        # The stack is in the dict insertion order.\n        self.stack: dict[\n            Node,\n            tuple[\n                # Node's finalizers.\n                list[Callable[[], object]],\n                # Node's exception and original traceback, if its setup raised.\n                tuple[OutcomeException | Exception, types.TracebackType | None] | None,\n            ],\n        ] = {}\n\n    def is_node_active(self, node: Node) -> bool:\n        \"\"\"Check if a node is currently active in the stack -- set up and not\n        torn down yet.\"\"\"\n        return node in self.stack\n\n    def setup(self, item: Item) -> None:\n        \"\"\"Setup objects along the collector chain to the item.\"\"\"\n        needed_collectors = item.listchain()\n\n        # If a collector fails its setup, fail its entire subtree of items.\n        # The setup is not retried for each item - the same exception is used.\n        for col, (finalizers, exc) in self.stack.items():\n            assert col in needed_collectors, \"previous item was not torn down properly\"\n            if exc:\n                raise exc[0].with_traceback(exc[1])\n\n        for col in needed_collectors[len(self.stack) :]:\n            assert col not in self.stack\n            # Push onto the stack.\n            self.stack[col] = ([col.teardown], None)\n            try:\n                col.setup()\n            except TEST_OUTCOME as exc:\n                self.stack[col] = (self.stack[col][0], (exc, exc.__traceback__))\n                raise\n\n    def addfinalizer(self, finalizer: Callable[[], object], node: Node) -> None:\n        \"\"\"Attach a finalizer to the given node.\n\n        The node must be currently active in the stack.\n        \"\"\"\n        assert node and not isinstance(node, tuple)\n        assert callable(finalizer)\n        assert node in self.stack, (node, self.stack)\n        self.stack[node][0].append(finalizer)\n\n    def teardown_exact(self, nextitem: Item | None) -> None:\n        \"\"\"Teardown the current stack up until reaching nodes that nextitem\n        also descends from.\n\n        When nextitem is None (meaning we're at the last item), the entire\n        stack is torn down.\n        \"\"\"\n        needed_collectors = (nextitem and nextitem.listchain()) or []\n        exceptions: list[BaseException] = []\n        while self.stack:\n            if list(self.stack.keys()) == needed_collectors[: len(self.stack)]:\n                break\n            node, (finalizers, _) = self.stack.popitem()\n            these_exceptions = []\n            while finalizers:\n                fin = finalizers.pop()\n                try:\n                    fin()\n                except TEST_OUTCOME as e:\n                    these_exceptions.append(e)\n\n            if len(these_exceptions) == 1:\n                exceptions.extend(these_exceptions)\n            elif these_exceptions:\n                msg = f\"errors while tearing down {node!r}\"\n                exceptions.append(BaseExceptionGroup(msg, these_exceptions[::-1]))\n\n        if len(exceptions) == 1:\n            raise exceptions[0]\n        elif exceptions:\n            raise BaseExceptionGroup(\"errors during test teardown\", exceptions[::-1])\n        if nextitem is None:\n            assert not self.stack\n\n\ndef collect_one_node(collector: Collector) -> CollectReport:\n    ihook = collector.ihook\n    ihook.pytest_collectstart(collector=collector)\n    rep: CollectReport = ihook.pytest_make_collect_report(collector=collector)\n    call = rep.__dict__.pop(\"call\", None)\n    if call and check_interactive_exception(call, rep):\n        ihook.pytest_exception_interact(node=collector, call=call, report=rep)\n    return rep\n"
  },
  {
    "path": "src/_pytest/scope.py",
    "content": "\"\"\"\nScope definition and related utilities.\n\nThose are defined here, instead of in the 'fixtures' module because\ntheir use is spread across many other pytest modules, and centralizing it in 'fixtures'\nwould cause circular references.\n\nAlso this makes the module light to import, as it should.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom enum import Enum\nfrom functools import total_ordering\nfrom typing import Literal\n\n\n_ScopeName = Literal[\"session\", \"package\", \"module\", \"class\", \"function\"]\n\n\n@total_ordering\nclass Scope(Enum):\n    \"\"\"\n    Represents one of the possible fixture scopes in pytest.\n\n    Scopes are ordered from lower to higher, that is:\n\n              ->>> higher ->>>\n\n    Function < Class < Module < Package < Session\n\n              <<<- lower  <<<-\n    \"\"\"\n\n    # Scopes need to be listed from lower to higher.\n    Function = \"function\"\n    Class = \"class\"\n    Module = \"module\"\n    Package = \"package\"\n    Session = \"session\"\n\n    def next_lower(self) -> Scope:\n        \"\"\"Return the next lower scope.\"\"\"\n        index = _SCOPE_INDICES[self]\n        if index == 0:\n            raise ValueError(f\"{self} is the lower-most scope\")\n        return _ALL_SCOPES[index - 1]\n\n    def next_higher(self) -> Scope:\n        \"\"\"Return the next higher scope.\"\"\"\n        index = _SCOPE_INDICES[self]\n        if index == len(_SCOPE_INDICES) - 1:\n            raise ValueError(f\"{self} is the upper-most scope\")\n        return _ALL_SCOPES[index + 1]\n\n    def __lt__(self, other: Scope) -> bool:\n        self_index = _SCOPE_INDICES[self]\n        other_index = _SCOPE_INDICES[other]\n        return self_index < other_index\n\n    @classmethod\n    def from_user(\n        cls, scope_name: _ScopeName, descr: str, where: str | None = None\n    ) -> Scope:\n        \"\"\"\n        Given a scope name from the user, return the equivalent Scope enum. Should be used\n        whenever we want to convert a user provided scope name to its enum object.\n\n        If the scope name is invalid, construct a user friendly message and call pytest.fail.\n        \"\"\"\n        from _pytest.outcomes import fail\n\n        try:\n            # Holding this reference is necessary for mypy at the moment.\n            scope = Scope(scope_name)\n        except ValueError:\n            fail(\n                \"{} {}got an unexpected scope value '{}'\".format(\n                    descr, f\"from {where} \" if where else \"\", scope_name\n                ),\n                pytrace=False,\n            )\n        return scope\n\n\n_ALL_SCOPES = list(Scope)\n_SCOPE_INDICES = {scope: index for index, scope in enumerate(_ALL_SCOPES)}\n\n\n# Ordered list of scopes which can contain many tests (in practice all except Function).\nHIGH_SCOPES = [x for x in Scope if x is not Scope.Function]\n"
  },
  {
    "path": "src/_pytest/setuponly.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Generator\n\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.fixtures import FixtureDef\nfrom _pytest.fixtures import SubRequest\nfrom _pytest.scope import Scope\nimport pytest\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"debugconfig\")\n    group.addoption(\n        \"--setuponly\",\n        \"--setup-only\",\n        action=\"store_true\",\n        help=\"Only setup fixtures, do not execute tests\",\n    )\n    group.addoption(\n        \"--setupshow\",\n        \"--setup-show\",\n        action=\"store_true\",\n        help=\"Show setup of fixtures while executing tests\",\n    )\n\n\n@pytest.hookimpl(wrapper=True)\ndef pytest_fixture_setup(\n    fixturedef: FixtureDef[object], request: SubRequest\n) -> Generator[None, object, object]:\n    try:\n        return (yield)\n    finally:\n        if request.config.option.setupshow:\n            if hasattr(request, \"param\"):\n                # Save the fixture parameter so ._show_fixture_action() can\n                # display it now and during the teardown (in .finish()).\n                if fixturedef.ids:\n                    if callable(fixturedef.ids):\n                        param = fixturedef.ids(request.param)\n                    else:\n                        param = fixturedef.ids[request.param_index]\n                else:\n                    param = request.param\n                fixturedef.cached_param = param  # type: ignore[attr-defined]\n            _show_fixture_action(fixturedef, request.config, \"SETUP\")\n\n\ndef pytest_fixture_post_finalizer(\n    fixturedef: FixtureDef[object], request: SubRequest\n) -> None:\n    if fixturedef.cached_result is not None:\n        config = request.config\n        if config.option.setupshow:\n            _show_fixture_action(fixturedef, request.config, \"TEARDOWN\")\n            if hasattr(fixturedef, \"cached_param\"):\n                del fixturedef.cached_param\n\n\ndef _show_fixture_action(\n    fixturedef: FixtureDef[object], config: Config, msg: str\n) -> None:\n    capman = config.pluginmanager.getplugin(\"capturemanager\")\n    if capman:\n        capman.suspend_global_capture()\n\n    tw = config.get_terminal_writer()\n    tw.line()\n    # Use smaller indentation the higher the scope: Session = 0, Package = 1, etc.\n    scope_indent = list(reversed(Scope)).index(fixturedef._scope)\n    tw.write(\" \" * 2 * scope_indent)\n\n    scopename = fixturedef.scope[0].upper()\n    tw.write(f\"{msg:<8} {scopename} {fixturedef.argname}\")\n\n    if msg == \"SETUP\":\n        deps = sorted(arg for arg in fixturedef.argnames if arg != \"request\")\n        if deps:\n            tw.write(\" (fixtures used: {})\".format(\", \".join(deps)))\n\n    if hasattr(fixturedef, \"cached_param\"):\n        tw.write(f\"[{saferepr(fixturedef.cached_param, maxsize=42)}]\")\n\n    tw.flush()\n\n    if capman:\n        capman.resume_global_capture()\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config: Config) -> int | ExitCode | None:\n    if config.option.setuponly:\n        config.option.setupshow = True\n    return None\n"
  },
  {
    "path": "src/_pytest/setupplan.py",
    "content": "from __future__ import annotations\n\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.fixtures import FixtureDef\nfrom _pytest.fixtures import SubRequest\nimport pytest\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"debugconfig\")\n    group.addoption(\n        \"--setupplan\",\n        \"--setup-plan\",\n        action=\"store_true\",\n        help=\"Show what fixtures and tests would be executed but \"\n        \"don't execute anything\",\n    )\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_fixture_setup(\n    fixturedef: FixtureDef[object], request: SubRequest\n) -> object | None:\n    # Will return a dummy fixture if the setuponly option is provided.\n    if request.config.option.setupplan:\n        my_cache_key = fixturedef.cache_key(request)\n        fixturedef.cached_result = (None, my_cache_key, None)\n        return fixturedef.cached_result\n    return None\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config: Config) -> int | ExitCode | None:\n    if config.option.setupplan:\n        config.option.setuponly = True\n        config.option.setupshow = True\n    return None\n"
  },
  {
    "path": "src/_pytest/skipping.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Support for skip/xfail functions and markers.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nfrom collections.abc import Mapping\nimport dataclasses\nimport os\nimport platform\nimport sys\nimport traceback\n\nfrom _pytest.config import Config\nfrom _pytest.config import hookimpl\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.mark.structures import Mark\nfrom _pytest.nodes import Item\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import skip\nfrom _pytest.outcomes import xfail\nfrom _pytest.raises import AbstractRaises\nfrom _pytest.reports import BaseReport\nfrom _pytest.reports import TestReport\nfrom _pytest.runner import CallInfo\nfrom _pytest.stash import StashKey\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"general\")\n    group.addoption(\n        \"--runxfail\",\n        action=\"store_true\",\n        dest=\"runxfail\",\n        default=False,\n        help=\"Report the results of xfail tests as if they were not marked\",\n    )\n\n    parser.addini(\n        \"strict_xfail\",\n        \"Default for the strict parameter of xfail \"\n        \"markers when not given explicitly (default: False) (alias: xfail_strict)\",\n        type=\"bool\",\n        # None => fallback to `strict`.\n        default=None,\n        aliases=[\"xfail_strict\"],\n    )\n\n\ndef pytest_configure(config: Config) -> None:\n    if config.option.runxfail:\n        # yay a hack\n        import pytest\n\n        old = pytest.xfail\n        config.add_cleanup(lambda: setattr(pytest, \"xfail\", old))\n\n        def nop(*args, **kwargs):\n            pass\n\n        nop.Exception = xfail.Exception  # type: ignore[attr-defined]\n        setattr(pytest, \"xfail\", nop)\n\n    config.addinivalue_line(\n        \"markers\",\n        \"skip(reason=None): skip the given test function with an optional reason. \"\n        'Example: skip(reason=\"no way of currently testing this\") skips the '\n        \"test.\",\n    )\n    config.addinivalue_line(\n        \"markers\",\n        \"skipif(condition, ..., *, reason=...): \"\n        \"skip the given test function if any of the conditions evaluate to True. \"\n        \"Example: skipif(sys.platform == 'win32') skips the test if we are on the win32 platform. \"\n        \"See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-skipif\",\n    )\n    config.addinivalue_line(\n        \"markers\",\n        \"xfail(condition, ..., *, reason=..., run=True, raises=None, strict=strict_xfail): \"\n        \"mark the test function as an expected failure if any of the conditions \"\n        \"evaluate to True. Optionally specify a reason for better reporting \"\n        \"and run=False if you don't even want to execute the test function. \"\n        \"If only specific exception(s) are expected, you can list them in \"\n        \"raises, and if the test fails in other ways, it will be reported as \"\n        \"a true failure. See https://docs.pytest.org/en/stable/reference/reference.html#pytest-mark-xfail\",\n    )\n\n\ndef evaluate_condition(item: Item, mark: Mark, condition: object) -> tuple[bool, str]:\n    \"\"\"Evaluate a single skipif/xfail condition.\n\n    If an old-style string condition is given, it is eval()'d, otherwise the\n    condition is bool()'d. If this fails, an appropriately formatted pytest.fail\n    is raised.\n\n    Returns (result, reason). The reason is only relevant if the result is True.\n    \"\"\"\n    # String condition.\n    if isinstance(condition, str):\n        globals_ = {\n            \"os\": os,\n            \"sys\": sys,\n            \"platform\": platform,\n            \"config\": item.config,\n        }\n        for dictionary in reversed(\n            item.ihook.pytest_markeval_namespace(config=item.config)\n        ):\n            if not isinstance(dictionary, Mapping):\n                raise ValueError(\n                    f\"pytest_markeval_namespace() needs to return a dict, got {dictionary!r}\"\n                )\n            globals_.update(dictionary)\n        if hasattr(item, \"obj\"):\n            globals_.update(item.obj.__globals__)\n        try:\n            filename = f\"<{mark.name} condition>\"\n            condition_code = compile(condition, filename, \"eval\")\n            result = eval(condition_code, globals_)\n        except SyntaxError as exc:\n            msglines = [\n                f\"Error evaluating {mark.name!r} condition\",\n                \"    \" + condition,\n                \"    \" + \" \" * (exc.offset or 0) + \"^\",\n                \"SyntaxError: invalid syntax\",\n            ]\n            fail(\"\\n\".join(msglines), pytrace=False)\n        except Exception as exc:\n            msglines = [\n                f\"Error evaluating {mark.name!r} condition\",\n                \"    \" + condition,\n                *traceback.format_exception_only(type(exc), exc),\n            ]\n            fail(\"\\n\".join(msglines), pytrace=False)\n\n    # Boolean condition.\n    else:\n        try:\n            result = bool(condition)\n        except Exception as exc:\n            msglines = [\n                f\"Error evaluating {mark.name!r} condition as a boolean\",\n                *traceback.format_exception_only(type(exc), exc),\n            ]\n            fail(\"\\n\".join(msglines), pytrace=False)\n\n    reason = mark.kwargs.get(\"reason\", None)\n    if reason is None:\n        if isinstance(condition, str):\n            reason = \"condition: \" + condition\n        else:\n            # XXX better be checked at collection time\n            msg = (\n                f\"Error evaluating {mark.name!r}: \"\n                + \"you need to specify reason=STRING when using booleans as conditions.\"\n            )\n            fail(msg, pytrace=False)\n\n    return result, reason\n\n\n@dataclasses.dataclass(frozen=True)\nclass Skip:\n    \"\"\"The result of evaluate_skip_marks().\"\"\"\n\n    reason: str = \"unconditional skip\"\n\n\ndef evaluate_skip_marks(item: Item) -> Skip | None:\n    \"\"\"Evaluate skip and skipif marks on item, returning Skip if triggered.\"\"\"\n    for mark in item.iter_markers(name=\"skipif\"):\n        if \"condition\" not in mark.kwargs:\n            conditions = mark.args\n        else:\n            conditions = (mark.kwargs[\"condition\"],)\n\n        # Unconditional.\n        if not conditions:\n            reason = mark.kwargs.get(\"reason\", \"\")\n            return Skip(reason)\n\n        # If any of the conditions are true.\n        for condition in conditions:\n            result, reason = evaluate_condition(item, mark, condition)\n            if result:\n                return Skip(reason)\n\n    for mark in item.iter_markers(name=\"skip\"):\n        try:\n            return Skip(*mark.args, **mark.kwargs)\n        except TypeError as e:\n            raise TypeError(str(e) + \" - maybe you meant pytest.mark.skipif?\") from None\n\n    return None\n\n\n@dataclasses.dataclass(frozen=True)\nclass Xfail:\n    \"\"\"The result of evaluate_xfail_marks().\"\"\"\n\n    __slots__ = (\"raises\", \"reason\", \"run\", \"strict\")\n\n    reason: str\n    run: bool\n    strict: bool\n    raises: (\n        type[BaseException]\n        | tuple[type[BaseException], ...]\n        | AbstractRaises[BaseException]\n        | None\n    )\n\n\ndef evaluate_xfail_marks(item: Item) -> Xfail | None:\n    \"\"\"Evaluate xfail marks on item, returning Xfail if triggered.\"\"\"\n    for mark in item.iter_markers(name=\"xfail\"):\n        run = mark.kwargs.get(\"run\", True)\n        strict = mark.kwargs.get(\"strict\")\n        if strict is None:\n            strict = item.config.getini(\"strict_xfail\")\n        if strict is None:\n            strict = item.config.getini(\"strict\")\n        raises = mark.kwargs.get(\"raises\", None)\n        if \"condition\" not in mark.kwargs:\n            conditions = mark.args\n        else:\n            conditions = (mark.kwargs[\"condition\"],)\n\n        # Unconditional.\n        if not conditions:\n            reason = mark.kwargs.get(\"reason\", \"\")\n            return Xfail(reason, run, strict, raises)\n\n        # If any of the conditions are true.\n        for condition in conditions:\n            result, reason = evaluate_condition(item, mark, condition)\n            if result:\n                return Xfail(reason, run, strict, raises)\n\n    return None\n\n\n# Saves the xfail mark evaluation. Can be refreshed during call if None.\nxfailed_key = StashKey[Xfail | None]()\n\n\n@hookimpl(tryfirst=True)\ndef pytest_runtest_setup(item: Item) -> None:\n    skipped = evaluate_skip_marks(item)\n    if skipped:\n        raise skip.Exception(skipped.reason, _use_item_location=True)\n\n    item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)\n    if xfailed and not item.config.option.runxfail and not xfailed.run:\n        xfail(\"[NOTRUN] \" + xfailed.reason)\n\n\n@hookimpl(wrapper=True)\ndef pytest_runtest_call(item: Item) -> Generator[None]:\n    xfailed = item.stash.get(xfailed_key, None)\n    if xfailed is None:\n        item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)\n\n    if xfailed and not item.config.option.runxfail and not xfailed.run:\n        xfail(\"[NOTRUN] \" + xfailed.reason)\n\n    try:\n        return (yield)\n    finally:\n        # The test run may have added an xfail mark dynamically.\n        xfailed = item.stash.get(xfailed_key, None)\n        if xfailed is None:\n            item.stash[xfailed_key] = xfailed = evaluate_xfail_marks(item)\n\n\n@hookimpl(wrapper=True)\ndef pytest_runtest_makereport(\n    item: Item, call: CallInfo[None]\n) -> Generator[None, TestReport, TestReport]:\n    rep = yield\n    xfailed = item.stash.get(xfailed_key, None)\n    if item.config.option.runxfail:\n        pass  # don't interfere\n    elif call.excinfo and isinstance(call.excinfo.value, xfail.Exception):\n        assert call.excinfo.value.msg is not None\n        rep.wasxfail = call.excinfo.value.msg\n        rep.outcome = \"skipped\"\n    elif not rep.skipped and xfailed:\n        if call.excinfo:\n            raises = xfailed.raises\n            if raises is None or (\n                (\n                    isinstance(raises, type | tuple)\n                    and isinstance(call.excinfo.value, raises)\n                )\n                or (\n                    isinstance(raises, AbstractRaises)\n                    and raises.matches(call.excinfo.value)\n                )\n            ):\n                rep.outcome = \"skipped\"\n                rep.wasxfail = xfailed.reason\n            else:\n                rep.outcome = \"failed\"\n        elif call.when == \"call\":\n            if xfailed.strict:\n                rep.outcome = \"failed\"\n                rep.longrepr = \"[XPASS(strict)] \" + xfailed.reason\n            else:\n                rep.outcome = \"passed\"\n                rep.wasxfail = xfailed.reason\n    return rep\n\n\ndef pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str] | None:\n    if hasattr(report, \"wasxfail\"):\n        if report.skipped:\n            return \"xfailed\", \"x\", \"XFAIL\"\n        elif report.passed:\n            return \"xpassed\", \"X\", \"XPASS\"\n    return None\n"
  },
  {
    "path": "src/_pytest/stash.py",
    "content": "from __future__ import annotations\n\nfrom typing import Any\nfrom typing import cast\nfrom typing import Generic\nfrom typing import TypeVar\n\n\n__all__ = [\"Stash\", \"StashKey\"]\n\n\nT = TypeVar(\"T\")\nD = TypeVar(\"D\")\n\n\nclass StashKey(Generic[T]):\n    \"\"\"``StashKey`` is an object used as a key to a :class:`Stash`.\n\n    A ``StashKey`` is associated with the type ``T`` of the value of the key.\n\n    A ``StashKey`` is unique and cannot conflict with another key.\n\n    .. versionadded:: 7.0\n    \"\"\"\n\n    __slots__ = ()\n\n\nclass Stash:\n    r\"\"\"``Stash`` is a type-safe heterogeneous mutable mapping that\n    allows keys and value types to be defined separately from\n    where it (the ``Stash``) is created.\n\n    Usually you will be given an object which has a ``Stash``, for example\n    :class:`~pytest.Config` or a :class:`~_pytest.nodes.Node`:\n\n    .. code-block:: python\n\n        stash: Stash = some_object.stash\n\n    If a module or plugin wants to store data in this ``Stash``, it creates\n    :class:`StashKey`\\s for its keys (at the module level):\n\n    .. code-block:: python\n\n        # At the top-level of the module\n        some_str_key = StashKey[str]()\n        some_bool_key = StashKey[bool]()\n\n    To store information:\n\n    .. code-block:: python\n\n        # Value type must match the key.\n        stash[some_str_key] = \"value\"\n        stash[some_bool_key] = True\n\n    To retrieve the information:\n\n    .. code-block:: python\n\n        # The static type of some_str is str.\n        some_str = stash[some_str_key]\n        # The static type of some_bool is bool.\n        some_bool = stash[some_bool_key]\n\n    .. versionadded:: 7.0\n    \"\"\"\n\n    __slots__ = (\"_storage\",)\n\n    def __init__(self) -> None:\n        self._storage: dict[StashKey[Any], object] = {}\n\n    def __setitem__(self, key: StashKey[T], value: T) -> None:\n        \"\"\"Set a value for key.\"\"\"\n        self._storage[key] = value\n\n    def __getitem__(self, key: StashKey[T]) -> T:\n        \"\"\"Get the value for key.\n\n        Raises ``KeyError`` if the key wasn't set before.\n        \"\"\"\n        return cast(T, self._storage[key])\n\n    def get(self, key: StashKey[T], default: D) -> T | D:\n        \"\"\"Get the value for key, or return default if the key wasn't set\n        before.\"\"\"\n        try:\n            return self[key]\n        except KeyError:\n            return default\n\n    def setdefault(self, key: StashKey[T], default: T) -> T:\n        \"\"\"Return the value of key if already set, otherwise set the value\n        of key to default and return default.\"\"\"\n        try:\n            return self[key]\n        except KeyError:\n            self[key] = default\n            return default\n\n    def __delitem__(self, key: StashKey[T]) -> None:\n        \"\"\"Delete the value for key.\n\n        Raises ``KeyError`` if the key wasn't set before.\n        \"\"\"\n        del self._storage[key]\n\n    def __contains__(self, key: StashKey[T]) -> bool:\n        \"\"\"Return whether key was set.\"\"\"\n        return key in self._storage\n\n    def __len__(self) -> int:\n        \"\"\"Return how many items exist in the stash.\"\"\"\n        return len(self._storage)\n"
  },
  {
    "path": "src/_pytest/stepwise.py",
    "content": "from __future__ import annotations\n\nimport dataclasses\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom typing import Any\nfrom typing import TYPE_CHECKING\n\nfrom _pytest import nodes\nfrom _pytest.cacheprovider import Cache\nfrom _pytest.config import Config\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.main import Session\nfrom _pytest.reports import TestReport\n\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\nSTEPWISE_CACHE_DIR = \"cache/stepwise\"\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"general\")\n    group.addoption(\n        \"--sw\",\n        \"--stepwise\",\n        action=\"store_true\",\n        default=False,\n        dest=\"stepwise\",\n        help=\"Exit on test failure and continue from last failing test next time\",\n    )\n    group.addoption(\n        \"--sw-skip\",\n        \"--stepwise-skip\",\n        action=\"store_true\",\n        default=False,\n        dest=\"stepwise_skip\",\n        help=\"Ignore the first failing test but stop on the next failing test. \"\n        \"Implicitly enables --stepwise.\",\n    )\n    group.addoption(\n        \"--sw-reset\",\n        \"--stepwise-reset\",\n        action=\"store_true\",\n        default=False,\n        dest=\"stepwise_reset\",\n        help=\"Resets stepwise state, restarting the stepwise workflow. \"\n        \"Implicitly enables --stepwise.\",\n    )\n\n\ndef pytest_configure(config: Config) -> None:\n    # --stepwise-skip/--stepwise-reset implies stepwise.\n    if config.option.stepwise_skip or config.option.stepwise_reset:\n        config.option.stepwise = True\n    if config.getoption(\"stepwise\"):\n        config.pluginmanager.register(StepwisePlugin(config), \"stepwiseplugin\")\n\n\ndef pytest_sessionfinish(session: Session) -> None:\n    if not session.config.getoption(\"stepwise\"):\n        assert session.config.cache is not None\n        if hasattr(session.config, \"workerinput\"):\n            # Do not update cache if this process is a xdist worker to prevent\n            # race conditions (#10641).\n            return\n\n\n@dataclasses.dataclass\nclass StepwiseCacheInfo:\n    # The nodeid of the last failed test.\n    last_failed: str | None\n\n    # The number of tests in the last time --stepwise was run.\n    # We use this information as a simple way to invalidate the cache information, avoiding\n    # confusing behavior in case the cache is stale.\n    last_test_count: int | None\n\n    # The date when the cache was last updated, for information purposes only.\n    last_cache_date_str: str\n\n    @property\n    def last_cache_date(self) -> datetime:\n        return datetime.fromisoformat(self.last_cache_date_str)\n\n    @classmethod\n    def empty(cls) -> Self:\n        return cls(\n            last_failed=None,\n            last_test_count=None,\n            last_cache_date_str=datetime.now().isoformat(),\n        )\n\n    def update_date_to_now(self) -> None:\n        self.last_cache_date_str = datetime.now().isoformat()\n\n\nclass StepwisePlugin:\n    def __init__(self, config: Config) -> None:\n        self.config = config\n        self.session: Session | None = None\n        self.report_status: list[str] = []\n        assert config.cache is not None\n        self.cache: Cache = config.cache\n        self.skip: bool = config.getoption(\"stepwise_skip\")\n        self.reset: bool = config.getoption(\"stepwise_reset\")\n        self.cached_info = self._load_cached_info()\n\n    def _load_cached_info(self) -> StepwiseCacheInfo:\n        cached_dict: dict[str, Any] | None = self.cache.get(STEPWISE_CACHE_DIR, None)\n        if cached_dict:\n            try:\n                return StepwiseCacheInfo(\n                    cached_dict[\"last_failed\"],\n                    cached_dict[\"last_test_count\"],\n                    cached_dict[\"last_cache_date_str\"],\n                )\n            except (KeyError, TypeError) as e:\n                error = f\"{type(e).__name__}: {e}\"\n                self.report_status.append(f\"error reading cache, discarding ({error})\")\n\n        # Cache not found or error during load, return a new cache.\n        return StepwiseCacheInfo.empty()\n\n    def pytest_sessionstart(self, session: Session) -> None:\n        self.session = session\n\n    def pytest_collection_modifyitems(\n        self, config: Config, items: list[nodes.Item]\n    ) -> None:\n        last_test_count = self.cached_info.last_test_count\n        self.cached_info.last_test_count = len(items)\n\n        if self.reset:\n            self.report_status.append(\"resetting state, not skipping.\")\n            self.cached_info.last_failed = None\n            return\n\n        if not self.cached_info.last_failed:\n            self.report_status.append(\"no previously failed tests, not skipping.\")\n            return\n\n        if last_test_count is not None and last_test_count != len(items):\n            self.report_status.append(\n                f\"test count changed, not skipping (now {len(items)} tests, previously {last_test_count}).\"\n            )\n            self.cached_info.last_failed = None\n            return\n\n        # Check all item nodes until we find a match on last failed.\n        failed_index = None\n        for index, item in enumerate(items):\n            if item.nodeid == self.cached_info.last_failed:\n                failed_index = index\n                break\n\n        # If the previously failed test was not found among the test items,\n        # do not skip any tests.\n        if failed_index is None:\n            self.report_status.append(\"previously failed test not found, not skipping.\")\n        else:\n            cache_age = datetime.now() - self.cached_info.last_cache_date\n            # Round up to avoid showing microseconds.\n            cache_age = timedelta(seconds=int(cache_age.total_seconds()))\n            self.report_status.append(\n                f\"skipping {failed_index} already passed items (cache from {cache_age} ago,\"\n                f\" use --sw-reset to discard).\"\n            )\n            deselected = items[:failed_index]\n            del items[:failed_index]\n            config.hook.pytest_deselected(items=deselected)\n\n    def pytest_runtest_logreport(self, report: TestReport) -> None:\n        if report.failed:\n            if self.skip:\n                # Remove test from the failed ones (if it exists) and unset the skip option\n                # to make sure the following tests will not be skipped.\n                if report.nodeid == self.cached_info.last_failed:\n                    self.cached_info.last_failed = None\n\n                self.skip = False\n            else:\n                # Mark test as the last failing and interrupt the test session.\n                self.cached_info.last_failed = report.nodeid\n                assert self.session is not None\n                self.session.shouldstop = (\n                    \"Test failed, continuing from this test next run.\"\n                )\n\n        else:\n            # If the test was actually run and did pass.\n            if report.when == \"call\":\n                # Remove test from the failed ones, if exists.\n                if report.nodeid == self.cached_info.last_failed:\n                    self.cached_info.last_failed = None\n\n    def pytest_report_collectionfinish(self) -> list[str] | None:\n        if self.config.get_verbosity() >= 0 and self.report_status:\n            return [f\"stepwise: {x}\" for x in self.report_status]\n        return None\n\n    def pytest_sessionfinish(self) -> None:\n        if hasattr(self.config, \"workerinput\"):\n            # Do not update cache if this process is a xdist worker to prevent\n            # race conditions (#10641).\n            return\n        self.cached_info.update_date_to_now()\n        self.cache.set(STEPWISE_CACHE_DIR, dataclasses.asdict(self.cached_info))\n"
  },
  {
    "path": "src/_pytest/subtests.py",
    "content": "\"\"\"Builtin plugin that adds subtests support.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom collections.abc import Callable\nfrom collections.abc import Iterator\nfrom collections.abc import Mapping\nfrom contextlib import AbstractContextManager\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nfrom contextlib import nullcontext\nimport dataclasses\nimport time\nfrom types import TracebackType\nfrom typing import Any\nfrom typing import TYPE_CHECKING\n\nimport pluggy\n\nfrom _pytest._code import ExceptionInfo\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest.capture import CaptureFixture\nfrom _pytest.capture import FDCapture\nfrom _pytest.capture import SysCapture\nfrom _pytest.config import Config\nfrom _pytest.config import hookimpl\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.fixtures import fixture\nfrom _pytest.fixtures import SubRequest\nfrom _pytest.logging import catching_logs\nfrom _pytest.logging import LogCaptureHandler\nfrom _pytest.logging import LoggingPlugin\nfrom _pytest.reports import TestReport\nfrom _pytest.runner import CallInfo\nfrom _pytest.runner import check_interactive_exception\nfrom _pytest.runner import get_reraise_exceptions\nfrom _pytest.stash import StashKey\n\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    Config._add_verbosity_ini(\n        parser,\n        Config.VERBOSITY_SUBTESTS,\n        help=(\n            \"Specify verbosity level for subtests. \"\n            \"Higher levels will generate output for passed subtests. Failed subtests are always reported.\"\n        ),\n    )\n\n\n@dataclasses.dataclass(frozen=True, slots=True, kw_only=True)\nclass SubtestContext:\n    \"\"\"The values passed to Subtests.test() that are included in the test report.\"\"\"\n\n    msg: str | None\n    kwargs: Mapping[str, Any]\n\n    def __post_init__(self) -> None:\n        # Brute-force the returned kwargs dict to be JSON serializable (pytest-dev/pytest-xdist#1273).\n        object.__setattr__(\n            self, \"kwargs\", {k: saferepr(v) for (k, v) in self.kwargs.items()}\n        )\n\n    def _to_json(self) -> dict[str, Any]:\n        result = dataclasses.asdict(self)\n        return result\n\n    @classmethod\n    def _from_json(cls, d: dict[str, Any]) -> Self:\n        return cls(msg=d[\"msg\"], kwargs=d[\"kwargs\"])\n\n\n@dataclasses.dataclass(init=False)\nclass SubtestReport(TestReport):\n    context: SubtestContext\n\n    @property\n    def head_line(self) -> str:\n        _, _, domain = self.location\n        return f\"{domain} {self._sub_test_description()}\"\n\n    def _sub_test_description(self) -> str:\n        parts = []\n        if self.context.msg is not None:\n            parts.append(f\"[{self.context.msg}]\")\n        if self.context.kwargs:\n            params_desc = \", \".join(\n                f\"{k}={v}\" for (k, v) in self.context.kwargs.items()\n            )\n            parts.append(f\"({params_desc})\")\n        return \" \".join(parts) or \"(<subtest>)\"\n\n    def _to_json(self) -> dict[str, Any]:\n        data = super()._to_json()\n        del data[\"context\"]\n        data[\"_report_type\"] = \"SubTestReport\"\n        data[\"_subtest.context\"] = self.context._to_json()\n        return data\n\n    @classmethod\n    def _from_json(cls, reportdict: dict[str, Any]) -> SubtestReport:\n        report = super()._from_json(reportdict)\n        report.context = SubtestContext._from_json(reportdict[\"_subtest.context\"])\n        return report\n\n    @classmethod\n    def _new(\n        cls,\n        test_report: TestReport,\n        context: SubtestContext,\n        captured_output: Captured | None,\n        captured_logs: CapturedLogs | None,\n    ) -> Self:\n        result = super()._from_json(test_report._to_json())\n        result.context = context\n\n        if captured_output:\n            if captured_output.out:\n                result.sections.append((\"Captured stdout call\", captured_output.out))\n            if captured_output.err:\n                result.sections.append((\"Captured stderr call\", captured_output.err))\n\n        if captured_logs and (log := captured_logs.handler.stream.getvalue()):\n            result.sections.append((\"Captured log call\", log))\n\n        return result\n\n\n@fixture\ndef subtests(request: SubRequest) -> Subtests:\n    \"\"\"Provides subtests functionality.\"\"\"\n    capmam = request.node.config.pluginmanager.get_plugin(\"capturemanager\")\n    suspend_capture_ctx = (\n        capmam.global_and_fixture_disabled if capmam is not None else nullcontext\n    )\n    return Subtests(request.node.ihook, suspend_capture_ctx, request, _ispytest=True)\n\n\nclass Subtests:\n    \"\"\"Subtests fixture, enables declaring subtests inside test functions via the :meth:`test` method.\"\"\"\n\n    def __init__(\n        self,\n        ihook: pluggy.HookRelay,\n        suspend_capture_ctx: Callable[[], AbstractContextManager[None]],\n        request: SubRequest,\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        self._ihook = ihook\n        self._suspend_capture_ctx = suspend_capture_ctx\n        self._request = request\n\n    def test(\n        self,\n        msg: str | None = None,\n        **kwargs: Any,\n    ) -> _SubTestContextManager:\n        \"\"\"\n        Context manager for subtests, capturing exceptions raised inside the subtest scope and\n        reporting assertion failures and errors individually.\n\n        Usage\n        -----\n\n        .. code-block:: python\n\n            def test(subtests):\n                for i in range(5):\n                    with subtests.test(\"custom message\", i=i):\n                        assert i % 2 == 0\n\n        :param msg:\n            If given, the message will be shown in the test report in case of subtest failure.\n\n        :param kwargs:\n            Arbitrary values that are also added to the subtest report.\n        \"\"\"\n        return _SubTestContextManager(\n            self._ihook,\n            msg,\n            kwargs,\n            request=self._request,\n            suspend_capture_ctx=self._suspend_capture_ctx,\n            config=self._request.config,\n        )\n\n\n@dataclasses.dataclass\nclass _SubTestContextManager:\n    \"\"\"\n    Context manager for subtests, capturing exceptions raised inside the subtest scope and handling\n    them through the pytest machinery.\n    \"\"\"\n\n    # Note: initially the logic for this context manager was implemented directly\n    # in Subtests.test() as a @contextmanager, however, it is not possible to control the output fully when\n    # exiting from it due to an exception when in `--exitfirst` mode, so this was refactored into an\n    # explicit context manager class (pytest-dev/pytest-subtests#134).\n\n    ihook: pluggy.HookRelay\n    msg: str | None\n    kwargs: dict[str, Any]\n    suspend_capture_ctx: Callable[[], AbstractContextManager[None]]\n    request: SubRequest\n    config: Config\n\n    def __enter__(self) -> None:\n        __tracebackhide__ = True\n\n        self._start = time.time()\n        self._precise_start = time.perf_counter()\n        self._exc_info = None\n\n        self._exit_stack = ExitStack()\n        self._captured_output = self._exit_stack.enter_context(\n            capturing_output(self.request)\n        )\n        self._captured_logs = self._exit_stack.enter_context(\n            capturing_logs(self.request)\n        )\n\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n    ) -> bool:\n        __tracebackhide__ = True\n        if exc_val is not None:\n            exc_info = ExceptionInfo.from_exception(exc_val)\n        else:\n            exc_info = None\n\n        self._exit_stack.close()\n\n        precise_stop = time.perf_counter()\n        duration = precise_stop - self._precise_start\n        stop = time.time()\n\n        call_info = CallInfo[None](\n            None,\n            exc_info,\n            start=self._start,\n            stop=stop,\n            duration=duration,\n            when=\"call\",\n            _ispytest=True,\n        )\n        report = self.ihook.pytest_runtest_makereport(\n            item=self.request.node, call=call_info\n        )\n        sub_report = SubtestReport._new(\n            report,\n            SubtestContext(msg=self.msg, kwargs=self.kwargs),\n            captured_output=self._captured_output,\n            captured_logs=self._captured_logs,\n        )\n\n        if sub_report.failed:\n            failed_subtests = self.config.stash[failed_subtests_key]\n            failed_subtests[self.request.node.nodeid] += 1\n\n        with self.suspend_capture_ctx():\n            self.ihook.pytest_runtest_logreport(report=sub_report)\n\n        if check_interactive_exception(call_info, sub_report):\n            self.ihook.pytest_exception_interact(\n                node=self.request.node, call=call_info, report=sub_report\n            )\n\n        if exc_val is not None:\n            if isinstance(exc_val, get_reraise_exceptions(self.config)):\n                return False\n            if self.request.session.shouldfail:\n                return False\n        return True\n\n\n@contextmanager\ndef capturing_output(request: SubRequest) -> Iterator[Captured]:\n    option = request.config.getoption(\"capture\", None)\n\n    capman = request.config.pluginmanager.getplugin(\"capturemanager\")\n    if getattr(capman, \"_capture_fixture\", None):\n        # capsys or capfd are active, subtest should not capture.\n        fixture = None\n    elif option == \"sys\":\n        fixture = CaptureFixture(SysCapture, request, _ispytest=True)\n    elif option == \"fd\":\n        fixture = CaptureFixture(FDCapture, request, _ispytest=True)\n    else:\n        fixture = None\n\n    if fixture is not None:\n        fixture._start()\n\n    captured = Captured()\n    try:\n        yield captured\n    finally:\n        if fixture is not None:\n            out, err = fixture.readouterr()\n            fixture.close()\n            captured.out = out\n            captured.err = err\n\n\n@contextmanager\ndef capturing_logs(\n    request: SubRequest,\n) -> Iterator[CapturedLogs | None]:\n    logging_plugin: LoggingPlugin | None = request.config.pluginmanager.getplugin(\n        \"logging-plugin\"\n    )\n    if logging_plugin is None:\n        yield None\n    else:\n        handler = LogCaptureHandler()\n        handler.setFormatter(logging_plugin.formatter)\n\n        captured_logs = CapturedLogs(handler)\n        with catching_logs(handler, level=logging_plugin.log_level):\n            yield captured_logs\n\n\n@dataclasses.dataclass\nclass Captured:\n    out: str = \"\"\n    err: str = \"\"\n\n\n@dataclasses.dataclass\nclass CapturedLogs:\n    handler: LogCaptureHandler\n\n\ndef pytest_report_to_serializable(report: TestReport) -> dict[str, Any] | None:\n    if isinstance(report, SubtestReport):\n        return report._to_json()\n    return None\n\n\ndef pytest_report_from_serializable(data: dict[str, Any]) -> SubtestReport | None:\n    if data.get(\"_report_type\") == \"SubTestReport\":\n        return SubtestReport._from_json(data)\n    return None\n\n\n# Dict of nodeid -> number of failed subtests.\n# Used to fail top-level tests that passed but contain failed subtests.\nfailed_subtests_key = StashKey[defaultdict[str, int]]()\n\n\ndef pytest_configure(config: Config) -> None:\n    config.stash[failed_subtests_key] = defaultdict(int)\n\n\n@hookimpl(tryfirst=True)\ndef pytest_report_teststatus(\n    report: TestReport,\n    config: Config,\n) -> tuple[str, str, str | Mapping[str, bool]] | None:\n    if report.when != \"call\":\n        return None\n\n    quiet = config.get_verbosity(Config.VERBOSITY_SUBTESTS) == 0\n    if isinstance(report, SubtestReport):\n        outcome = report.outcome\n        description = report._sub_test_description()\n\n        if hasattr(report, \"wasxfail\"):\n            if quiet:\n                return \"\", \"\", \"\"\n            elif outcome == \"skipped\":\n                category = \"xfailed\"\n                short = \"y\"  # x letter is used for regular xfail, y for subtest xfail\n                status = \"SUBXFAIL\"\n            # outcome == \"passed\" in an xfail is only possible via a @pytest.mark.xfail mark, which\n            # is not applicable to a subtest, which only handles pytest.xfail().\n            else:  # pragma: no cover\n                # This should not normally happen, unless some plugin is setting wasxfail without\n                # the correct outcome. Pytest expects the call outcome to be either skipped or\n                # passed in case of xfail.\n                # Let's pass this report to the next hook.\n                return None\n            return category, short, f\"{status}{description}\"\n\n        if report.failed:\n            return outcome, \"u\", f\"SUBFAILED{description}\"\n        else:\n            if report.passed:\n                if quiet:\n                    return \"\", \"\", \"\"\n                else:\n                    return f\"subtests {outcome}\", \"u\", f\"SUBPASSED{description}\"\n            elif report.skipped:\n                if quiet:\n                    return \"\", \"\", \"\"\n                else:\n                    return outcome, \"-\", f\"SUBSKIPPED{description}\"\n\n    else:\n        failed_subtests_count = config.stash[failed_subtests_key][report.nodeid]\n        # Top-level test, fail if it contains failed subtests and it has passed.\n        if report.passed and failed_subtests_count > 0:\n            report.outcome = \"failed\"\n            suffix = \"s\" if failed_subtests_count > 1 else \"\"\n            report.longrepr = f\"contains {failed_subtests_count} failed subtest{suffix}\"\n\n    return None\n"
  },
  {
    "path": "src/_pytest/terminal.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Terminal reporting of the full testing process.\n\nThis is a good source for looking at the various reporting hooks.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nfrom collections import Counter\nfrom collections.abc import Callable\nfrom collections.abc import Generator\nfrom collections.abc import Mapping\nfrom collections.abc import Sequence\nimport dataclasses\nimport datetime\nfrom functools import partial\nimport inspect\nfrom pathlib import Path\nimport platform\nimport sys\nimport textwrap\nfrom typing import Any\nfrom typing import ClassVar\nfrom typing import final\nfrom typing import Literal\nfrom typing import NamedTuple\nfrom typing import TextIO\nfrom typing import TYPE_CHECKING\nimport warnings\n\nimport pluggy\n\nfrom _pytest import compat\nfrom _pytest import nodes\nfrom _pytest import timing\nfrom _pytest._code import ExceptionInfo\nfrom _pytest._code.code import ExceptionRepr\nfrom _pytest._io import TerminalWriter\nfrom _pytest._io.wcwidth import wcswidth\nimport _pytest._version\nfrom _pytest.compat import running_on_ci\nfrom _pytest.config import _PluggyPlugin\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.config import hookimpl\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.nodes import Item\nfrom _pytest.nodes import Node\nfrom _pytest.pathlib import absolutepath\nfrom _pytest.pathlib import bestrelpath\nfrom _pytest.reports import BaseReport\nfrom _pytest.reports import CollectReport\nfrom _pytest.reports import TestReport\n\n\nif TYPE_CHECKING:\n    from _pytest.main import Session\n\n\nREPORT_COLLECTING_RESOLUTION = 0.5\n\nKNOWN_TYPES = (\n    \"failed\",\n    \"passed\",\n    \"skipped\",\n    \"deselected\",\n    \"xfailed\",\n    \"xpassed\",\n    \"warnings\",\n    \"error\",\n    \"subtests passed\",\n    \"subtests failed\",\n    \"subtests skipped\",\n)\n\n_REPORTCHARS_DEFAULT = \"fE\"\n\n\nclass MoreQuietAction(argparse.Action):\n    \"\"\"A modified copy of the argparse count action which counts down and updates\n    the legacy quiet attribute at the same time.\n\n    Used to unify verbosity handling.\n    \"\"\"\n\n    def __init__(\n        self,\n        option_strings: Sequence[str],\n        dest: str,\n        default: object = None,\n        required: bool = False,\n        help: str | None = None,\n    ) -> None:\n        super().__init__(\n            option_strings=option_strings,\n            dest=dest,\n            nargs=0,\n            default=default,\n            required=required,\n            help=help,\n        )\n\n    def __call__(\n        self,\n        parser: argparse.ArgumentParser,\n        namespace: argparse.Namespace,\n        values: str | Sequence[object] | None,\n        option_string: str | None = None,\n    ) -> None:\n        new_count = getattr(namespace, self.dest, 0) - 1\n        setattr(namespace, self.dest, new_count)\n        # todo Deprecate config.quiet\n        namespace.quiet = getattr(namespace, \"quiet\", 0) + 1\n\n\nclass TestShortLogReport(NamedTuple):\n    \"\"\"Used to store the test status result category, shortletter and verbose word.\n    For example ``\"rerun\", \"R\", (\"RERUN\", {\"yellow\": True})``.\n\n    :ivar category:\n        The class of result, for example ``“passed”``, ``“skipped”``, ``“error”``, or the empty string.\n\n    :ivar letter:\n        The short letter shown as testing progresses, for example ``\".\"``, ``\"s\"``, ``\"E\"``, or the empty string.\n\n    :ivar word:\n        Verbose word is shown as testing progresses in verbose mode, for example ``\"PASSED\"``, ``\"SKIPPED\"``,\n        ``\"ERROR\"``, or the empty string.\n    \"\"\"\n\n    category: str\n    letter: str\n    word: str | tuple[str, Mapping[str, bool]]\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    group = parser.getgroup(\"terminal reporting\", \"Reporting\", after=\"general\")\n    group._addoption(  # private to use reserved lower-case short option\n        \"-v\",\n        \"--verbose\",\n        action=\"count\",\n        default=0,\n        dest=\"verbose\",\n        help=\"Increase verbosity\",\n    )\n    group.addoption(\n        \"--no-header\",\n        action=\"store_true\",\n        default=False,\n        dest=\"no_header\",\n        help=\"Disable header\",\n    )\n    group.addoption(\n        \"--no-summary\",\n        action=\"store_true\",\n        default=False,\n        dest=\"no_summary\",\n        help=\"Disable summary\",\n    )\n    group.addoption(\n        \"--no-fold-skipped\",\n        action=\"store_false\",\n        dest=\"fold_skipped\",\n        default=True,\n        help=\"Do not fold skipped tests in short summary.\",\n    )\n    group.addoption(\n        \"--force-short-summary\",\n        action=\"store_true\",\n        dest=\"force_short_summary\",\n        default=False,\n        help=\"Force condensed summary output regardless of verbosity level.\",\n    )\n    group._addoption(  # private to use reserved lower-case short option\n        \"-q\",\n        \"--quiet\",\n        action=MoreQuietAction,\n        default=0,\n        dest=\"verbose\",\n        help=\"Decrease verbosity\",\n    )\n    group.addoption(\n        \"--verbosity\",\n        dest=\"verbose\",\n        type=int,\n        default=0,\n        help=\"Set verbosity. Default: 0.\",\n    )\n    group._addoption(  # private to use reserved lower-case short option\n        \"-r\",\n        \"--report-chars\",\n        action=\"store\",\n        dest=\"reportchars\",\n        default=_REPORTCHARS_DEFAULT,\n        metavar=\"chars\",\n        help=\"Show extra test summary info as specified by chars: (f)ailed, \"\n        \"(E)rror, (s)kipped, (x)failed, (X)passed, \"\n        \"(p)assed, (P)assed with output, (a)ll except passed (p/P), or (A)ll. \"\n        \"(w)arnings are enabled by default (see --disable-warnings), \"\n        \"'N' can be used to reset the list. (default: 'fE').\",\n    )\n    group.addoption(\n        \"--disable-warnings\",\n        \"--disable-pytest-warnings\",\n        default=False,\n        dest=\"disable_warnings\",\n        action=\"store_true\",\n        help=\"Disable warnings summary\",\n    )\n    group._addoption(  # private to use reserved lower-case short option\n        \"-l\",\n        \"--showlocals\",\n        action=\"store_true\",\n        dest=\"showlocals\",\n        default=False,\n        help=\"Show locals in tracebacks (disabled by default)\",\n    )\n    group.addoption(\n        \"--no-showlocals\",\n        action=\"store_false\",\n        dest=\"showlocals\",\n        help=\"Hide locals in tracebacks (negate --showlocals passed through addopts)\",\n    )\n    group.addoption(\n        \"--tb\",\n        metavar=\"style\",\n        action=\"store\",\n        dest=\"tbstyle\",\n        default=\"auto\",\n        choices=[\"auto\", \"long\", \"short\", \"no\", \"line\", \"native\"],\n        help=\"Traceback print mode (auto/long/short/line/native/no)\",\n    )\n    group.addoption(\n        \"--xfail-tb\",\n        action=\"store_true\",\n        dest=\"xfail_tb\",\n        default=False,\n        help=\"Show tracebacks for xfail (as long as --tb != no)\",\n    )\n    group.addoption(\n        \"--show-capture\",\n        action=\"store\",\n        dest=\"showcapture\",\n        choices=[\"no\", \"stdout\", \"stderr\", \"log\", \"all\"],\n        default=\"all\",\n        help=\"Controls how captured stdout/stderr/log is shown on failed tests. \"\n        \"Default: all.\",\n    )\n    group.addoption(\n        \"--fulltrace\",\n        \"--full-trace\",\n        action=\"store_true\",\n        default=False,\n        help=\"Don't cut any tracebacks (default is to cut)\",\n    )\n    group.addoption(\n        \"--color\",\n        metavar=\"color\",\n        action=\"store\",\n        dest=\"color\",\n        default=\"auto\",\n        choices=[\"yes\", \"no\", \"auto\"],\n        help=\"Color terminal output (yes/no/auto)\",\n    )\n    group.addoption(\n        \"--code-highlight\",\n        default=\"yes\",\n        choices=[\"yes\", \"no\"],\n        help=\"Whether code should be highlighted (only if --color is also enabled). \"\n        \"Default: yes.\",\n    )\n\n    parser.addini(\n        \"console_output_style\",\n        help='Console output: \"classic\", or with additional progress information '\n        '(\"progress\" (percentage) | \"count\" | \"progress-even-when-capture-no\" (forces '\n        \"progress even when capture=no)\",\n        default=\"progress\",\n    )\n    Config._add_verbosity_ini(\n        parser,\n        Config.VERBOSITY_TEST_CASES,\n        help=(\n            \"Specify a verbosity level for test case execution, overriding the main level. \"\n            \"Higher levels will provide more detailed information about each test case executed.\"\n        ),\n    )\n\n\ndef pytest_configure(config: Config) -> None:\n    reporter = TerminalReporter(config, sys.stdout)\n    config.pluginmanager.register(reporter, \"terminalreporter\")\n    if config.option.debug or config.option.traceconfig:\n\n        def mywriter(tags, args):\n            msg = \" \".join(map(str, args))\n            reporter.write_line(\"[traceconfig] \" + msg)\n\n        config.trace.root.setprocessor(\"pytest:config\", mywriter)\n\n    # See terminalprogress.py.\n    # On Windows it's safe to load by default.\n    if sys.platform == \"win32\":\n        config.pluginmanager.import_plugin(\"terminalprogress\")\n\n\ndef getreportopt(config: Config) -> str:\n    reportchars: str = config.option.reportchars\n\n    old_aliases = {\"F\", \"S\"}\n    reportopts = \"\"\n    for char in reportchars:\n        if char in old_aliases:\n            char = char.lower()\n        if char == \"a\":\n            reportopts = \"sxXEf\"\n        elif char == \"A\":\n            reportopts = \"PpsxXEf\"\n        elif char == \"N\":\n            reportopts = \"\"\n        elif char not in reportopts:\n            reportopts += char\n\n    if not config.option.disable_warnings and \"w\" not in reportopts:\n        reportopts = \"w\" + reportopts\n    elif config.option.disable_warnings and \"w\" in reportopts:\n        reportopts = reportopts.replace(\"w\", \"\")\n\n    return reportopts\n\n\n@hookimpl(trylast=True)  # after _pytest.runner\ndef pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str]:\n    letter = \"F\"\n    if report.passed:\n        letter = \".\"\n    elif report.skipped:\n        letter = \"s\"\n\n    outcome: str = report.outcome\n    if report.when in (\"collect\", \"setup\", \"teardown\") and outcome == \"failed\":\n        outcome = \"error\"\n        letter = \"E\"\n\n    return outcome, letter, outcome.upper()\n\n\n@dataclasses.dataclass\nclass WarningReport:\n    \"\"\"Simple structure to hold warnings information captured by ``pytest_warning_recorded``.\n\n    :ivar str message:\n        User friendly message about the warning.\n    :ivar str|None nodeid:\n        nodeid that generated the warning (see ``get_location``).\n    :ivar tuple fslocation:\n        File system location of the source of the warning (see ``get_location``).\n    \"\"\"\n\n    message: str\n    nodeid: str | None = None\n    fslocation: tuple[str, int] | None = None\n\n    count_towards_summary: ClassVar = True\n\n    def get_location(self, config: Config) -> str | None:\n        \"\"\"Return the more user-friendly information about the location of a warning, or None.\"\"\"\n        if self.nodeid:\n            return self.nodeid\n        if self.fslocation:\n            filename, linenum = self.fslocation\n            relpath = bestrelpath(config.invocation_params.dir, absolutepath(filename))\n            return f\"{relpath}:{linenum}\"\n        return None\n\n\n@final\nclass TerminalReporter:\n    def __init__(self, config: Config, file: TextIO | None = None) -> None:\n        import _pytest.config\n\n        self.config = config\n        self._numcollected = 0\n        self._session: Session | None = None\n        self._showfspath: bool | None = None\n\n        self.stats: dict[str, list[Any]] = {}\n        self._main_color: str | None = None\n        self._known_types: list[str] | None = None\n        self.startpath = config.invocation_params.dir\n        if file is None:\n            file = sys.stdout\n        self._tw = _pytest.config.create_terminal_writer(config, file)\n        self._screen_width = self._tw.fullwidth\n        self.currentfspath: None | Path | str | int = None\n        self.reportchars = getreportopt(config)\n        self.foldskipped = config.option.fold_skipped\n        self.hasmarkup = self._tw.hasmarkup\n        # isatty should be a method but was wrongly implemented as a boolean.\n        # We use CallableBool here to support both.\n        self.isatty = compat.CallableBool(file.isatty())\n        self._progress_nodeids_reported: set[str] = set()\n        self._timing_nodeids_reported: set[str] = set()\n        self._show_progress_info = self._determine_show_progress_info()\n        self._collect_report_last_write = timing.Instant()\n        self._already_displayed_warnings: int | None = None\n        self._keyboardinterrupt_memo: ExceptionRepr | None = None\n\n    def _determine_show_progress_info(\n        self,\n    ) -> Literal[\"progress\", \"count\", \"times\", False]:\n        \"\"\"Return whether we should display progress information based on the current config.\"\"\"\n        # do not show progress if we are not capturing output (#3038) unless explicitly\n        # overridden by progress-even-when-capture-no\n        if (\n            self.config.getoption(\"capture\", \"no\") == \"no\"\n            and self.config.getini(\"console_output_style\")\n            != \"progress-even-when-capture-no\"\n        ):\n            return False\n        # do not show progress if we are showing fixture setup/teardown\n        if self.config.getoption(\"setupshow\", False):\n            return False\n        cfg: str = self.config.getini(\"console_output_style\")\n        if cfg in {\"progress\", \"progress-even-when-capture-no\"}:\n            return \"progress\"\n        elif cfg == \"count\":\n            return \"count\"\n        elif cfg == \"times\":\n            return \"times\"\n        else:\n            return False\n\n    @property\n    def verbosity(self) -> int:\n        verbosity: int = self.config.option.verbose\n        return verbosity\n\n    @property\n    def showheader(self) -> bool:\n        return self.verbosity >= 0\n\n    @property\n    def no_header(self) -> bool:\n        return bool(self.config.option.no_header)\n\n    @property\n    def no_summary(self) -> bool:\n        return bool(self.config.option.no_summary)\n\n    @property\n    def showfspath(self) -> bool:\n        if self._showfspath is None:\n            return self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) >= 0\n        return self._showfspath\n\n    @showfspath.setter\n    def showfspath(self, value: bool | None) -> None:\n        self._showfspath = value\n\n    @property\n    def showlongtestinfo(self) -> bool:\n        return self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) > 0\n\n    @property\n    def reported_progress(self) -> int:\n        \"\"\"The amount of items reported in the progress so far.\n\n        :meta private:\n        \"\"\"\n        return len(self._progress_nodeids_reported)\n\n    def hasopt(self, char: str) -> bool:\n        char = {\"xfailed\": \"x\", \"skipped\": \"s\"}.get(char, char)\n        return char in self.reportchars\n\n    def write_fspath_result(self, nodeid: str, res: str, **markup: bool) -> None:\n        fspath = self.config.rootpath / nodeid.split(\"::\")[0]\n        if self.currentfspath is None or fspath != self.currentfspath:\n            if self.currentfspath is not None and self._show_progress_info:\n                self._write_progress_information_filling_space()\n            self.currentfspath = fspath\n            relfspath = bestrelpath(self.startpath, fspath)\n            self._tw.line()\n            self._tw.write(relfspath + \" \")\n        self._tw.write(res, flush=True, **markup)\n\n    def write_ensure_prefix(self, prefix: str, extra: str = \"\", **kwargs) -> None:\n        if self.currentfspath != prefix:\n            self._tw.line()\n            self.currentfspath = prefix\n            self._tw.write(prefix)\n        if extra:\n            self._tw.write(extra, **kwargs)\n            self.currentfspath = -2\n\n    def ensure_newline(self) -> None:\n        if self.currentfspath:\n            self._tw.line()\n            self.currentfspath = None\n\n    def wrap_write(\n        self,\n        content: str,\n        *,\n        flush: bool = False,\n        margin: int = 8,\n        line_sep: str = \"\\n\",\n        **markup: bool,\n    ) -> None:\n        \"\"\"Wrap message with margin for progress info.\"\"\"\n        width_of_current_line = self._tw.width_of_current_line\n        wrapped = line_sep.join(\n            textwrap.wrap(\n                \" \" * width_of_current_line + content,\n                width=self._screen_width - margin,\n                drop_whitespace=True,\n                replace_whitespace=False,\n            ),\n        )\n        wrapped = wrapped[width_of_current_line:]\n        self._tw.write(wrapped, flush=flush, **markup)\n\n    def write(self, content: str, *, flush: bool = False, **markup: bool) -> None:\n        self._tw.write(content, flush=flush, **markup)\n\n    def write_raw(self, content: str, *, flush: bool = False) -> None:\n        self._tw.write_raw(content, flush=flush)\n\n    def flush(self) -> None:\n        self._tw.flush()\n\n    def write_line(self, line: str | bytes, **markup: bool) -> None:\n        if not isinstance(line, str):\n            line = str(line, errors=\"replace\")\n        self.ensure_newline()\n        self._tw.line(line, **markup)\n\n    def rewrite(self, line: str, **markup: bool) -> None:\n        \"\"\"Rewinds the terminal cursor to the beginning and writes the given line.\n\n        :param erase:\n            If True, will also add spaces until the full terminal width to ensure\n            previous lines are properly erased.\n\n        The rest of the keyword arguments are markup instructions.\n        \"\"\"\n        erase = markup.pop(\"erase\", False)\n        if erase:\n            fill_count = self._tw.fullwidth - len(line) - 1\n            fill = \" \" * fill_count\n        else:\n            fill = \"\"\n        line = str(line)\n        self._tw.write(\"\\r\" + line + fill, **markup)\n\n    def write_sep(\n        self,\n        sep: str,\n        title: str | None = None,\n        fullwidth: int | None = None,\n        **markup: bool,\n    ) -> None:\n        self.ensure_newline()\n        self._tw.sep(sep, title, fullwidth, **markup)\n\n    def section(self, title: str, sep: str = \"=\", **kw: bool) -> None:\n        self._tw.sep(sep, title, **kw)\n\n    def line(self, msg: str, **kw: bool) -> None:\n        self._tw.line(msg, **kw)\n\n    def _add_stats(self, category: str, items: Sequence[Any]) -> None:\n        set_main_color = category not in self.stats\n        self.stats.setdefault(category, []).extend(items)\n        if set_main_color:\n            self._set_main_color()\n\n    def pytest_internalerror(self, excrepr: ExceptionRepr) -> bool:\n        for line in str(excrepr).split(\"\\n\"):\n            self.write_line(\"INTERNALERROR> \" + line)\n        return True\n\n    def pytest_warning_recorded(\n        self,\n        warning_message: warnings.WarningMessage,\n        nodeid: str,\n    ) -> None:\n        from _pytest.warnings import warning_record_to_str\n\n        fslocation = warning_message.filename, warning_message.lineno\n        message = warning_record_to_str(warning_message)\n\n        warning_report = WarningReport(\n            fslocation=fslocation, message=message, nodeid=nodeid\n        )\n        self._add_stats(\"warnings\", [warning_report])\n\n    def pytest_plugin_registered(self, plugin: _PluggyPlugin) -> None:\n        if self.config.option.traceconfig:\n            msg = f\"PLUGIN registered: {plugin}\"\n            # XXX This event may happen during setup/teardown time\n            #     which unfortunately captures our output here\n            #     which garbles our output if we use self.write_line.\n            self.write_line(msg)\n\n    def pytest_deselected(self, items: Sequence[Item]) -> None:\n        self._add_stats(\"deselected\", items)\n\n    def pytest_runtest_logstart(\n        self, nodeid: str, location: tuple[str, int | None, str]\n    ) -> None:\n        fspath, lineno, domain = location\n        # Ensure that the path is printed before the\n        # 1st test of a module starts running.\n        if self.showlongtestinfo:\n            line = self._locationline(nodeid, fspath, lineno, domain)\n            self.write_ensure_prefix(line, \"\")\n            self.flush()\n        elif self.showfspath:\n            self.write_fspath_result(nodeid, \"\")\n            self.flush()\n\n    def pytest_runtest_logreport(self, report: TestReport) -> None:\n        self._tests_ran = True\n        rep = report\n\n        res = TestShortLogReport(\n            *self.config.hook.pytest_report_teststatus(report=rep, config=self.config)\n        )\n        category, letter, word = res.category, res.letter, res.word\n        if not isinstance(word, tuple):\n            markup = None\n        else:\n            word, markup = word\n        self._add_stats(category, [rep])\n        if not letter and not word:\n            # Probably passed setup/teardown.\n            return\n        if markup is None:\n            was_xfail = hasattr(report, \"wasxfail\")\n            if rep.passed and not was_xfail:\n                markup = {\"green\": True}\n            elif rep.passed and was_xfail:\n                markup = {\"yellow\": True}\n            elif rep.failed:\n                markup = {\"red\": True}\n            elif rep.skipped:\n                markup = {\"yellow\": True}\n            else:\n                markup = {}\n        self._progress_nodeids_reported.add(rep.nodeid)\n        if self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) <= 0:\n            self._tw.write(letter, **markup)\n            # When running in xdist, the logreport and logfinish of multiple\n            # items are interspersed, e.g. `logreport`, `logreport`,\n            # `logfinish`, `logfinish`. To avoid the \"past edge\" calculation\n            # from getting confused and overflowing (#7166), do the past edge\n            # printing here and not in logfinish, except for the 100% which\n            # should only be printed after all teardowns are finished.\n            if self._show_progress_info and not self._is_last_item:\n                self._write_progress_information_if_past_edge()\n        else:\n            line = self._locationline(rep.nodeid, *rep.location)\n            running_xdist = hasattr(rep, \"node\")\n            if not running_xdist:\n                self.write_ensure_prefix(line, word, **markup)\n                if rep.skipped or hasattr(report, \"wasxfail\"):\n                    reason = _get_raw_skip_reason(rep)\n                    if self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) < 2:\n                        available_width = (\n                            (self._tw.fullwidth - self._tw.width_of_current_line)\n                            - len(\" [100%]\")\n                            - 1\n                        )\n                        formatted_reason = _format_trimmed(\n                            \" ({})\", reason, available_width\n                        )\n                    else:\n                        formatted_reason = f\" ({reason})\"\n\n                    if reason and formatted_reason is not None:\n                        self.wrap_write(formatted_reason)\n                if self._show_progress_info:\n                    self._write_progress_information_filling_space()\n            else:\n                self.ensure_newline()\n                self._tw.write(f\"[{rep.node.gateway.id}]\")\n                if self._show_progress_info:\n                    self._tw.write(\n                        self._get_progress_information_message() + \" \", cyan=True\n                    )\n                else:\n                    self._tw.write(\" \")\n                self._tw.write(word, **markup)\n                self._tw.write(\" \" + line)\n                self.currentfspath = -2\n        self.flush()\n\n    @property\n    def _is_last_item(self) -> bool:\n        assert self._session is not None\n        return self.reported_progress == self._session.testscollected\n\n    @hookimpl(wrapper=True)\n    def pytest_runtestloop(self) -> Generator[None, object, object]:\n        result = yield\n\n        # Write the final/100% progress -- deferred until the loop is complete.\n        if (\n            self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) <= 0\n            and self._show_progress_info\n            and self.reported_progress\n        ):\n            self._write_progress_information_filling_space()\n\n        return result\n\n    def _get_progress_information_message(self) -> str:\n        assert self._session\n        collected = self._session.testscollected\n        if self._show_progress_info == \"count\":\n            if collected:\n                progress = self.reported_progress\n                counter_format = f\"{{:{len(str(collected))}d}}\"\n                format_string = f\" [{counter_format}/{{}}]\"\n                return format_string.format(progress, collected)\n            return f\" [ {collected} / {collected} ]\"\n        if self._show_progress_info == \"times\":\n            if not collected:\n                return \"\"\n            all_reports = (\n                self._get_reports_to_display(\"passed\")\n                + self._get_reports_to_display(\"xpassed\")\n                + self._get_reports_to_display(\"failed\")\n                + self._get_reports_to_display(\"xfailed\")\n                + self._get_reports_to_display(\"skipped\")\n                + self._get_reports_to_display(\"error\")\n                + self._get_reports_to_display(\"\")\n            )\n            current_location = all_reports[-1].location[0]\n            not_reported = [\n                r for r in all_reports if r.nodeid not in self._timing_nodeids_reported\n            ]\n            tests_in_module = sum(\n                i.location[0] == current_location for i in self._session.items\n            )\n            tests_completed = sum(\n                r.when == \"setup\"\n                for r in not_reported\n                if r.location[0] == current_location\n            )\n            last_in_module = tests_completed == tests_in_module\n            if self.showlongtestinfo or last_in_module:\n                self._timing_nodeids_reported.update(r.nodeid for r in not_reported)\n                return format_node_duration(\n                    sum(r.duration for r in not_reported if isinstance(r, TestReport))\n                )\n            return \"\"\n        if collected:\n            return f\" [{self.reported_progress * 100 // collected:3d}%]\"\n        return \" [100%]\"\n\n    def _write_progress_information_if_past_edge(self) -> None:\n        w = self._width_of_current_line\n        if self._show_progress_info == \"count\":\n            assert self._session\n            num_tests = self._session.testscollected\n            progress_length = len(f\" [{num_tests}/{num_tests}]\")\n        elif self._show_progress_info == \"times\":\n            progress_length = len(\" 99h 59m\")\n        else:\n            progress_length = len(\" [100%]\")\n        past_edge = w + progress_length + 1 >= self._screen_width\n        if past_edge:\n            main_color, _ = self._get_main_color()\n            msg = self._get_progress_information_message()\n            self._tw.write(msg + \"\\n\", **{main_color: True})\n\n    def _write_progress_information_filling_space(self) -> None:\n        color, _ = self._get_main_color()\n        msg = self._get_progress_information_message()\n        w = self._width_of_current_line\n        fill = self._tw.fullwidth - w - 1\n        self.write(msg.rjust(fill), flush=True, **{color: True})\n\n    @property\n    def _width_of_current_line(self) -> int:\n        \"\"\"Return the width of the current line.\"\"\"\n        return self._tw.width_of_current_line\n\n    def pytest_collection(self) -> None:\n        if self.isatty():\n            if self.config.option.verbose >= 0:\n                self.write(\"collecting ... \", flush=True, bold=True)\n        elif self.config.option.verbose >= 1:\n            self.write(\"collecting ... \", flush=True, bold=True)\n\n    def pytest_collectreport(self, report: CollectReport) -> None:\n        if report.failed:\n            self._add_stats(\"error\", [report])\n        elif report.skipped:\n            self._add_stats(\"skipped\", [report])\n        items = [x for x in report.result if isinstance(x, Item)]\n        self._numcollected += len(items)\n        if self.isatty():\n            self.report_collect()\n\n    def report_collect(self, final: bool = False) -> None:\n        if self.config.option.verbose < 0:\n            return\n\n        if not final:\n            # Only write the \"collecting\" report every `REPORT_COLLECTING_RESOLUTION`.\n            if (\n                self._collect_report_last_write.elapsed().seconds\n                < REPORT_COLLECTING_RESOLUTION\n            ):\n                return\n            self._collect_report_last_write = timing.Instant()\n\n        errors = len(self.stats.get(\"error\", []))\n        skipped = len(self.stats.get(\"skipped\", []))\n        deselected = len(self.stats.get(\"deselected\", []))\n        selected = self._numcollected - deselected\n        line = \"collected \" if final else \"collecting \"\n        line += (\n            str(self._numcollected) + \" item\" + (\"\" if self._numcollected == 1 else \"s\")\n        )\n        if errors:\n            line += f\" / {errors} error{'s' if errors != 1 else ''}\"\n        if deselected:\n            line += f\" / {deselected} deselected\"\n        if skipped:\n            line += f\" / {skipped} skipped\"\n        if self._numcollected > selected:\n            line += f\" / {selected} selected\"\n        if self.isatty():\n            self.rewrite(line, bold=True, erase=True)\n            if final:\n                self.write(\"\\n\")\n        else:\n            self.write_line(line)\n\n    @hookimpl(trylast=True)\n    def pytest_sessionstart(self, session: Session) -> None:\n        self._session = session\n        self._session_start = timing.Instant()\n        if not self.showheader:\n            return\n        self.write_sep(\"=\", \"test session starts\", bold=True)\n        verinfo = platform.python_version()\n        if not self.no_header:\n            msg = f\"platform {sys.platform} -- Python {verinfo}\"\n            pypy_version_info = getattr(sys, \"pypy_version_info\", None)\n            if pypy_version_info:\n                verinfo = \".\".join(map(str, pypy_version_info[:3]))\n                msg += f\"[pypy-{verinfo}-{pypy_version_info[3]}]\"\n            msg += f\", pytest-{_pytest._version.version}, pluggy-{pluggy.__version__}\"\n            if (\n                self.verbosity > 0\n                or self.config.option.debug\n                or getattr(self.config.option, \"pastebin\", None)\n            ):\n                msg += \" -- \" + str(sys.executable)\n            self.write_line(msg)\n            lines = self.config.hook.pytest_report_header(\n                config=self.config, start_path=self.startpath\n            )\n            self._write_report_lines_from_hooks(lines)\n\n    def _write_report_lines_from_hooks(\n        self, lines: Sequence[str | Sequence[str]]\n    ) -> None:\n        for line_or_lines in reversed(lines):\n            if isinstance(line_or_lines, str):\n                self.write_line(line_or_lines)\n            else:\n                for line in line_or_lines:\n                    self.write_line(line)\n\n    def pytest_report_header(self, config: Config) -> list[str]:\n        result = [f\"rootdir: {config.rootpath}\"]\n\n        if config.inipath:\n            warning = \"\"\n            if config._ignored_config_files:\n                warning = f\" (WARNING: ignoring pytest config in {', '.join(config._ignored_config_files)}!)\"\n            result.append(\n                \"configfile: \" + bestrelpath(config.rootpath, config.inipath) + warning\n            )\n\n        if config.args_source == Config.ArgsSource.TESTPATHS:\n            testpaths: list[str] = config.getini(\"testpaths\")\n            result.append(\"testpaths: {}\".format(\", \".join(testpaths)))\n\n        plugininfo = config.pluginmanager.list_plugin_distinfo()\n        if plugininfo:\n            result.append(\n                \"plugins: {}\".format(\", \".join(_plugin_nameversions(plugininfo)))\n            )\n        return result\n\n    def pytest_collection_finish(self, session: Session) -> None:\n        self.report_collect(True)\n\n        lines = self.config.hook.pytest_report_collectionfinish(\n            config=self.config,\n            start_path=self.startpath,\n            items=session.items,\n        )\n        self._write_report_lines_from_hooks(lines)\n\n        if self.config.getoption(\"collectonly\"):\n            if session.items:\n                if self.config.option.verbose > -1:\n                    self._tw.line(\"\")\n                self._printcollecteditems(session.items)\n\n            failed = self.stats.get(\"failed\")\n            if failed:\n                self._tw.sep(\"!\", \"collection failures\")\n                for rep in failed:\n                    rep.toterminal(self._tw)\n\n    def _printcollecteditems(self, items: Sequence[Item]) -> None:\n        test_cases_verbosity = self.config.get_verbosity(Config.VERBOSITY_TEST_CASES)\n        if test_cases_verbosity < 0:\n            if test_cases_verbosity < -1:\n                counts = Counter(item.nodeid.split(\"::\", 1)[0] for item in items)\n                for name, count in sorted(counts.items()):\n                    self._tw.line(f\"{name}: {count}\")\n            else:\n                for item in items:\n                    self._tw.line(item.nodeid)\n            return\n        stack: list[Node] = []\n        indent = \"\"\n        for item in items:\n            needed_collectors = item.listchain()[1:]  # strip root node\n            while stack:\n                if stack == needed_collectors[: len(stack)]:\n                    break\n                stack.pop()\n            for col in needed_collectors[len(stack) :]:\n                stack.append(col)\n                indent = (len(stack) - 1) * \"  \"\n                self._tw.line(f\"{indent}{col}\")\n                if test_cases_verbosity >= 1:\n                    obj = getattr(col, \"obj\", None)\n                    doc = inspect.getdoc(obj) if obj else None\n                    if doc:\n                        for line in doc.splitlines():\n                            self._tw.line(\"{}{}\".format(indent + \"  \", line))\n\n    @hookimpl(wrapper=True)\n    def pytest_sessionfinish(\n        self, session: Session, exitstatus: int | ExitCode\n    ) -> Generator[None]:\n        result = yield\n        self._tw.line(\"\")\n        summary_exit_codes = (\n            ExitCode.OK,\n            ExitCode.TESTS_FAILED,\n            ExitCode.INTERRUPTED,\n            ExitCode.USAGE_ERROR,\n            ExitCode.NO_TESTS_COLLECTED,\n        )\n        if exitstatus in summary_exit_codes and not self.no_summary:\n            self.config.hook.pytest_terminal_summary(\n                terminalreporter=self, exitstatus=exitstatus, config=self.config\n            )\n        if session.shouldfail:\n            self.write_sep(\"!\", str(session.shouldfail), red=True)\n        if exitstatus == ExitCode.INTERRUPTED:\n            self._report_keyboardinterrupt()\n            self._keyboardinterrupt_memo = None\n        elif session.shouldstop:\n            self.write_sep(\"!\", str(session.shouldstop), red=True)\n        self.summary_stats()\n        return result\n\n    @hookimpl(wrapper=True)\n    def pytest_terminal_summary(self) -> Generator[None]:\n        self.summary_errors()\n        self.summary_failures()\n        self.summary_xfailures()\n        self.summary_warnings()\n        self.summary_passes()\n        self.summary_xpasses()\n        try:\n            return (yield)\n        finally:\n            self.short_test_summary()\n            # Display any extra warnings from teardown here (if any).\n            self.summary_warnings()\n\n    def pytest_keyboard_interrupt(self, excinfo: ExceptionInfo[BaseException]) -> None:\n        self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True)\n\n    def pytest_unconfigure(self) -> None:\n        if self._keyboardinterrupt_memo is not None:\n            self._report_keyboardinterrupt()\n\n    def _report_keyboardinterrupt(self) -> None:\n        excrepr = self._keyboardinterrupt_memo\n        assert excrepr is not None\n        assert excrepr.reprcrash is not None\n        msg = excrepr.reprcrash.message\n        self.write_sep(\"!\", msg)\n        if \"KeyboardInterrupt\" in msg:\n            if self.config.option.fulltrace:\n                excrepr.toterminal(self._tw)\n            else:\n                excrepr.reprcrash.toterminal(self._tw)\n                self._tw.line(\n                    \"(to show a full traceback on KeyboardInterrupt use --full-trace)\",\n                    yellow=True,\n                )\n\n    def _locationline(\n        self, nodeid: str, fspath: str, lineno: int | None, domain: str\n    ) -> str:\n        def mkrel(nodeid: str) -> str:\n            line = self.config.cwd_relative_nodeid(nodeid)\n            if domain and line.endswith(domain):\n                line = line[: -len(domain)]\n                values = domain.split(\"[\")\n                values[0] = values[0].replace(\".\", \"::\")  # don't replace '.' in params\n                line += \"[\".join(values)\n            return line\n\n        # fspath comes from testid which has a \"/\"-normalized path.\n        if fspath:\n            res = mkrel(nodeid)\n            if self.verbosity >= 2 and nodeid.split(\"::\")[0] != nodes.norm_sep(fspath):\n                res += \" <- \" + bestrelpath(self.startpath, Path(fspath))\n        else:\n            res = \"[location]\"\n        return res + \" \"\n\n    def _getfailureheadline(self, rep):\n        head_line = rep.head_line\n        if head_line:\n            return head_line\n        return \"test session\"  # XXX?\n\n    def _getcrashline(self, rep):\n        try:\n            return str(rep.longrepr.reprcrash)\n        except AttributeError:\n            try:\n                return str(rep.longrepr)[:50]\n            except AttributeError:\n                return \"\"\n\n    #\n    # Summaries for sessionfinish.\n    #\n    def getreports(self, name: str):\n        return [x for x in self.stats.get(name, ()) if not hasattr(x, \"_pdbshown\")]\n\n    def summary_warnings(self) -> None:\n        if self.hasopt(\"w\"):\n            all_warnings: list[WarningReport] | None = self.stats.get(\"warnings\")\n            if not all_warnings:\n                return\n\n            final = self._already_displayed_warnings is not None\n            if final:\n                warning_reports = all_warnings[self._already_displayed_warnings :]\n            else:\n                warning_reports = all_warnings\n            self._already_displayed_warnings = len(warning_reports)\n            if not warning_reports:\n                return\n\n            reports_grouped_by_message: dict[str, list[WarningReport]] = {}\n            for wr in warning_reports:\n                reports_grouped_by_message.setdefault(wr.message, []).append(wr)\n\n            def collapsed_location_report(reports: list[WarningReport]) -> str:\n                locations = []\n                for w in reports:\n                    location = w.get_location(self.config)\n                    if location:\n                        locations.append(location)\n\n                if len(locations) < 10:\n                    return \"\\n\".join(map(str, locations))\n\n                counts_by_filename = Counter(\n                    str(loc).split(\"::\", 1)[0] for loc in locations\n                )\n                return \"\\n\".join(\n                    \"{}: {} warning{}\".format(k, v, \"s\" if v > 1 else \"\")\n                    for k, v in counts_by_filename.items()\n                )\n\n            title = \"warnings summary (final)\" if final else \"warnings summary\"\n            self.write_sep(\"=\", title, yellow=True, bold=False)\n            for message, message_reports in reports_grouped_by_message.items():\n                maybe_location = collapsed_location_report(message_reports)\n                if maybe_location:\n                    self._tw.line(maybe_location)\n                    lines = message.splitlines()\n                    indented = \"\\n\".join(\"  \" + x for x in lines)\n                    message = indented.rstrip()\n                else:\n                    message = message.rstrip()\n                self._tw.line(message)\n                self._tw.line()\n            self._tw.line(\n                \"-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html\"\n            )\n\n    def summary_passes(self) -> None:\n        self.summary_passes_combined(\"passed\", \"PASSES\", \"P\")\n\n    def summary_xpasses(self) -> None:\n        self.summary_passes_combined(\"xpassed\", \"XPASSES\", \"X\")\n\n    def summary_passes_combined(\n        self, which_reports: str, sep_title: str, needed_opt: str\n    ) -> None:\n        if self.config.option.tbstyle != \"no\":\n            if self.hasopt(needed_opt):\n                reports: list[TestReport] = self.getreports(which_reports)\n                if not reports:\n                    return\n                self.write_sep(\"=\", sep_title)\n                for rep in reports:\n                    if rep.sections:\n                        msg = self._getfailureheadline(rep)\n                        self.write_sep(\"_\", msg, green=True, bold=True)\n                        self._outrep_summary(rep)\n                    self._handle_teardown_sections(rep.nodeid)\n\n    def _get_teardown_reports(self, nodeid: str) -> list[TestReport]:\n        reports = self.getreports(\"\")\n        return [\n            report\n            for report in reports\n            if report.when == \"teardown\" and report.nodeid == nodeid\n        ]\n\n    def _handle_teardown_sections(self, nodeid: str) -> None:\n        for report in self._get_teardown_reports(nodeid):\n            self.print_teardown_sections(report)\n\n    def print_teardown_sections(self, rep: TestReport) -> None:\n        showcapture = self.config.option.showcapture\n        if showcapture == \"no\":\n            return\n        for secname, content in rep.sections:\n            if showcapture != \"all\" and showcapture not in secname:\n                continue\n            if \"teardown\" in secname:\n                self._tw.sep(\"-\", secname)\n                if content[-1:] == \"\\n\":\n                    content = content[:-1]\n                self._tw.line(content)\n\n    def summary_failures(self) -> None:\n        style = self.config.option.tbstyle\n        self.summary_failures_combined(\"failed\", \"FAILURES\", style=style)\n\n    def summary_xfailures(self) -> None:\n        show_tb = self.config.option.xfail_tb\n        style = self.config.option.tbstyle if show_tb else \"no\"\n        self.summary_failures_combined(\"xfailed\", \"XFAILURES\", style=style)\n\n    def summary_failures_combined(\n        self,\n        which_reports: str,\n        sep_title: str,\n        *,\n        style: str,\n        needed_opt: str | None = None,\n    ) -> None:\n        if style != \"no\":\n            if not needed_opt or self.hasopt(needed_opt):\n                reports: list[BaseReport] = self.getreports(which_reports)\n                if not reports:\n                    return\n                self.write_sep(\"=\", sep_title)\n                if style == \"line\":\n                    for rep in reports:\n                        line = self._getcrashline(rep)\n                        self._outrep_summary(rep)\n                        self.write_line(line)\n                else:\n                    for rep in reports:\n                        msg = self._getfailureheadline(rep)\n                        self.write_sep(\"_\", msg, red=True, bold=True)\n                        self._outrep_summary(rep)\n                        self._handle_teardown_sections(rep.nodeid)\n\n    def summary_errors(self) -> None:\n        if self.config.option.tbstyle != \"no\":\n            reports: list[BaseReport] = self.getreports(\"error\")\n            if not reports:\n                return\n            self.write_sep(\"=\", \"ERRORS\")\n            for rep in self.stats[\"error\"]:\n                msg = self._getfailureheadline(rep)\n                if rep.when == \"collect\":\n                    msg = \"ERROR collecting \" + msg\n                else:\n                    msg = f\"ERROR at {rep.when} of {msg}\"\n                self.write_sep(\"_\", msg, red=True, bold=True)\n                self._outrep_summary(rep)\n\n    def _outrep_summary(self, rep: BaseReport) -> None:\n        rep.toterminal(self._tw)\n        showcapture = self.config.option.showcapture\n        if showcapture == \"no\":\n            return\n        for secname, content in rep.sections:\n            if showcapture != \"all\" and showcapture not in secname:\n                continue\n            self._tw.sep(\"-\", secname)\n            if content[-1:] == \"\\n\":\n                content = content[:-1]\n            self._tw.line(content)\n\n    def summary_stats(self) -> None:\n        if self.verbosity < -1:\n            return\n\n        session_duration = self._session_start.elapsed()\n        (parts, main_color) = self.build_summary_stats_line()\n        line_parts = []\n\n        display_sep = self.verbosity >= 0\n        if display_sep:\n            fullwidth = self._tw.fullwidth\n        for text, markup in parts:\n            with_markup = self._tw.markup(text, **markup)\n            if display_sep:\n                fullwidth += len(with_markup) - len(text)\n            line_parts.append(with_markup)\n        msg = \", \".join(line_parts)\n\n        main_markup = {main_color: True}\n        duration = f\" in {format_session_duration(session_duration.seconds)}\"\n        duration_with_markup = self._tw.markup(duration, **main_markup)\n        if display_sep:\n            fullwidth += len(duration_with_markup) - len(duration)\n        msg += duration_with_markup\n\n        if display_sep:\n            markup_for_end_sep = self._tw.markup(\"\", **main_markup)\n            if markup_for_end_sep.endswith(\"\\x1b[0m\"):\n                markup_for_end_sep = markup_for_end_sep[:-4]\n            fullwidth += len(markup_for_end_sep)\n            msg += markup_for_end_sep\n\n        if display_sep:\n            self.write_sep(\"=\", msg, fullwidth=fullwidth, **main_markup)\n        else:\n            self.write_line(msg, **main_markup)\n\n    def short_test_summary(self) -> None:\n        if not self.reportchars:\n            return\n\n        def show_simple(lines: list[str], *, stat: str) -> None:\n            failed = self.stats.get(stat, [])\n            if not failed:\n                return\n            config = self.config\n            for rep in failed:\n                color = _color_for_type.get(stat, _color_for_type_default)\n                line = _get_line_with_reprcrash_message(\n                    config, rep, self._tw, {color: True}\n                )\n                lines.append(line)\n\n        def show_xfailed(lines: list[str]) -> None:\n            xfailed = self.stats.get(\"xfailed\", [])\n            for rep in xfailed:\n                verbose_word, verbose_markup = rep._get_verbose_word_with_markup(\n                    self.config, {_color_for_type[\"warnings\"]: True}\n                )\n                markup_word = self._tw.markup(verbose_word, **verbose_markup)\n                nodeid = _get_node_id_with_markup(self._tw, self.config, rep)\n                line = f\"{markup_word} {nodeid}\"\n                reason = rep.wasxfail\n                if reason:\n                    line += \" - \" + str(reason)\n\n                lines.append(line)\n\n        def show_xpassed(lines: list[str]) -> None:\n            xpassed = self.stats.get(\"xpassed\", [])\n            for rep in xpassed:\n                verbose_word, verbose_markup = rep._get_verbose_word_with_markup(\n                    self.config, {_color_for_type[\"warnings\"]: True}\n                )\n                markup_word = self._tw.markup(verbose_word, **verbose_markup)\n                nodeid = _get_node_id_with_markup(self._tw, self.config, rep)\n                line = f\"{markup_word} {nodeid}\"\n                reason = rep.wasxfail\n                if reason:\n                    line += \" - \" + str(reason)\n                lines.append(line)\n\n        def show_skipped_folded(lines: list[str]) -> None:\n            skipped: list[CollectReport] = self.stats.get(\"skipped\", [])\n            fskips = _folded_skips(self.startpath, skipped) if skipped else []\n            if not fskips:\n                return\n            verbose_word, verbose_markup = skipped[0]._get_verbose_word_with_markup(\n                self.config, {_color_for_type[\"warnings\"]: True}\n            )\n            markup_word = self._tw.markup(verbose_word, **verbose_markup)\n            prefix = \"Skipped: \"\n            for num, fspath, lineno, reason in fskips:\n                if reason.startswith(prefix):\n                    reason = reason[len(prefix) :]\n                if lineno is not None:\n                    lines.append(f\"{markup_word} [{num}] {fspath}:{lineno}: {reason}\")\n                else:\n                    lines.append(f\"{markup_word} [{num}] {fspath}: {reason}\")\n\n        def show_skipped_unfolded(lines: list[str]) -> None:\n            skipped: list[CollectReport] = self.stats.get(\"skipped\", [])\n\n            for rep in skipped:\n                assert rep.longrepr is not None\n                assert isinstance(rep.longrepr, tuple), (rep, rep.longrepr)\n                assert len(rep.longrepr) == 3, (rep, rep.longrepr)\n\n                verbose_word, verbose_markup = rep._get_verbose_word_with_markup(\n                    self.config, {_color_for_type[\"warnings\"]: True}\n                )\n                markup_word = self._tw.markup(verbose_word, **verbose_markup)\n                nodeid = _get_node_id_with_markup(self._tw, self.config, rep)\n                line = f\"{markup_word} {nodeid}\"\n                reason = rep.longrepr[2]\n                if reason:\n                    line += \" - \" + str(reason)\n                lines.append(line)\n\n        def show_skipped(lines: list[str]) -> None:\n            if self.foldskipped:\n                show_skipped_folded(lines)\n            else:\n                show_skipped_unfolded(lines)\n\n        REPORTCHAR_ACTIONS: Mapping[str, Callable[[list[str]], None]] = {\n            \"x\": show_xfailed,\n            \"X\": show_xpassed,\n            \"f\": partial(show_simple, stat=\"failed\"),\n            \"s\": show_skipped,\n            \"p\": partial(show_simple, stat=\"passed\"),\n            \"E\": partial(show_simple, stat=\"error\"),\n        }\n\n        lines: list[str] = []\n        for char in self.reportchars:\n            action = REPORTCHAR_ACTIONS.get(char)\n            if action:  # skipping e.g. \"P\" (passed with output) here.\n                action(lines)\n\n        if lines:\n            self.write_sep(\"=\", \"short test summary info\", cyan=True, bold=True)\n            for line in lines:\n                self.write_line(line)\n\n    def _get_main_color(self) -> tuple[str, list[str]]:\n        if self._main_color is None or self._known_types is None or self._is_last_item:\n            self._set_main_color()\n            assert self._main_color\n            assert self._known_types\n        return self._main_color, self._known_types\n\n    def _determine_main_color(self, unknown_type_seen: bool) -> str:\n        stats = self.stats\n        if \"failed\" in stats or \"error\" in stats:\n            main_color = \"red\"\n        elif \"warnings\" in stats or \"xpassed\" in stats or unknown_type_seen:\n            main_color = \"yellow\"\n        elif \"passed\" in stats or not self._is_last_item:\n            main_color = \"green\"\n        else:\n            main_color = \"yellow\"\n        return main_color\n\n    def _set_main_color(self) -> None:\n        unknown_types: list[str] = []\n        for found_type in self.stats:\n            if found_type:  # setup/teardown reports have an empty key, ignore them\n                if found_type not in KNOWN_TYPES and found_type not in unknown_types:\n                    unknown_types.append(found_type)\n        self._known_types = list(KNOWN_TYPES) + unknown_types\n        self._main_color = self._determine_main_color(bool(unknown_types))\n\n    def build_summary_stats_line(self) -> tuple[list[tuple[str, dict[str, bool]]], str]:\n        \"\"\"\n        Build the parts used in the last summary stats line.\n\n        The summary stats line is the line shown at the end, \"=== 12 passed, 2 errors in Xs===\".\n\n        This function builds a list of the \"parts\" that make up for the text in that line, in\n        the example above it would be::\n\n            [\n                (\"12 passed\", {\"green\": True}),\n                (\"2 errors\", {\"red\": True}\n            ]\n\n        That last dict for each line is a \"markup dictionary\", used by TerminalWriter to\n        color output.\n\n        The final color of the line is also determined by this function, and is the second\n        element of the returned tuple.\n        \"\"\"\n        if self.config.getoption(\"collectonly\"):\n            return self._build_collect_only_summary_stats_line()\n        else:\n            return self._build_normal_summary_stats_line()\n\n    def _get_reports_to_display(self, key: str) -> list[Any]:\n        \"\"\"Get test/collection reports for the given status key, such as `passed` or `error`.\"\"\"\n        reports = self.stats.get(key, [])\n        return [x for x in reports if getattr(x, \"count_towards_summary\", True)]\n\n    def _build_normal_summary_stats_line(\n        self,\n    ) -> tuple[list[tuple[str, dict[str, bool]]], str]:\n        main_color, known_types = self._get_main_color()\n        parts = []\n\n        for key in known_types:\n            reports = self._get_reports_to_display(key)\n            if reports:\n                count = len(reports)\n                color = _color_for_type.get(key, _color_for_type_default)\n                markup = {color: True, \"bold\": color == main_color}\n                parts.append((\"%d %s\" % pluralize(count, key), markup))  # noqa: UP031\n\n        if not parts:\n            parts = [(\"no tests ran\", {_color_for_type_default: True})]\n\n        return parts, main_color\n\n    def _build_collect_only_summary_stats_line(\n        self,\n    ) -> tuple[list[tuple[str, dict[str, bool]]], str]:\n        deselected = len(self._get_reports_to_display(\"deselected\"))\n        errors = len(self._get_reports_to_display(\"error\"))\n\n        if self._numcollected == 0:\n            parts = [(\"no tests collected\", {\"yellow\": True})]\n            main_color = \"yellow\"\n\n        elif deselected == 0:\n            main_color = \"green\"\n            collected_output = \"%d %s collected\" % pluralize(self._numcollected, \"test\")  # noqa: UP031\n            parts = [(collected_output, {main_color: True})]\n        else:\n            all_tests_were_deselected = self._numcollected == deselected\n            if all_tests_were_deselected:\n                main_color = \"yellow\"\n                collected_output = f\"no tests collected ({deselected} deselected)\"\n            else:\n                main_color = \"green\"\n                selected = self._numcollected - deselected\n                collected_output = f\"{selected}/{self._numcollected} tests collected ({deselected} deselected)\"\n\n            parts = [(collected_output, {main_color: True})]\n\n        if errors:\n            main_color = _color_for_type[\"error\"]\n            parts += [(\"%d %s\" % pluralize(errors, \"error\"), {main_color: True})]  # noqa: UP031\n\n        return parts, main_color\n\n\ndef _get_node_id_with_markup(tw: TerminalWriter, config: Config, rep: BaseReport):\n    nodeid = config.cwd_relative_nodeid(rep.nodeid)\n    path, *parts = nodeid.split(\"::\")\n    if parts:\n        parts_markup = tw.markup(\"::\".join(parts), bold=True)\n        return path + \"::\" + parts_markup\n    else:\n        return path\n\n\ndef _format_trimmed(format: str, msg: str, available_width: int) -> str | None:\n    \"\"\"Format msg into format, ellipsizing it if doesn't fit in available_width.\n\n    Returns None if even the ellipsis can't fit.\n    \"\"\"\n    # Only use the first line.\n    i = msg.find(\"\\n\")\n    if i != -1:\n        msg = msg[:i]\n\n    ellipsis = \"...\"\n    format_width = wcswidth(format.format(\"\"))\n    if format_width + len(ellipsis) > available_width:\n        return None\n\n    if format_width + wcswidth(msg) > available_width:\n        available_width -= len(ellipsis)\n        msg = msg[:available_width]\n        while format_width + wcswidth(msg) > available_width:\n            msg = msg[:-1]\n        msg += ellipsis\n\n    return format.format(msg)\n\n\ndef _get_line_with_reprcrash_message(\n    config: Config, rep: BaseReport, tw: TerminalWriter, word_markup: dict[str, bool]\n) -> str:\n    \"\"\"Get summary line for a report, trying to add reprcrash message.\"\"\"\n    verbose_word, verbose_markup = rep._get_verbose_word_with_markup(\n        config, word_markup\n    )\n    word = tw.markup(verbose_word, **verbose_markup)\n    node = _get_node_id_with_markup(tw, config, rep)\n\n    line = f\"{word} {node}\"\n    line_width = wcswidth(line)\n\n    msg: str | None\n    try:\n        if isinstance(rep.longrepr, str):\n            msg = rep.longrepr\n        else:\n            # Type ignored intentionally -- possible AttributeError expected.\n            msg = rep.longrepr.reprcrash.message  # type: ignore[union-attr]\n    except AttributeError:\n        pass\n    else:\n        if (\n            running_on_ci() or config.option.verbose >= 2\n        ) and not config.option.force_short_summary:\n            msg = f\" - {msg}\"\n        else:\n            available_width = tw.fullwidth - line_width\n            msg = _format_trimmed(\" - {}\", msg, available_width)\n        if msg is not None:\n            line += msg\n\n    return line\n\n\ndef _folded_skips(\n    startpath: Path,\n    skipped: Sequence[CollectReport],\n) -> list[tuple[int, str, int | None, str]]:\n    d: dict[tuple[str, int | None, str], list[CollectReport]] = {}\n    for event in skipped:\n        assert event.longrepr is not None\n        assert isinstance(event.longrepr, tuple), (event, event.longrepr)\n        assert len(event.longrepr) == 3, (event, event.longrepr)\n        fspath, lineno, reason = event.longrepr\n        # For consistency, report all fspaths in relative form.\n        fspath = bestrelpath(startpath, Path(fspath))\n        keywords = getattr(event, \"keywords\", {})\n        # Folding reports with global pytestmark variable.\n        # This is a workaround, because for now we cannot identify the scope of a skip marker\n        # TODO: Revisit after marks scope would be fixed.\n        if (\n            event.when == \"setup\"\n            and \"skip\" in keywords\n            and \"pytestmark\" not in keywords\n        ):\n            key: tuple[str, int | None, str] = (fspath, None, reason)\n        else:\n            key = (fspath, lineno, reason)\n        d.setdefault(key, []).append(event)\n    values: list[tuple[int, str, int | None, str]] = []\n    for key, events in d.items():\n        values.append((len(events), *key))\n    return values\n\n\n_color_for_type = {\n    \"failed\": \"red\",\n    \"error\": \"red\",\n    \"warnings\": \"yellow\",\n    \"passed\": \"green\",\n    \"subtests passed\": \"green\",\n    \"subtests failed\": \"red\",\n}\n_color_for_type_default = \"yellow\"\n\n\ndef pluralize(count: int, noun: str) -> tuple[int, str]:\n    # No need to pluralize words such as `failed` or `passed`.\n    if noun not in [\"error\", \"warnings\", \"test\"]:\n        return count, noun\n\n    # The `warnings` key is plural. To avoid API breakage, we keep it that way but\n    # set it to singular here so we can determine plurality in the same way as we do\n    # for `error`.\n    noun = noun.replace(\"warnings\", \"warning\")\n\n    return count, noun + \"s\" if count != 1 else noun\n\n\ndef _plugin_nameversions(plugininfo) -> list[str]:\n    values: list[str] = []\n    for plugin, dist in plugininfo:\n        # Gets us name and version!\n        name = f\"{dist.project_name}-{dist.version}\"\n        # Questionable convenience, but it keeps things short.\n        if name.startswith(\"pytest-\"):\n            name = name[7:]\n        # We decided to print python package names they can have more than one plugin.\n        if name not in values:\n            values.append(name)\n    return values\n\n\ndef format_session_duration(seconds: float) -> str:\n    \"\"\"Format the given seconds in a human readable manner to show in the final summary.\"\"\"\n    if seconds < 60:\n        return f\"{seconds:.2f}s\"\n    else:\n        dt = datetime.timedelta(seconds=int(seconds))\n        return f\"{seconds:.2f}s ({dt})\"\n\n\ndef format_node_duration(seconds: float) -> str:\n    \"\"\"Format the given seconds in a human readable manner to show in the test progress.\"\"\"\n    # The formatting is designed to be compact and readable, with at most 7 characters\n    # for durations below 100 hours.\n    if seconds < 0.00001:\n        return f\" {seconds * 1000000:.3f}us\"\n    if seconds < 0.0001:\n        return f\" {seconds * 1000000:.2f}us\"\n    if seconds < 0.001:\n        return f\" {seconds * 1000000:.1f}us\"\n    if seconds < 0.01:\n        return f\" {seconds * 1000:.3f}ms\"\n    if seconds < 0.1:\n        return f\" {seconds * 1000:.2f}ms\"\n    if seconds < 1:\n        return f\" {seconds * 1000:.1f}ms\"\n    if seconds < 60:\n        return f\" {seconds:.3f}s\"\n    if seconds < 3600:\n        return f\" {seconds // 60:.0f}m {seconds % 60:.0f}s\"\n    return f\" {seconds // 3600:.0f}h {(seconds % 3600) // 60:.0f}m\"\n\n\ndef _get_raw_skip_reason(report: TestReport) -> str:\n    \"\"\"Get the reason string of a skip/xfail/xpass test report.\n\n    The string is just the part given by the user.\n    \"\"\"\n    if hasattr(report, \"wasxfail\"):\n        reason = report.wasxfail\n        if reason.startswith(\"reason: \"):\n            reason = reason[len(\"reason: \") :]\n        return reason\n    else:\n        assert report.skipped\n        assert isinstance(report.longrepr, tuple)\n        _, _, reason = report.longrepr\n        if reason.startswith(\"Skipped: \"):\n            reason = reason[len(\"Skipped: \") :]\n        elif reason == \"Skipped\":\n            reason = \"\"\n        return reason\n\n\nclass TerminalProgressPlugin:\n    \"\"\"Terminal progress reporting plugin using OSC 9;4 ANSI sequences.\n\n    Emits OSC 9;4 sequences to indicate test progress to terminal\n    tabs/windows/etc.\n\n    Not all terminal emulators support this feature.\n\n    Ref: https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC\n    \"\"\"\n\n    def __init__(self, tr: TerminalReporter) -> None:\n        self._tr = tr\n        self._session: Session | None = None\n        self._has_failures = False\n\n    def _emit_progress(\n        self,\n        state: Literal[\"remove\", \"normal\", \"error\", \"indeterminate\", \"paused\"],\n        progress: int | None = None,\n    ) -> None:\n        \"\"\"Emit OSC 9;4 sequence for indicating progress to the terminal.\n\n        :param state:\n            Progress state to set.\n        :param progress:\n            Progress value 0-100. Required for \"normal\", optional for \"error\"\n            and \"paused\", otherwise ignored.\n        \"\"\"\n        assert progress is None or 0 <= progress <= 100\n\n        # OSC 9;4 sequence: ESC ] 9 ; 4 ; state ; progress ST\n        # ST can be ESC \\ or BEL. ESC \\ seems better supported.\n        match state:\n            case \"remove\":\n                sequence = \"\\x1b]9;4;0;\\x1b\\\\\"\n            case \"normal\":\n                assert progress is not None\n                sequence = f\"\\x1b]9;4;1;{progress}\\x1b\\\\\"\n            case \"error\":\n                if progress is not None:\n                    sequence = f\"\\x1b]9;4;2;{progress}\\x1b\\\\\"\n                else:\n                    sequence = \"\\x1b]9;4;2;\\x1b\\\\\"\n            case \"indeterminate\":\n                sequence = \"\\x1b]9;4;3;\\x1b\\\\\"\n            case \"paused\":\n                if progress is not None:\n                    sequence = f\"\\x1b]9;4;4;{progress}\\x1b\\\\\"\n                else:\n                    sequence = \"\\x1b]9;4;4;\\x1b\\\\\"\n\n        self._tr.write_raw(sequence, flush=True)\n\n    @hookimpl\n    def pytest_sessionstart(self, session: Session) -> None:\n        self._session = session\n        # Show indeterminate progress during collection.\n        self._emit_progress(\"indeterminate\")\n\n    @hookimpl\n    def pytest_collection_finish(self) -> None:\n        assert self._session is not None\n        if self._session.testscollected > 0:\n            # Switch from indeterminate to 0% progress.\n            self._emit_progress(\"normal\", 0)\n\n    @hookimpl\n    def pytest_runtest_logreport(self, report: TestReport) -> None:\n        if report.failed:\n            self._has_failures = True\n\n        # Let's consider the \"call\" phase for progress.\n        if report.when != \"call\":\n            return\n\n        # Calculate and emit progress.\n        assert self._session is not None\n        collected = self._session.testscollected\n        if collected > 0:\n            reported = self._tr.reported_progress\n            progress = min(reported * 100 // collected, 100)\n            self._emit_progress(\"error\" if self._has_failures else \"normal\", progress)\n\n    @hookimpl\n    def pytest_sessionfinish(self) -> None:\n        self._emit_progress(\"remove\")\n"
  },
  {
    "path": "src/_pytest/terminalprogress.py",
    "content": "# A plugin to register the TerminalProgressPlugin plugin.\n#\n# This plugin is not loaded by default due to compatibility issues (#13896),\n# but can be enabled in one of these ways:\n# - The terminal plugin enables it in a few cases where it's safe, and not\n#   blocked by the user (using e.g. `-p no:terminalprogress`).\n# - The user explicitly requests it, e.g. using `-p terminalprogress`.\n#\n# In a few years, if it's safe, we can consider enabling it by default. Then,\n# this file will become unnecessary and can be inlined into terminal.py.\n\nfrom __future__ import annotations\n\nimport os\n\nfrom _pytest.config import Config\nfrom _pytest.config import hookimpl\nfrom _pytest.terminal import TerminalProgressPlugin\nfrom _pytest.terminal import TerminalReporter\n\n\n@hookimpl(trylast=True)\ndef pytest_configure(config: Config) -> None:\n    reporter: TerminalReporter | None = config.pluginmanager.get_plugin(\n        \"terminalreporter\"\n    )\n\n    if reporter is not None and reporter.isatty() and os.environ.get(\"TERM\") != \"dumb\":\n        plugin = TerminalProgressPlugin(reporter)\n        config.pluginmanager.register(plugin, name=\"terminalprogress-plugin\")\n"
  },
  {
    "path": "src/_pytest/threadexception.py",
    "content": "from __future__ import annotations\n\nimport collections\nfrom collections.abc import Callable\nimport functools\nimport sys\nimport threading\nimport traceback\nfrom typing import NamedTuple\nfrom typing import TYPE_CHECKING\nimport warnings\n\nfrom _pytest.config import Config\nfrom _pytest.nodes import Item\nfrom _pytest.stash import StashKey\nfrom _pytest.tracemalloc import tracemalloc_message\nimport pytest\n\n\nif TYPE_CHECKING:\n    pass\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import ExceptionGroup\n\n\nclass ThreadExceptionMeta(NamedTuple):\n    msg: str\n    cause_msg: str\n    exc_value: BaseException | None\n\n\nthread_exceptions: StashKey[collections.deque[ThreadExceptionMeta | BaseException]] = (\n    StashKey()\n)\n\n\ndef collect_thread_exception(config: Config) -> None:\n    pop_thread_exception = config.stash[thread_exceptions].pop\n    errors: list[pytest.PytestUnhandledThreadExceptionWarning | RuntimeError] = []\n    meta = None\n    hook_error = None\n    try:\n        while True:\n            try:\n                meta = pop_thread_exception()\n            except IndexError:\n                break\n\n            if isinstance(meta, BaseException):\n                hook_error = RuntimeError(\"Failed to process thread exception\")\n                hook_error.__cause__ = meta\n                errors.append(hook_error)\n                continue\n\n            msg = meta.msg\n            try:\n                warnings.warn(pytest.PytestUnhandledThreadExceptionWarning(msg))\n            except pytest.PytestUnhandledThreadExceptionWarning as e:\n                # This except happens when the warning is treated as an error (e.g. `-Werror`).\n                if meta.exc_value is not None:\n                    # Exceptions have a better way to show the traceback, but\n                    # warnings do not, so hide the traceback from the msg and\n                    # set the cause so the traceback shows up in the right place.\n                    e.args = (meta.cause_msg,)\n                    e.__cause__ = meta.exc_value\n                errors.append(e)\n\n        if len(errors) == 1:\n            raise errors[0]\n        if errors:\n            raise ExceptionGroup(\"multiple thread exception warnings\", errors)\n    finally:\n        del errors, meta, hook_error\n\n\ndef cleanup(\n    *, config: Config, prev_hook: Callable[[threading.ExceptHookArgs], object]\n) -> None:\n    try:\n        try:\n            # We don't join threads here, so exceptions raised from any\n            # threads still running by the time _threading_atexits joins them\n            # do not get captured (see #13027).\n            collect_thread_exception(config)\n        finally:\n            threading.excepthook = prev_hook\n    finally:\n        del config.stash[thread_exceptions]\n\n\ndef thread_exception_hook(\n    args: threading.ExceptHookArgs,\n    /,\n    *,\n    append: Callable[[ThreadExceptionMeta | BaseException], object],\n) -> None:\n    try:\n        # we need to compute these strings here as they might change after\n        # the excepthook finishes and before the metadata object is\n        # collected by a pytest hook\n        thread_name = \"<unknown>\" if args.thread is None else args.thread.name\n        summary = f\"Exception in thread {thread_name}\"\n        traceback_message = \"\\n\\n\" + \"\".join(\n            traceback.format_exception(\n                args.exc_type,\n                args.exc_value,\n                args.exc_traceback,\n            )\n        )\n        tracemalloc_tb = \"\\n\" + tracemalloc_message(args.thread)\n        msg = summary + traceback_message + tracemalloc_tb\n        cause_msg = summary + tracemalloc_tb\n\n        append(\n            ThreadExceptionMeta(\n                # Compute these strings here as they might change later\n                msg=msg,\n                cause_msg=cause_msg,\n                exc_value=args.exc_value,\n            )\n        )\n    except BaseException as e:\n        append(e)\n        # Raising this will cause the exception to be logged twice, once in our\n        # collect_thread_exception and once by sys.excepthook\n        # which is fine - this should never happen anyway and if it does\n        # it should probably be reported as a pytest bug.\n        raise\n\n\ndef pytest_configure(config: Config) -> None:\n    prev_hook = threading.excepthook\n    deque: collections.deque[ThreadExceptionMeta | BaseException] = collections.deque()\n    config.stash[thread_exceptions] = deque\n    config.add_cleanup(functools.partial(cleanup, config=config, prev_hook=prev_hook))\n    threading.excepthook = functools.partial(thread_exception_hook, append=deque.append)\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_runtest_setup(item: Item) -> None:\n    collect_thread_exception(item.config)\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_runtest_call(item: Item) -> None:\n    collect_thread_exception(item.config)\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_runtest_teardown(item: Item) -> None:\n    collect_thread_exception(item.config)\n"
  },
  {
    "path": "src/_pytest/timing.py",
    "content": "\"\"\"Indirection for time functions.\n\nWe intentionally grab some \"time\" functions internally to avoid tests mocking \"time\" to affect\npytest runtime information (issue #185).\n\nFixture \"mock_timing\" also interacts with this module for pytest's own tests.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport dataclasses\nfrom datetime import datetime\nfrom datetime import timezone\nfrom time import perf_counter\nfrom time import sleep\nfrom time import time\nfrom typing import TYPE_CHECKING\n\n\nif TYPE_CHECKING:\n    from pytest import MonkeyPatch\n\n\n@dataclasses.dataclass(frozen=True)\nclass Instant:\n    \"\"\"\n    Represents an instant in time, used to both get the timestamp value and to measure\n    the duration of a time span.\n\n    Inspired by Rust's `std::time::Instant`.\n    \"\"\"\n\n    # Creation time of this instant, using time.time(), to measure actual time.\n    # Note: using a `lambda` to correctly get the mocked time via `MockTiming`.\n    time: float = dataclasses.field(default_factory=lambda: time(), init=False)\n\n    # Performance counter tick of the instant, used to measure precise elapsed time.\n    # Note: using a `lambda` to correctly get the mocked time via `MockTiming`.\n    perf_count: float = dataclasses.field(\n        default_factory=lambda: perf_counter(), init=False\n    )\n\n    def elapsed(self) -> Duration:\n        \"\"\"Measure the duration since `Instant` was created.\"\"\"\n        return Duration(start=self, stop=Instant())\n\n    def as_utc(self) -> datetime:\n        \"\"\"Instant as UTC datetime.\"\"\"\n        return datetime.fromtimestamp(self.time, timezone.utc)\n\n\n@dataclasses.dataclass(frozen=True)\nclass Duration:\n    \"\"\"A span of time as measured by `Instant.elapsed()`.\"\"\"\n\n    start: Instant\n    stop: Instant\n\n    @property\n    def seconds(self) -> float:\n        \"\"\"Elapsed time of the duration in seconds, measured using a performance counter for precise timing.\"\"\"\n        return self.stop.perf_count - self.start.perf_count\n\n\n@dataclasses.dataclass\nclass MockTiming:\n    \"\"\"Mocks _pytest.timing with a known object that can be used to control timing in tests\n    deterministically.\n\n    pytest itself should always use functions from `_pytest.timing` instead of `time` directly.\n\n    This then allows us more control over time during testing, if testing code also\n    uses `_pytest.timing` functions.\n\n    Time is static, and only advances through `sleep` calls, thus tests might sleep over large\n    numbers and obtain accurate time() calls at the end, making tests reliable and instant.\"\"\"\n\n    _current_time: float = datetime(2020, 5, 22, 14, 20, 50).timestamp()\n\n    def sleep(self, seconds: float) -> None:\n        self._current_time += seconds\n\n    def time(self) -> float:\n        return self._current_time\n\n    def patch(self, monkeypatch: MonkeyPatch) -> None:\n        # pylint: disable-next=import-self\n        from _pytest import timing  # noqa: PLW0406\n\n        monkeypatch.setattr(timing, \"sleep\", self.sleep)\n        monkeypatch.setattr(timing, \"time\", self.time)\n        monkeypatch.setattr(timing, \"perf_counter\", self.time)\n\n\n__all__ = [\"perf_counter\", \"sleep\", \"time\"]\n"
  },
  {
    "path": "src/_pytest/tmpdir.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Support for providing temporary directories to test functions.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nimport dataclasses\nimport os\nfrom pathlib import Path\nimport re\nfrom shutil import rmtree\nimport tempfile\nfrom typing import Any\nfrom typing import final\nfrom typing import Literal\n\nfrom .pathlib import cleanup_dead_symlinks\nfrom .pathlib import LOCK_TIMEOUT\nfrom .pathlib import make_numbered_dir\nfrom .pathlib import make_numbered_dir_with_cleanup\nfrom .pathlib import rm_rf\nfrom _pytest.compat import get_user_id\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.config import hookimpl\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.deprecated import check_ispytest\nfrom _pytest.fixtures import fixture\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.nodes import Item\nfrom _pytest.reports import TestReport\nfrom _pytest.stash import StashKey\n\n\ntmppath_result_key = StashKey[dict[str, bool]]()\nRetentionType = Literal[\"all\", \"failed\", \"none\"]\n\n\n@final\n@dataclasses.dataclass\nclass TempPathFactory:\n    \"\"\"Factory for temporary directories under the common base temp directory,\n    as discussed at :ref:`temporary directory location and retention`.\n    \"\"\"\n\n    _given_basetemp: Path | None\n    # pluggy TagTracerSub, not currently exposed, so Any.\n    _trace: Any\n    _basetemp: Path | None\n    _retention_count: int\n    _retention_policy: RetentionType\n\n    def __init__(\n        self,\n        given_basetemp: Path | None,\n        retention_count: int,\n        retention_policy: RetentionType,\n        trace,\n        basetemp: Path | None = None,\n        *,\n        _ispytest: bool = False,\n    ) -> None:\n        check_ispytest(_ispytest)\n        if given_basetemp is None:\n            self._given_basetemp = None\n        else:\n            # Use os.path.abspath() to get absolute path instead of resolve() as it\n            # does not work the same in all platforms (see #4427).\n            # Path.absolute() exists, but it is not public (see https://bugs.python.org/issue25012).\n            self._given_basetemp = Path(os.path.abspath(str(given_basetemp)))\n        self._trace = trace\n        self._retention_count = retention_count\n        self._retention_policy = retention_policy\n        self._basetemp = basetemp\n\n    @classmethod\n    def from_config(\n        cls,\n        config: Config,\n        *,\n        _ispytest: bool = False,\n    ) -> TempPathFactory:\n        \"\"\"Create a factory according to pytest configuration.\n\n        :meta private:\n        \"\"\"\n        check_ispytest(_ispytest)\n        count = int(config.getini(\"tmp_path_retention_count\"))\n        if count < 0:\n            raise ValueError(\n                f\"tmp_path_retention_count must be >= 0. Current input: {count}.\"\n            )\n\n        policy = config.getini(\"tmp_path_retention_policy\")\n        if policy not in (\"all\", \"failed\", \"none\"):\n            raise ValueError(\n                f\"tmp_path_retention_policy must be either all, failed, none. Current input: {policy}.\"\n            )\n\n        return cls(\n            given_basetemp=config.option.basetemp,\n            trace=config.trace.get(\"tmpdir\"),\n            retention_count=count,\n            retention_policy=policy,\n            _ispytest=True,\n        )\n\n    def _ensure_relative_to_basetemp(self, basename: str) -> str:\n        basename = os.path.normpath(basename)\n        if (self.getbasetemp() / basename).resolve().parent != self.getbasetemp():\n            raise ValueError(f\"{basename} is not a normalized and relative path\")\n        return basename\n\n    def mktemp(self, basename: str, numbered: bool = True) -> Path:\n        \"\"\"Create a new temporary directory managed by the factory.\n\n        :param basename:\n            Directory base name, must be a relative path.\n\n        :param numbered:\n            If ``True``, ensure the directory is unique by adding a numbered\n            suffix greater than any existing one: ``basename=\"foo-\"`` and ``numbered=True``\n            means that this function will create directories named ``\"foo-0\"``,\n            ``\"foo-1\"``, ``\"foo-2\"`` and so on.\n\n        :returns:\n            The path to the new directory.\n        \"\"\"\n        basename = self._ensure_relative_to_basetemp(basename)\n        if not numbered:\n            p = self.getbasetemp().joinpath(basename)\n            p.mkdir(mode=0o700)\n        else:\n            p = make_numbered_dir(root=self.getbasetemp(), prefix=basename, mode=0o700)\n            self._trace(\"mktemp\", p)\n        return p\n\n    def getbasetemp(self) -> Path:\n        \"\"\"Return the base temporary directory, creating it if needed.\n\n        :returns:\n            The base temporary directory.\n        \"\"\"\n        if self._basetemp is not None:\n            return self._basetemp\n\n        if self._given_basetemp is not None:\n            basetemp = self._given_basetemp\n            if basetemp.exists():\n                rm_rf(basetemp)\n            basetemp.mkdir(mode=0o700)\n            basetemp = basetemp.resolve()\n        else:\n            from_env = os.environ.get(\"PYTEST_DEBUG_TEMPROOT\")\n            temproot = Path(from_env or tempfile.gettempdir()).resolve()\n            user = get_user() or \"unknown\"\n            # use a sub-directory in the temproot to speed-up\n            # make_numbered_dir() call\n            rootdir = temproot.joinpath(f\"pytest-of-{user}\")\n            try:\n                rootdir.mkdir(mode=0o700, exist_ok=True)\n            except OSError:\n                # getuser() likely returned illegal characters for the platform, use unknown back off mechanism\n                rootdir = temproot.joinpath(\"pytest-of-unknown\")\n                rootdir.mkdir(mode=0o700, exist_ok=True)\n            # Because we use exist_ok=True with a predictable name, make sure\n            # we are the owners, to prevent any funny business (on unix, where\n            # temproot is usually shared).\n            # Also, to keep things private, fixup any world-readable temp\n            # rootdir's permissions. Historically 0o755 was used, so we can't\n            # just error out on this, at least for a while.\n            uid = get_user_id()\n            if uid is not None:\n                rootdir_stat = rootdir.stat()\n                if rootdir_stat.st_uid != uid:\n                    raise OSError(\n                        f\"The temporary directory {rootdir} is not owned by the current user. \"\n                        \"Fix this and try again.\"\n                    )\n                if (rootdir_stat.st_mode & 0o077) != 0:\n                    os.chmod(rootdir, rootdir_stat.st_mode & ~0o077)\n            keep = self._retention_count\n            if self._retention_policy == \"none\":\n                keep = 0\n            basetemp = make_numbered_dir_with_cleanup(\n                prefix=\"pytest-\",\n                root=rootdir,\n                keep=keep,\n                lock_timeout=LOCK_TIMEOUT,\n                mode=0o700,\n            )\n        assert basetemp is not None, basetemp\n        self._basetemp = basetemp\n        self._trace(\"new basetemp\", basetemp)\n        return basetemp\n\n\ndef get_user() -> str | None:\n    \"\"\"Return the current user name, or None if getuser() does not work\n    in the current environment (see #1010).\"\"\"\n    try:\n        # In some exotic environments, getpass may not be importable.\n        import getpass\n\n        return getpass.getuser()\n    except (ImportError, OSError, KeyError):\n        return None\n\n\ndef pytest_configure(config: Config) -> None:\n    \"\"\"Create a TempPathFactory and attach it to the config object.\n\n    This is to comply with existing plugins which expect the handler to be\n    available at pytest_configure time, but ideally should be moved entirely\n    to the tmp_path_factory session fixture.\n    \"\"\"\n    mp = MonkeyPatch()\n    config.add_cleanup(mp.undo)\n    _tmp_path_factory = TempPathFactory.from_config(config, _ispytest=True)\n    mp.setattr(config, \"_tmp_path_factory\", _tmp_path_factory, raising=False)\n\n\ndef pytest_addoption(parser: Parser) -> None:\n    parser.addini(\n        \"tmp_path_retention_count\",\n        help=\"How many sessions should we keep the `tmp_path` directories, according to `tmp_path_retention_policy`.\",\n        default=\"3\",\n        # NOTE: Would have been better as an `int` but can't change it now.\n        type=\"string\",\n    )\n\n    parser.addini(\n        \"tmp_path_retention_policy\",\n        help=\"Controls which directories created by the `tmp_path` fixture are kept around, based on test outcome. \"\n        \"(all/failed/none)\",\n        type=\"string\",\n        default=\"all\",\n    )\n\n\n@fixture(scope=\"session\")\ndef tmp_path_factory(request: FixtureRequest) -> TempPathFactory:\n    \"\"\"Return a :class:`pytest.TempPathFactory` instance for the test session.\"\"\"\n    # Set dynamically by pytest_configure() above.\n    return request.config._tmp_path_factory  # type: ignore\n\n\ndef _mk_tmp(request: FixtureRequest, factory: TempPathFactory) -> Path:\n    name = request.node.name\n    name = re.sub(r\"[\\W]\", \"_\", name)\n    MAXVAL = 30\n    name = name[:MAXVAL]\n    return factory.mktemp(name, numbered=True)\n\n\n@fixture\ndef tmp_path(\n    request: FixtureRequest, tmp_path_factory: TempPathFactory\n) -> Generator[Path]:\n    \"\"\"Return a temporary directory (as :class:`pathlib.Path` object)\n    which is unique to each test function invocation.\n    The temporary directory is created as a subdirectory\n    of the base temporary directory, with configurable retention,\n    as discussed in :ref:`temporary directory location and retention`.\n    \"\"\"\n    path = _mk_tmp(request, tmp_path_factory)\n    yield path\n\n    # Remove the tmpdir if the policy is \"failed\" and the test passed.\n    policy = tmp_path_factory._retention_policy\n    result_dict = request.node.stash[tmppath_result_key]\n\n    if policy == \"failed\" and result_dict.get(\"call\", True):\n        # We do a \"best effort\" to remove files, but it might not be possible due to some leaked resource,\n        # permissions, etc, in which case we ignore it.\n        rmtree(path, ignore_errors=True)\n\n    del request.node.stash[tmppath_result_key]\n\n\ndef pytest_sessionfinish(session, exitstatus: int | ExitCode):\n    \"\"\"After each session, remove base directory if all the tests passed,\n    the policy is \"failed\", and the basetemp is not specified by a user.\n    \"\"\"\n    tmp_path_factory: TempPathFactory = session.config._tmp_path_factory\n    basetemp = tmp_path_factory._basetemp\n    if basetemp is None:\n        return\n\n    policy = tmp_path_factory._retention_policy\n    if (\n        exitstatus == 0\n        and policy == \"failed\"\n        and tmp_path_factory._given_basetemp is None\n    ):\n        if basetemp.is_dir():\n            # We do a \"best effort\" to remove files, but it might not be possible due to some leaked resource,\n            # permissions, etc, in which case we ignore it.\n            rmtree(basetemp, ignore_errors=True)\n\n    # Remove dead symlinks.\n    if basetemp.is_dir():\n        cleanup_dead_symlinks(basetemp)\n\n\n@hookimpl(wrapper=True, tryfirst=True)\ndef pytest_runtest_makereport(\n    item: Item, call\n) -> Generator[None, TestReport, TestReport]:\n    rep = yield\n    assert rep.when is not None\n    empty: dict[str, bool] = {}\n    item.stash.setdefault(tmppath_result_key, empty)[rep.when] = rep.passed\n    return rep\n"
  },
  {
    "path": "src/_pytest/tracemalloc.py",
    "content": "from __future__ import annotations\n\n\ndef tracemalloc_message(source: object) -> str:\n    if source is None:\n        return \"\"\n\n    try:\n        import tracemalloc\n    except ImportError:\n        return \"\"\n\n    tb = tracemalloc.get_object_traceback(source)\n    if tb is not None:\n        formatted_tb = \"\\n\".join(tb.format())\n        # Use a leading new line to better separate the (large) output\n        # from the traceback to the previous warning text.\n        return f\"\\nObject allocated at:\\n{formatted_tb}\"\n    # No need for a leading new line.\n    url = \"https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings\"\n    return (\n        \"Enable tracemalloc to get traceback where the object was allocated.\\n\"\n        f\"See {url} for more info.\"\n    )\n"
  },
  {
    "path": "src/_pytest/unittest.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Discover and run std-library \"unittest\" style tests.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom collections.abc import Generator\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\nfrom enum import auto\nfrom enum import Enum\nimport inspect\nimport sys\nimport traceback\nimport types\nfrom typing import Any\nfrom typing import TYPE_CHECKING\nfrom unittest import TestCase\n\nimport _pytest._code\nfrom _pytest._code import ExceptionInfo\nfrom _pytest.compat import assert_never\nfrom _pytest.compat import is_async_function\nfrom _pytest.config import hookimpl\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import Item\nfrom _pytest.outcomes import exit\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import skip\nfrom _pytest.outcomes import xfail\nfrom _pytest.python import Class\nfrom _pytest.python import Function\nfrom _pytest.python import Module\nfrom _pytest.runner import CallInfo\nfrom _pytest.runner import check_interactive_exception\nfrom _pytest.subtests import SubtestContext\nfrom _pytest.subtests import SubtestReport\n\n\nif sys.version_info[:2] < (3, 11):\n    from exceptiongroup import ExceptionGroup\n\nif TYPE_CHECKING:\n    from types import TracebackType\n    import unittest\n\n    import twisted.trial.unittest\n\n\n_SysExcInfoType = (\n    tuple[type[BaseException], BaseException, types.TracebackType]\n    | tuple[None, None, None]\n)\n\n\ndef pytest_pycollect_makeitem(\n    collector: Module | Class, name: str, obj: object\n) -> UnitTestCase | None:\n    try:\n        # Has unittest been imported?\n        ut = sys.modules[\"unittest\"]\n        # Is obj a subclass of unittest.TestCase?\n        # Type ignored because `ut` is an opaque module.\n        if not issubclass(obj, ut.TestCase):  # type: ignore\n            return None\n    except Exception:\n        return None\n    # Is obj a concrete class?\n    # Abstract classes can't be instantiated so no point collecting them.\n    if inspect.isabstract(obj):\n        return None\n    # Yes, so let's collect it.\n    return UnitTestCase.from_parent(collector, name=name, obj=obj)\n\n\nclass UnitTestCase(Class):\n    # Marker for fixturemanger.getfixtureinfo()\n    # to declare that our children do not support funcargs.\n    nofuncargs = True\n\n    def newinstance(self):\n        # TestCase __init__ takes the method (test) name. The TestCase\n        # constructor treats the name \"runTest\" as a special no-op, so it can be\n        # used when a dummy instance is needed. While unittest.TestCase has a\n        # default, some subclasses omit the default (#9610), so always supply\n        # it.\n        return self.obj(\"runTest\")\n\n    def collect(self) -> Iterable[Item | Collector]:\n        from unittest import TestLoader\n\n        cls = self.obj\n        if not getattr(cls, \"__test__\", True):\n            return\n\n        skipped = _is_skipped(cls)\n        if not skipped:\n            self._register_unittest_setup_method_fixture(cls)\n            self._register_unittest_setup_class_fixture(cls)\n            self._register_setup_class_fixture()\n\n        self.session._fixturemanager.parsefactories(self.newinstance(), self.nodeid)\n\n        loader = TestLoader()\n        foundsomething = False\n        for name in loader.getTestCaseNames(self.obj):\n            x = getattr(self.obj, name)\n            if not getattr(x, \"__test__\", True):\n                continue\n            yield TestCaseFunction.from_parent(self, name=name)\n            foundsomething = True\n\n        if not foundsomething:\n            runtest = getattr(self.obj, \"runTest\", None)\n            if runtest is not None:\n                ut = sys.modules.get(\"twisted.trial.unittest\", None)\n                if ut is None or runtest != ut.TestCase.runTest:\n                    yield TestCaseFunction.from_parent(self, name=\"runTest\")\n\n    def _register_unittest_setup_class_fixture(self, cls: type) -> None:\n        \"\"\"Register an auto-use fixture to invoke setUpClass and\n        tearDownClass (#517).\"\"\"\n        setup = getattr(cls, \"setUpClass\", None)\n        teardown = getattr(cls, \"tearDownClass\", None)\n        if setup is None and teardown is None:\n            return None\n        cleanup = getattr(cls, \"doClassCleanups\", lambda: None)\n\n        def process_teardown_exceptions() -> None:\n            # tearDown_exceptions is a list set in the class containing exc_infos for errors during\n            # teardown for the class.\n            exc_infos = getattr(cls, \"tearDown_exceptions\", None)\n            if not exc_infos:\n                return\n            exceptions = [exc for (_, exc, _) in exc_infos]\n            # If a single exception, raise it directly as this provides a more readable\n            # error (hopefully this will improve in #12255).\n            if len(exceptions) == 1:\n                raise exceptions[0]\n            else:\n                raise ExceptionGroup(\"Unittest class cleanup errors\", exceptions)\n\n        def unittest_setup_class_fixture(\n            request: FixtureRequest,\n        ) -> Generator[None]:\n            cls = request.cls\n            if _is_skipped(cls):\n                reason = cls.__unittest_skip_why__\n                raise skip.Exception(reason, _use_item_location=True)\n            if setup is not None:\n                try:\n                    setup()\n                # unittest does not call the cleanup function for every BaseException, so we\n                # follow this here.\n                except Exception:\n                    cleanup()\n                    process_teardown_exceptions()\n                    raise\n            yield\n            try:\n                if teardown is not None:\n                    teardown()\n            finally:\n                cleanup()\n                process_teardown_exceptions()\n\n        self.session._fixturemanager._register_fixture(\n            # Use a unique name to speed up lookup.\n            name=f\"_unittest_setUpClass_fixture_{cls.__qualname__}\",\n            func=unittest_setup_class_fixture,\n            nodeid=self.nodeid,\n            scope=\"class\",\n            autouse=True,\n        )\n\n    def _register_unittest_setup_method_fixture(self, cls: type) -> None:\n        \"\"\"Register an auto-use fixture to invoke setup_method and\n        teardown_method (#517).\"\"\"\n        setup = getattr(cls, \"setup_method\", None)\n        teardown = getattr(cls, \"teardown_method\", None)\n        if setup is None and teardown is None:\n            return None\n\n        def unittest_setup_method_fixture(\n            request: FixtureRequest,\n        ) -> Generator[None]:\n            self = request.instance\n            if _is_skipped(self):\n                reason = self.__unittest_skip_why__\n                raise skip.Exception(reason, _use_item_location=True)\n            if setup is not None:\n                setup(self, request.function)\n            yield\n            if teardown is not None:\n                teardown(self, request.function)\n\n        self.session._fixturemanager._register_fixture(\n            # Use a unique name to speed up lookup.\n            name=f\"_unittest_setup_method_fixture_{cls.__qualname__}\",\n            func=unittest_setup_method_fixture,\n            nodeid=self.nodeid,\n            scope=\"function\",\n            autouse=True,\n        )\n\n\nclass TestCaseFunction(Function):\n    nofuncargs = True\n    failfast = False\n    _excinfo: list[_pytest._code.ExceptionInfo[BaseException]] | None = None\n\n    def _getinstance(self):\n        assert isinstance(self.parent, UnitTestCase)\n        return self.parent.obj(self.name)\n\n    # Backward compat for pytest-django; can be removed after pytest-django\n    # updates + some slack.\n    @property\n    def _testcase(self):\n        return self.instance\n\n    def setup(self) -> None:\n        # A bound method to be called during teardown() if set (see 'runtest()').\n        self._explicit_tearDown: Callable[[], None] | None = None\n        super().setup()\n        if sys.version_info < (3, 11):\n            # A cache of the subTest errors and non-subtest skips in self._outcome.\n            # Compute and cache these lists once, instead of computing them again and again for each subtest (#13965).\n            self._cached_errors_and_skips: tuple[list[Any], list[Any]] | None = None\n\n    def teardown(self) -> None:\n        if self._explicit_tearDown is not None:\n            self._explicit_tearDown()\n            self._explicit_tearDown = None\n        self._obj = None\n        del self._instance\n        super().teardown()\n\n    def startTest(self, testcase: unittest.TestCase) -> None:\n        pass\n\n    def _addexcinfo(self, rawexcinfo: _SysExcInfoType) -> None:\n        rawexcinfo = _handle_twisted_exc_info(rawexcinfo)\n        try:\n            excinfo = _pytest._code.ExceptionInfo[BaseException].from_exc_info(\n                rawexcinfo  # type: ignore[arg-type]\n            )\n            # Invoke the attributes to trigger storing the traceback\n            # trial causes some issue there.\n            _ = excinfo.value\n            _ = excinfo.traceback\n        except TypeError:\n            try:\n                try:\n                    values = traceback.format_exception(*rawexcinfo)\n                    values.insert(\n                        0,\n                        \"NOTE: Incompatible Exception Representation, \"\n                        \"displaying natively:\\n\\n\",\n                    )\n                    fail(\"\".join(values), pytrace=False)\n                except (fail.Exception, KeyboardInterrupt):\n                    raise\n                except BaseException:\n                    fail(\n                        \"ERROR: Unknown Incompatible Exception \"\n                        f\"representation:\\n{rawexcinfo!r}\",\n                        pytrace=False,\n                    )\n            except KeyboardInterrupt:\n                raise\n            except fail.Exception:\n                excinfo = _pytest._code.ExceptionInfo.from_current()\n        self.__dict__.setdefault(\"_excinfo\", []).append(excinfo)\n\n    def addError(\n        self, testcase: unittest.TestCase, rawexcinfo: _SysExcInfoType\n    ) -> None:\n        try:\n            if isinstance(rawexcinfo[1], exit.Exception):\n                exit(rawexcinfo[1].msg)\n        except TypeError:\n            pass\n        self._addexcinfo(rawexcinfo)\n\n    def addFailure(\n        self, testcase: unittest.TestCase, rawexcinfo: _SysExcInfoType\n    ) -> None:\n        self._addexcinfo(rawexcinfo)\n\n    def addSkip(\n        self, testcase: unittest.TestCase, reason: str, *, handle_subtests: bool = True\n    ) -> None:\n        from unittest.case import _SubTest  # type: ignore[attr-defined]\n\n        def add_skip() -> None:\n            try:\n                raise skip.Exception(reason, _use_item_location=True)\n            except skip.Exception:\n                self._addexcinfo(sys.exc_info())\n\n        if not handle_subtests:\n            add_skip()\n            return\n\n        if isinstance(testcase, _SubTest):\n            add_skip()\n            if self._excinfo is not None:\n                exc_info = self._excinfo[-1]\n                self.addSubTest(testcase.test_case, testcase, exc_info)\n        else:\n            # For python < 3.11: the non-subtest skips have to be added by `add_skip` only after all subtest\n            # failures are processed by `_addSubTest`: `self.instance._outcome` has no attribute\n            # `skipped/errors` anymore.\n            # We also need to check if `self.instance._outcome` is `None` (this happens if the test\n            # class/method is decorated with `unittest.skip`, see pytest-dev/pytest-subtests#173).\n            if sys.version_info < (3, 11) and self.instance._outcome is not None:\n                subtest_errors, _ = self._obtain_errors_and_skips()\n                if len(subtest_errors) == 0:\n                    add_skip()\n            else:\n                add_skip()\n\n    def addExpectedFailure(\n        self,\n        testcase: unittest.TestCase,\n        rawexcinfo: _SysExcInfoType,\n        reason: str = \"\",\n    ) -> None:\n        try:\n            xfail(str(reason))\n        except xfail.Exception:\n            self._addexcinfo(sys.exc_info())\n\n    def addUnexpectedSuccess(\n        self,\n        testcase: unittest.TestCase,\n        reason: twisted.trial.unittest.Todo | None = None,\n    ) -> None:\n        msg = \"Unexpected success\"\n        if reason:\n            msg += f\": {reason.reason}\"\n        # Preserve unittest behaviour - fail the test. Explicitly not an XPASS.\n        try:\n            fail(msg, pytrace=False)\n        except fail.Exception:\n            self._addexcinfo(sys.exc_info())\n\n    def addSuccess(self, testcase: unittest.TestCase) -> None:\n        pass\n\n    def stopTest(self, testcase: unittest.TestCase) -> None:\n        pass\n\n    def addDuration(self, testcase: unittest.TestCase, elapsed: float) -> None:\n        pass\n\n    def runtest(self) -> None:\n        from _pytest.debugging import maybe_wrap_pytest_function_for_tracing\n\n        testcase = self.instance\n        assert testcase is not None\n\n        maybe_wrap_pytest_function_for_tracing(self)\n\n        # Let the unittest framework handle async functions.\n        if is_async_function(self.obj):\n            testcase(result=self)\n        else:\n            # When --pdb is given, we want to postpone calling tearDown() otherwise\n            # when entering the pdb prompt, tearDown() would have probably cleaned up\n            # instance variables, which makes it difficult to debug.\n            # Arguably we could always postpone tearDown(), but this changes the moment where the\n            # TestCase instance interacts with the results object, so better to only do it\n            # when absolutely needed.\n            # We need to consider if the test itself is skipped, or the whole class.\n            assert isinstance(self.parent, UnitTestCase)\n            skipped = _is_skipped(self.obj) or _is_skipped(self.parent.obj)\n            if self.config.getoption(\"usepdb\") and not skipped:\n                self._explicit_tearDown = testcase.tearDown\n                setattr(testcase, \"tearDown\", lambda *args: None)\n\n            # We need to update the actual bound method with self.obj, because\n            # wrap_pytest_function_for_tracing replaces self.obj by a wrapper.\n            setattr(testcase, self.name, self.obj)\n            try:\n                testcase(result=self)\n            finally:\n                delattr(testcase, self.name)\n\n    def _traceback_filter(\n        self, excinfo: _pytest._code.ExceptionInfo[BaseException]\n    ) -> _pytest._code.Traceback:\n        traceback = super()._traceback_filter(excinfo)\n        ntraceback = traceback.filter(\n            lambda x: not x.frame.f_globals.get(\"__unittest\"),\n        )\n        if not ntraceback:\n            ntraceback = traceback\n        return ntraceback\n\n    def addSubTest(\n        self,\n        test_case: Any,\n        test: TestCase,\n        exc_info: ExceptionInfo[BaseException]\n        | tuple[type[BaseException], BaseException, TracebackType]\n        | None,\n    ) -> None:\n        # Importing this private symbol locally in case this symbol is renamed/removed in the future; importing\n        # it globally would break pytest entirely, importing it locally only will break unittests using `addSubTest`.\n        from unittest.case import _subtest_msg_sentinel  # type: ignore[attr-defined]\n\n        exception_info: ExceptionInfo[BaseException] | None\n        match exc_info:\n            case tuple():\n                exception_info = ExceptionInfo(exc_info, _ispytest=True)\n            case ExceptionInfo() | None:\n                exception_info = exc_info\n            case unreachable:\n                assert_never(unreachable)\n\n        call_info = CallInfo[None](\n            None,\n            exception_info,\n            start=0,\n            stop=0,\n            duration=0,\n            when=\"call\",\n            _ispytest=True,\n        )\n        msg = None if test._message is _subtest_msg_sentinel else str(test._message)  # type: ignore[attr-defined]\n        report = self.ihook.pytest_runtest_makereport(item=self, call=call_info)\n        sub_report = SubtestReport._new(\n            report,\n            SubtestContext(msg=msg, kwargs=dict(test.params)),  # type: ignore[attr-defined]\n            captured_output=None,\n            captured_logs=None,\n        )\n        self.ihook.pytest_runtest_logreport(report=sub_report)\n        if check_interactive_exception(call_info, sub_report):\n            self.ihook.pytest_exception_interact(\n                node=self, call=call_info, report=sub_report\n            )\n\n        # For python < 3.11: add non-subtest skips once all subtest failures are processed by # `_addSubTest`.\n        if sys.version_info < (3, 11):\n            subtest_errors, non_subtest_skip = self._obtain_errors_and_skips()\n\n            # Check if we have non-subtest skips: if there are also sub failures, non-subtest skips are not treated in\n            # `_addSubTest` and have to be added using `add_skip` after all subtest failures are processed.\n            if len(non_subtest_skip) > 0 and len(subtest_errors) > 0:\n                # Make sure we have processed the last subtest failure\n                last_subset_error = subtest_errors[-1]\n                if exc_info is last_subset_error[-1]:\n                    # Add non-subtest skips (as they could not be treated in `_addSkip`)\n                    for testcase, reason in non_subtest_skip:\n                        self.addSkip(testcase, reason, handle_subtests=False)\n\n    def _obtain_errors_and_skips(self) -> tuple[list[Any], list[Any]]:\n        \"\"\"Compute or obtain the cached values for subtest errors and non-subtest skips.\"\"\"\n        from unittest.case import _SubTest  # type: ignore[attr-defined]\n\n        assert sys.version_info < (3, 11), (\n            \"This workaround only should be used in Python 3.10\"\n        )\n        if self._cached_errors_and_skips is not None:\n            return self._cached_errors_and_skips\n\n        subtest_errors = [\n            (x, y)\n            for x, y in self.instance._outcome.errors\n            if isinstance(x, _SubTest) and y is not None\n        ]\n\n        non_subtest_skips = [\n            (x, y)\n            for x, y in self.instance._outcome.skipped\n            if not isinstance(x, _SubTest)\n        ]\n        self._cached_errors_and_skips = (subtest_errors, non_subtest_skips)\n        return subtest_errors, non_subtest_skips\n\n\n@hookimpl(tryfirst=True)\ndef pytest_runtest_makereport(item: Item, call: CallInfo[None]) -> None:\n    if isinstance(item, TestCaseFunction):\n        if item._excinfo:\n            call.excinfo = item._excinfo.pop(0)\n            try:\n                del call.result\n            except AttributeError:\n                pass\n\n    # Convert unittest.SkipTest to pytest.skip.\n    # This covers explicit `raise unittest.SkipTest`.\n    unittest = sys.modules.get(\"unittest\")\n    if unittest and call.excinfo and isinstance(call.excinfo.value, unittest.SkipTest):\n        excinfo = call.excinfo\n        call2 = CallInfo[None].from_call(lambda: skip(str(excinfo.value)), call.when)\n        call.excinfo = call2.excinfo\n\n\ndef _is_skipped(obj) -> bool:\n    \"\"\"Return True if the given object has been marked with @unittest.skip.\"\"\"\n    return bool(getattr(obj, \"__unittest_skip__\", False))\n\n\ndef pytest_configure() -> None:\n    \"\"\"Register the TestCaseFunction class as an IReporter if twisted.trial is available.\"\"\"\n    if _get_twisted_version() is not TwistedVersion.NotInstalled:\n        from twisted.trial.itrial import IReporter\n        from zope.interface import classImplements\n\n        classImplements(TestCaseFunction, IReporter)\n\n\nclass TwistedVersion(Enum):\n    \"\"\"\n    The Twisted version installed in the environment.\n\n    We have different workarounds in place for different versions of Twisted.\n    \"\"\"\n\n    # Twisted version 24 or prior.\n    Version24 = auto()\n    # Twisted version 25 or later.\n    Version25 = auto()\n    # Twisted version is not available.\n    NotInstalled = auto()\n\n\ndef _get_twisted_version() -> TwistedVersion:\n    # We need to check if \"twisted.trial.unittest\" is specifically present in sys.modules.\n    # This is because we intend to integrate with Trial only when it's actively running\n    # the test suite, but not needed when only other Twisted components are in use.\n    if \"twisted.trial.unittest\" not in sys.modules:\n        return TwistedVersion.NotInstalled\n\n    import importlib.metadata\n\n    import packaging.version\n\n    version_str = importlib.metadata.version(\"twisted\")\n    version = packaging.version.parse(version_str)\n    if version.major <= 24:\n        return TwistedVersion.Version24\n    else:\n        return TwistedVersion.Version25\n\n\n# Name of the attribute in `twisted.python.Failure` instances that stores\n# the `sys.exc_info()` tuple.\n# See twisted.trial support in `pytest_runtest_protocol`.\nTWISTED_RAW_EXCINFO_ATTR = \"_twisted_raw_excinfo\"\n\n\n@hookimpl(wrapper=True)\ndef pytest_runtest_protocol(item: Item) -> Iterator[None]:\n    if _get_twisted_version() is TwistedVersion.Version24:\n        import twisted.python.failure as ut\n\n        # Monkeypatch `Failure.__init__` to store the raw exception info.\n        original__init__ = ut.Failure.__init__\n\n        def store_raw_exception_info(\n            self, exc_value=None, exc_type=None, exc_tb=None, captureVars=None\n        ):  # pragma: no cover\n            if exc_value is None:\n                raw_exc_info = sys.exc_info()\n            else:\n                if exc_type is None:\n                    exc_type = type(exc_value)\n                if exc_tb is None:\n                    exc_tb = sys.exc_info()[2]\n                raw_exc_info = (exc_type, exc_value, exc_tb)\n            setattr(self, TWISTED_RAW_EXCINFO_ATTR, tuple(raw_exc_info))\n            try:\n                original__init__(\n                    self, exc_value, exc_type, exc_tb, captureVars=captureVars\n                )\n            except TypeError:  # pragma: no cover\n                original__init__(self, exc_value, exc_type, exc_tb)\n\n        with MonkeyPatch.context() as patcher:\n            patcher.setattr(ut.Failure, \"__init__\", store_raw_exception_info)\n            return (yield)\n    else:\n        return (yield)\n\n\ndef _handle_twisted_exc_info(\n    rawexcinfo: _SysExcInfoType | BaseException,\n) -> _SysExcInfoType:\n    \"\"\"\n    Twisted passes a custom Failure instance to `addError()` instead of using `sys.exc_info()`.\n    Therefore, if `rawexcinfo` is a `Failure` instance, convert it into the equivalent `sys.exc_info()` tuple\n    as expected by pytest.\n    \"\"\"\n    twisted_version = _get_twisted_version()\n    if twisted_version is TwistedVersion.NotInstalled:\n        # Unfortunately, because we cannot import `twisted.python.failure` at the top of the file\n        # and use it in the signature, we need to use `type:ignore` here because we cannot narrow\n        # the type properly in the `if` statement above.\n        return rawexcinfo  # type:ignore[return-value]\n    elif twisted_version is TwistedVersion.Version24:\n        # Twisted calls addError() passing its own classes (like `twisted.python.Failure`), which violates\n        # the `addError()` signature, so we extract the original `sys.exc_info()` tuple which is stored\n        # in the object.\n        if hasattr(rawexcinfo, TWISTED_RAW_EXCINFO_ATTR):\n            saved_exc_info = getattr(rawexcinfo, TWISTED_RAW_EXCINFO_ATTR)\n            # Delete the attribute from the original object to avoid leaks.\n            delattr(rawexcinfo, TWISTED_RAW_EXCINFO_ATTR)\n            return saved_exc_info  # type:ignore[no-any-return]\n        return rawexcinfo  # type:ignore[return-value]\n    elif twisted_version is TwistedVersion.Version25:\n        if isinstance(rawexcinfo, BaseException):\n            import twisted.python.failure\n\n            if isinstance(rawexcinfo, twisted.python.failure.Failure):\n                tb = rawexcinfo.__traceback__\n                if tb is None:\n                    tb = sys.exc_info()[2]\n                return type(rawexcinfo.value), rawexcinfo.value, tb\n\n        return rawexcinfo  # type:ignore[return-value]\n    else:\n        # Ideally we would use assert_never() here, but it is not available in all Python versions\n        # we support, plus we do not require `type_extensions` currently.\n        assert False, f\"Unexpected Twisted version: {twisted_version}\"\n"
  },
  {
    "path": "src/_pytest/unraisableexception.py",
    "content": "from __future__ import annotations\n\nimport collections\nfrom collections.abc import Callable\nimport functools\nimport gc\nimport sys\nimport traceback\nfrom typing import NamedTuple\nfrom typing import TYPE_CHECKING\nimport warnings\n\nfrom _pytest.config import Config\nfrom _pytest.nodes import Item\nfrom _pytest.stash import StashKey\nfrom _pytest.tracemalloc import tracemalloc_message\nimport pytest\n\n\nif TYPE_CHECKING:\n    pass\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import ExceptionGroup\n\n\n# This is a stash item and not a simple constant to allow pytester to override it.\ngc_collect_iterations_key = StashKey[int]()\n\n\ndef gc_collect_harder(iterations: int) -> None:\n    for _ in range(iterations):\n        gc.collect()\n\n\nclass UnraisableMeta(NamedTuple):\n    msg: str\n    cause_msg: str\n    exc_value: BaseException | None\n\n\nunraisable_exceptions: StashKey[collections.deque[UnraisableMeta | BaseException]] = (\n    StashKey()\n)\n\n\ndef collect_unraisable(config: Config) -> None:\n    pop_unraisable = config.stash[unraisable_exceptions].pop\n    errors: list[pytest.PytestUnraisableExceptionWarning | RuntimeError] = []\n    meta = None\n    hook_error = None\n    try:\n        while True:\n            try:\n                meta = pop_unraisable()\n            except IndexError:\n                break\n\n            if isinstance(meta, BaseException):\n                hook_error = RuntimeError(\"Failed to process unraisable exception\")\n                hook_error.__cause__ = meta\n                errors.append(hook_error)\n                continue\n\n            msg = meta.msg\n            try:\n                warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))\n            except pytest.PytestUnraisableExceptionWarning as e:\n                # This except happens when the warning is treated as an error (e.g. `-Werror`).\n                if meta.exc_value is not None:\n                    # Exceptions have a better way to show the traceback, but\n                    # warnings do not, so hide the traceback from the msg and\n                    # set the cause so the traceback shows up in the right place.\n                    e.args = (meta.cause_msg,)\n                    e.__cause__ = meta.exc_value\n                errors.append(e)\n\n        if len(errors) == 1:\n            raise errors[0]\n        if errors:\n            raise ExceptionGroup(\"multiple unraisable exception warnings\", errors)\n    finally:\n        del errors, meta, hook_error\n\n\ndef cleanup(\n    *, config: Config, prev_hook: Callable[[sys.UnraisableHookArgs], object]\n) -> None:\n    # A single collection doesn't necessarily collect everything.\n    # Constant determined experimentally by the Trio project.\n    gc_collect_iterations = config.stash.get(gc_collect_iterations_key, 5)\n    try:\n        try:\n            gc_collect_harder(gc_collect_iterations)\n            collect_unraisable(config)\n        finally:\n            sys.unraisablehook = prev_hook\n    finally:\n        del config.stash[unraisable_exceptions]\n\n\ndef unraisable_hook(\n    unraisable: sys.UnraisableHookArgs,\n    /,\n    *,\n    append: Callable[[UnraisableMeta | BaseException], object],\n) -> None:\n    try:\n        # we need to compute these strings here as they might change after\n        # the unraisablehook finishes and before the metadata object is\n        # collected by a pytest hook\n        err_msg = (\n            \"Exception ignored in\" if unraisable.err_msg is None else unraisable.err_msg\n        )\n        summary = f\"{err_msg}: {unraisable.object!r}\"\n        traceback_message = \"\\n\\n\" + \"\".join(\n            traceback.format_exception(\n                unraisable.exc_type,\n                unraisable.exc_value,\n                unraisable.exc_traceback,\n            )\n        )\n        tracemalloc_tb = \"\\n\" + tracemalloc_message(unraisable.object)\n        msg = summary + traceback_message + tracemalloc_tb\n        cause_msg = summary + tracemalloc_tb\n\n        append(\n            UnraisableMeta(\n                msg=msg,\n                cause_msg=cause_msg,\n                exc_value=unraisable.exc_value,\n            )\n        )\n    except BaseException as e:\n        append(e)\n        # Raising this will cause the exception to be logged twice, once in our\n        # collect_unraisable and once by the unraisablehook calling machinery\n        # which is fine - this should never happen anyway and if it does\n        # it should probably be reported as a pytest bug.\n        raise\n\n\ndef pytest_configure(config: Config) -> None:\n    prev_hook = sys.unraisablehook\n    deque: collections.deque[UnraisableMeta | BaseException] = collections.deque()\n    config.stash[unraisable_exceptions] = deque\n    config.add_cleanup(functools.partial(cleanup, config=config, prev_hook=prev_hook))\n    sys.unraisablehook = functools.partial(unraisable_hook, append=deque.append)\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_runtest_setup(item: Item) -> None:\n    collect_unraisable(item.config)\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_runtest_call(item: Item) -> None:\n    collect_unraisable(item.config)\n\n\n@pytest.hookimpl(trylast=True)\ndef pytest_runtest_teardown(item: Item) -> None:\n    collect_unraisable(item.config)\n"
  },
  {
    "path": "src/_pytest/warning_types.py",
    "content": "from __future__ import annotations\n\nimport dataclasses\nimport inspect\nfrom types import FunctionType\nfrom typing import Any\nfrom typing import final\nfrom typing import Generic\nfrom typing import TypeVar\nimport warnings\n\n\nclass PytestWarning(UserWarning):\n    \"\"\"Base class for all warnings emitted by pytest.\"\"\"\n\n    __module__ = \"pytest\"\n\n\n@final\nclass PytestAssertRewriteWarning(PytestWarning):\n    \"\"\"Warning emitted by the pytest assert rewrite module.\"\"\"\n\n    __module__ = \"pytest\"\n\n\n@final\nclass PytestCacheWarning(PytestWarning):\n    \"\"\"Warning emitted by the cache plugin in various situations.\"\"\"\n\n    __module__ = \"pytest\"\n\n\n@final\nclass PytestConfigWarning(PytestWarning):\n    \"\"\"Warning emitted for configuration issues.\"\"\"\n\n    __module__ = \"pytest\"\n\n\n@final\nclass PytestCollectionWarning(PytestWarning):\n    \"\"\"Warning emitted when pytest is not able to collect a file or symbol in a module.\"\"\"\n\n    __module__ = \"pytest\"\n\n\nclass PytestDeprecationWarning(PytestWarning, DeprecationWarning):\n    \"\"\"Warning class for features that will be removed in a future version.\"\"\"\n\n    __module__ = \"pytest\"\n\n\nclass PytestRemovedIn9Warning(PytestDeprecationWarning):\n    \"\"\"Warning class for features that will be removed in pytest 9.\"\"\"\n\n    __module__ = \"pytest\"\n\n\nclass PytestRemovedIn10Warning(PytestDeprecationWarning):\n    \"\"\"Warning class for features that will be removed in pytest 10.\"\"\"\n\n    __module__ = \"pytest\"\n\n\n@final\nclass PytestExperimentalApiWarning(PytestWarning, FutureWarning):\n    \"\"\"Warning category used to denote experiments in pytest.\n\n    Use sparingly as the API might change or even be removed completely in a\n    future version.\n    \"\"\"\n\n    __module__ = \"pytest\"\n\n    @classmethod\n    def simple(cls, apiname: str) -> PytestExperimentalApiWarning:\n        return cls(f\"{apiname} is an experimental api that may change over time\")\n\n\n@final\nclass PytestReturnNotNoneWarning(PytestWarning):\n    \"\"\"\n    Warning emitted when a test function returns a value other than ``None``.\n\n    See :ref:`return-not-none` for details.\n    \"\"\"\n\n    __module__ = \"pytest\"\n\n\n@final\nclass PytestUnknownMarkWarning(PytestWarning):\n    \"\"\"Warning emitted on use of unknown markers.\n\n    See :ref:`mark` for details.\n    \"\"\"\n\n    __module__ = \"pytest\"\n\n\n@final\nclass PytestUnraisableExceptionWarning(PytestWarning):\n    \"\"\"An unraisable exception was reported.\n\n    Unraisable exceptions are exceptions raised in :meth:`__del__ <object.__del__>`\n    implementations and similar situations when the exception cannot be raised\n    as normal.\n    \"\"\"\n\n    __module__ = \"pytest\"\n\n\n@final\nclass PytestUnhandledThreadExceptionWarning(PytestWarning):\n    \"\"\"An unhandled exception occurred in a :class:`~threading.Thread`.\n\n    Such exceptions don't propagate normally.\n    \"\"\"\n\n    __module__ = \"pytest\"\n\n\n_W = TypeVar(\"_W\", bound=PytestWarning)\n\n\n@final\n@dataclasses.dataclass\nclass UnformattedWarning(Generic[_W]):\n    \"\"\"A warning meant to be formatted during runtime.\n\n    This is used to hold warnings that need to format their message at runtime,\n    as opposed to a direct message.\n    \"\"\"\n\n    category: type[_W]\n    template: str\n\n    def format(self, **kwargs: Any) -> _W:\n        \"\"\"Return an instance of the warning category, formatted with given kwargs.\"\"\"\n        return self.category(self.template.format(**kwargs))\n\n\n@final\nclass PytestFDWarning(PytestWarning):\n    \"\"\"When the lsof plugin finds leaked fds.\"\"\"\n\n    __module__ = \"pytest\"\n\n\ndef warn_explicit_for(method: FunctionType, message: PytestWarning) -> None:\n    \"\"\"\n    Issue the warning :param:`message` for the definition of the given :param:`method`\n\n    this helps to log warnings for functions defined prior to finding an issue with them\n    (like hook wrappers being marked in a legacy mechanism)\n    \"\"\"\n    lineno = method.__code__.co_firstlineno\n    filename = inspect.getfile(method)\n    module = method.__module__\n    mod_globals = method.__globals__\n    try:\n        warnings.warn_explicit(\n            message,\n            type(message),\n            filename=filename,\n            module=module,\n            registry=mod_globals.setdefault(\"__warningregistry__\", {}),\n            lineno=lineno,\n        )\n    except Warning as w:\n        # If warnings are errors (e.g. -Werror), location information gets lost, so we add it to the message.\n        raise type(w)(f\"{w}\\n at {filename}:{lineno}\") from None\n"
  },
  {
    "path": "src/_pytest/warnings.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nfrom contextlib import contextmanager\nfrom contextlib import ExitStack\nimport sys\nfrom typing import Literal\nimport warnings\n\nfrom _pytest.config import apply_warning_filters\nfrom _pytest.config import Config\nfrom _pytest.config import parse_warning_filter\nfrom _pytest.main import Session\nfrom _pytest.nodes import Item\nfrom _pytest.terminal import TerminalReporter\nfrom _pytest.tracemalloc import tracemalloc_message\nimport pytest\n\n\n@contextmanager\ndef catch_warnings_for_item(\n    config: Config,\n    ihook,\n    when: Literal[\"config\", \"collect\", \"runtest\"],\n    item: Item | None,\n    *,\n    record: bool = True,\n) -> Generator[None]:\n    \"\"\"Context manager that catches warnings generated in the contained execution block.\n\n    ``item`` can be None if we are not in the context of an item execution.\n\n    Each warning captured triggers the ``pytest_warning_recorded`` hook.\n    \"\"\"\n    config_filters = config.getini(\"filterwarnings\")\n    cmdline_filters = config.known_args_namespace.pythonwarnings or []\n    with warnings.catch_warnings(record=record) as log:\n        if not sys.warnoptions:\n            # If user is not explicitly configuring warning filters, show deprecation warnings by default (#2908).\n            warnings.filterwarnings(\"always\", category=DeprecationWarning)\n            warnings.filterwarnings(\"always\", category=PendingDeprecationWarning)\n\n        warnings.filterwarnings(\"error\", category=pytest.PytestRemovedIn9Warning)\n\n        apply_warning_filters(config_filters, cmdline_filters)\n\n        # apply filters from \"filterwarnings\" marks\n        nodeid = \"\" if item is None else item.nodeid\n        if item is not None:\n            for mark in item.iter_markers(name=\"filterwarnings\"):\n                for arg in mark.args:\n                    warnings.filterwarnings(*parse_warning_filter(arg, escape=False))\n\n        try:\n            yield\n        finally:\n            if record:\n                # mypy can't infer that record=True means log is not None; help it.\n                assert log is not None\n\n                for warning_message in log:\n                    ihook.pytest_warning_recorded.call_historic(\n                        kwargs=dict(\n                            warning_message=warning_message,\n                            nodeid=nodeid,\n                            when=when,\n                            location=None,\n                        )\n                    )\n\n\ndef warning_record_to_str(warning_message: warnings.WarningMessage) -> str:\n    \"\"\"Convert a warnings.WarningMessage to a string.\"\"\"\n    return warnings.formatwarning(\n        str(warning_message.message),\n        warning_message.category,\n        warning_message.filename,\n        warning_message.lineno,\n        warning_message.line,\n    ) + tracemalloc_message(warning_message.source)\n\n\n@pytest.hookimpl(wrapper=True, tryfirst=True)\ndef pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:\n    with catch_warnings_for_item(\n        config=item.config, ihook=item.ihook, when=\"runtest\", item=item\n    ):\n        return (yield)\n\n\n@pytest.hookimpl(wrapper=True, tryfirst=True)\ndef pytest_collection(session: Session) -> Generator[None, object, object]:\n    config = session.config\n    with catch_warnings_for_item(\n        config=config, ihook=config.hook, when=\"collect\", item=None\n    ):\n        return (yield)\n\n\n@pytest.hookimpl(wrapper=True)\ndef pytest_terminal_summary(\n    terminalreporter: TerminalReporter,\n) -> Generator[None]:\n    config = terminalreporter.config\n    with catch_warnings_for_item(\n        config=config, ihook=config.hook, when=\"config\", item=None\n    ):\n        return (yield)\n\n\n@pytest.hookimpl(wrapper=True)\ndef pytest_sessionfinish(session: Session) -> Generator[None]:\n    config = session.config\n    with catch_warnings_for_item(\n        config=config, ihook=config.hook, when=\"config\", item=None\n    ):\n        return (yield)\n\n\n@pytest.hookimpl(wrapper=True)\ndef pytest_load_initial_conftests(\n    early_config: Config,\n) -> Generator[None]:\n    with catch_warnings_for_item(\n        config=early_config, ihook=early_config.hook, when=\"config\", item=None\n    ):\n        return (yield)\n\n\ndef pytest_configure(config: Config) -> None:\n    with ExitStack() as stack:\n        stack.enter_context(\n            catch_warnings_for_item(\n                config=config,\n                ihook=config.hook,\n                when=\"config\",\n                item=None,\n                # this disables recording because the terminalreporter has\n                # finished by the time it comes to reporting logged warnings\n                # from the end of config cleanup. So for now, this is only\n                # useful for setting a warning filter with an 'error' action.\n                record=False,\n            )\n        )\n        config.addinivalue_line(\n            \"markers\",\n            \"filterwarnings(warning): add a warning filter to the given test. \"\n            \"see https://docs.pytest.org/en/stable/how-to/capture-warnings.html#pytest-mark-filterwarnings \",\n        )\n        config.add_cleanup(stack.pop_all().close)\n"
  },
  {
    "path": "src/py.py",
    "content": "# shim for pylib going away\n# if pylib is installed this file will get skipped\n# (`py/__init__.py` has higher precedence)\nfrom __future__ import annotations\n\nimport sys\n\nimport _pytest._py.error as error\nimport _pytest._py.path as path\n\n\nsys.modules[\"py.error\"] = error\nsys.modules[\"py.path\"] = path\n\n__all__ = [\"error\", \"path\"]\n"
  },
  {
    "path": "src/pytest/__init__.py",
    "content": "# PYTHON_ARGCOMPLETE_OK\n\"\"\"pytest: unit and functional testing with Python.\"\"\"\n\nfrom __future__ import annotations\n\nfrom _pytest import __version__\nfrom _pytest import version_tuple\nfrom _pytest._code import ExceptionInfo\nfrom _pytest.assertion import register_assert_rewrite\nfrom _pytest.cacheprovider import Cache\nfrom _pytest.capture import CaptureFixture\nfrom _pytest.config import cmdline\nfrom _pytest.config import Config\nfrom _pytest.config import console_main\nfrom _pytest.config import ExitCode\nfrom _pytest.config import hookimpl\nfrom _pytest.config import hookspec\nfrom _pytest.config import main\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.config import UsageError\nfrom _pytest.config.argparsing import OptionGroup\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.debugging import pytestPDB as __pytestPDB\nfrom _pytest.doctest import DoctestItem\nfrom _pytest.fixtures import fixture\nfrom _pytest.fixtures import FixtureDef\nfrom _pytest.fixtures import FixtureLookupError\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.fixtures import yield_fixture\nfrom _pytest.freeze_support import freeze_includes\nfrom _pytest.legacypath import TempdirFactory\nfrom _pytest.legacypath import Testdir\nfrom _pytest.logging import LogCaptureFixture\nfrom _pytest.main import Dir\nfrom _pytest.main import Session\nfrom _pytest.mark import HIDDEN_PARAM\nfrom _pytest.mark import Mark\nfrom _pytest.mark import MARK_GEN as mark\nfrom _pytest.mark import MarkDecorator\nfrom _pytest.mark import MarkGenerator\nfrom _pytest.mark import param\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import Directory\nfrom _pytest.nodes import File\nfrom _pytest.nodes import Item\nfrom _pytest.outcomes import exit\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import importorskip\nfrom _pytest.outcomes import skip\nfrom _pytest.outcomes import xfail\nfrom _pytest.pytester import HookRecorder\nfrom _pytest.pytester import LineMatcher\nfrom _pytest.pytester import Pytester\nfrom _pytest.pytester import RecordedHookCall\nfrom _pytest.pytester import RunResult\nfrom _pytest.python import Class\nfrom _pytest.python import Function\nfrom _pytest.python import Metafunc\nfrom _pytest.python import Module\nfrom _pytest.python import Package\nfrom _pytest.python_api import approx\nfrom _pytest.raises import raises\nfrom _pytest.raises import RaisesExc\nfrom _pytest.raises import RaisesGroup\nfrom _pytest.recwarn import deprecated_call\nfrom _pytest.recwarn import WarningsRecorder\nfrom _pytest.recwarn import warns\nfrom _pytest.reports import CollectReport\nfrom _pytest.reports import TestReport\nfrom _pytest.runner import CallInfo\nfrom _pytest.stash import Stash\nfrom _pytest.stash import StashKey\nfrom _pytest.subtests import SubtestReport\nfrom _pytest.subtests import Subtests\nfrom _pytest.terminal import TerminalReporter\nfrom _pytest.terminal import TestShortLogReport\nfrom _pytest.tmpdir import TempPathFactory\nfrom _pytest.warning_types import PytestAssertRewriteWarning\nfrom _pytest.warning_types import PytestCacheWarning\nfrom _pytest.warning_types import PytestCollectionWarning\nfrom _pytest.warning_types import PytestConfigWarning\nfrom _pytest.warning_types import PytestDeprecationWarning\nfrom _pytest.warning_types import PytestExperimentalApiWarning\nfrom _pytest.warning_types import PytestFDWarning\nfrom _pytest.warning_types import PytestRemovedIn9Warning\nfrom _pytest.warning_types import PytestRemovedIn10Warning\nfrom _pytest.warning_types import PytestReturnNotNoneWarning\nfrom _pytest.warning_types import PytestUnhandledThreadExceptionWarning\nfrom _pytest.warning_types import PytestUnknownMarkWarning\nfrom _pytest.warning_types import PytestUnraisableExceptionWarning\nfrom _pytest.warning_types import PytestWarning\n\n\nset_trace = __pytestPDB.set_trace\n\n\n__all__ = [\n    \"HIDDEN_PARAM\",\n    \"Cache\",\n    \"CallInfo\",\n    \"CaptureFixture\",\n    \"Class\",\n    \"CollectReport\",\n    \"Collector\",\n    \"Config\",\n    \"Dir\",\n    \"Directory\",\n    \"DoctestItem\",\n    \"ExceptionInfo\",\n    \"ExitCode\",\n    \"File\",\n    \"FixtureDef\",\n    \"FixtureLookupError\",\n    \"FixtureRequest\",\n    \"Function\",\n    \"HookRecorder\",\n    \"Item\",\n    \"LineMatcher\",\n    \"LogCaptureFixture\",\n    \"Mark\",\n    \"MarkDecorator\",\n    \"MarkGenerator\",\n    \"Metafunc\",\n    \"Module\",\n    \"MonkeyPatch\",\n    \"OptionGroup\",\n    \"Package\",\n    \"Parser\",\n    \"PytestAssertRewriteWarning\",\n    \"PytestCacheWarning\",\n    \"PytestCollectionWarning\",\n    \"PytestConfigWarning\",\n    \"PytestDeprecationWarning\",\n    \"PytestExperimentalApiWarning\",\n    \"PytestFDWarning\",\n    \"PytestPluginManager\",\n    \"PytestRemovedIn9Warning\",\n    \"PytestRemovedIn10Warning\",\n    \"PytestReturnNotNoneWarning\",\n    \"PytestUnhandledThreadExceptionWarning\",\n    \"PytestUnknownMarkWarning\",\n    \"PytestUnraisableExceptionWarning\",\n    \"PytestWarning\",\n    \"Pytester\",\n    \"RaisesExc\",\n    \"RaisesGroup\",\n    \"RecordedHookCall\",\n    \"RunResult\",\n    \"Session\",\n    \"Stash\",\n    \"StashKey\",\n    \"SubtestReport\",\n    \"Subtests\",\n    \"TempPathFactory\",\n    \"TempdirFactory\",\n    \"TerminalReporter\",\n    \"TestReport\",\n    \"TestShortLogReport\",\n    \"Testdir\",\n    \"UsageError\",\n    \"WarningsRecorder\",\n    \"__version__\",\n    \"approx\",\n    \"cmdline\",\n    \"console_main\",\n    \"deprecated_call\",\n    \"exit\",\n    \"fail\",\n    \"fixture\",\n    \"freeze_includes\",\n    \"hookimpl\",\n    \"hookspec\",\n    \"importorskip\",\n    \"main\",\n    \"mark\",\n    \"param\",\n    \"raises\",\n    \"register_assert_rewrite\",\n    \"set_trace\",\n    \"skip\",\n    \"version_tuple\",\n    \"warns\",\n    \"xfail\",\n    \"yield_fixture\",\n]\n"
  },
  {
    "path": "src/pytest/__main__.py",
    "content": "\"\"\"The pytest entry point.\"\"\"\n\nfrom __future__ import annotations\n\nimport pytest\n\n\nif __name__ == \"__main__\":\n    raise SystemExit(pytest.console_main())\n"
  },
  {
    "path": "src/pytest/py.typed",
    "content": ""
  },
  {
    "path": "testing/_py/test_local.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport contextlib\nimport multiprocessing\nimport os\nimport sys\nimport time\nfrom unittest import mock\nimport warnings\n\nfrom py.path import local\n\nfrom py import error\n\nimport pytest\n\n\n@contextlib.contextmanager\ndef ignore_encoding_warning():\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\", EncodingWarning)\n        yield\n\n\nclass CommonFSTests:\n    def test_constructor_equality(self, path1):\n        p = path1.__class__(path1)\n        assert p == path1\n\n    def test_eq_nonstring(self, path1):\n        p1 = path1.join(\"sampledir\")\n        p2 = path1.join(\"sampledir\")\n        assert p1 == p2\n\n    def test_new_identical(self, path1):\n        assert path1 == path1.new()\n\n    def test_join(self, path1):\n        p = path1.join(\"sampledir\")\n        strp = str(p)\n        assert strp.endswith(\"sampledir\")\n        assert strp.startswith(str(path1))\n\n    def test_join_normalized(self, path1):\n        newpath = path1.join(path1.sep + \"sampledir\")\n        strp = str(newpath)\n        assert strp.endswith(\"sampledir\")\n        assert strp.startswith(str(path1))\n        newpath = path1.join((path1.sep * 2) + \"sampledir\")\n        strp = str(newpath)\n        assert strp.endswith(\"sampledir\")\n        assert strp.startswith(str(path1))\n\n    def test_join_noargs(self, path1):\n        newpath = path1.join()\n        assert path1 == newpath\n\n    def test_add_something(self, path1):\n        p = path1.join(\"sample\")\n        p = p + \"dir\"\n        assert p.check()\n        assert p.exists()\n        assert p.isdir()\n        assert not p.isfile()\n\n    def test_parts(self, path1):\n        newpath = path1.join(\"sampledir\", \"otherfile\")\n        par = newpath.parts()[-3:]\n        assert par == [path1, path1.join(\"sampledir\"), newpath]\n\n        revpar = newpath.parts(reverse=True)[:3]\n        assert revpar == [newpath, path1.join(\"sampledir\"), path1]\n\n    def test_common(self, path1):\n        other = path1.join(\"sampledir\")\n        x = other.common(path1)\n        assert x == path1\n\n    # def test_parents_nonexisting_file(self, path1):\n    #    newpath = path1 / 'dirnoexist' / 'nonexisting file'\n    #    par = list(newpath.parents())\n    #    assert par[:2] == [path1 / 'dirnoexist', path1]\n\n    def test_basename_checks(self, path1):\n        newpath = path1.join(\"sampledir\")\n        assert newpath.check(basename=\"sampledir\")\n        assert newpath.check(notbasename=\"xyz\")\n        assert newpath.basename == \"sampledir\"\n\n    def test_basename(self, path1):\n        newpath = path1.join(\"sampledir\")\n        assert newpath.check(basename=\"sampledir\")\n        assert newpath.basename, \"sampledir\"\n\n    def test_dirname(self, path1):\n        newpath = path1.join(\"sampledir\")\n        assert newpath.dirname == str(path1)\n\n    def test_dirpath(self, path1):\n        newpath = path1.join(\"sampledir\")\n        assert newpath.dirpath() == path1\n\n    def test_dirpath_with_args(self, path1):\n        newpath = path1.join(\"sampledir\")\n        assert newpath.dirpath(\"x\") == path1.join(\"x\")\n\n    def test_newbasename(self, path1):\n        newpath = path1.join(\"samplefile\")\n        newbase = newpath.new(basename=\"samplefile2\")\n        assert newbase.basename == \"samplefile2\"\n        assert newbase.dirpath() == newpath.dirpath()\n\n    def test_not_exists(self, path1):\n        assert not path1.join(\"does_not_exist\").check()\n        assert path1.join(\"does_not_exist\").check(exists=0)\n\n    def test_exists(self, path1):\n        assert path1.join(\"samplefile\").check()\n        assert path1.join(\"samplefile\").check(exists=1)\n        assert path1.join(\"samplefile\").exists()\n        assert path1.join(\"samplefile\").isfile()\n        assert not path1.join(\"samplefile\").isdir()\n\n    def test_dir(self, path1):\n        # print repr(path1.join(\"sampledir\"))\n        assert path1.join(\"sampledir\").check(dir=1)\n        assert path1.join(\"samplefile\").check(notdir=1)\n        assert not path1.join(\"samplefile\").check(dir=1)\n        assert path1.join(\"samplefile\").exists()\n        assert not path1.join(\"samplefile\").isdir()\n        assert path1.join(\"samplefile\").isfile()\n\n    def test_fnmatch_file(self, path1):\n        assert path1.join(\"samplefile\").check(fnmatch=\"s*e\")\n        assert path1.join(\"samplefile\").fnmatch(\"s*e\")\n        assert not path1.join(\"samplefile\").fnmatch(\"s*x\")\n        assert not path1.join(\"samplefile\").check(fnmatch=\"s*x\")\n\n    # def test_fnmatch_dir(self, path1):\n\n    #    pattern = path1.sep.join(['s*file'])\n    #    sfile = path1.join(\"samplefile\")\n    #    assert sfile.check(fnmatch=pattern)\n\n    def test_relto(self, path1):\n        p = path1.join(\"sampledir\", \"otherfile\")\n        assert p.relto(path1) == p.sep.join([\"sampledir\", \"otherfile\"])\n        assert p.check(relto=path1)\n        assert path1.check(notrelto=p)\n        assert not path1.check(relto=p)\n\n    def test_bestrelpath(self, path1):\n        curdir = path1\n        sep = curdir.sep\n        s = curdir.bestrelpath(curdir)\n        assert s == \".\"\n        s = curdir.bestrelpath(curdir.join(\"hello\", \"world\"))\n        assert s == \"hello\" + sep + \"world\"\n\n        s = curdir.bestrelpath(curdir.dirpath().join(\"sister\"))\n        assert s == \"..\" + sep + \"sister\"\n        assert curdir.bestrelpath(curdir.dirpath()) == \"..\"\n\n        assert curdir.bestrelpath(\"hello\") == \"hello\"\n\n    def test_relto_not_relative(self, path1):\n        l1 = path1.join(\"bcde\")\n        l2 = path1.join(\"b\")\n        assert not l1.relto(l2)\n        assert not l2.relto(l1)\n\n    def test_listdir(self, path1):\n        p = path1.listdir()\n        assert path1.join(\"sampledir\") in p\n        assert path1.join(\"samplefile\") in p\n        with pytest.raises(error.ENOTDIR):\n            path1.join(\"samplefile\").listdir()\n\n    def test_listdir_fnmatchstring(self, path1):\n        p = path1.listdir(\"s*dir\")\n        assert len(p)\n        assert p[0], path1.join(\"sampledir\")\n\n    def test_listdir_filter(self, path1):\n        p = path1.listdir(lambda x: x.check(dir=1))\n        assert path1.join(\"sampledir\") in p\n        assert path1.join(\"samplefile\") not in p\n\n    def test_listdir_sorted(self, path1):\n        p = path1.listdir(lambda x: x.check(basestarts=\"sample\"), sort=True)\n        assert path1.join(\"sampledir\") == p[0]\n        assert path1.join(\"samplefile\") == p[1]\n        assert path1.join(\"samplepickle\") == p[2]\n\n    def test_visit_nofilter(self, path1):\n        lst = []\n        for i in path1.visit():\n            lst.append(i.relto(path1))\n        assert \"sampledir\" in lst\n        assert path1.sep.join([\"sampledir\", \"otherfile\"]) in lst\n\n    def test_visit_norecurse(self, path1):\n        lst = []\n        for i in path1.visit(None, lambda x: x.basename != \"sampledir\"):\n            lst.append(i.relto(path1))\n        assert \"sampledir\" in lst\n        assert path1.sep.join([\"sampledir\", \"otherfile\"]) not in lst\n\n    def test_visit_filterfunc_is_string(self, path1):\n        lst = []\n        for i in path1.visit(\"*dir\"):\n            lst.append(i.relto(path1))\n        assert len(lst), 2  # noqa: PLC1802,RUF040\n        assert \"sampledir\" in lst\n        assert \"otherdir\" in lst\n\n    def test_visit_ignore(self, path1):\n        p = path1.join(\"nonexisting\")\n        assert list(p.visit(ignore=error.ENOENT)) == []\n\n    def test_visit_endswith(self, path1):\n        p = []\n        for i in path1.visit(lambda x: x.check(endswith=\"file\")):\n            p.append(i.relto(path1))\n        assert path1.sep.join([\"sampledir\", \"otherfile\"]) in p\n        assert \"samplefile\" in p\n\n    def test_cmp(self, path1):\n        path1 = path1.join(\"samplefile\")\n        path2 = path1.join(\"samplefile2\")\n        assert (path1 < path2) == (\"samplefile\" < \"samplefile2\")\n        assert not (path1 < path1)\n\n    def test_simple_read(self, path1):\n        with ignore_encoding_warning():\n            x = path1.join(\"samplefile\").read(\"r\")\n        assert x == \"samplefile\\n\"\n\n    def test_join_div_operator(self, path1):\n        newpath = path1 / \"/sampledir\" / \"/test//\"\n        newpath2 = path1.join(\"sampledir\", \"test\")\n        assert newpath == newpath2\n\n    def test_ext(self, path1):\n        newpath = path1.join(\"sampledir.ext\")\n        assert newpath.ext == \".ext\"\n        newpath = path1.join(\"sampledir\")\n        assert not newpath.ext\n\n    def test_purebasename(self, path1):\n        newpath = path1.join(\"samplefile.py\")\n        assert newpath.purebasename == \"samplefile\"\n\n    def test_multiple_parts(self, path1):\n        newpath = path1.join(\"samplefile.py\")\n        dirname, purebasename, basename, ext = newpath._getbyspec(\n            \"dirname,purebasename,basename,ext\"\n        )\n        assert str(path1).endswith(dirname)  # be careful with win32 'drive'\n        assert purebasename == \"samplefile\"\n        assert basename == \"samplefile.py\"\n        assert ext == \".py\"\n\n    def test_dotted_name_ext(self, path1):\n        newpath = path1.join(\"a.b.c\")\n        ext = newpath.ext\n        assert ext == \".c\"\n        assert newpath.ext == \".c\"\n\n    def test_newext(self, path1):\n        newpath = path1.join(\"samplefile.py\")\n        newext = newpath.new(ext=\".txt\")\n        assert newext.basename == \"samplefile.txt\"\n        assert newext.purebasename == \"samplefile\"\n\n    def test_readlines(self, path1):\n        fn = path1.join(\"samplefile\")\n        with ignore_encoding_warning():\n            contents = fn.readlines()\n        assert contents == [\"samplefile\\n\"]\n\n    def test_readlines_nocr(self, path1):\n        fn = path1.join(\"samplefile\")\n        with ignore_encoding_warning():\n            contents = fn.readlines(cr=0)\n        assert contents == [\"samplefile\", \"\"]\n\n    def test_file(self, path1):\n        assert path1.join(\"samplefile\").check(file=1)\n\n    def test_not_file(self, path1):\n        assert not path1.join(\"sampledir\").check(file=1)\n        assert path1.join(\"sampledir\").check(file=0)\n\n    def test_non_existent(self, path1):\n        assert path1.join(\"sampledir.nothere\").check(dir=0)\n        assert path1.join(\"sampledir.nothere\").check(file=0)\n        assert path1.join(\"sampledir.nothere\").check(notfile=1)\n        assert path1.join(\"sampledir.nothere\").check(notdir=1)\n        assert path1.join(\"sampledir.nothere\").check(notexists=1)\n        assert not path1.join(\"sampledir.nothere\").check(notfile=0)\n\n    #    pattern = path1.sep.join(['s*file'])\n    #    sfile = path1.join(\"samplefile\")\n    #    assert sfile.check(fnmatch=pattern)\n\n    def test_size(self, path1):\n        url = path1.join(\"samplefile\")\n        assert url.size() > len(\"samplefile\")\n\n    def test_mtime(self, path1):\n        url = path1.join(\"samplefile\")\n        assert url.mtime() > 0\n\n    def test_relto_wrong_type(self, path1):\n        with pytest.raises(TypeError):\n            path1.relto(42)\n\n    def test_load(self, path1):\n        p = path1.join(\"samplepickle\")\n        obj = p.load()\n        assert type(obj) is dict\n        assert obj.get(\"answer\", None) == 42\n\n    def test_visit_filesonly(self, path1):\n        p = []\n        for i in path1.visit(lambda x: x.check(file=1)):\n            p.append(i.relto(path1))\n        assert \"sampledir\" not in p\n        assert path1.sep.join([\"sampledir\", \"otherfile\"]) in p\n\n    def test_visit_nodotfiles(self, path1):\n        p = []\n        for i in path1.visit(lambda x: x.check(dotfile=0)):\n            p.append(i.relto(path1))\n        assert \"sampledir\" in p\n        assert path1.sep.join([\"sampledir\", \"otherfile\"]) in p\n        assert \".dotfile\" not in p\n\n    def test_visit_breadthfirst(self, path1):\n        lst = []\n        for i in path1.visit(bf=True):\n            lst.append(i.relto(path1))\n        for i, p in enumerate(lst):\n            if path1.sep in p:\n                for j in range(i, len(lst)):\n                    assert path1.sep in lst[j]\n                break\n        else:\n            pytest.fail(\"huh\")\n\n    def test_visit_sort(self, path1):\n        lst = []\n        for i in path1.visit(bf=True, sort=True):\n            lst.append(i.relto(path1))\n        for i, p in enumerate(lst):\n            if path1.sep in p:\n                break\n        assert lst[:i] == sorted(lst[:i])\n        assert lst[i:] == sorted(lst[i:])\n\n    def test_endswith(self, path1):\n        def chk(p):\n            return p.check(endswith=\"pickle\")\n\n        assert not chk(path1)\n        assert not chk(path1.join(\"samplefile\"))\n        assert chk(path1.join(\"somepickle\"))\n\n    def test_copy_file(self, path1):\n        otherdir = path1.join(\"otherdir\")\n        initpy = otherdir.join(\"__init__.py\")\n        copied = otherdir.join(\"copied\")\n        initpy.copy(copied)\n        try:\n            assert copied.check()\n            s1 = initpy.read_text(encoding=\"utf-8\")\n            s2 = copied.read_text(encoding=\"utf-8\")\n            assert s1 == s2\n        finally:\n            if copied.check():\n                copied.remove()\n\n    def test_copy_dir(self, path1):\n        otherdir = path1.join(\"otherdir\")\n        copied = path1.join(\"newdir\")\n        try:\n            otherdir.copy(copied)\n            assert copied.check(dir=1)\n            assert copied.join(\"__init__.py\").check(file=1)\n            s1 = otherdir.join(\"__init__.py\").read_text(encoding=\"utf-8\")\n            s2 = copied.join(\"__init__.py\").read_text(encoding=\"utf-8\")\n            assert s1 == s2\n        finally:\n            if copied.check(dir=1):\n                copied.remove(rec=1)\n\n    def test_remove_file(self, path1):\n        d = path1.ensure(\"todeleted\")\n        assert d.check()\n        d.remove()\n        assert not d.check()\n\n    def test_remove_dir_recursive_by_default(self, path1):\n        d = path1.ensure(\"to\", \"be\", \"deleted\")\n        assert d.check()\n        p = path1.join(\"to\")\n        p.remove()\n        assert not p.check()\n\n    def test_ensure_dir(self, path1):\n        b = path1.ensure_dir(\"001\", \"002\")\n        assert b.basename == \"002\"\n        assert b.isdir()\n\n    def test_mkdir_and_remove(self, path1):\n        tmpdir = path1\n        with pytest.raises(error.EEXIST):\n            tmpdir.mkdir(\"sampledir\")\n        new = tmpdir.join(\"mktest1\")\n        new.mkdir()\n        assert new.check(dir=1)\n        new.remove()\n\n        new = tmpdir.mkdir(\"mktest\")\n        assert new.check(dir=1)\n        new.remove()\n        assert tmpdir.join(\"mktest\") == new\n\n    def test_move_file(self, path1):\n        p = path1.join(\"samplefile\")\n        newp = p.dirpath(\"moved_samplefile\")\n        p.move(newp)\n        try:\n            assert newp.check(file=1)\n            assert not p.check()\n        finally:\n            dp = newp.dirpath()\n            if hasattr(dp, \"revert\"):\n                dp.revert()\n            else:\n                newp.move(p)\n                assert p.check()\n\n    def test_move_dir(self, path1):\n        source = path1.join(\"sampledir\")\n        dest = path1.join(\"moveddir\")\n        source.move(dest)\n        assert dest.check(dir=1)\n        assert dest.join(\"otherfile\").check(file=1)\n        assert not source.join(\"sampledir\").check()\n\n    def test_fspath_protocol_match_strpath(self, path1):\n        assert path1.__fspath__() == path1.strpath\n\n    def test_fspath_func_match_strpath(self, path1):\n        from os import fspath\n\n        assert fspath(path1) == path1.strpath\n\n    def test_fspath_open(self, path1):\n        f = path1.join(\"samplefile\")\n        stream = open(f, encoding=\"utf-8\")\n        stream.close()\n\n    def test_fspath_fsencode(self, path1):\n        from os import fsencode\n\n        assert fsencode(path1) == fsencode(path1.strpath)\n\n\ndef setuptestfs(path):\n    if path.join(\"samplefile\").check():\n        return\n    # print \"setting up test fs for\", repr(path)\n    samplefile = path.ensure(\"samplefile\")\n    samplefile.write_text(\"samplefile\\n\", encoding=\"utf-8\")\n\n    execfile = path.ensure(\"execfile\")\n    execfile.write_text(\"x=42\", encoding=\"utf-8\")\n\n    execfilepy = path.ensure(\"execfile.py\")\n    execfilepy.write_text(\"x=42\", encoding=\"utf-8\")\n\n    d = {1: 2, \"hello\": \"world\", \"answer\": 42}\n    path.ensure(\"samplepickle\").dump(d)\n\n    sampledir = path.ensure(\"sampledir\", dir=1)\n    sampledir.ensure(\"otherfile\")\n\n    otherdir = path.ensure(\"otherdir\", dir=1)\n    otherdir.ensure(\"__init__.py\")\n\n    module_a = otherdir.ensure(\"a.py\")\n    module_a.write_text(\"from .b import stuff as result\\n\", encoding=\"utf-8\")\n    module_b = otherdir.ensure(\"b.py\")\n    module_b.write_text('stuff=\"got it\"\\n', encoding=\"utf-8\")\n    module_c = otherdir.ensure(\"c.py\")\n    module_c.write_text(\n        \"\"\"import py;\nimport otherdir.a\nvalue = otherdir.a.result\n\"\"\",\n        encoding=\"utf-8\",\n    )\n    module_d = otherdir.ensure(\"d.py\")\n    module_d.write_text(\n        \"\"\"import py;\nfrom otherdir import a\nvalue2 = a.result\n\"\"\",\n        encoding=\"utf-8\",\n    )\n\n\nwin32only = pytest.mark.skipif(\n    \"not (sys.platform == 'win32' or getattr(os, '_name', None) == 'nt')\"\n)\nskiponwin32 = pytest.mark.skipif(\n    \"sys.platform == 'win32' or getattr(os, '_name', None) == 'nt'\"\n)\n\nATIME_RESOLUTION = 0.01\n\n\n@pytest.fixture(scope=\"session\")\ndef path1(tmpdir_factory):\n    path = tmpdir_factory.mktemp(\"path\")\n    setuptestfs(path)\n    yield path\n    assert path.join(\"samplefile\").check()\n\n\n@pytest.fixture\ndef fake_fspath_obj(request):\n    class FakeFSPathClass:\n        def __init__(self, path):\n            self._path = path\n\n        def __fspath__(self):\n            return self._path\n\n    return FakeFSPathClass(os.path.join(\"this\", \"is\", \"a\", \"fake\", \"path\"))\n\n\ndef batch_make_numbered_dirs(rootdir, repeats):\n    for i in range(repeats):\n        dir_ = local.make_numbered_dir(prefix=\"repro-\", rootdir=rootdir)\n        file_ = dir_.join(\"foo\")\n        file_.write_text(f\"{i}\", encoding=\"utf-8\")\n        actual = int(file_.read_text(encoding=\"utf-8\"))\n        assert actual == i, (\n            f\"int(file_.read_text(encoding='utf-8')) is {actual} instead of {i}\"\n        )\n        dir_.join(\".lock\").remove(ignore_errors=True)\n    return True\n\n\nclass TestLocalPath(CommonFSTests):\n    def test_join_normpath(self, tmpdir):\n        assert tmpdir.join(\".\") == tmpdir\n        p = tmpdir.join(f\"../{tmpdir.basename}\")\n        assert p == tmpdir\n        p = tmpdir.join(f\"..//{tmpdir.basename}/\")\n        assert p == tmpdir\n\n    @skiponwin32\n    def test_dirpath_abs_no_abs(self, tmpdir):\n        p = tmpdir.join(\"foo\")\n        assert p.dirpath(\"/bar\") == tmpdir.join(\"bar\")\n        assert tmpdir.dirpath(\"/bar\", abs=True) == local(\"/bar\")\n\n    def test_gethash(self, tmpdir):\n        from hashlib import md5\n        from hashlib import sha1 as sha\n\n        fn = tmpdir.join(\"testhashfile\")\n        data = b\"hello\"\n        fn.write(data, mode=\"wb\")\n        assert fn.computehash(\"md5\") == md5(data).hexdigest()\n        assert fn.computehash(\"sha1\") == sha(data).hexdigest()\n        with pytest.raises(ValueError):\n            fn.computehash(\"asdasd\")\n\n    def test_remove_removes_readonly_file(self, tmpdir):\n        readonly_file = tmpdir.join(\"readonly\").ensure()\n        readonly_file.chmod(0)\n        readonly_file.remove()\n        assert not readonly_file.check(exists=1)\n\n    def test_remove_removes_readonly_dir(self, tmpdir):\n        readonly_dir = tmpdir.join(\"readonlydir\").ensure(dir=1)\n        readonly_dir.chmod(int(\"500\", 8))\n        readonly_dir.remove()\n        assert not readonly_dir.check(exists=1)\n\n    def test_remove_removes_dir_and_readonly_file(self, tmpdir):\n        readonly_dir = tmpdir.join(\"readonlydir\").ensure(dir=1)\n        readonly_file = readonly_dir.join(\"readonlyfile\").ensure()\n        readonly_file.chmod(0)\n        readonly_dir.remove()\n        assert not readonly_dir.check(exists=1)\n\n    def test_remove_routes_ignore_errors(self, tmpdir, monkeypatch):\n        lst = []\n        monkeypatch.setattr(\"shutil.rmtree\", lambda *args, **kwargs: lst.append(kwargs))\n        tmpdir.remove()\n        assert not lst[0][\"ignore_errors\"]\n        for val in (True, False):\n            lst[:] = []\n            tmpdir.remove(ignore_errors=val)\n            assert lst[0][\"ignore_errors\"] == val\n\n    def test_initialize_curdir(self):\n        assert str(local()) == os.getcwd()\n\n    @skiponwin32\n    def test_chdir_gone(self, path1):\n        p = path1.ensure(\"dir_to_be_removed\", dir=1)\n        p.chdir()\n        p.remove()\n        pytest.raises(error.ENOENT, local)\n        assert path1.chdir() is None\n        assert os.getcwd() == str(path1)\n\n        with pytest.raises(error.ENOENT):\n            with p.as_cwd():\n                raise NotImplementedError\n\n    @skiponwin32\n    def test_chdir_gone_in_as_cwd(self, path1):\n        p = path1.ensure(\"dir_to_be_removed\", dir=1)\n        p.chdir()\n        p.remove()\n\n        with path1.as_cwd() as old:\n            assert old is None\n\n    def test_as_cwd(self, path1):\n        dir = path1.ensure(\"subdir\", dir=1)\n        old = local()\n        with dir.as_cwd() as x:\n            assert x == old\n            assert local() == dir\n        assert os.getcwd() == str(old)\n\n    def test_as_cwd_exception(self, path1):\n        old = local()\n        dir = path1.ensure(\"subdir\", dir=1)\n        with pytest.raises(ValueError):\n            with dir.as_cwd():\n                raise ValueError()\n        assert old == local()\n\n    def test_initialize_reldir(self, path1):\n        with path1.as_cwd():\n            p = local(\"samplefile\")\n            assert p.check()\n\n    def test_tilde_expansion(self, monkeypatch, tmpdir):\n        monkeypatch.setenv(\"HOME\", str(tmpdir))\n        p = local(\"~\", expanduser=True)\n        assert p == os.path.expanduser(\"~\")\n\n    @pytest.mark.skipif(\n        not sys.platform.startswith(\"win32\"), reason=\"case-insensitive only on windows\"\n    )\n    def test_eq_hash_are_case_insensitive_on_windows(self):\n        a = local(\"/some/path\")\n        b = local(\"/some/PATH\")\n        assert a == b\n        assert hash(a) == hash(b)\n        assert a in {b}\n        assert a in {b: \"b\"}\n\n    def test_eq_with_strings(self, path1):\n        path1 = path1.join(\"sampledir\")\n        path2 = str(path1)\n        assert path1 == path2\n        assert path2 == path1\n        path3 = path1.join(\"samplefile\")\n        assert path3 != path2\n        assert path2 != path3\n\n    def test_eq_with_none(self, path1):\n        assert path1 != None  # noqa: E711\n\n    def test_eq_non_ascii_unicode(self, path1):\n        path2 = path1.join(\"temp\")\n        path3 = path1.join(\"ação\")\n        path4 = path1.join(\"ディレクトリ\")\n\n        assert path2 != path3\n        assert path2 != path4\n        assert path4 != path3\n\n    def test_gt_with_strings(self, path1):\n        path2 = path1.join(\"sampledir\")\n        path3 = str(path1.join(\"ttt\"))\n        assert path3 > path2\n        assert path2 < path3\n        assert path2 < \"ttt\"\n        assert \"ttt\" > path2\n        path4 = path1.join(\"aaa\")\n        lst = [path2, path4, path3]\n        assert sorted(lst) == [path4, path2, path3]\n\n    def test_open_and_ensure(self, path1):\n        p = path1.join(\"sub1\", \"sub2\", \"file\")\n        with p.open(\"w\", ensure=1, encoding=\"utf-8\") as f:\n            f.write(\"hello\")\n        assert p.read_text(encoding=\"utf-8\") == \"hello\"\n\n    def test_write_and_ensure(self, path1):\n        p = path1.join(\"sub1\", \"sub2\", \"file\")\n        p.write_text(\"hello\", ensure=1, encoding=\"utf-8\")\n        assert p.read_text(encoding=\"utf-8\") == \"hello\"\n\n    @pytest.mark.parametrize(\"bin\", (False, True))\n    def test_dump(self, tmpdir, bin):\n        path = tmpdir.join(f\"dumpfile{int(bin)}\")\n        try:\n            d = {\"answer\": 42}\n            path.dump(d, bin=bin)\n            f = path.open(\"rb+\")\n            import pickle\n\n            dnew = pickle.load(f)\n            assert d == dnew\n        finally:\n            f.close()\n\n    def test_setmtime(self):\n        import tempfile\n\n        fd, name = tempfile.mkstemp()\n        os.close(fd)\n        try:\n            # Do not use _pytest.timing here, as we do not want time mocking to affect this test.\n            mtime = int(time.time()) - 100\n            path = local(name)\n            assert path.mtime() != mtime\n            path.setmtime(mtime)\n            assert path.mtime() == mtime\n            path.setmtime()\n            assert path.mtime() != mtime\n        finally:\n            os.remove(name)\n\n    def test_normpath(self, path1):\n        new1 = path1.join(\"/otherdir\")\n        new2 = path1.join(\"otherdir\")\n        assert str(new1) == str(new2)\n\n    def test_mkdtemp_creation(self):\n        d = local.mkdtemp()\n        try:\n            assert d.check(dir=1)\n        finally:\n            d.remove(rec=1)\n\n    def test_tmproot(self):\n        d = local.mkdtemp()\n        tmproot = local.get_temproot()\n        try:\n            assert d.check(dir=1)\n            assert d.dirpath() == tmproot\n        finally:\n            d.remove(rec=1)\n\n    def test_chdir(self, tmpdir):\n        old = local()\n        try:\n            res = tmpdir.chdir()\n            assert str(res) == str(old)\n            assert os.getcwd() == str(tmpdir)\n        finally:\n            old.chdir()\n\n    def test_ensure_filepath_withdir(self, tmpdir):\n        newfile = tmpdir.join(\"test1\", \"test\")\n        newfile.ensure()\n        assert newfile.check(file=1)\n        newfile.write_text(\"42\", encoding=\"utf-8\")\n        newfile.ensure()\n        s = newfile.read_text(encoding=\"utf-8\")\n        assert s == \"42\"\n\n    def test_ensure_filepath_withoutdir(self, tmpdir):\n        newfile = tmpdir.join(\"test1file\")\n        t = newfile.ensure()\n        assert t == newfile\n        assert newfile.check(file=1)\n\n    def test_ensure_dirpath(self, tmpdir):\n        newfile = tmpdir.join(\"test1\", \"testfile\")\n        t = newfile.ensure(dir=1)\n        assert t == newfile\n        assert newfile.check(dir=1)\n\n    def test_ensure_non_ascii_unicode(self, tmpdir):\n        newfile = tmpdir.join(\"ação\", \"ディレクトリ\")\n        t = newfile.ensure(dir=1)\n        assert t == newfile\n        assert newfile.check(dir=1)\n\n    @pytest.mark.xfail(run=False, reason=\"unreliable est for long filenames\")\n    def test_long_filenames(self, tmpdir):\n        if sys.platform == \"win32\":\n            pytest.skip(\"win32: work around needed for path length limit\")\n        # see http://codespeak.net/pipermail/py-dev/2008q2/000922.html\n\n        # testing paths > 260 chars (which is Windows' limitation, but\n        # depending on how the paths are used), but > 4096 (which is the\n        # Linux' limitation) - the behaviour of paths with names > 4096 chars\n        # is undetermined\n        newfilename = \"/test\" * 60  # type:ignore[unreachable,unused-ignore]\n        l1 = tmpdir.join(newfilename)\n        l1.ensure(file=True)\n        l1.write_text(\"foo\", encoding=\"utf-8\")\n        l2 = tmpdir.join(newfilename)\n        assert l2.read_text(encoding=\"utf-8\") == \"foo\"\n\n    def test_visit_depth_first(self, tmpdir):\n        tmpdir.ensure(\"a\", \"1\")\n        tmpdir.ensure(\"b\", \"2\")\n        p3 = tmpdir.ensure(\"breadth\")\n        lst = list(tmpdir.visit(lambda x: x.check(file=1)))\n        assert len(lst) == 3\n        # check that breadth comes last\n        assert lst[2] == p3\n\n    def test_visit_rec_fnmatch(self, tmpdir):\n        p1 = tmpdir.ensure(\"a\", \"123\")\n        tmpdir.ensure(\".b\", \"345\")\n        lst = list(tmpdir.visit(\"???\", rec=\"[!.]*\"))\n        assert len(lst) == 1\n        # check that breadth comes last\n        assert lst[0] == p1\n\n    def test_fnmatch_file_abspath(self, tmpdir):\n        b = tmpdir.join(\"a\", \"b\")\n        assert b.fnmatch(os.sep.join(\"ab\"))\n        pattern = os.sep.join([str(tmpdir), \"*\", \"b\"])\n        assert b.fnmatch(pattern)\n\n    def test_sysfind(self):\n        name = (sys.platform == \"win32\" and \"cmd\") or \"test\"\n        x = local.sysfind(name)\n        assert x.check(file=1)\n        assert local.sysfind(\"jaksdkasldqwe\") is None\n        assert local.sysfind(name, paths=[]) is None\n        x2 = local.sysfind(name, paths=[x.dirpath()])\n        assert x2 == x\n\n    def test_fspath_protocol_other_class(self, fake_fspath_obj):\n        # py.path is always absolute\n        py_path = local(fake_fspath_obj)\n        str_path = fake_fspath_obj.__fspath__()\n        assert py_path.check(endswith=str_path)\n        assert py_path.join(fake_fspath_obj).strpath == os.path.join(\n            py_path.strpath, str_path\n        )\n\n    @pytest.mark.xfail(\n        reason=\"#11603\", raises=(error.EEXIST, error.ENOENT), strict=False\n    )\n    def test_make_numbered_dir_multiprocess_safe(self, tmpdir):\n        # https://github.com/pytest-dev/py/issues/30\n        with multiprocessing.Pool() as pool:\n            results = [\n                pool.apply_async(batch_make_numbered_dirs, [tmpdir, 100])\n                for _ in range(20)\n            ]\n            for r in results:\n                assert r.get()\n\n\nclass TestExecutionOnWindows:\n    pytestmark = win32only\n\n    def test_sysfind_bat_exe_before(self, tmpdir, monkeypatch):\n        monkeypatch.setenv(\"PATH\", str(tmpdir), prepend=os.pathsep)\n        tmpdir.ensure(\"hello\")\n        h = tmpdir.ensure(\"hello.bat\")\n        x = local.sysfind(\"hello\")\n        assert x == h\n\n\nclass TestExecution:\n    pytestmark = skiponwin32\n\n    def test_sysfind_no_permission_ignored(self, monkeypatch, tmpdir):\n        noperm = tmpdir.ensure(\"noperm\", dir=True)\n        monkeypatch.setenv(\"PATH\", str(noperm), prepend=\":\")\n        noperm.chmod(0)\n        try:\n            assert local.sysfind(\"jaksdkasldqwe\") is None\n        finally:\n            noperm.chmod(0o644)\n\n    def test_sysfind_absolute(self):\n        x = local.sysfind(\"test\")\n        assert x.check(file=1)\n        y = local.sysfind(str(x))\n        assert y.check(file=1)\n        assert y == x\n\n    def test_sysfind_multiple(self, tmpdir, monkeypatch):\n        monkeypatch.setenv(\n            \"PATH\", \"{}:{}\".format(tmpdir.ensure(\"a\"), tmpdir.join(\"b\")), prepend=\":\"\n        )\n        tmpdir.ensure(\"b\", \"a\")\n        x = local.sysfind(\"a\", checker=lambda x: x.dirpath().basename == \"b\")\n        assert x.basename == \"a\"\n        assert x.dirpath().basename == \"b\"\n        assert local.sysfind(\"a\", checker=lambda x: None) is None\n\n    def test_sysexec(self):\n        x = local.sysfind(\"ls\")\n        out = x.sysexec(\"-a\")\n        for x in local().listdir():\n            assert out.find(x.basename) != -1\n\n    def test_sysexec_failing(self):\n        try:\n            from py._process.cmdexec import ExecutionFailed  # py library\n        except ImportError:\n            ExecutionFailed = RuntimeError  # py vendored\n        x = local.sysfind(\"false\")\n        with pytest.raises(ExecutionFailed):\n            x.sysexec(\"aksjdkasjd\")\n\n    def test_make_numbered_dir(self, tmpdir):\n        tmpdir.ensure(\"base.not_an_int\", dir=1)\n        for i in range(10):\n            numdir = local.make_numbered_dir(\n                prefix=\"base.\", rootdir=tmpdir, keep=2, lock_timeout=0\n            )\n            assert numdir.check()\n            assert numdir.basename == f\"base.{i}\"\n            if i >= 1:\n                assert numdir.new(ext=str(i - 1)).check()\n            if i >= 2:\n                assert numdir.new(ext=str(i - 2)).check()\n            if i >= 3:\n                assert not numdir.new(ext=str(i - 3)).check()\n\n    def test_make_numbered_dir_case(self, tmpdir):\n        \"\"\"make_numbered_dir does not make assumptions on the underlying\n        filesystem based on the platform and will assume it _could_ be case\n        insensitive.\n\n        See issues:\n        - https://github.com/pytest-dev/pytest/issues/708\n        - https://github.com/pytest-dev/pytest/issues/3451\n        \"\"\"\n        d1 = local.make_numbered_dir(\n            prefix=\"CAse.\",\n            rootdir=tmpdir,\n            keep=2,\n            lock_timeout=0,\n        )\n        d2 = local.make_numbered_dir(\n            prefix=\"caSE.\",\n            rootdir=tmpdir,\n            keep=2,\n            lock_timeout=0,\n        )\n        assert str(d1).lower() != str(d2).lower()\n        assert str(d2).endswith(\".1\")\n\n    def test_make_numbered_dir_NotImplemented_Error(self, tmpdir, monkeypatch):\n        def notimpl(x, y):\n            raise NotImplementedError(42)\n\n        monkeypatch.setattr(os, \"symlink\", notimpl)\n        x = tmpdir.make_numbered_dir(rootdir=tmpdir, lock_timeout=0)\n        assert x.relto(tmpdir)\n        assert x.check()\n\n    def test_locked_make_numbered_dir(self, tmpdir):\n        for i in range(10):\n            numdir = local.make_numbered_dir(prefix=\"base2.\", rootdir=tmpdir, keep=2)\n            assert numdir.check()\n            assert numdir.basename == f\"base2.{i}\"\n            for j in range(i):\n                assert numdir.new(ext=str(j)).check()\n\n    def test_error_preservation(self, path1):\n        pytest.raises(EnvironmentError, path1.join(\"qwoeqiwe\").mtime)\n        pytest.raises(EnvironmentError, path1.join(\"qwoeqiwe\").read)\n\n    # def test_parentdirmatch(self):\n    #    local.parentdirmatch('std', startmodule=__name__)\n    #\n\n\nclass TestImport:\n    @pytest.fixture(autouse=True)\n    def preserve_sys(self):\n        with mock.patch.dict(sys.modules):\n            with mock.patch.object(sys, \"path\", list(sys.path)):\n                yield\n\n    def test_pyimport(self, path1):\n        obj = path1.join(\"execfile.py\").pyimport()\n        assert obj.x == 42\n        assert obj.__name__ == \"execfile\"\n\n    def test_pyimport_renamed_dir_creates_mismatch(self, tmpdir, monkeypatch):\n        p = tmpdir.ensure(\"a\", \"test_x123.py\")\n        p.pyimport()\n        tmpdir.join(\"a\").move(tmpdir.join(\"b\"))\n        with pytest.raises(tmpdir.ImportMismatchError):\n            tmpdir.join(\"b\", \"test_x123.py\").pyimport()\n\n        # Errors can be ignored.\n        monkeypatch.setenv(\"PY_IGNORE_IMPORTMISMATCH\", \"1\")\n        tmpdir.join(\"b\", \"test_x123.py\").pyimport()\n\n        # PY_IGNORE_IMPORTMISMATCH=0 does not ignore error.\n        monkeypatch.setenv(\"PY_IGNORE_IMPORTMISMATCH\", \"0\")\n        with pytest.raises(tmpdir.ImportMismatchError):\n            tmpdir.join(\"b\", \"test_x123.py\").pyimport()\n\n    def test_pyimport_messy_name(self, tmpdir):\n        # http://bitbucket.org/hpk42/py-trunk/issue/129\n        path = tmpdir.ensure(\"foo__init__.py\")\n        path.pyimport()\n\n    def test_pyimport_dir(self, tmpdir):\n        p = tmpdir.join(\"hello_123\")\n        p_init = p.ensure(\"__init__.py\")\n        m = p.pyimport()\n        assert m.__name__ == \"hello_123\"\n        m = p_init.pyimport()\n        assert m.__name__ == \"hello_123\"\n\n    def test_pyimport_execfile_different_name(self, path1):\n        obj = path1.join(\"execfile.py\").pyimport(modname=\"0x.y.z\")\n        assert obj.x == 42\n        assert obj.__name__ == \"0x.y.z\"\n\n    def test_pyimport_a(self, path1):\n        otherdir = path1.join(\"otherdir\")\n        mod = otherdir.join(\"a.py\").pyimport()\n        assert mod.result == \"got it\"\n        assert mod.__name__ == \"otherdir.a\"\n\n    def test_pyimport_b(self, path1):\n        otherdir = path1.join(\"otherdir\")\n        mod = otherdir.join(\"b.py\").pyimport()\n        assert mod.stuff == \"got it\"\n        assert mod.__name__ == \"otherdir.b\"\n\n    def test_pyimport_c(self, path1):\n        otherdir = path1.join(\"otherdir\")\n        mod = otherdir.join(\"c.py\").pyimport()\n        assert mod.value == \"got it\"\n\n    def test_pyimport_d(self, path1):\n        otherdir = path1.join(\"otherdir\")\n        mod = otherdir.join(\"d.py\").pyimport()\n        assert mod.value2 == \"got it\"\n\n    def test_pyimport_and_import(self, tmpdir):\n        tmpdir.ensure(\"xxxpackage\", \"__init__.py\")\n        mod1path = tmpdir.ensure(\"xxxpackage\", \"module1.py\")\n        mod1 = mod1path.pyimport()\n        assert mod1.__name__ == \"xxxpackage.module1\"\n        from xxxpackage import module1\n\n        assert module1 is mod1\n\n    def test_pyimport_check_filepath_consistency(self, monkeypatch, tmpdir):\n        name = \"pointsback123\"\n        ModuleType = type(os)\n        p = tmpdir.ensure(name + \".py\")\n        with monkeypatch.context() as mp:\n            for ending in (\".pyc\", \"$py.class\", \".pyo\"):\n                mod = ModuleType(name)\n                pseudopath = tmpdir.ensure(name + ending)\n                mod.__file__ = str(pseudopath)\n                mp.setitem(sys.modules, name, mod)\n                newmod = p.pyimport()\n                assert mod == newmod\n        mod = ModuleType(name)\n        pseudopath = tmpdir.ensure(name + \"123.py\")\n        mod.__file__ = str(pseudopath)\n        monkeypatch.setitem(sys.modules, name, mod)\n        excinfo = pytest.raises(pseudopath.ImportMismatchError, p.pyimport)\n        modname, modfile, orig = excinfo.value.args\n        assert modname == name\n        assert modfile == pseudopath\n        assert orig == p\n        assert issubclass(pseudopath.ImportMismatchError, ImportError)\n\n    def test_issue131_pyimport_on__init__(self, tmpdir):\n        # __init__.py files may be namespace packages, and thus the\n        # __file__ of an imported module may not be ourselves\n        # see issue\n        p1 = tmpdir.ensure(\"proja\", \"__init__.py\")\n        p2 = tmpdir.ensure(\"sub\", \"proja\", \"__init__.py\")\n        m1 = p1.pyimport()\n        m2 = p2.pyimport()\n        assert m1 == m2\n\n    def test_ensuresyspath_append(self, tmpdir):\n        root1 = tmpdir.mkdir(\"root1\")\n        file1 = root1.ensure(\"x123.py\")\n        assert str(root1) not in sys.path\n        file1.pyimport(ensuresyspath=\"append\")\n        assert str(root1) == sys.path[-1]\n        assert str(root1) not in sys.path[:-1]\n\n\nclass TestImportlibImport:\n    OPTS = {\"ensuresyspath\": \"importlib\"}\n\n    def test_pyimport(self, path1):\n        obj = path1.join(\"execfile.py\").pyimport(**self.OPTS)\n        assert obj.x == 42\n        assert obj.__name__ == \"execfile\"\n\n    def test_pyimport_dir_fails(self, tmpdir):\n        p = tmpdir.join(\"hello_123\")\n        p.ensure(\"__init__.py\")\n        with pytest.raises(ImportError):\n            p.pyimport(**self.OPTS)\n\n    def test_pyimport_execfile_different_name(self, path1):\n        obj = path1.join(\"execfile.py\").pyimport(modname=\"0x.y.z\", **self.OPTS)\n        assert obj.x == 42\n        assert obj.__name__ == \"0x.y.z\"\n\n    def test_pyimport_relative_import_fails(self, path1):\n        otherdir = path1.join(\"otherdir\")\n        with pytest.raises(ImportError):\n            otherdir.join(\"a.py\").pyimport(**self.OPTS)\n\n    def test_pyimport_doesnt_use_sys_modules(self, tmpdir):\n        p = tmpdir.ensure(\"file738jsk.py\")\n        mod = p.pyimport(**self.OPTS)\n        assert mod.__name__ == \"file738jsk\"\n        assert \"file738jsk\" not in sys.modules\n\n\ndef test_pypkgdir(tmpdir):\n    pkg = tmpdir.ensure(\"pkg1\", dir=1)\n    pkg.ensure(\"__init__.py\")\n    pkg.ensure(\"subdir/__init__.py\")\n    assert pkg.pypkgpath() == pkg\n    assert pkg.join(\"subdir\", \"__init__.py\").pypkgpath() == pkg\n\n\ndef test_pypkgdir_unimportable(tmpdir):\n    pkg = tmpdir.ensure(\"pkg1-1\", dir=1)  # unimportable\n    pkg.ensure(\"__init__.py\")\n    subdir = pkg.ensure(\"subdir/__init__.py\").dirpath()\n    assert subdir.pypkgpath() == subdir\n    assert subdir.ensure(\"xyz.py\").pypkgpath() == subdir\n    assert not pkg.pypkgpath()\n\n\ndef test_isimportable():\n    try:\n        from py.path import isimportable  # py vendored version\n    except ImportError:\n        from py._path.local import isimportable  # py library\n\n    assert not isimportable(\"\")\n    assert isimportable(\"x\")\n    assert isimportable(\"x1\")\n    assert isimportable(\"x_1\")\n    assert isimportable(\"_\")\n    assert isimportable(\"_1\")\n    assert not isimportable(\"x-1\")\n    assert not isimportable(\"x:1\")\n\n\ndef test_homedir_from_HOME(monkeypatch):\n    path = os.getcwd()\n    monkeypatch.setenv(\"HOME\", path)\n    assert local._gethomedir() == local(path)\n\n\ndef test_homedir_not_exists(monkeypatch):\n    monkeypatch.delenv(\"HOME\", raising=False)\n    monkeypatch.delenv(\"HOMEDRIVE\", raising=False)\n    homedir = local._gethomedir()\n    assert homedir is None\n\n\ndef test_samefile(tmpdir):\n    assert tmpdir.samefile(tmpdir)\n    p = tmpdir.ensure(\"hello\")\n    assert p.samefile(p)\n    with p.dirpath().as_cwd():\n        assert p.samefile(p.basename)\n    if sys.platform == \"win32\":\n        p1 = p.__class__(str(p).lower())\n        p2 = p.__class__(str(p).upper())\n        assert p1.samefile(p2)\n\n\n@pytest.mark.skipif(not hasattr(os, \"symlink\"), reason=\"os.symlink not available\")\ndef test_samefile_symlink(tmpdir):\n    p1 = tmpdir.ensure(\"foo.txt\")\n    p2 = tmpdir.join(\"linked.txt\")\n    try:\n        os.symlink(str(p1), str(p2))\n    except (OSError, NotImplementedError) as e:\n        # on Windows this might fail if the user doesn't have special symlink permissions\n        # pypy3 on Windows doesn't implement os.symlink and raises NotImplementedError\n        pytest.skip(str(e.args[0]))\n\n    assert p1.samefile(p2)\n\n\ndef test_listdir_single_arg(tmpdir):\n    tmpdir.ensure(\"hello\")\n    assert tmpdir.listdir(\"hello\")[0].basename == \"hello\"\n\n\ndef test_mkdtemp_rootdir(tmpdir):\n    dtmp = local.mkdtemp(rootdir=tmpdir)\n    assert tmpdir.listdir() == [dtmp]\n\n\nclass TestWINLocalPath:\n    pytestmark = win32only\n\n    def test_owner_group_not_implemented(self, path1):\n        with pytest.raises(NotImplementedError):\n            _ = path1.stat().owner\n        with pytest.raises(NotImplementedError):\n            _ = path1.stat().group\n\n    def test_chmod_simple_int(self, path1):\n        mode = path1.stat().mode\n        # Ensure that we actually change the mode to something different.\n        path1.chmod((mode == 0 and 1) or 0)\n        try:\n            print(path1.stat().mode)\n            print(mode)\n            assert path1.stat().mode != mode\n        finally:\n            path1.chmod(mode)\n            assert path1.stat().mode == mode\n\n    def test_path_comparison_lowercase_mixed(self, path1):\n        t1 = path1.join(\"a_path\")\n        t2 = path1.join(\"A_path\")\n        assert t1 == t1\n        assert t1 == t2\n\n    def test_relto_with_mixed_case(self, path1):\n        t1 = path1.join(\"a_path\", \"fiLe\")\n        t2 = path1.join(\"A_path\")\n        assert t1.relto(t2) == \"fiLe\"\n\n    def test_allow_unix_style_paths(self, path1):\n        t1 = path1.join(\"a_path\")\n        assert t1 == str(path1) + \"\\\\a_path\"\n        t1 = path1.join(\"a_path/\")\n        assert t1 == str(path1) + \"\\\\a_path\"\n        t1 = path1.join(\"dir/a_path\")\n        assert t1 == str(path1) + \"\\\\dir\\\\a_path\"\n\n    def test_sysfind_in_currentdir(self, path1):\n        cmd = local.sysfind(\"cmd\")\n        root = cmd.new(dirname=\"\", basename=\"\")  # c:\\ in most installations\n        with root.as_cwd():\n            x = local.sysfind(cmd.relto(root))\n            assert x.check(file=1)\n\n    def test_fnmatch_file_abspath_posix_pattern_on_win32(self, tmpdir):\n        # path-matching patterns might contain a posix path separator '/'\n        # Test that we can match that pattern on windows.\n        import posixpath\n\n        b = tmpdir.join(\"a\", \"b\")\n        assert b.fnmatch(posixpath.sep.join(\"ab\"))\n        pattern = posixpath.sep.join([str(tmpdir), \"*\", \"b\"])\n        assert b.fnmatch(pattern)\n\n\nclass TestPOSIXLocalPath:\n    pytestmark = skiponwin32\n\n    def test_hardlink(self, tmpdir):\n        linkpath = tmpdir.join(\"test\")\n        filepath = tmpdir.join(\"file\")\n        filepath.write_text(\"Hello\", encoding=\"utf-8\")\n        nlink = filepath.stat().nlink\n        linkpath.mklinkto(filepath)\n        assert filepath.stat().nlink == nlink + 1\n\n    def test_symlink_are_identical(self, tmpdir):\n        filepath = tmpdir.join(\"file\")\n        filepath.write_text(\"Hello\", encoding=\"utf-8\")\n        linkpath = tmpdir.join(\"test\")\n        linkpath.mksymlinkto(filepath)\n        assert linkpath.readlink() == str(filepath)\n\n    def test_symlink_isfile(self, tmpdir):\n        linkpath = tmpdir.join(\"test\")\n        filepath = tmpdir.join(\"file\")\n        filepath.write_text(\"\", encoding=\"utf-8\")\n        linkpath.mksymlinkto(filepath)\n        assert linkpath.check(file=1)\n        assert not linkpath.check(link=0, file=1)\n        assert linkpath.islink()\n\n    def test_symlink_relative(self, tmpdir):\n        linkpath = tmpdir.join(\"test\")\n        filepath = tmpdir.join(\"file\")\n        filepath.write_text(\"Hello\", encoding=\"utf-8\")\n        linkpath.mksymlinkto(filepath, absolute=False)\n        assert linkpath.readlink() == \"file\"\n        assert filepath.read_text(encoding=\"utf-8\") == linkpath.read_text(\n            encoding=\"utf-8\"\n        )\n\n    def test_symlink_not_existing(self, tmpdir):\n        linkpath = tmpdir.join(\"testnotexisting\")\n        assert not linkpath.check(link=1)\n        assert linkpath.check(link=0)\n\n    def test_relto_with_root(self, path1, tmpdir):\n        y = path1.join(\"x\").relto(local(\"/\"))\n        assert y[0] == str(path1)[1]\n\n    def test_visit_recursive_symlink(self, tmpdir):\n        linkpath = tmpdir.join(\"test\")\n        linkpath.mksymlinkto(tmpdir)\n        visitor = tmpdir.visit(None, lambda x: x.check(link=0))\n        assert list(visitor) == [linkpath]\n\n    def test_symlink_isdir(self, tmpdir):\n        linkpath = tmpdir.join(\"test\")\n        linkpath.mksymlinkto(tmpdir)\n        assert linkpath.check(dir=1)\n        assert not linkpath.check(link=0, dir=1)\n\n    def test_symlink_remove(self, tmpdir):\n        linkpath = tmpdir.join(\"test\")\n        linkpath.mksymlinkto(linkpath)  # point to itself\n        assert linkpath.check(link=1)\n        linkpath.remove()\n        assert not linkpath.check()\n\n    def test_realpath_file(self, tmpdir):\n        linkpath = tmpdir.join(\"test\")\n        filepath = tmpdir.join(\"file\")\n        filepath.write_text(\"\", encoding=\"utf-8\")\n        linkpath.mksymlinkto(filepath)\n        realpath = linkpath.realpath()\n        assert realpath.basename == \"file\"\n\n    def test_owner(self, path1, tmpdir):\n        from grp import getgrgid  # type:ignore[attr-defined,unused-ignore]\n        from pwd import getpwuid  # type:ignore[attr-defined,unused-ignore]\n\n        stat = path1.stat()\n        assert stat.path == path1\n\n        uid = stat.uid\n        gid = stat.gid\n        owner = getpwuid(uid)[0]\n        group = getgrgid(gid)[0]\n\n        assert uid == stat.uid\n        assert owner == stat.owner\n        assert gid == stat.gid\n        assert group == stat.group\n\n    def test_stat_helpers(self, tmpdir, monkeypatch):\n        path1 = tmpdir.ensure(\"file\")\n        stat1 = path1.stat()\n        stat2 = tmpdir.stat()\n        assert stat1.isfile()\n        assert stat2.isdir()\n        assert not stat1.islink()\n        assert not stat2.islink()\n\n    def test_stat_non_raising(self, tmpdir):\n        path1 = tmpdir.join(\"file\")\n        pytest.raises(error.ENOENT, lambda: path1.stat())\n        res = path1.stat(raising=False)\n        assert res is None\n\n    def test_atime(self, tmpdir):\n        import time\n\n        path = tmpdir.ensure(\"samplefile\")\n        # Do not use _pytest.timing here, as we do not want time mocking to affect this test.\n        now = time.time()\n        atime1 = path.atime()\n        # we could wait here but timer resolution is very\n        # system dependent\n        path.read_binary()\n        time.sleep(ATIME_RESOLUTION)\n        atime2 = path.atime()\n        time.sleep(ATIME_RESOLUTION)\n        duration = time.time() - now\n        assert (atime2 - atime1) <= duration\n\n    def test_commondir(self, path1):\n        # XXX This is here in local until we find a way to implement this\n        #     using the subversion command line api.\n        p1 = path1.join(\"something\")\n        p2 = path1.join(\"otherthing\")\n        assert p1.common(p2) == path1\n        assert p2.common(p1) == path1\n\n    def test_commondir_nocommon(self, path1):\n        # XXX This is here in local until we find a way to implement this\n        #     using the subversion command line api.\n        p1 = path1.join(\"something\")\n        p2 = local(path1.sep + \"blabla\")\n        assert p1.common(p2) == \"/\"\n\n    def test_join_to_root(self, path1):\n        root = path1.parts()[0]\n        assert len(str(root)) == 1\n        assert str(root.join(\"a\")) == \"/a\"\n\n    def test_join_root_to_root_with_no_abs(self, path1):\n        nroot = path1.join(\"/\")\n        assert str(path1) == str(nroot)\n        assert path1 == nroot\n\n    def test_chmod_simple_int(self, path1):\n        mode = path1.stat().mode\n        path1.chmod(int(mode / 2))\n        try:\n            assert path1.stat().mode != mode\n        finally:\n            path1.chmod(mode)\n            assert path1.stat().mode == mode\n\n    def test_chmod_rec_int(self, path1):\n        # XXX fragile test\n        def recfilter(x):\n            return x.check(dotfile=0, link=0)\n\n        oldmodes = {}\n        for x in path1.visit(rec=recfilter):\n            oldmodes[x] = x.stat().mode\n        path1.chmod(int(\"772\", 8), rec=recfilter)\n        try:\n            for x in path1.visit(rec=recfilter):\n                assert x.stat().mode & int(\"777\", 8) == int(\"772\", 8)\n        finally:\n            for x, y in oldmodes.items():\n                x.chmod(y)\n\n    def test_copy_archiving(self, tmpdir):\n        unicode_fn = \"something-\\342\\200\\223.txt\"\n        f = tmpdir.ensure(\"a\", unicode_fn)\n        a = f.dirpath()\n        oldmode = f.stat().mode\n        newmode = oldmode ^ 1\n        f.chmod(newmode)\n        b = tmpdir.join(\"b\")\n        a.copy(b, mode=True)\n        assert b.join(f.basename).stat().mode == newmode\n\n    def test_copy_stat_file(self, tmpdir):\n        src = tmpdir.ensure(\"src\")\n        dst = tmpdir.join(\"dst\")\n        # a small delay before the copy\n        time.sleep(ATIME_RESOLUTION)\n        src.copy(dst, stat=True)\n        oldstat = src.stat()\n        newstat = dst.stat()\n        assert oldstat.mode == newstat.mode\n        assert (dst.atime() - src.atime()) < ATIME_RESOLUTION\n        assert (dst.mtime() - src.mtime()) < ATIME_RESOLUTION\n\n    def test_copy_stat_dir(self, tmpdir):\n        test_files = [\"a\", \"b\", \"c\"]\n        src = tmpdir.join(\"src\")\n        for f in test_files:\n            src.join(f).write_text(f, ensure=True, encoding=\"utf-8\")\n        dst = tmpdir.join(\"dst\")\n        # a small delay before the copy\n        time.sleep(ATIME_RESOLUTION)\n        src.copy(dst, stat=True)\n        for f in test_files:\n            oldstat = src.join(f).stat()\n            newstat = dst.join(f).stat()\n            assert (newstat.atime - oldstat.atime) < ATIME_RESOLUTION\n            assert (newstat.mtime - oldstat.mtime) < ATIME_RESOLUTION\n            assert oldstat.mode == newstat.mode\n\n    def test_chown_identity(self, path1):\n        owner = path1.stat().owner\n        group = path1.stat().group\n        path1.chown(owner, group)\n\n    def test_chown_dangling_link(self, path1):\n        owner = path1.stat().owner\n        group = path1.stat().group\n        x = path1.join(\"hello\")\n        x.mksymlinkto(\"qlwkejqwlek\")\n        try:\n            path1.chown(owner, group, rec=1)\n        finally:\n            x.remove(rec=0)\n\n    def test_chown_identity_rec_mayfail(self, path1):\n        owner = path1.stat().owner\n        group = path1.stat().group\n        path1.chown(owner, group)\n\n\nclass TestUnicode:\n    def test_join_ensure(self, tmpdir, monkeypatch):\n        if \"LANG\" not in os.environ:\n            pytest.skip(\"cannot run test without locale\")\n        x = local(tmpdir.strpath)\n        part = \"hällo\"\n        y = x.ensure(part)\n        assert x.join(part) == y\n\n    def test_listdir(self, tmpdir):\n        if \"LANG\" not in os.environ:\n            pytest.skip(\"cannot run test without locale\")\n        x = local(tmpdir.strpath)\n        part = \"hällo\"\n        y = x.ensure(part)\n        assert x.listdir(part)[0] == y\n\n    @pytest.mark.xfail(reason=\"changing read/write might break existing usages\")\n    def test_read_write(self, tmpdir):\n        x = tmpdir.join(\"hello\")\n        part = \"hällo\"\n        with ignore_encoding_warning():\n            x.write(part)\n            assert x.read() == part\n            x.write(part.encode(sys.getdefaultencoding()))\n            assert x.read() == part.encode(sys.getdefaultencoding())\n\n\nclass TestBinaryAndTextMethods:\n    def test_read_binwrite(self, tmpdir):\n        x = tmpdir.join(\"hello\")\n        part = \"hällo\"\n        part_utf8 = part.encode(\"utf8\")\n        x.write_binary(part_utf8)\n        assert x.read_binary() == part_utf8\n        s = x.read_text(encoding=\"utf8\")\n        assert s == part\n        assert isinstance(s, str)\n\n    def test_read_textwrite(self, tmpdir):\n        x = tmpdir.join(\"hello\")\n        part = \"hällo\"\n        part_utf8 = part.encode(\"utf8\")\n        x.write_text(part, encoding=\"utf8\")\n        assert x.read_binary() == part_utf8\n        assert x.read_text(encoding=\"utf8\") == part\n\n    def test_default_encoding(self, tmpdir):\n        x = tmpdir.join(\"hello\")\n        # Can't use UTF8 as the default encoding (ASCII) doesn't support it\n        part = \"hello\"\n        x.write_text(part, \"ascii\")\n        s = x.read_text(\"ascii\")\n        assert s == part\n        assert type(s) is type(part)\n"
  },
  {
    "path": "testing/acceptance_test.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nimport dataclasses\nimport importlib.metadata\nimport os\nfrom pathlib import Path\nimport subprocess\nimport sys\nimport types\n\nimport setuptools\n\nfrom _pytest.config import ExitCode\nfrom _pytest.pathlib import symlink_or_skip\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\ndef prepend_pythonpath(*dirs) -> str:\n    cur = os.getenv(\"PYTHONPATH\")\n    if cur:\n        dirs += (cur,)\n    return os.pathsep.join(str(p) for p in dirs)\n\n\nclass TestGeneralUsage:\n    def test_config_error(self, pytester: Pytester) -> None:\n        pytester.copy_example(\"conftest_usageerror/conftest.py\")\n        result = pytester.runpytest(pytester.path)\n        assert result.ret == ExitCode.USAGE_ERROR\n        result.stderr.fnmatch_lines([\"*ERROR: hello\"])\n        result.stdout.fnmatch_lines([\"*pytest_unconfigure_called\"])\n\n    def test_root_conftest_syntax_error(self, pytester: Pytester) -> None:\n        pytester.makepyfile(conftest=\"raise SyntaxError\\n\")\n        result = pytester.runpytest()\n        result.stderr.fnmatch_lines([\"*raise SyntaxError*\"])\n        assert result.ret != 0\n\n    def test_early_hook_error_issue38_1(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_sessionstart():\n                0 / 0\n        \"\"\"\n        )\n        result = pytester.runpytest(pytester.path)\n        assert result.ret != 0\n        # tracestyle is native by default for hook failures\n        result.stdout.fnmatch_lines(\n            [\"*INTERNALERROR*File*conftest.py*line 2*\", \"*0 / 0*\"]\n        )\n        result = pytester.runpytest(pytester.path, \"--fulltrace\")\n        assert result.ret != 0\n        # tracestyle is native by default for hook failures\n        result.stdout.fnmatch_lines(\n            [\"*INTERNALERROR*def pytest_sessionstart():*\", \"*INTERNALERROR*0 / 0*\"]\n        )\n\n    def test_early_hook_configure_error_issue38(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_configure():\n                0 / 0\n        \"\"\"\n        )\n        result = pytester.runpytest(pytester.path)\n        assert result.ret != 0\n        # here we get it on stderr\n        result.stderr.fnmatch_lines(\n            [\"*INTERNALERROR*File*conftest.py*line 2*\", \"*0 / 0*\"]\n        )\n\n    def test_file_not_found(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"asd\")\n        assert result.ret != 0\n        result.stderr.fnmatch_lines([\"ERROR: file or directory not found: asd\"])\n\n    def test_file_not_found_unconfigure_issue143(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_configure():\n                print(\"---configure\")\n            def pytest_unconfigure():\n                print(\"---unconfigure\")\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\", \"asd\")\n        assert result.ret == ExitCode.USAGE_ERROR\n        result.stderr.fnmatch_lines([\"ERROR: file or directory not found: asd\"])\n        result.stdout.fnmatch_lines([\"*---configure\", \"*---unconfigure\"])\n\n    def test_config_preparse_plugin_option(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            pytest_xyz=\"\"\"\n            def pytest_addoption(parser):\n                parser.addoption(\"--xyz\", dest=\"xyz\", action=\"store\")\n        \"\"\"\n        )\n        pytester.makepyfile(\n            test_one=\"\"\"\n            def test_option(pytestconfig):\n                assert pytestconfig.option.xyz == \"123\"\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-p\", \"pytest_xyz\", \"--xyz=123\", syspathinsert=True)\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    @pytest.mark.parametrize(\"load_cov_early\", [True, False])\n    def test_early_load_setuptools_name(\n        self, pytester: Pytester, monkeypatch, load_cov_early\n    ) -> None:\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\")\n\n        pytester.makepyfile(mytestplugin1_module=\"\")\n        pytester.makepyfile(mytestplugin2_module=\"\")\n        pytester.makepyfile(mycov_module=\"\")\n        pytester.syspathinsert()\n\n        loaded = []\n\n        @dataclasses.dataclass\n        class DummyEntryPoint:\n            name: str\n            module: str\n            group: str = \"pytest11\"\n\n            def load(self):\n                mod = importlib.import_module(self.module)\n                loaded.append(self.name)\n                return mod\n\n        entry_points = [\n            DummyEntryPoint(\"myplugin1\", \"mytestplugin1_module\"),\n            DummyEntryPoint(\"myplugin2\", \"mytestplugin2_module\"),\n            DummyEntryPoint(\"mycov\", \"mycov_module\"),\n        ]\n\n        @dataclasses.dataclass\n        class DummyDist:\n            entry_points: object\n            files: object = ()\n\n        def my_dists():\n            return (DummyDist(entry_points),)\n\n        monkeypatch.setattr(importlib.metadata, \"distributions\", my_dists)\n        params = (\"-p\", \"mycov\") if load_cov_early else ()\n        pytester.runpytest_inprocess(*params)\n        if load_cov_early:\n            assert loaded == [\"mycov\", \"myplugin1\", \"myplugin2\"]\n        else:\n            assert loaded == [\"myplugin1\", \"myplugin2\", \"mycov\"]\n\n    @pytest.mark.parametrize(\"import_mode\", [\"prepend\", \"append\", \"importlib\"])\n    def test_assertion_rewrite(self, pytester: Pytester, import_mode) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_this():\n                x = 0\n                assert x\n        \"\"\"\n        )\n        result = pytester.runpytest(p, f\"--import-mode={import_mode}\")\n        result.stdout.fnmatch_lines([\">       assert x\", \"E       assert 0\"])\n        assert result.ret == 1\n\n    def test_nested_import_error(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n                import import_fails\n                def test_this():\n                    assert import_fails.a == 1\n        \"\"\"\n        )\n        pytester.makepyfile(import_fails=\"import does_not_work\")\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines(\n            [\n                \"ImportError while importing test module*\",\n                \"*No module named *does_not_work*\",\n            ]\n        )\n        assert result.ret == 2\n\n    def test_not_collectable_arguments(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\"\")\n        p2 = pytester.makefile(\".pyc\", \"123\")\n        result = pytester.runpytest(p1, p2)\n        assert result.ret == ExitCode.USAGE_ERROR\n        result.stderr.fnmatch_lines(\n            [\n                f\"ERROR: not found: {p2}\",\n                \"(no match in any of *)\",\n                \"\",\n            ]\n        )\n\n    @pytest.mark.filterwarnings(\"default\")\n    def test_better_reporting_on_conftest_load_failure(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Show a user-friendly traceback on conftest import failures (#486, #3332)\"\"\"\n        pytester.makepyfile(\"\")\n        conftest = pytester.makeconftest(\n            \"\"\"\n            def foo():\n                import qwerty\n            foo()\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--help\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *--version*\n            *warning*conftest.py*\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.stdout.lines == []\n        assert result.stderr.lines == [\n            f\"ImportError while loading conftest '{conftest}'.\",\n            \"conftest.py:3: in <module>\",\n            \"    foo()\",\n            \"conftest.py:2: in foo\",\n            \"    import qwerty\",\n            \"E   ModuleNotFoundError: No module named 'qwerty'\",\n        ]\n\n    def test_early_skip(self, pytester: Pytester) -> None:\n        pytester.mkdir(\"xyz\")\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            def pytest_collect_file():\n                pytest.skip(\"early\")\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n        result.stdout.fnmatch_lines([\"*1 skip*\"])\n\n    def test_issue88_initial_file_multinodes(self, pytester: Pytester) -> None:\n        pytester.copy_example(\"issue88_initial_file_multinodes\")\n        p = pytester.makepyfile(\"def test_hello(): pass\")\n        result = pytester.runpytest(p, \"--collect-only\")\n        result.stdout.fnmatch_lines([\"*MyFile*test_issue88*\", \"*Module*test_issue88*\"])\n\n    def test_issue93_initialnode_importing_capturing(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import sys\n            print(\"should not be seen\")\n            sys.stderr.write(\"stder42\\\\n\")\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n        result.stdout.no_fnmatch_line(\"*should not be seen*\")\n        assert \"stderr42\" not in result.stderr.str()\n\n    def test_conftest_printing_shows_if_error(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            print(\"should be seen\")\n            assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret != 0\n        assert \"should be seen\" in result.stdout.str()\n\n    def test_issue109_sibling_conftests_not_loaded(self, pytester: Pytester) -> None:\n        sub1 = pytester.mkdir(\"sub1\")\n        sub2 = pytester.mkdir(\"sub2\")\n        sub1.joinpath(\"conftest.py\").write_text(\"assert 0\", encoding=\"utf-8\")\n        result = pytester.runpytest(sub2)\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n        sub2.joinpath(\"__init__.py\").touch()\n        p = sub2.joinpath(\"test_hello.py\")\n        p.touch()\n        result = pytester.runpytest(p)\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n        result = pytester.runpytest(sub1)\n        assert result.ret == ExitCode.USAGE_ERROR\n\n    def test_directory_skipped(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            def pytest_ignore_collect():\n                pytest.skip(\"intentional\")\n        \"\"\"\n        )\n        pytester.makepyfile(\"def test_hello(): pass\")\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n        result.stdout.fnmatch_lines([\"*1 skipped*\"])\n\n    def test_multiple_items_per_collector_byid(self, pytester: Pytester) -> None:\n        c = pytester.makeconftest(\n            \"\"\"\n            import pytest\n            class MyItem(pytest.Item):\n                def runtest(self):\n                    pass\n            class MyCollector(pytest.File):\n                def collect(self):\n                    return [MyItem.from_parent(name=\"xyz\", parent=self)]\n            def pytest_collect_file(file_path, parent):\n                if file_path.name.startswith(\"conftest\"):\n                    return MyCollector.from_parent(path=file_path, parent=parent)\n        \"\"\"\n        )\n        result = pytester.runpytest(c.name + \"::\" + \"xyz\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*1 pass*\"])\n\n    def test_skip_on_generated_funcarg_id(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize('x', [3], ids=['hello-123'])\n            def pytest_runtest_setup(item):\n                print(item.keywords)\n                if 'hello-123' in item.keywords:\n                    pytest.skip(\"hello\")\n                assert 0\n        \"\"\"\n        )\n        p = pytester.makepyfile(\"\"\"def test_func(x): pass\"\"\")\n        res = pytester.runpytest(p)\n        assert res.ret == 0\n        res.stdout.fnmatch_lines([\"*1 skipped*\"])\n\n    def test_direct_addressing_selects(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize('i', [1, 2], ids=[\"1\", \"2\"])\n            def test_func(i):\n                pass\n        \"\"\"\n        )\n        res = pytester.runpytest(p.name + \"::\" + \"test_func[1]\")\n        assert res.ret == 0\n        res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_direct_addressing_selects_duplicates(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"a\", [1, 2, 10, 11, 2, 1, 12, 11])\n            def test_func(a):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.assert_outcomes(failed=0, passed=8)\n\n    def test_direct_addressing_selects_duplicates_1(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"a\", [1, 2, 10, 11, 2, 1, 12, 1_1,2_1])\n            def test_func(a):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.assert_outcomes(failed=0, passed=9)\n\n    def test_direct_addressing_selects_duplicates_2(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"a\", [\"a\",\"b\",\"c\",\"a\",\"a1\"])\n            def test_func(a):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.assert_outcomes(failed=0, passed=5)\n\n    def test_direct_addressing_notfound(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_func():\n                pass\n        \"\"\"\n        )\n        res = pytester.runpytest(p.name + \"::\" + \"test_notfound\")\n        assert res.ret\n        res.stderr.fnmatch_lines([\"*ERROR*not found*\"])\n\n    def test_docstring_on_hookspec(self) -> None:\n        from _pytest import hookspec\n\n        for name, value in vars(hookspec).items():\n            if name.startswith(\"pytest_\"):\n                assert value.__doc__, f\"no docstring for {name}\"\n\n    def test_initialization_error_issue49(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_configure():\n                x\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 3  # internal error\n        result.stderr.fnmatch_lines([\"INTERNAL*pytest_configure*\", \"INTERNAL*x*\"])\n        assert \"sessionstarttime\" not in result.stderr.str()\n\n    @pytest.mark.parametrize(\"lookfor\", [\"test_fun.py::test_a\"])\n    def test_issue134_report_error_when_collecting_member(\n        self, pytester: Pytester, lookfor\n    ) -> None:\n        pytester.makepyfile(\n            test_fun=\"\"\"\n            def test_a():\n                pass\n            def\"\"\"\n        )\n        result = pytester.runpytest(lookfor)\n        result.stdout.fnmatch_lines([\"*SyntaxError*\"])\n        if \"::\" in lookfor:\n            result.stderr.fnmatch_lines([\"*ERROR*\"])\n            assert result.ret == 4  # usage error only if item not found\n\n    def test_report_all_failed_collections_initargs(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            from _pytest.config import ExitCode\n\n            def pytest_sessionfinish(exitstatus):\n                assert exitstatus == ExitCode.USAGE_ERROR\n                print(\"pytest_sessionfinish_called\")\n            \"\"\"\n        )\n        pytester.makepyfile(test_a=\"def\", test_b=\"def\")\n        result = pytester.runpytest(\"test_a.py::a\", \"test_b.py::b\")\n        result.stderr.fnmatch_lines([\"*ERROR*test_a.py::a*\", \"*ERROR*test_b.py::b*\"])\n        result.stdout.fnmatch_lines([\"pytest_sessionfinish_called\"])\n        assert result.ret == ExitCode.USAGE_ERROR\n\n    def test_namespace_import_doesnt_confuse_import_hook(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Ref #383.\n\n        Python 3.3's namespace package messed with our import hooks.\n        Importing a module that didn't exist, even if the ImportError was\n        gracefully handled, would make our test crash.\n        \"\"\"\n        pytester.mkdir(\"not_a_package\")\n        p = pytester.makepyfile(\n            \"\"\"\n            try:\n                from not_a_package import doesnt_exist\n            except ImportError:\n                # We handle the import error gracefully here\n                pass\n\n            def test_whatever():\n                pass\n        \"\"\"\n        )\n        res = pytester.runpytest(p.name)\n        assert res.ret == 0\n\n    def test_unknown_option(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"--qwlkej\")\n        result.stderr.fnmatch_lines(\n            \"\"\"\n            *unrecognized*\n        \"\"\"\n        )\n\n    def test_getsourcelines_error_issue553(\n        self, pytester: Pytester, monkeypatch\n    ) -> None:\n        monkeypatch.setattr(\"inspect.getsourcelines\", None)\n        p = pytester.makepyfile(\n            \"\"\"\n            def raise_error(obj):\n                raise OSError('source code not available')\n\n            import inspect\n            inspect.getsourcelines = raise_error\n\n            def test_foo(invalid_fixture):\n                pass\n        \"\"\"\n        )\n        res = pytester.runpytest(p)\n        res.stdout.fnmatch_lines(\n            [\"*source code not available*\", \"E*fixture 'invalid_fixture' not found\"]\n        )\n\n    def test_plugins_given_as_strings(\n        self, pytester: Pytester, monkeypatch, _sys_snapshot\n    ) -> None:\n        \"\"\"Test that str values passed to main() as `plugins` arg are\n        interpreted as module names to be imported and registered (#855).\"\"\"\n        with pytest.raises(ImportError) as excinfo:\n            pytest.main([str(pytester.path)], plugins=[\"invalid.module\"])\n        assert \"invalid\" in str(excinfo.value)\n\n        p = pytester.path.joinpath(\"test_test_plugins_given_as_strings.py\")\n        p.write_text(\"def test_foo(): pass\", encoding=\"utf-8\")\n        mod = types.ModuleType(\"myplugin\")\n        monkeypatch.setitem(sys.modules, \"myplugin\", mod)\n        assert pytest.main(args=[str(pytester.path)], plugins=[\"myplugin\"]) == 0\n\n    def test_parametrized_with_bytes_regex(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import re\n            import pytest\n            @pytest.mark.parametrize('r', [re.compile(b'foo')])\n            def test_stuff(r):\n                pass\n        \"\"\"\n        )\n        res = pytester.runpytest(p)\n        res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_parametrized_with_null_bytes(self, pytester: Pytester) -> None:\n        \"\"\"Test parametrization with values that contain null bytes and unicode characters (#2644, #2957)\"\"\"\n        p = pytester.makepyfile(\n            \"\"\"\\\n            import pytest\n\n            @pytest.mark.parametrize(\"data\", [b\"\\\\x00\", \"\\\\x00\", 'ação'])\n            def test_foo(data):\n                assert data\n            \"\"\"\n        )\n        res = pytester.runpytest(p)\n        res.assert_outcomes(passed=3)\n\n    # Warning ignore because of:\n    # https://github.com/python/cpython/issues/85308\n    # Can be removed once Python<3.12 support is dropped.\n    @pytest.mark.filterwarnings(\"ignore:'encoding' argument not specified\")\n    def test_command_line_args_from_file(\n        self, pytester: Pytester, tmp_path: Path\n    ) -> None:\n        pytester.makepyfile(\n            test_file=\"\"\"\n            import pytest\n\n            class TestClass:\n                @pytest.mark.parametrize(\"a\", [\"x\",\"y\"])\n                def test_func(self, a):\n                    pass\n            \"\"\"\n        )\n        tests = [\n            \"test_file.py::TestClass::test_func[x]\",\n            \"test_file.py::TestClass::test_func[y]\",\n            \"-q\",\n        ]\n        args_file = pytester.maketxtfile(tests=\"\\n\".join(tests))\n        result = pytester.runpytest(f\"@{args_file}\")\n        result.assert_outcomes(failed=0, passed=2)\n\n\nclass TestInvocationVariants:\n    def test_earlyinit(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            assert hasattr(pytest, 'mark')\n        \"\"\"\n        )\n        result = pytester.runpython(p)\n        assert result.ret == 0\n\n    def test_pydoc(self, pytester: Pytester) -> None:\n        result = pytester.runpython_c(\"import pytest;help(pytest)\")\n        assert result.ret == 0\n        s = result.stdout.str()\n        assert \"MarkGenerator\" in s\n\n    def test_import_star_pytest(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            from pytest import *\n            #Item\n            #File\n            main\n            skip\n            xfail\n        \"\"\"\n        )\n        result = pytester.runpython(p)\n        assert result.ret == 0\n\n    def test_double_pytestcmdline(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            run=\"\"\"\n            import pytest\n            pytest.main()\n            pytest.main()\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_hello():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpython(p)\n        result.stdout.fnmatch_lines([\"*1 passed*\", \"*1 passed*\"])\n\n    def test_python_minus_m_invocation_ok(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\"def test_hello(): pass\")\n        res = pytester.run(sys.executable, \"-m\", \"pytest\", str(p1))\n        assert res.ret == 0\n\n    def test_python_minus_m_invocation_fail(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\"def test_fail(): 0/0\")\n        res = pytester.run(sys.executable, \"-m\", \"pytest\", str(p1))\n        assert res.ret == 1\n\n    def test_python_pytest_package(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\"def test_pass(): pass\")\n        res = pytester.run(sys.executable, \"-m\", \"pytest\", str(p1))\n        assert res.ret == 0\n        res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_invoke_with_invalid_type(self) -> None:\n        with pytest.raises(\n            TypeError, match=\"expected to be a list of strings, got: '-h'\"\n        ):\n            pytest.main(\"-h\")  # type: ignore[arg-type]\n\n    def test_invoke_with_path(self, pytester: Pytester) -> None:\n        retcode = pytest.main([str(pytester.path)])\n        assert retcode == ExitCode.NO_TESTS_COLLECTED\n\n    def test_invoke_plugin_api(self, capsys) -> None:\n        class MyPlugin:\n            def pytest_addoption(self, parser):\n                parser.addoption(\"--myopt\")\n\n        pytest.main([\"-h\"], plugins=[MyPlugin()])\n        out, _err = capsys.readouterr()\n        assert \"--myopt\" in out\n\n    def test_pyargs_importerror(self, pytester: Pytester, monkeypatch) -> None:\n        monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", False)\n        path = pytester.mkpydir(\"tpkg\")\n        path.joinpath(\"test_hello.py\").write_text(\"raise ImportError\", encoding=\"utf-8\")\n\n        result = pytester.runpytest(\"--pyargs\", \"tpkg.test_hello\", syspathinsert=True)\n        assert result.ret != 0\n\n        result.stdout.fnmatch_lines([\"collected*0*items*/*1*error\"])\n\n    def test_pyargs_only_imported_once(self, pytester: Pytester) -> None:\n        pkg = pytester.mkpydir(\"foo\")\n        pkg.joinpath(\"test_foo.py\").write_text(\n            \"print('hello from test_foo')\\ndef test(): pass\", encoding=\"utf-8\"\n        )\n        pkg.joinpath(\"conftest.py\").write_text(\n            \"def pytest_configure(config): print('configuring')\", encoding=\"utf-8\"\n        )\n\n        result = pytester.runpytest(\n            \"--pyargs\", \"foo.test_foo\", \"-s\", syspathinsert=True\n        )\n        # should only import once\n        assert result.outlines.count(\"hello from test_foo\") == 1\n        # should only configure once\n        assert result.outlines.count(\"configuring\") == 1\n\n    def test_pyargs_filename_looks_like_module(self, pytester: Pytester) -> None:\n        pytester.path.joinpath(\"conftest.py\").touch()\n        pytester.path.joinpath(\"t.py\").write_text(\"def test(): pass\", encoding=\"utf-8\")\n        result = pytester.runpytest(\"--pyargs\", \"t.py\")\n        assert result.ret == ExitCode.OK\n\n    def test_cmdline_python_package(self, pytester: Pytester, monkeypatch) -> None:\n        import warnings\n\n        monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", False)\n        path = pytester.mkpydir(\"tpkg\")\n        path.joinpath(\"test_hello.py\").write_text(\n            \"def test_hello(): pass\", encoding=\"utf-8\"\n        )\n        path.joinpath(\"test_world.py\").write_text(\n            \"def test_world(): pass\", encoding=\"utf-8\"\n        )\n        result = pytester.runpytest(\"--pyargs\", \"tpkg\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n        result = pytester.runpytest(\"--pyargs\", \"tpkg.test_hello\", syspathinsert=True)\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n        empty_package = pytester.mkpydir(\"empty_package\")\n        monkeypatch.setenv(\"PYTHONPATH\", str(empty_package), prepend=os.pathsep)\n        # the path which is not a package raises a warning on pypy;\n        # no idea why only pypy and not normal python warn about it here\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\", ImportWarning)\n            result = pytester.runpytest(\"--pyargs\", \".\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n        monkeypatch.setenv(\"PYTHONPATH\", str(pytester), prepend=os.pathsep)\n        result = pytester.runpytest(\"--pyargs\", \"tpkg.test_missing\", syspathinsert=True)\n        assert result.ret != 0\n        result.stderr.fnmatch_lines([\"*not*found*test_missing*\"])\n\n    @pytest.mark.skipif(\n        int(setuptools.__version__.split(\".\")[0]) >= 80,\n        reason=\"modern setuptools removing pkg_resources\",\n    )\n    def test_cmdline_python_legacy_namespace_package(\n        self, pytester: Pytester, monkeypatch\n    ) -> None:\n        \"\"\"Test --pyargs option with legacy namespace packages (#1567).\n\n        Ref: https://packaging.python.org/guides/packaging-namespace-packages/\n        \"\"\"\n        monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n\n        search_path = []\n        for dirname in \"hello\", \"world\":\n            d = pytester.mkdir(dirname)\n            search_path.append(d)\n            ns = d.joinpath(\"ns_pkg\")\n            ns.mkdir()\n            ns.joinpath(\"__init__.py\").write_text(\n                \"__import__('pkg_resources').declare_namespace(__name__)\",\n                encoding=\"utf-8\",\n            )\n            lib = ns.joinpath(dirname)\n            lib.mkdir()\n            lib.joinpath(\"__init__.py\").touch()\n            lib.joinpath(f\"test_{dirname}.py\").write_text(\n                f\"def test_{dirname}(): pass\\ndef test_other():pass\",\n                encoding=\"utf-8\",\n            )\n\n        # The structure of the test directory is now:\n        # .\n        # ├── hello\n        # │   └── ns_pkg\n        # │       ├── __init__.py\n        # │       └── hello\n        # │           ├── __init__.py\n        # │           └── test_hello.py\n        # └── world\n        #     └── ns_pkg\n        #         ├── __init__.py\n        #         └── world\n        #             ├── __init__.py\n        #             └── test_world.py\n\n        # NOTE: the different/reversed ordering is intentional here.\n        monkeypatch.setenv(\"PYTHONPATH\", prepend_pythonpath(*search_path))\n        for p in search_path:\n            monkeypatch.syspath_prepend(p)\n\n        # mixed module and filenames:\n        monkeypatch.chdir(\"world\")\n\n        # pgk_resources.declare_namespace has been deprecated in favor of implicit namespace packages.\n        # pgk_resources has been deprecated entirely.\n        # While we could change the test to use implicit namespace packages, seems better\n        # to still ensure the old declaration via declare_namespace still works.\n        ignore_w = (\n            r\"-Wignore:Deprecated call to `pkg_resources.declare_namespace\",\n            r\"-Wignore:pkg_resources is deprecated\",\n        )\n        result = pytester.runpytest(\n            \"--pyargs\", \"-v\", \"ns_pkg.hello\", \"ns_pkg/world\", *ignore_w\n        )\n        assert result.ret == 0\n        result.stdout.fnmatch_lines(\n            [\n                \"test_hello.py::test_hello*PASSED*\",\n                \"test_hello.py::test_other*PASSED*\",\n                \"ns_pkg/world/test_world.py::test_world*PASSED*\",\n                \"ns_pkg/world/test_world.py::test_other*PASSED*\",\n                \"*4 passed in*\",\n            ]\n        )\n\n        # specify tests within a module\n        pytester.chdir()\n        result = pytester.runpytest(\n            \"--pyargs\", \"-v\", \"ns_pkg.world.test_world::test_other\"\n        )\n        assert result.ret == 0\n        result.stdout.fnmatch_lines(\n            [\"*test_world.py::test_other*PASSED*\", \"*1 passed*\"]\n        )\n\n    def test_invoke_test_and_doctestmodules(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def test():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(str(p) + \"::test\", \"--doctest-modules\")\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_cmdline_python_package_symlink(\n        self, pytester: Pytester, monkeypatch\n    ) -> None:\n        \"\"\"\n        --pyargs with packages with path containing symlink can have conftest.py in\n        their package (#2985)\n        \"\"\"\n        monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n\n        dirname = \"lib\"\n        d = pytester.mkdir(dirname)\n        foo = d.joinpath(\"foo\")\n        foo.mkdir()\n        foo.joinpath(\"__init__.py\").touch()\n        lib = foo.joinpath(\"bar\")\n        lib.mkdir()\n        lib.joinpath(\"__init__.py\").touch()\n        lib.joinpath(\"test_bar.py\").write_text(\n            \"def test_bar(): pass\\ndef test_other(a_fixture):pass\", encoding=\"utf-8\"\n        )\n        lib.joinpath(\"conftest.py\").write_text(\n            \"import pytest\\n@pytest.fixture\\ndef a_fixture():pass\", encoding=\"utf-8\"\n        )\n\n        d_local = pytester.mkdir(\"symlink_root\")\n        symlink_location = d_local / \"lib\"\n        symlink_or_skip(d, symlink_location, target_is_directory=True)\n\n        # The structure of the test directory is now:\n        # .\n        # ├── symlink_root\n        # │   └── lib -> ../lib\n        # └── lib\n        #     └── foo\n        #         ├── __init__.py\n        #         └── bar\n        #             ├── __init__.py\n        #             ├── conftest.py\n        #             └── test_bar.py\n\n        # NOTE: the different/reversed ordering is intentional here.\n        search_path = [\"lib\", os.path.join(\"symlink_root\", \"lib\")]\n        monkeypatch.setenv(\"PYTHONPATH\", prepend_pythonpath(*search_path))\n        for p in search_path:\n            monkeypatch.syspath_prepend(p)\n\n        # module picked up in symlink-ed directory:\n        # It picks up symlink_root/lib/foo/bar (symlink) via sys.path.\n        result = pytester.runpytest(\"--pyargs\", \"-v\", \"foo.bar\")\n        pytester.chdir()\n        assert result.ret == 0\n        result.stdout.fnmatch_lines(\n            [\n                \"symlink_root/lib/foo/bar/test_bar.py::test_bar PASSED*\",\n                \"symlink_root/lib/foo/bar/test_bar.py::test_other PASSED*\",\n                \"*2 passed*\",\n            ]\n        )\n\n    def test_cmdline_python_package_not_exists(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"--pyargs\", \"tpkgwhatv\")\n        assert result.ret\n        result.stderr.fnmatch_lines([\"ERROR*module*or*package*not*found*\"])\n\n    @pytest.mark.xfail(reason=\"decide: feature or bug\")\n    def test_noclass_discovery_if_not_testcase(self, pytester: Pytester) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n            import unittest\n            class TestHello(object):\n                def test_hello(self):\n                    assert self.attr\n\n            class RealTest(unittest.TestCase, TestHello):\n                attr = 42\n        \"\"\"\n        )\n        reprec = pytester.inline_run(testpath)\n        reprec.assertoutcome(passed=1)\n\n    def test_doctest_id(self, pytester: Pytester) -> None:\n        pytester.makefile(\n            \".txt\",\n            \"\"\"\n            >>> x=3\n            >>> x\n            4\n        \"\"\",\n        )\n        testid = \"test_doctest_id.txt::test_doctest_id.txt\"\n        expected_lines = [\n            \"*= FAILURES =*\",\n            \"*_ ?doctest? test_doctest_id.txt _*\",\n            \"FAILED test_doctest_id.txt::test_doctest_id.txt\",\n            \"*= 1 failed in*\",\n        ]\n        result = pytester.runpytest(testid, \"-rf\", \"--tb=short\")\n        result.stdout.fnmatch_lines(expected_lines)\n\n        # Ensure that re-running it will still handle it as\n        # doctest.DocTestFailure, which was not the case before when\n        # re-importing doctest, but not creating a new RUNNER_CLASS.\n        result = pytester.runpytest(testid, \"-rf\", \"--tb=short\")\n        result.stdout.fnmatch_lines(expected_lines)\n\n    def test_core_backward_compatibility(self) -> None:\n        \"\"\"Test backward compatibility for get_plugin_manager function. See #787.\"\"\"\n        import _pytest.config\n\n        assert (\n            type(_pytest.config.get_plugin_manager())\n            is _pytest.config.PytestPluginManager\n        )\n\n    def test_has_plugin(self, request) -> None:\n        \"\"\"Test hasplugin function of the plugin manager (#932).\"\"\"\n        assert request.config.pluginmanager.hasplugin(\"python\")\n\n\nclass TestDurations:\n    source = \"\"\"\n        from _pytest import timing\n        def test_something():\n            pass\n        def test_2():\n            timing.sleep(0.010)\n        def test_1():\n            timing.sleep(0.002)\n        def test_3():\n            timing.sleep(0.020)\n    \"\"\"\n\n    def test_calls(self, pytester: Pytester, mock_timing) -> None:\n        pytester.makepyfile(self.source)\n        result = pytester.runpytest_inprocess(\"--durations=10\")\n        assert result.ret == 0\n\n        result.stdout.fnmatch_lines_random(\n            [\"*durations*\", \"*call*test_3*\", \"*call*test_2*\"]\n        )\n\n        result.stdout.fnmatch_lines(\n            [\"(8 durations < 0.005s hidden.  Use -vv to show these durations.)\"]\n        )\n\n    def test_calls_show_2(self, pytester: Pytester, mock_timing) -> None:\n        pytester.makepyfile(self.source)\n        result = pytester.runpytest_inprocess(\"--durations=2\")\n        assert result.ret == 0\n\n        lines = result.stdout.get_lines_after(\"*slowest*durations*\")\n        assert \"4 passed\" in lines[2]\n\n    def test_calls_showall(self, pytester: Pytester, mock_timing) -> None:\n        pytester.makepyfile(self.source)\n        result = pytester.runpytest_inprocess(\"--durations=0\")\n        assert result.ret == 0\n        TestDurations.check_tests_in_output(result.stdout.lines, 2, 3)\n\n    def test_calls_showall_verbose(self, pytester: Pytester, mock_timing) -> None:\n        pytester.makepyfile(self.source)\n        result = pytester.runpytest_inprocess(\"--durations=0\", \"-vv\")\n        assert result.ret == 0\n        TestDurations.check_tests_in_output(result.stdout.lines, 1, 2, 3)\n\n    def test_calls_showall_durationsmin(self, pytester: Pytester, mock_timing) -> None:\n        pytester.makepyfile(self.source)\n        result = pytester.runpytest_inprocess(\"--durations=0\", \"--durations-min=0.015\")\n        assert result.ret == 0\n        TestDurations.check_tests_in_output(result.stdout.lines, 3)\n\n    def test_calls_showall_durationsmin_verbose(\n        self, pytester: Pytester, mock_timing\n    ) -> None:\n        pytester.makepyfile(self.source)\n        result = pytester.runpytest_inprocess(\n            \"--durations=0\", \"--durations-min=0.015\", \"-vv\"\n        )\n        assert result.ret == 0\n        TestDurations.check_tests_in_output(result.stdout.lines, 3)\n\n    @staticmethod\n    def check_tests_in_output(\n        lines: Sequence[str], *expected_test_numbers: int, number_of_tests: int = 3\n    ) -> None:\n        found_test_numbers = {\n            test_number\n            for test_number in range(1, number_of_tests + 1)\n            if any(\n                line.endswith(f\"test_{test_number}\") and \" call \" in line\n                for line in lines\n            )\n        }\n        assert found_test_numbers == set(expected_test_numbers)\n\n    def test_with_deselected(self, pytester: Pytester, mock_timing) -> None:\n        pytester.makepyfile(self.source)\n        result = pytester.runpytest_inprocess(\"--durations=2\", \"-k test_3\")\n        assert result.ret == 0\n\n        result.stdout.fnmatch_lines([\"*durations*\", \"*call*test_3*\"])\n\n    def test_with_failing_collection(self, pytester: Pytester, mock_timing) -> None:\n        pytester.makepyfile(self.source)\n        pytester.makepyfile(test_collecterror=\"\"\"xyz\"\"\")\n        result = pytester.runpytest_inprocess(\"--durations=2\", \"-k test_1\")\n        assert result.ret == 2\n\n        result.stdout.fnmatch_lines([\"*Interrupted: 1 error during collection*\"])\n        # Collection errors abort test execution, therefore no duration is\n        # output\n        result.stdout.no_fnmatch_line(\"*duration*\")\n\n    def test_with_not(self, pytester: Pytester, mock_timing) -> None:\n        pytester.makepyfile(self.source)\n        result = pytester.runpytest_inprocess(\"-k not 1\")\n        assert result.ret == 0\n\n\nclass TestDurationsWithFixture:\n    source = \"\"\"\n        import pytest\n        from _pytest import timing\n\n        @pytest.fixture\n        def setup_fixt():\n            timing.sleep(2)\n\n        def test_1(setup_fixt):\n            timing.sleep(5)\n    \"\"\"\n\n    def test_setup_function(self, pytester: Pytester, mock_timing) -> None:\n        pytester.makepyfile(self.source)\n        result = pytester.runpytest_inprocess(\"--durations=10\")\n        assert result.ret == 0\n\n        result.stdout.fnmatch_lines_random(\n            \"\"\"\n            *durations*\n            5.00s call *test_1*\n            2.00s setup *test_1*\n        \"\"\"\n        )\n\n\ndef test_zipimport_hook(pytester: Pytester) -> None:\n    \"\"\"Test package loader is being used correctly (see #1837).\"\"\"\n    zipapp = pytest.importorskip(\"zipapp\")\n    pytester.path.joinpath(\"app\").mkdir()\n    pytester.makepyfile(\n        **{\n            \"app/foo.py\": \"\"\"\n            import pytest\n            def main():\n                pytest.main(['--pyargs', 'foo'])\n        \"\"\"\n        }\n    )\n    target = pytester.path.joinpath(\"foo.zip\")\n    zipapp.create_archive(\n        str(pytester.path.joinpath(\"app\")), str(target), main=\"foo:main\"\n    )\n    result = pytester.runpython(target)\n    assert result.ret == 0\n    result.stderr.fnmatch_lines([\"*not found*foo*\"])\n    result.stdout.no_fnmatch_line(\"*INTERNALERROR>*\")\n\n\ndef test_import_plugin_unicode_name(pytester: Pytester) -> None:\n    pytester.makepyfile(myplugin=\"\")\n    pytester.makepyfile(\"def test(): pass\")\n    pytester.makeconftest(\"pytest_plugins = ['myplugin']\")\n    r = pytester.runpytest()\n    assert r.ret == 0\n\n\ndef test_pytest_plugins_as_module(pytester: Pytester) -> None:\n    \"\"\"Do not raise an error if pytest_plugins attribute is a module (#3899)\"\"\"\n    pytester.makepyfile(\n        **{\n            \"__init__.py\": \"\",\n            \"pytest_plugins.py\": \"\",\n            \"conftest.py\": \"from . import pytest_plugins\",\n            \"test_foo.py\": \"def test(): pass\",\n        }\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n\ndef test_deferred_hook_checking(pytester: Pytester) -> None:\n    \"\"\"Check hooks as late as possible (#1821).\"\"\"\n    pytester.syspathinsert()\n    pytester.makepyfile(\n        **{\n            \"plugin.py\": \"\"\"\n        class Hooks(object):\n            def pytest_my_hook(self, config):\n                pass\n\n        def pytest_configure(config):\n            config.pluginmanager.add_hookspecs(Hooks)\n        \"\"\",\n            \"conftest.py\": \"\"\"\n            pytest_plugins = ['plugin']\n            def pytest_my_hook(config):\n                return 40\n        \"\"\",\n            \"test_foo.py\": \"\"\"\n            def test(request):\n                assert request.config.hook.pytest_my_hook(config=request.config) == [40]\n        \"\"\",\n        }\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n\ndef test_fixture_values_leak(pytester: Pytester) -> None:\n    \"\"\"Ensure that fixture objects are properly destroyed by the garbage collector at the end of their expected\n    life-times (#2981).\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import dataclasses\n        import gc\n        import pytest\n        import weakref\n\n        @dataclasses.dataclass\n        class SomeObj:\n            name: str\n\n        fix_of_test1_ref = None\n        session_ref = None\n\n        @pytest.fixture(scope='session')\n        def session_fix():\n            global session_ref\n            obj = SomeObj(name='session-fixture')\n            session_ref = weakref.ref(obj)\n            return obj\n\n        @pytest.fixture\n        def fix(session_fix):\n            global fix_of_test1_ref\n            obj = SomeObj(name='local-fixture')\n            fix_of_test1_ref = weakref.ref(obj)\n            return obj\n\n        def test1(fix):\n            assert fix_of_test1_ref() is fix\n\n        def test2():\n            gc.collect()\n            # fixture \"fix\" created during test1 must have been destroyed by now\n            assert fix_of_test1_ref() is None\n    \"\"\"\n    )\n    # Running on subprocess does not activate the HookRecorder\n    # which holds itself a reference to objects in case of the\n    # pytest_assert_reprcompare hook\n    result = pytester.runpytest_subprocess()\n    result.stdout.fnmatch_lines([\"* 2 passed *\"])\n\n\ndef test_fixture_order_respects_scope(pytester: Pytester) -> None:\n    \"\"\"Ensure that fixtures are created according to scope order (#2405).\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        data = {}\n\n        @pytest.fixture(scope='module')\n        def clean_data():\n            data.clear()\n\n        @pytest.fixture(autouse=True)\n        def add_data():\n            data.update(value=True)\n\n        @pytest.mark.usefixtures('clean_data')\n        def test_value():\n            assert data.get('value')\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n\n\ndef test_frame_leak_on_failing_test(pytester: Pytester) -> None:\n    \"\"\"Pytest would leak garbage referencing the frames of tests that failed\n    that could never be reclaimed (#2798).\n\n    Unfortunately it was not possible to remove the actual circles because most of them\n    are made of traceback objects which cannot be weakly referenced. Those objects at least\n    can be eventually claimed by the garbage collector.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import gc\n        import weakref\n\n        class Obj:\n            pass\n\n        ref = None\n\n        def test1():\n            obj = Obj()\n            global ref\n            ref = weakref.ref(obj)\n            assert 0\n\n        def test2():\n            gc.collect()\n            assert ref() is None\n    \"\"\"\n    )\n    result = pytester.runpytest_subprocess()\n    result.stdout.fnmatch_lines([\"*1 failed, 1 passed in*\"])\n\n\ndef test_fixture_mock_integration(pytester: Pytester) -> None:\n    \"\"\"Test that decorators applied to fixture are left working (#3774)\"\"\"\n    p = pytester.copy_example(\"acceptance/fixture_mock_integration.py\")\n    result = pytester.runpytest(p)\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_usage_error_code(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"-unknown-option-\")\n    assert result.ret == ExitCode.USAGE_ERROR\n\n\ndef test_error_on_async_function(pytester: Pytester) -> None:\n    # In the below we .close() the coroutine only to avoid\n    # \"RuntimeWarning: coroutine 'test_2' was never awaited\"\n    # which messes with other tests.\n    pytester.makepyfile(\n        test_async=\"\"\"\n        async def test_1():\n            pass\n        async def test_2():\n            pass\n        def test_3():\n            coro = test_2()\n            coro.close()\n            return coro\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"*async def functions are not natively supported*\",\n            \"*test_async.py::test_1*\",\n            \"*test_async.py::test_2*\",\n            \"*test_async.py::test_3*\",\n        ]\n    )\n    result.assert_outcomes(failed=3)\n\n\ndef test_error_on_async_gen_function(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_async=\"\"\"\n        async def test_1():\n            yield\n        async def test_2():\n            yield\n        def test_3():\n            return test_2()\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"*async def functions are not natively supported*\",\n            \"*test_async.py::test_1*\",\n            \"*test_async.py::test_2*\",\n            \"*test_async.py::test_3*\",\n        ]\n    )\n    result.assert_outcomes(failed=3)\n\n\ndef test_error_on_sync_test_async_fixture(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_sync=\"\"\"\n            import pytest\n\n            @pytest.fixture\n            async def async_fixture():\n                ...\n\n            def test_foo(async_fixture):\n                # suppress unawaited coroutine warning\n                try:\n                    async_fixture.send(None)\n                except StopIteration:\n                    pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(errors=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"'test_foo' requested an async fixture 'async_fixture', with no plugin or hook that handled it. \"\n            \"This is an error, as pytest does not natively support it.\"\n        ]\n    )\n\n\ndef test_error_on_sync_test_async_fixture_gen(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_sync=\"\"\"\n            import pytest\n\n            @pytest.fixture\n            async def async_fixture():\n                yield\n\n            def test_foo(async_fixture):\n                # async gens don't emit unawaited-coroutine\n                ...\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(errors=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"'test_foo' requested an async fixture 'async_fixture', with no plugin or hook that handled it. \"\n            \"This is an error, as pytest does not natively support it.\"\n        ]\n    )\n\n\ndef test_error_on_sync_test_async_autouse_fixture(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_sync=\"\"\"\n            import pytest\n\n            @pytest.fixture(autouse=True)\n            async def async_fixture():\n                ...\n\n            # We explicitly request the fixture to be able to\n            # suppress the RuntimeWarning for unawaited coroutine.\n            def test_foo(async_fixture):\n                try:\n                    async_fixture.send(None)\n                except StopIteration:\n                    pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(errors=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"'test_foo' requested an async fixture 'async_fixture' with autouse=True, \"\n            \"with no plugin or hook that handled it. \"\n            \"This is an error, as pytest does not natively support it.\"\n        ]\n    )\n\n\ndef test_pdb_can_be_rewritten(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        **{\n            \"conftest.py\": \"\"\"\n                import pytest\n                pytest.register_assert_rewrite(\"pdb\")\n                \"\"\",\n            \"__init__.py\": \"\",\n            \"pdb.py\": \"\"\"\n                def check():\n                    assert 1 == 2\n                \"\"\",\n            \"test_pdb.py\": \"\"\"\n                def test():\n                    import pdb\n                    assert pdb.check()\n                \"\"\",\n        }\n    )\n    # Disable debugging plugin itself to avoid:\n    # > INTERNALERROR> AttributeError: module 'pdb' has no attribute 'set_trace'\n    result = pytester.runpytest_subprocess(\"-p\", \"no:debugging\", \"-vv\")\n    result.stdout.fnmatch_lines(\n        [\n            \"    def check():\",\n            \">       assert 1 == 2\",\n            \"E       assert 1 == 2\",\n            \"\",\n            \"pdb.py:2: AssertionError\",\n            \"*= 1 failed in *\",\n        ]\n    )\n    assert result.ret == 1\n\n\ndef test_tee_stdio_captures_and_live_prints(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import sys\n        def test_simple():\n            print (\"@this is stdout@\")\n            print (\"@this is stderr@\", file=sys.stderr)\n    \"\"\"\n    )\n    result = pytester.runpytest_subprocess(\n        testpath,\n        \"--capture=tee-sys\",\n        \"--junitxml=output.xml\",\n        \"-o\",\n        \"junit_logging=all\",\n    )\n\n    # ensure stdout/stderr were 'live printed'\n    result.stdout.fnmatch_lines([\"*@this is stdout@*\"])\n    result.stderr.fnmatch_lines([\"*@this is stderr@*\"])\n\n    # now ensure the output is in the junitxml\n    fullXml = pytester.path.joinpath(\"output.xml\").read_text(encoding=\"utf-8\")\n    assert \"@this is stdout@\\n\" in fullXml\n    assert \"@this is stderr@\\n\" in fullXml\n\n\n@pytest.mark.skipif(\n    sys.platform == \"win32\",\n    reason=\"Windows raises `OSError: [Errno 22] Invalid argument` instead\",\n)\ndef test_no_brokenpipeerror_message(pytester: Pytester) -> None:\n    \"\"\"Ensure that the broken pipe error message is suppressed.\n\n    In some Python versions, it reaches sys.unraisablehook, in others\n    a BrokenPipeError exception is propagated, but either way it prints\n    to stderr on shutdown, so checking nothing is printed is enough.\n    \"\"\"\n    popen = pytester.popen((*pytester._getpytestargs(), \"--help\"))\n    popen.stdout.close()\n    ret = popen.wait()\n    assert popen.stderr.read() == b\"\"\n    assert ret == 1\n\n    # Cleanup.\n    popen.stderr.close()\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_function_return_non_none_warning(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_stuff():\n            return \"something\"\n    \"\"\"\n    )\n    res = pytester.runpytest()\n    res.stdout.fnmatch_lines([\"*Did you mean to use `assert` instead of `return`?*\"])\n\n\ndef test_doctest_and_normal_imports_with_importlib(pytester: Pytester) -> None:\n    \"\"\"\n    Regression test for #10811: previously import_path with ImportMode.importlib would\n    not return a module if already in sys.modules, resulting in modules being imported\n    multiple times, which causes problems with modules that have import side effects.\n    \"\"\"\n    # Uses the exact reproducer form #10811, given it is very minimal\n    # and illustrates the problem well.\n    pytester.makepyfile(\n        **{\n            \"pmxbot/commands.py\": \"from . import logging\",\n            \"pmxbot/logging.py\": \"\",\n            \"tests/__init__.py\": \"\",\n            \"tests/test_commands.py\": \"\"\"\n                import importlib\n                from pmxbot import logging\n\n                class TestCommands:\n                    def test_boo(self):\n                        assert importlib.import_module('pmxbot.logging') is logging\n                \"\"\",\n        }\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        addopts=\n            --doctest-modules\n            --import-mode importlib\n        \"\"\"\n    )\n    result = pytester.runpytest_subprocess()\n    result.stdout.fnmatch_lines(\"*1 passed*\")\n\n\n@pytest.mark.skip(reason=\"Test is not isolated\")\ndef test_issue_9765(pytester: Pytester) -> None:\n    \"\"\"Reproducer for issue #9765 on Windows\n\n    https://github.com/pytest-dev/pytest/issues/9765\n    \"\"\"\n    pytester.makepyprojecttoml(\n        \"\"\"\n        [tool.pytest.ini_options]\n        addopts = \"-p my_package.plugin.my_plugin\"\n        \"\"\"\n    )\n    pytester.makepyfile(\n        **{\n            \"setup.py\": (\n                \"\"\"\n                from setuptools import setup\n\n                if __name__ == '__main__':\n                    setup(name='my_package', packages=['my_package', 'my_package.plugin'])\n                \"\"\"\n            ),\n            \"my_package/__init__.py\": \"\",\n            \"my_package/conftest.py\": \"\",\n            \"my_package/test_foo.py\": \"def test(): pass\",\n            \"my_package/plugin/__init__.py\": \"\",\n            \"my_package/plugin/my_plugin.py\": (\n                \"\"\"\n                import pytest\n\n                def pytest_configure(config):\n\n                    class SimplePlugin:\n                        @pytest.fixture(params=[1, 2, 3])\n                        def my_fixture(self, request):\n                            yield request.param\n\n                    config.pluginmanager.register(SimplePlugin())\n                \"\"\"\n            ),\n        }\n    )\n\n    subprocess.run(\n        [sys.executable, \"-Im\", \"pip\", \"install\", \"-e\", \".\"],\n        check=True,\n    )\n    try:\n        # We are using subprocess.run rather than pytester.run on purpose.\n        # pytester.run is adding the current directory to PYTHONPATH which avoids\n        # the bug. We also use pytest rather than python -m pytest for the same\n        # PYTHONPATH reason.\n        subprocess.run(\n            [\"pytest\", \"my_package\"],\n            capture_output=True,\n            check=True,\n            encoding=\"utf-8\",\n            text=True,\n        )\n    except subprocess.CalledProcessError as exc:\n        raise AssertionError(\n            f\"pytest command failed:\\n{exc.stdout=!s}\\n{exc.stderr=!s}\"\n        ) from exc\n\n\ndef test_no_terminal_plugin(pytester: Pytester) -> None:\n    \"\"\"Smoke test to ensure pytest can execute without the terminal plugin (#9422).\"\"\"\n    pytester.makepyfile(\"def test(): assert 1 == 2\")\n    result = pytester.runpytest(\"-pno:terminal\", \"-s\")\n    assert result.ret == ExitCode.TESTS_FAILED\n\n\ndef test_stop_iteration_from_collect(pytester: Pytester) -> None:\n    pytester.makepyfile(test_it=\"raise StopIteration('hello')\")\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.INTERRUPTED\n    result.assert_outcomes(failed=0, passed=0, errors=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"=* short test summary info =*\",\n            \"ERROR test_it.py - StopIteration: hello\",\n            \"!* Interrupted: 1 error during collection !*\",\n            \"=* 1 error in * =*\",\n        ]\n    )\n\n\ndef test_stop_iteration_runtest_protocol(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import pytest\n        @pytest.fixture\n        def fail_setup():\n            raise StopIteration(1)\n        def test_fail_setup(fail_setup):\n            pass\n        def test_fail_teardown(request):\n            def stop_iteration():\n                raise StopIteration(2)\n            request.addfinalizer(stop_iteration)\n        def test_fail_call():\n            raise StopIteration(3)\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.TESTS_FAILED\n    result.assert_outcomes(failed=1, passed=1, errors=2)\n    result.stdout.fnmatch_lines(\n        [\n            \"=* short test summary info =*\",\n            \"FAILED test_it.py::test_fail_call - StopIteration: 3\",\n            \"ERROR test_it.py::test_fail_setup - StopIteration: 1\",\n            \"ERROR test_it.py::test_fail_teardown - StopIteration: 2\",\n            \"=* 1 failed, 1 passed, 2 errors in * =*\",\n        ]\n    )\n"
  },
  {
    "path": "testing/code/test_code.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport re\nimport sys\nfrom types import FrameType\nfrom unittest import mock\n\nfrom _pytest._code import Code\nfrom _pytest._code import ExceptionInfo\nfrom _pytest._code import Frame\nfrom _pytest._code import Source\nfrom _pytest._code.code import ExceptionChainRepr\nfrom _pytest._code.code import ReprFuncArgs\nimport pytest\n\n\ndef test_ne() -> None:\n    code1 = Code(compile('foo = \"bar\"', \"\", \"exec\"))\n    assert code1 == code1\n    code2 = Code(compile('foo = \"baz\"', \"\", \"exec\"))\n    assert code2 != code1\n\n\ndef test_code_gives_back_name_for_not_existing_file() -> None:\n    name = \"abc-123\"\n    co_code = compile(\"pass\\n\", name, \"exec\")\n    assert co_code.co_filename == name\n    code = Code(co_code)\n    assert str(code.path) == name\n    assert code.fullsource is None\n\n\ndef test_code_from_function_with_class() -> None:\n    class A:\n        pass\n\n    with pytest.raises(TypeError):\n        Code.from_function(A)\n\n\ndef x() -> None:\n    raise NotImplementedError()\n\n\ndef test_code_fullsource() -> None:\n    code = Code.from_function(x)\n    full = code.fullsource\n    assert \"test_code_fullsource()\" in str(full)\n\n\ndef test_code_source() -> None:\n    code = Code.from_function(x)\n    src = code.source()\n    expected = \"\"\"def x() -> None:\n    raise NotImplementedError()\"\"\"\n    assert str(src) == expected\n\n\ndef test_frame_getsourcelineno_myself() -> None:\n    def func() -> FrameType:\n        return sys._getframe(0)\n\n    f = Frame(func())\n    source, lineno = f.code.fullsource, f.lineno\n    assert source is not None\n    assert source[lineno].startswith(\"        return sys._getframe(0)\")\n\n\ndef test_getstatement_empty_fullsource() -> None:\n    def func() -> FrameType:\n        return sys._getframe(0)\n\n    f = Frame(func())\n    with mock.patch.object(f.code.__class__, \"fullsource\", None):\n        assert f.statement == Source(\"\")\n\n\ndef test_code_from_func() -> None:\n    co = Code.from_function(test_frame_getsourcelineno_myself)\n    assert co.firstlineno\n    assert co.path\n\n\ndef test_unicode_handling() -> None:\n    value = \"ąć\".encode()\n\n    def f() -> None:\n        raise ValueError(value)\n\n    excinfo = pytest.raises(ValueError, f)\n    str(excinfo)\n\n\ndef test_code_getargs() -> None:\n    def f1(x):\n        raise NotImplementedError()\n\n    c1 = Code.from_function(f1)\n    assert c1.getargs(var=True) == (\"x\",)\n\n    def f2(x, *y):\n        raise NotImplementedError()\n\n    c2 = Code.from_function(f2)\n    assert c2.getargs(var=True) == (\"x\", \"y\")\n\n    def f3(x, **z):\n        raise NotImplementedError()\n\n    c3 = Code.from_function(f3)\n    assert c3.getargs(var=True) == (\"x\", \"z\")\n\n    def f4(x, *y, **z):\n        raise NotImplementedError()\n\n    c4 = Code.from_function(f4)\n    assert c4.getargs(var=True) == (\"x\", \"y\", \"z\")\n\n\ndef test_frame_getargs() -> None:\n    def f1(x) -> FrameType:\n        return sys._getframe(0)\n\n    fr1 = Frame(f1(\"a\"))\n    assert fr1.getargs(var=True) == [(\"x\", \"a\")]\n\n    def f2(x, *y) -> FrameType:\n        return sys._getframe(0)\n\n    fr2 = Frame(f2(\"a\", \"b\", \"c\"))\n    assert fr2.getargs(var=True) == [(\"x\", \"a\"), (\"y\", (\"b\", \"c\"))]\n\n    def f3(x, **z) -> FrameType:\n        return sys._getframe(0)\n\n    fr3 = Frame(f3(\"a\", b=\"c\"))\n    assert fr3.getargs(var=True) == [(\"x\", \"a\"), (\"z\", {\"b\": \"c\"})]\n\n    def f4(x, *y, **z) -> FrameType:\n        return sys._getframe(0)\n\n    fr4 = Frame(f4(\"a\", \"b\", c=\"d\"))\n    assert fr4.getargs(var=True) == [(\"x\", \"a\"), (\"y\", (\"b\",)), (\"z\", {\"c\": \"d\"})]\n\n\nclass TestExceptionInfo:\n    def test_bad_getsource(self) -> None:\n        try:\n            if False:\n                pass\n            else:\n                assert False\n        except AssertionError:\n            exci = ExceptionInfo.from_current()\n        assert exci.getrepr()\n\n    def test_from_current_with_missing(self) -> None:\n        with pytest.raises(AssertionError, match=\"no current exception\"):\n            ExceptionInfo.from_current()\n\n\nclass TestTracebackEntry:\n    def test_getsource(self) -> None:\n        try:\n            if False:\n                pass\n            else:\n                assert False\n        except AssertionError:\n            exci = ExceptionInfo.from_current()\n        entry = exci.traceback[0]\n        source = entry.getsource()\n        assert source is not None\n        assert len(source) == 6\n        assert \"assert False\" in source[5]\n\n    def test_tb_entry_str(self):\n        try:\n            assert False\n        except AssertionError:\n            exci = ExceptionInfo.from_current()\n        pattern = r\"  File '.*test_code.py':\\d+ in test_tb_entry_str\\n  assert False\"\n        entry = str(exci.traceback[0])\n        assert re.match(pattern, entry)\n\n\nclass TestReprFuncArgs:\n    def test_not_raise_exception_with_mixed_encoding(self, tw_mock) -> None:\n        args = [(\"unicode_string\", \"São Paulo\"), (\"utf8_string\", b\"S\\xc3\\xa3o Paulo\")]\n\n        r = ReprFuncArgs(args)\n        r.toterminal(tw_mock)\n\n        assert (\n            tw_mock.lines[0]\n            == r\"unicode_string = São Paulo, utf8_string = b'S\\xc3\\xa3o Paulo'\"\n        )\n\n\ndef test_ExceptionChainRepr():\n    \"\"\"Test ExceptionChainRepr, especially with regard to being hashable.\"\"\"\n    try:\n        raise ValueError()\n    except ValueError:\n        excinfo1 = ExceptionInfo.from_current()\n        excinfo2 = ExceptionInfo.from_current()\n\n    repr1 = excinfo1.getrepr()\n    repr2 = excinfo2.getrepr()\n    assert repr1 != repr2\n\n    assert isinstance(repr1, ExceptionChainRepr)\n    assert hash(repr1) != hash(repr2)\n    assert repr1 is not excinfo1.getrepr()\n"
  },
  {
    "path": "testing/code/test_excinfo.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport fnmatch\nimport importlib\nimport io\nimport operator\nfrom pathlib import Path\nimport queue\nimport re\nimport sys\nimport textwrap\nfrom typing import Any\nfrom typing import cast\nfrom typing import TYPE_CHECKING\n\nimport _pytest._code\nfrom _pytest._code.code import ExceptionChainRepr\nfrom _pytest._code.code import ExceptionInfo\nfrom _pytest._code.code import FormattedExcinfo\nfrom _pytest._io import TerminalWriter\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pathlib import bestrelpath\nfrom _pytest.pathlib import import_path\nfrom _pytest.pytester import LineMatcher\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nif TYPE_CHECKING:\n    from _pytest._code.code import TracebackStyle\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import BaseExceptionGroup\n    from exceptiongroup import ExceptionGroup\n\n\n@pytest.fixture\ndef limited_recursion_depth():\n    before = sys.getrecursionlimit()\n    sys.setrecursionlimit(150)\n    yield\n    sys.setrecursionlimit(before)\n\n\ndef test_excinfo_simple() -> None:\n    try:\n        raise ValueError\n    except ValueError:\n        info = _pytest._code.ExceptionInfo.from_current()\n    assert info.type == ValueError\n\n\ndef test_excinfo_from_exc_info_simple() -> None:\n    try:\n        raise ValueError\n    except ValueError as e:\n        assert e.__traceback__ is not None\n        info = _pytest._code.ExceptionInfo.from_exc_info((type(e), e, e.__traceback__))\n    assert info.type == ValueError\n\n\ndef test_excinfo_from_exception_simple() -> None:\n    try:\n        raise ValueError\n    except ValueError as e:\n        assert e.__traceback__ is not None\n        info = _pytest._code.ExceptionInfo.from_exception(e)\n    assert info.type == ValueError\n\n\ndef test_excinfo_from_exception_missing_traceback_assertion() -> None:\n    with pytest.raises(AssertionError, match=r\"must have.*__traceback__\"):\n        _pytest._code.ExceptionInfo.from_exception(ValueError())\n\n\ndef test_excinfo_getstatement():\n    def g():\n        raise ValueError\n\n    def f():\n        g()\n\n    try:\n        f()\n    except ValueError:\n        excinfo = _pytest._code.ExceptionInfo.from_current()\n    linenumbers = [\n        f.__code__.co_firstlineno - 1 + 4,\n        f.__code__.co_firstlineno - 1 + 1,\n        g.__code__.co_firstlineno - 1 + 1,\n    ]\n    values = list(excinfo.traceback)\n    foundlinenumbers = [x.lineno for x in values]\n    assert foundlinenumbers == linenumbers\n    # for x in info:\n    #    print \"%s:%d  %s\" %(x.path.relto(root), x.lineno, x.statement)\n    # xxx\n\n\n# testchain for getentries test below\n\n\ndef f():\n    #\n    raise ValueError\n    #\n\n\ndef g():\n    #\n    __tracebackhide__ = True\n    f()\n    #\n\n\ndef h():\n    #\n    g()\n    #\n\n\nclass TestTraceback_f_g_h:\n    def setup_method(self, method):\n        try:\n            h()\n        except ValueError:\n            self.excinfo = _pytest._code.ExceptionInfo.from_current()\n\n    def test_traceback_entries(self):\n        tb = self.excinfo.traceback\n        entries = list(tb)\n        assert len(tb) == 4  # maybe fragile test\n        assert len(entries) == 4  # maybe fragile test\n        names = [\"f\", \"g\", \"h\"]\n        for entry in entries:\n            try:\n                names.remove(entry.frame.code.name)\n            except ValueError:\n                pass\n        assert not names\n\n    def test_traceback_entry_getsource(self):\n        tb = self.excinfo.traceback\n        s = str(tb[-1].getsource())\n        assert s.startswith(\"def f():\")\n        assert s.endswith(\"raise ValueError\")\n\n    def test_traceback_entry_getsource_in_construct(self):\n        def xyz():\n            try:\n                raise ValueError\n            except somenoname:  # type: ignore[name-defined] # noqa: F821\n                pass  # pragma: no cover\n\n        try:\n            xyz()\n        except NameError:\n            excinfo = _pytest._code.ExceptionInfo.from_current()\n        else:\n            assert False, \"did not raise NameError\"\n\n        tb = excinfo.traceback\n        source = tb[-1].getsource()\n        assert source is not None\n        assert source.deindent().lines == [\n            \"def xyz():\",\n            \"    try:\",\n            \"        raise ValueError\",\n            \"    except somenoname:  # type: ignore[name-defined] # noqa: F821\",\n        ]\n\n    def test_traceback_cut(self) -> None:\n        co = _pytest._code.Code.from_function(f)\n        path, firstlineno = co.path, co.firstlineno\n        assert isinstance(path, Path)\n        traceback = self.excinfo.traceback\n        newtraceback = traceback.cut(path=path, firstlineno=firstlineno)\n        assert len(newtraceback) == 1\n        newtraceback = traceback.cut(path=path, lineno=firstlineno + 2)\n        assert len(newtraceback) == 1\n\n    def test_traceback_cut_excludepath(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\"def f(): raise ValueError\")\n        with pytest.raises(ValueError) as excinfo:\n            import_path(p, root=pytester.path, consider_namespace_packages=False).f()\n        basedir = Path(pytest.__file__).parent\n        newtraceback = excinfo.traceback.cut(excludepath=basedir)\n        for x in newtraceback:\n            assert isinstance(x.path, Path)\n            assert basedir not in x.path.parents\n        assert newtraceback[-1].frame.code.path == p\n\n    def test_traceback_filter(self):\n        traceback = self.excinfo.traceback\n        ntraceback = traceback.filter(self.excinfo)\n        assert len(ntraceback) == len(traceback) - 1\n\n    @pytest.mark.parametrize(\n        \"tracebackhide, matching\",\n        [\n            (lambda info: True, True),\n            (lambda info: False, False),\n            (operator.methodcaller(\"errisinstance\", ValueError), True),\n            (operator.methodcaller(\"errisinstance\", IndexError), False),\n        ],\n    )\n    def test_traceback_filter_selective(self, tracebackhide, matching):\n        def f():\n            #\n            raise ValueError\n            #\n\n        def g():\n            #\n            __tracebackhide__ = tracebackhide\n            f()\n            #\n\n        def h():\n            #\n            g()\n            #\n\n        excinfo = pytest.raises(ValueError, h)\n        traceback = excinfo.traceback\n        ntraceback = traceback.filter(excinfo)\n        print(f\"old: {traceback!r}\")\n        print(f\"new: {ntraceback!r}\")\n\n        if matching:\n            assert len(ntraceback) == len(traceback) - 2\n        else:\n            # -1 because of the __tracebackhide__ in pytest.raises\n            assert len(ntraceback) == len(traceback) - 1\n\n    def test_traceback_recursion_index(self):\n        def f(n):\n            if n < 10:\n                n += 1\n            f(n)\n\n        excinfo = pytest.raises(RecursionError, f, 8)\n        traceback = excinfo.traceback\n        recindex = traceback.recursionindex()\n        assert recindex == 3\n\n    def test_traceback_only_specific_recursion_errors(self, monkeypatch):\n        def f(n):\n            if n == 0:\n                raise RuntimeError(\"hello\")\n            f(n - 1)\n\n        excinfo = pytest.raises(RuntimeError, f, 25)\n        monkeypatch.delattr(excinfo.traceback.__class__, \"recursionindex\")\n        repr = excinfo.getrepr()\n        assert \"RuntimeError: hello\" in str(repr.reprcrash)\n\n    def test_traceback_no_recursion_index(self) -> None:\n        def do_stuff() -> None:\n            raise RuntimeError\n\n        def reraise_me() -> None:\n            import sys\n\n            _exc, val, tb = sys.exc_info()\n            assert val is not None\n            raise val.with_traceback(tb)\n\n        def f(n: int) -> None:\n            try:\n                do_stuff()\n            except BaseException:\n                reraise_me()\n\n        excinfo = pytest.raises(RuntimeError, f, 8)\n        assert excinfo is not None\n        traceback = excinfo.traceback\n        recindex = traceback.recursionindex()\n        assert recindex is None\n\n    def test_traceback_messy_recursion(self):\n        # XXX: simplified locally testable version\n        decorator = pytest.importorskip(\"decorator\").decorator\n\n        def log(f, *k, **kw):\n            print(f\"{k} {kw}\")\n            f(*k, **kw)\n\n        log = decorator(log)\n\n        def fail():\n            raise ValueError(\"\")\n\n        fail = log(log(fail))\n\n        excinfo = pytest.raises(ValueError, fail)\n        assert excinfo.traceback.recursionindex() is None\n\n    def test_getreprcrash(self):\n        def i():\n            __tracebackhide__ = True\n            raise ValueError\n\n        def h():\n            i()\n\n        def g():\n            __tracebackhide__ = True\n            h()\n\n        def f():\n            g()\n\n        excinfo = pytest.raises(ValueError, f)\n        reprcrash = excinfo._getreprcrash()\n        assert reprcrash is not None\n        co = _pytest._code.Code.from_function(h)\n        assert reprcrash.path == str(co.path)\n        assert reprcrash.lineno == co.firstlineno + 1 + 1\n\n    def test_getreprcrash_empty(self):\n        def g():\n            __tracebackhide__ = True\n            raise ValueError\n\n        def f():\n            __tracebackhide__ = True\n            g()\n\n        excinfo = pytest.raises(ValueError, f)\n        assert excinfo._getreprcrash() is None\n\n\ndef test_excinfo_exconly():\n    excinfo = pytest.raises(ValueError, h)\n    assert excinfo.exconly().startswith(\"ValueError\")\n    with pytest.raises(ValueError) as excinfo:\n        raise ValueError(\"hello\\nworld\")\n    msg = excinfo.exconly(tryshort=True)\n    assert msg.startswith(\"ValueError\")\n    assert msg.endswith(\"world\")\n\n\ndef test_excinfo_repr_str() -> None:\n    excinfo1 = pytest.raises(ValueError, h)\n    assert repr(excinfo1) == \"<ExceptionInfo ValueError() tblen=4>\"\n    assert str(excinfo1) == \"<ExceptionInfo ValueError() tblen=4>\"\n\n    class CustomException(Exception):\n        def __repr__(self):\n            return \"custom_repr\"\n\n    def raises() -> None:\n        raise CustomException()\n\n    excinfo2 = pytest.raises(CustomException, raises)\n    assert repr(excinfo2) == \"<ExceptionInfo custom_repr tblen=2>\"\n    assert str(excinfo2) == \"<ExceptionInfo custom_repr tblen=2>\"\n\n\ndef test_excinfo_for_later() -> None:\n    e = ExceptionInfo[BaseException].for_later()\n    assert \"for raises\" in repr(e)\n    assert \"for raises\" in str(e)\n\n\ndef test_excinfo_errisinstance():\n    excinfo = pytest.raises(ValueError, h)\n    assert excinfo.errisinstance(ValueError)\n\n\ndef test_excinfo_no_sourcecode():\n    try:\n        exec(\"raise ValueError()\")\n    except ValueError:\n        excinfo = _pytest._code.ExceptionInfo.from_current()\n    s = str(excinfo.traceback[-1])\n    # TODO: Since Python 3.13b1 under pytest-xdist, the * is `import\n    # sys;exec(eval(sys.stdin.readline()))` (execnet bootstrap code)\n    # instead of `???` like before. Is this OK?\n    fnmatch.fnmatch(s, \"  File '<string>':1 in <module>\\n  *\\n\")\n\n\ndef test_excinfo_no_python_sourcecode(tmp_path: Path) -> None:\n    # XXX: simplified locally testable version\n    tmp_path.joinpath(\"test.txt\").write_text(\"{{ h()}}:\", encoding=\"utf-8\")\n\n    jinja2 = pytest.importorskip(\"jinja2\")\n    loader = jinja2.FileSystemLoader(str(tmp_path))\n    env = jinja2.Environment(loader=loader)\n    template = env.get_template(\"test.txt\")\n    excinfo = pytest.raises(ValueError, template.render, h=h)\n    for item in excinfo.traceback:\n        print(item)  # XXX: for some reason jinja.Template.render is printed in full\n        _ = item.source  # shouldn't fail\n        if isinstance(item.path, Path) and item.path.name == \"test.txt\":\n            assert str(item.source) == \"{{ h()}}:\"\n\n\ndef test_entrysource_Queue_example():\n    try:\n        queue.Queue().get(timeout=0.001)\n    except queue.Empty:\n        excinfo = _pytest._code.ExceptionInfo.from_current()\n    entry = excinfo.traceback[-1]\n    source = entry.getsource()\n    assert source is not None\n    s = str(source).strip()\n    assert s.startswith(\"def get\")\n\n\ndef test_codepath_Queue_example() -> None:\n    try:\n        queue.Queue().get(timeout=0.001)\n    except queue.Empty:\n        excinfo = _pytest._code.ExceptionInfo.from_current()\n    entry = excinfo.traceback[-1]\n    path = entry.path\n    assert isinstance(path, Path)\n    assert path.name.lower() == \"queue.py\"\n    assert path.exists()\n\n\ndef test_match_succeeds():\n    with pytest.raises(ZeroDivisionError) as excinfo:\n        _ = 0 // 0\n    excinfo.match(r\".*zero.*\")\n\n\ndef test_match_raises_error(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def test_division_zero():\n            with pytest.raises(ZeroDivisionError) as excinfo:\n                0 / 0\n            excinfo.match(r'[123]+')\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--tb=short\")\n    assert result.ret != 0\n\n    match = [\n        r\"E\\s+AssertionError: Regex pattern did not match.\",\n        r\"E\\s+Expected regex: '\\[123\\]\\+'\",\n        r\"E\\s+Actual message: 'division by zero'\",\n    ]\n    result.stdout.re_match_lines(match)\n    result.stdout.no_fnmatch_line(\"*__tracebackhide__ = True*\")\n\n    result = pytester.runpytest(\"--fulltrace\")\n    assert result.ret != 0\n    result.stdout.re_match_lines([r\".*__tracebackhide__ = True.*\", *match])\n\n\ndef test_raises_accepts_generic_group() -> None:\n    with pytest.raises(ExceptionGroup[Exception]) as exc_info:\n        raise ExceptionGroup(\"\", [RuntimeError()])\n    assert exc_info.group_contains(RuntimeError)\n\n\ndef test_raises_accepts_generic_base_group() -> None:\n    with pytest.raises(BaseExceptionGroup[BaseException]) as exc_info:\n        raise ExceptionGroup(\"\", [RuntimeError()])\n    assert exc_info.group_contains(RuntimeError)\n\n\ndef test_raises_rejects_specific_generic_group() -> None:\n    with pytest.raises(ValueError):\n        pytest.raises(ExceptionGroup[RuntimeError])\n\n\ndef test_raises_accepts_generic_group_in_tuple() -> None:\n    with pytest.raises((ValueError, ExceptionGroup[Exception])) as exc_info:\n        raise ExceptionGroup(\"\", [RuntimeError()])\n    assert exc_info.group_contains(RuntimeError)\n\n\ndef test_raises_exception_escapes_generic_group() -> None:\n    try:\n        with pytest.raises(ExceptionGroup[Exception]):\n            raise ValueError(\"my value error\")\n    except ValueError as e:\n        assert str(e) == \"my value error\"\n    else:\n        pytest.fail(\"Expected ValueError to be raised\")\n\n\nclass TestGroupContains:\n    def test_contains_exception_type(self) -> None:\n        exc_group = ExceptionGroup(\"\", [RuntimeError()])\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert exc_info.group_contains(RuntimeError)\n\n    def test_doesnt_contain_exception_type(self) -> None:\n        exc_group = ExceptionGroup(\"\", [ValueError()])\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert not exc_info.group_contains(RuntimeError)\n\n    def test_contains_exception_match(self) -> None:\n        exc_group = ExceptionGroup(\"\", [RuntimeError(\"exception message\")])\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert exc_info.group_contains(RuntimeError, match=r\"^exception message$\")\n\n    def test_doesnt_contain_exception_match(self) -> None:\n        exc_group = ExceptionGroup(\"\", [RuntimeError(\"message that will not match\")])\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert not exc_info.group_contains(RuntimeError, match=r\"^exception message$\")\n\n    def test_contains_exception_type_unlimited_depth(self) -> None:\n        exc_group = ExceptionGroup(\"\", [ExceptionGroup(\"\", [RuntimeError()])])\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert exc_info.group_contains(RuntimeError)\n\n    def test_contains_exception_type_at_depth_1(self) -> None:\n        exc_group = ExceptionGroup(\"\", [RuntimeError()])\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert exc_info.group_contains(RuntimeError, depth=1)\n\n    def test_doesnt_contain_exception_type_past_depth(self) -> None:\n        exc_group = ExceptionGroup(\"\", [ExceptionGroup(\"\", [RuntimeError()])])\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert not exc_info.group_contains(RuntimeError, depth=1)\n\n    def test_contains_exception_type_specific_depth(self) -> None:\n        exc_group = ExceptionGroup(\"\", [ExceptionGroup(\"\", [RuntimeError()])])\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert exc_info.group_contains(RuntimeError, depth=2)\n\n    def test_contains_exception_match_unlimited_depth(self) -> None:\n        exc_group = ExceptionGroup(\n            \"\", [ExceptionGroup(\"\", [RuntimeError(\"exception message\")])]\n        )\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert exc_info.group_contains(RuntimeError, match=r\"^exception message$\")\n\n    def test_contains_exception_match_at_depth_1(self) -> None:\n        exc_group = ExceptionGroup(\"\", [RuntimeError(\"exception message\")])\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert exc_info.group_contains(\n            RuntimeError, match=r\"^exception message$\", depth=1\n        )\n\n    def test_doesnt_contain_exception_match_past_depth(self) -> None:\n        exc_group = ExceptionGroup(\n            \"\", [ExceptionGroup(\"\", [RuntimeError(\"exception message\")])]\n        )\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert not exc_info.group_contains(\n            RuntimeError, match=r\"^exception message$\", depth=1\n        )\n\n    def test_contains_exception_match_specific_depth(self) -> None:\n        exc_group = ExceptionGroup(\n            \"\", [ExceptionGroup(\"\", [RuntimeError(\"exception message\")])]\n        )\n        with pytest.raises(ExceptionGroup) as exc_info:\n            raise exc_group\n        assert exc_info.group_contains(\n            RuntimeError, match=r\"^exception message$\", depth=2\n        )\n\n\nclass TestFormattedExcinfo:\n    @pytest.fixture\n    def importasmod(self, tmp_path: Path, _sys_snapshot):\n        def importasmod(source):\n            source = textwrap.dedent(source)\n            modpath = tmp_path.joinpath(\"mod.py\")\n            tmp_path.joinpath(\"__init__.py\").touch()\n            modpath.write_text(source, encoding=\"utf-8\")\n            importlib.invalidate_caches()\n            return import_path(\n                modpath, root=tmp_path, consider_namespace_packages=False\n            )\n\n        return importasmod\n\n    def test_repr_source(self):\n        pr = FormattedExcinfo()\n        source = _pytest._code.Source(\n            \"\"\"\\\n            def f(x):\n                pass\n            \"\"\"\n        ).strip()\n        pr.flow_marker = \"|\"  # type: ignore[misc]\n        lines = pr.get_source(source, 0)\n        assert len(lines) == 2\n        assert lines[0] == \"|   def f(x):\"\n        assert lines[1] == \"        pass\"\n\n    def test_repr_source_out_of_bounds(self):\n        pr = FormattedExcinfo()\n        source = _pytest._code.Source(\n            \"\"\"\\\n            def f(x):\n                pass\n            \"\"\"\n        ).strip()\n        pr.flow_marker = \"|\"  # type: ignore[misc]\n\n        lines = pr.get_source(source, 100)\n        assert len(lines) == 1\n        assert lines[0] == \"|   ???\"\n\n        lines = pr.get_source(source, -100)\n        assert len(lines) == 1\n        assert lines[0] == \"|   ???\"\n\n    def test_repr_source_excinfo(self) -> None:\n        \"\"\"Check if indentation is right.\"\"\"\n        try:\n\n            def f():\n                _ = 1 / 0\n\n            f()\n\n        except BaseException:\n            excinfo = _pytest._code.ExceptionInfo.from_current()\n        else:\n            assert False, \"did not raise\"\n\n        pr = FormattedExcinfo()\n        source = pr._getentrysource(excinfo.traceback[-1])\n        assert source is not None\n        lines = pr.get_source(source, 1, excinfo)\n        for line in lines:\n            print(line)\n        assert lines == [\n            \"    def f():\",\n            \">       _ = 1 / 0\",\n            \"E       ZeroDivisionError: division by zero\",\n        ]\n\n    def test_repr_source_not_existing(self):\n        pr = FormattedExcinfo()\n        co = compile(\"raise ValueError()\", \"\", \"exec\")\n        try:\n            exec(co)\n        except ValueError:\n            excinfo = _pytest._code.ExceptionInfo.from_current()\n        repr = pr.repr_excinfo(excinfo)\n        assert repr.reprtraceback.reprentries[1].lines[0] == \">   ???\"\n        assert repr.chain[0][0].reprentries[1].lines[0] == \">   ???\"\n\n    def test_repr_many_line_source_not_existing(self):\n        pr = FormattedExcinfo()\n        co = compile(\n            \"\"\"\na = 1\nraise ValueError()\n\"\"\",\n            \"\",\n            \"exec\",\n        )\n        try:\n            exec(co)\n        except ValueError:\n            excinfo = _pytest._code.ExceptionInfo.from_current()\n        repr = pr.repr_excinfo(excinfo)\n        assert repr.reprtraceback.reprentries[1].lines[0] == \">   ???\"\n        assert repr.chain[0][0].reprentries[1].lines[0] == \">   ???\"\n\n    def test_repr_source_failing_fullsource(self, monkeypatch) -> None:\n        pr = FormattedExcinfo()\n\n        try:\n            _ = 1 / 0\n        except ZeroDivisionError:\n            excinfo = ExceptionInfo.from_current()\n\n        with monkeypatch.context() as m:\n            m.setattr(_pytest._code.Code, \"fullsource\", property(lambda self: None))\n            repr = pr.repr_excinfo(excinfo)\n\n        assert repr.reprtraceback.reprentries[0].lines[0] == \">   ???\"\n        assert repr.chain[0][0].reprentries[0].lines[0] == \">   ???\"\n\n    def test_repr_local(self) -> None:\n        p = FormattedExcinfo(showlocals=True)\n        loc = {\"y\": 5, \"z\": 7, \"x\": 3, \"@x\": 2, \"__builtins__\": {}}\n        reprlocals = p.repr_locals(loc)\n        assert reprlocals is not None\n        assert reprlocals.lines\n        assert reprlocals.lines[0] == \"__builtins__ = <builtins>\"\n        assert reprlocals.lines[1] == \"x          = 3\"\n        assert reprlocals.lines[2] == \"y          = 5\"\n        assert reprlocals.lines[3] == \"z          = 7\"\n\n    def test_repr_local_with_error(self) -> None:\n        class ObjWithErrorInRepr:\n            def __repr__(self):\n                raise NotImplementedError\n\n        p = FormattedExcinfo(showlocals=True, truncate_locals=False)\n        loc = {\"x\": ObjWithErrorInRepr(), \"__builtins__\": {}}\n        reprlocals = p.repr_locals(loc)\n        assert reprlocals is not None\n        assert reprlocals.lines\n        assert reprlocals.lines[0] == \"__builtins__ = <builtins>\"\n        assert \"[NotImplementedError() raised in repr()]\" in reprlocals.lines[1]\n\n    def test_repr_local_with_exception_in_class_property(self) -> None:\n        class ExceptionWithBrokenClass(Exception):\n            # Type ignored because it's bypassed intentionally.\n            @property  # type: ignore\n            def __class__(self):\n                raise TypeError(\"boom!\")\n\n        class ObjWithErrorInRepr:\n            def __repr__(self):\n                raise ExceptionWithBrokenClass()\n\n        p = FormattedExcinfo(showlocals=True, truncate_locals=False)\n        loc = {\"x\": ObjWithErrorInRepr(), \"__builtins__\": {}}\n        reprlocals = p.repr_locals(loc)\n        assert reprlocals is not None\n        assert reprlocals.lines\n        assert reprlocals.lines[0] == \"__builtins__ = <builtins>\"\n        assert \"[ExceptionWithBrokenClass() raised in repr()]\" in reprlocals.lines[1]\n\n    def test_repr_local_truncated(self) -> None:\n        loc = {\"l\": [i for i in range(10)]}\n        p = FormattedExcinfo(showlocals=True)\n        truncated_reprlocals = p.repr_locals(loc)\n        assert truncated_reprlocals is not None\n        assert truncated_reprlocals.lines\n        assert truncated_reprlocals.lines[0] == \"l          = [0, 1, 2, 3, 4, 5, ...]\"\n\n        q = FormattedExcinfo(showlocals=True, truncate_locals=False)\n        full_reprlocals = q.repr_locals(loc)\n        assert full_reprlocals is not None\n        assert full_reprlocals.lines\n        assert full_reprlocals.lines[0] == \"l          = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\"\n\n    def test_repr_args_not_truncated(self, importasmod) -> None:\n        mod = importasmod(\n            \"\"\"\n            def func1(m):\n                raise ValueError(\"hello\\\\nworld\")\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.func1, \"m\" * 500)\n        excinfo.traceback = excinfo.traceback.filter(excinfo)\n        entry = excinfo.traceback[-1]\n        p = FormattedExcinfo(funcargs=True, truncate_args=True)\n        reprfuncargs = p.repr_args(entry)\n        assert reprfuncargs is not None\n        arg1 = cast(str, reprfuncargs.args[0][1])\n        assert len(arg1) < 500\n        assert \"...\" in arg1\n        # again without truncate\n        p = FormattedExcinfo(funcargs=True, truncate_args=False)\n        reprfuncargs = p.repr_args(entry)\n        assert reprfuncargs is not None\n        assert reprfuncargs.args[0] == (\"m\", repr(\"m\" * 500))\n        assert \"...\" not in cast(str, reprfuncargs.args[0][1])\n\n    def test_repr_tracebackentry_lines(self, importasmod) -> None:\n        mod = importasmod(\n            \"\"\"\n            def func1():\n                raise ValueError(\"hello\\\\nworld\")\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.func1)\n        excinfo.traceback = excinfo.traceback.filter(excinfo)\n        p = FormattedExcinfo()\n        reprtb = p.repr_traceback_entry(excinfo.traceback[-1])\n\n        # test as intermittent entry\n        lines = reprtb.lines\n        assert lines[0] == \"    def func1():\"\n        assert lines[1] == '>       raise ValueError(\"hello\\\\nworld\")'\n\n        # test as last entry\n        p = FormattedExcinfo(showlocals=True)\n        repr_entry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n        lines = repr_entry.lines\n        assert lines[0] == \"    def func1():\"\n        assert lines[1] == '>       raise ValueError(\"hello\\\\nworld\")'\n        assert lines[2] == \"E       ValueError: hello\"\n        assert lines[3] == \"E       world\"\n        assert not lines[4:]\n\n        loc = repr_entry.reprfileloc\n        assert loc is not None\n        assert loc.path == mod.__file__\n        assert loc.lineno == 3\n        # assert loc.message == \"ValueError: hello\"\n\n    def test_repr_tracebackentry_lines2(self, importasmod, tw_mock) -> None:\n        mod = importasmod(\n            \"\"\"\n            def func1(m, x, y, z):\n                raise ValueError(\"hello\\\\nworld\")\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.func1, \"m\" * 90, 5, 13, \"z\" * 120)\n        excinfo.traceback = excinfo.traceback.filter(excinfo)\n        entry = excinfo.traceback[-1]\n        p = FormattedExcinfo(funcargs=True)\n        reprfuncargs = p.repr_args(entry)\n        assert reprfuncargs is not None\n        assert reprfuncargs.args[0] == (\"m\", repr(\"m\" * 90))\n        assert reprfuncargs.args[1] == (\"x\", \"5\")\n        assert reprfuncargs.args[2] == (\"y\", \"13\")\n        assert reprfuncargs.args[3] == (\"z\", repr(\"z\" * 120))\n\n        p = FormattedExcinfo(funcargs=True)\n        repr_entry = p.repr_traceback_entry(entry)\n        assert repr_entry.reprfuncargs is not None\n        assert repr_entry.reprfuncargs.args == reprfuncargs.args\n        repr_entry.toterminal(tw_mock)\n        assert tw_mock.lines[0] == \"m = \" + repr(\"m\" * 90)\n        assert tw_mock.lines[1] == \"x = 5, y = 13\"\n        assert tw_mock.lines[2] == \"z = \" + repr(\"z\" * 120)\n\n    def test_repr_tracebackentry_lines_var_kw_args(self, importasmod, tw_mock) -> None:\n        mod = importasmod(\n            \"\"\"\n            def func1(x, *y, **z):\n                raise ValueError(\"hello\\\\nworld\")\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.func1, \"a\", \"b\", c=\"d\")\n        excinfo.traceback = excinfo.traceback.filter(excinfo)\n        entry = excinfo.traceback[-1]\n        p = FormattedExcinfo(funcargs=True)\n        reprfuncargs = p.repr_args(entry)\n        assert reprfuncargs is not None\n        assert reprfuncargs.args[0] == (\"x\", repr(\"a\"))\n        assert reprfuncargs.args[1] == (\"y\", repr((\"b\",)))\n        assert reprfuncargs.args[2] == (\"z\", repr({\"c\": \"d\"}))\n\n        p = FormattedExcinfo(funcargs=True)\n        repr_entry = p.repr_traceback_entry(entry)\n        assert repr_entry.reprfuncargs\n        assert repr_entry.reprfuncargs.args == reprfuncargs.args\n        repr_entry.toterminal(tw_mock)\n        assert tw_mock.lines[0] == \"x = 'a', y = ('b',), z = {'c': 'd'}\"\n\n    def test_repr_tracebackentry_short(self, importasmod) -> None:\n        mod = importasmod(\n            \"\"\"\n            def func1():\n                raise ValueError(\"hello\")\n            def entry():\n                func1()\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.entry)\n        p = FormattedExcinfo(style=\"short\")\n        reprtb = p.repr_traceback_entry(excinfo.traceback[-2])\n        lines = reprtb.lines\n        basename = Path(mod.__file__).name\n        assert lines[0] == \"    func1()\"\n        assert reprtb.reprfileloc is not None\n        assert basename in str(reprtb.reprfileloc.path)\n        assert reprtb.reprfileloc.lineno == 5\n\n        # test last entry\n        p = FormattedExcinfo(style=\"short\")\n        reprtb = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n        lines = reprtb.lines\n        assert lines[0] == '    raise ValueError(\"hello\")'\n        assert lines[1] == \"E   ValueError: hello\"\n        assert reprtb.reprfileloc is not None\n        assert basename in str(reprtb.reprfileloc.path)\n        assert reprtb.reprfileloc.lineno == 3\n\n    @pytest.mark.skipif(\n        \"sys.version_info < (3,11)\",\n        reason=\"Column level traceback info added in python 3.11\",\n    )\n    def test_repr_traceback_entry_short_carets(self, importasmod) -> None:\n        mod = importasmod(\n            \"\"\"\n            def div_by_zero():\n                return 1 / 0\n            def func1():\n                return 42 + div_by_zero()\n            def entry():\n                func1()\n        \"\"\"\n        )\n        excinfo = pytest.raises(ZeroDivisionError, mod.entry)\n        p = FormattedExcinfo(style=\"short\")\n        reprtb = p.repr_traceback_entry(excinfo.traceback[-3])\n        assert len(reprtb.lines) == 1\n        assert reprtb.lines[0] == \"    func1()\"\n\n        reprtb = p.repr_traceback_entry(excinfo.traceback[-2])\n        assert len(reprtb.lines) == 2\n        assert reprtb.lines[0] == \"    return 42 + div_by_zero()\"\n        assert reprtb.lines[1] == \"                ^^^^^^^^^^^^^\"\n\n        reprtb = p.repr_traceback_entry(excinfo.traceback[-1])\n        assert len(reprtb.lines) == 2\n        assert reprtb.lines[0] == \"    return 1 / 0\"\n        assert reprtb.lines[1] == \"           ^^^^^\"\n\n    def test_repr_tracebackentry_no(self, importasmod):\n        mod = importasmod(\n            \"\"\"\n            def func1():\n                raise ValueError(\"hello\")\n            def entry():\n                func1()\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.entry)\n        p = FormattedExcinfo(style=\"no\")\n        p.repr_traceback_entry(excinfo.traceback[-2])\n\n        p = FormattedExcinfo(style=\"no\")\n        reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n        lines = reprentry.lines\n        assert lines[0] == \"E   ValueError: hello\"\n        assert not lines[1:]\n\n    def test_repr_traceback_tbfilter(self, importasmod):\n        mod = importasmod(\n            \"\"\"\n            def f(x):\n                raise ValueError(x)\n            def entry():\n                f(0)\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.entry)\n        p = FormattedExcinfo(tbfilter=True)\n        reprtb = p.repr_traceback(excinfo)\n        assert len(reprtb.reprentries) == 2\n        p = FormattedExcinfo(tbfilter=False)\n        reprtb = p.repr_traceback(excinfo)\n        assert len(reprtb.reprentries) == 3\n\n    def test_traceback_short_no_source(\n        self,\n        importasmod,\n        monkeypatch: pytest.MonkeyPatch,\n    ) -> None:\n        mod = importasmod(\n            \"\"\"\n            def func1():\n                raise ValueError(\"hello\")\n            def entry():\n                func1()\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.entry)\n        from _pytest._code.code import Code\n\n        with monkeypatch.context() as mp:\n            mp.setattr(Code, \"path\", \"bogus\")\n            p = FormattedExcinfo(style=\"short\")\n            reprtb = p.repr_traceback_entry(excinfo.traceback[-2])\n            lines = reprtb.lines\n            last_p = FormattedExcinfo(style=\"short\")\n            last_reprtb = last_p.repr_traceback_entry(excinfo.traceback[-1], excinfo)\n            last_lines = last_reprtb.lines\n        assert lines[0] == \"    func1()\"\n\n        assert last_lines[0] == '    raise ValueError(\"hello\")'\n        assert last_lines[1] == \"E   ValueError: hello\"\n\n    def test_repr_traceback_and_excinfo(self, importasmod) -> None:\n        mod = importasmod(\n            \"\"\"\n            def f(x):\n                raise ValueError(x)\n            def entry():\n                f(0)\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.entry)\n\n        styles: tuple[TracebackStyle, ...] = (\"long\", \"short\")\n        for style in styles:\n            p = FormattedExcinfo(style=style)\n            reprtb = p.repr_traceback(excinfo)\n            assert len(reprtb.reprentries) == 2\n            assert reprtb.style == style\n            assert not reprtb.extraline\n            repr = p.repr_excinfo(excinfo)\n            assert repr.reprtraceback\n            assert len(repr.reprtraceback.reprentries) == len(reprtb.reprentries)\n\n            assert repr.chain[0][0]\n            assert len(repr.chain[0][0].reprentries) == len(reprtb.reprentries)\n            assert repr.reprcrash is not None\n            assert repr.reprcrash.path.endswith(\"mod.py\")\n            assert repr.reprcrash.message == \"ValueError: 0\"\n\n    def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch) -> None:\n        mod = importasmod(\n            \"\"\"\n            def f(x):\n                raise ValueError(x)\n            def entry():\n                f(0)\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.entry)\n\n        p = FormattedExcinfo(abspath=False)\n\n        raised = 0\n\n        orig_path_cwd = Path.cwd\n\n        def raiseos():\n            nonlocal raised\n            upframe = sys._getframe().f_back\n            assert upframe is not None\n            if upframe.f_code.co_name == \"_makepath\":\n                # Only raise with expected calls, and not accidentally via 'inspect'\n                # See 79ae86cc3f76d69460e1c7beca4ce95e68ab80a6\n                raised += 1\n                raise OSError(2, \"custom_oserror\")\n            return orig_path_cwd()\n\n        monkeypatch.setattr(Path, \"cwd\", raiseos)\n        assert p._makepath(Path(__file__)) == __file__\n        assert raised == 1\n        repr_tb = p.repr_traceback(excinfo)\n\n        matcher = LineMatcher(str(repr_tb).splitlines())\n        matcher.fnmatch_lines(\n            [\n                \"def entry():\",\n                \">       f(0)\",\n                \"\",\n                f\"{mod.__file__}:5: \",\n                \"_ _ *\",\n                \"\",\n                \"    def f(x):\",\n                \">       raise ValueError(x)\",\n                \"E       ValueError: 0\",\n                \"\",\n                f\"{mod.__file__}:3: ValueError\",\n            ]\n        )\n        assert raised == 3\n\n    def test_repr_excinfo_addouterr(self, importasmod, tw_mock):\n        mod = importasmod(\n            \"\"\"\n            def entry():\n                raise ValueError()\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.entry)\n        repr = excinfo.getrepr()\n        repr.addsection(\"title\", \"content\")\n        repr.toterminal(tw_mock)\n        assert tw_mock.lines[-1] == \"content\"\n        assert tw_mock.lines[-2] == (\"-\", \"title\")\n\n    def test_repr_excinfo_reprcrash(self, importasmod) -> None:\n        mod = importasmod(\n            \"\"\"\n            def entry():\n                raise ValueError()\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.entry)\n        repr = excinfo.getrepr()\n        assert repr.reprcrash is not None\n        assert repr.reprcrash.path.endswith(\"mod.py\")\n        assert repr.reprcrash.lineno == 3\n        assert repr.reprcrash.message == \"ValueError\"\n        assert str(repr.reprcrash).endswith(\"mod.py:3: ValueError\")\n\n    def test_repr_traceback_recursion(self, importasmod):\n        mod = importasmod(\n            \"\"\"\n            def rec2(x):\n                return rec1(x+1)\n            def rec1(x):\n                return rec2(x-1)\n            def entry():\n                rec1(42)\n        \"\"\"\n        )\n        excinfo = pytest.raises(RuntimeError, mod.entry)\n\n        for style in (\"short\", \"long\", \"no\"):\n            p = FormattedExcinfo(style=\"short\")\n            reprtb = p.repr_traceback(excinfo)\n            assert reprtb.extraline == \"!!! Recursion detected (same locals & position)\"\n            assert str(reprtb)\n\n    def test_reprexcinfo_getrepr(self, importasmod) -> None:\n        mod = importasmod(\n            \"\"\"\n            def f(x):\n                raise ValueError(x)\n            def entry():\n                f(0)\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.entry)\n\n        styles: tuple[TracebackStyle, ...] = (\"short\", \"long\", \"no\")\n        for style in styles:\n            for showlocals in (True, False):\n                repr = excinfo.getrepr(style=style, showlocals=showlocals)\n                assert repr.reprtraceback.style == style\n\n                assert isinstance(repr, ExceptionChainRepr)\n                for r in repr.chain:\n                    assert r[0].style == style\n\n    def test_reprexcinfo_unicode(self):\n        from _pytest._code.code import TerminalRepr\n\n        class MyRepr(TerminalRepr):\n            def toterminal(self, tw: TerminalWriter) -> None:\n                tw.line(\"я\")\n\n        x = str(MyRepr())\n        assert x == \"я\"\n\n    def test_toterminal_long(self, importasmod, tw_mock):\n        mod = importasmod(\n            \"\"\"\n            def g(x):\n                raise ValueError(x)\n            def f():\n                g(3)\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.f)\n        excinfo.traceback = excinfo.traceback.filter(excinfo)\n        repr = excinfo.getrepr()\n        repr.toterminal(tw_mock)\n        assert tw_mock.lines[0] == \"\"\n        tw_mock.lines.pop(0)\n        assert tw_mock.lines[0] == \"    def f():\"\n        assert tw_mock.lines[1] == \">       g(3)\"\n        assert tw_mock.lines[2] == \"\"\n        line = tw_mock.get_write_msg(3)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[4] == (\":5: \")\n        assert tw_mock.lines[5] == (\"_ \", None)\n        assert tw_mock.lines[6] == \"\"\n        assert tw_mock.lines[7] == \"    def g(x):\"\n        assert tw_mock.lines[8] == \">       raise ValueError(x)\"\n        assert tw_mock.lines[9] == \"E       ValueError: 3\"\n        assert tw_mock.lines[10] == \"\"\n        line = tw_mock.get_write_msg(11)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[12] == \":3: ValueError\"\n\n    def test_toterminal_long_missing_source(\n        self, importasmod, tmp_path: Path, tw_mock\n    ) -> None:\n        mod = importasmod(\n            \"\"\"\n            def g(x):\n                raise ValueError(x)\n            def f():\n                g(3)\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.f)\n        tmp_path.joinpath(\"mod.py\").unlink()\n        excinfo.traceback = excinfo.traceback.filter(excinfo)\n        repr = excinfo.getrepr()\n        repr.toterminal(tw_mock)\n        assert tw_mock.lines[0] == \"\"\n        tw_mock.lines.pop(0)\n        assert tw_mock.lines[0] == \">   ???\"\n        assert tw_mock.lines[1] == \"\"\n        line = tw_mock.get_write_msg(2)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[3] == \":5: \"\n        assert tw_mock.lines[4] == (\"_ \", None)\n        assert tw_mock.lines[5] == \"\"\n        assert tw_mock.lines[6] == \">   ???\"\n        assert tw_mock.lines[7] == \"E   ValueError: 3\"\n        assert tw_mock.lines[8] == \"\"\n        line = tw_mock.get_write_msg(9)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[10] == \":3: ValueError\"\n\n    def test_toterminal_long_incomplete_source(\n        self, importasmod, tmp_path: Path, tw_mock\n    ) -> None:\n        mod = importasmod(\n            \"\"\"\n            def g(x):\n                raise ValueError(x)\n            def f():\n                g(3)\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.f)\n        tmp_path.joinpath(\"mod.py\").write_text(\"asdf\", encoding=\"utf-8\")\n        excinfo.traceback = excinfo.traceback.filter(excinfo)\n        repr = excinfo.getrepr()\n        repr.toterminal(tw_mock)\n        assert tw_mock.lines[0] == \"\"\n        tw_mock.lines.pop(0)\n        assert tw_mock.lines[0] == \">   ???\"\n        assert tw_mock.lines[1] == \"\"\n        line = tw_mock.get_write_msg(2)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[3] == \":5: \"\n        assert tw_mock.lines[4] == (\"_ \", None)\n        assert tw_mock.lines[5] == \"\"\n        assert tw_mock.lines[6] == \">   ???\"\n        assert tw_mock.lines[7] == \"E   ValueError: 3\"\n        assert tw_mock.lines[8] == \"\"\n        line = tw_mock.get_write_msg(9)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[10] == \":3: ValueError\"\n\n    def test_toterminal_long_filenames(\n        self, importasmod, tw_mock, monkeypatch: MonkeyPatch\n    ) -> None:\n        mod = importasmod(\n            \"\"\"\n            def f():\n                raise ValueError()\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.f)\n        path = Path(mod.__file__)\n        monkeypatch.chdir(path.parent)\n        repr = excinfo.getrepr(abspath=False)\n        repr.toterminal(tw_mock)\n        x = bestrelpath(Path.cwd(), path)\n        if len(x) < len(str(path)):\n            msg = tw_mock.get_write_msg(-2)\n            assert msg == \"mod.py\"\n            assert tw_mock.lines[-1] == \":3: ValueError\"\n\n        repr = excinfo.getrepr(abspath=True)\n        repr.toterminal(tw_mock)\n        msg = tw_mock.get_write_msg(-2)\n        assert msg == str(path)\n        line = tw_mock.lines[-1]\n        assert line == \":3: ValueError\"\n\n    def test_toterminal_value(self, importasmod, tw_mock):\n        mod = importasmod(\n            \"\"\"\n            def g(x):\n                raise ValueError(x)\n            def f():\n                g('some_value')\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.f)\n        excinfo.traceback = excinfo.traceback.filter(excinfo)\n        repr = excinfo.getrepr(style=\"value\")\n        repr.toterminal(tw_mock)\n\n        assert tw_mock.get_write_msg(0) == \"some_value\"\n        assert tw_mock.get_write_msg(1) == \"\\n\"\n\n    @pytest.mark.parametrize(\n        \"reproptions\",\n        [\n            pytest.param(\n                {\n                    \"style\": style,\n                    \"showlocals\": showlocals,\n                    \"funcargs\": funcargs,\n                    \"tbfilter\": tbfilter,\n                },\n                id=f\"style={style},showlocals={showlocals},funcargs={funcargs},tbfilter={tbfilter}\",\n            )\n            for style in [\"long\", \"short\", \"line\", \"no\", \"native\", \"value\", \"auto\"]\n            for showlocals in (True, False)\n            for tbfilter in (True, False)\n            for funcargs in (True, False)\n        ],\n    )\n    def test_format_excinfo(self, reproptions: dict[str, Any]) -> None:\n        def bar():\n            assert False, \"some error\"\n\n        def foo():\n            bar()\n\n        # using inline functions as opposed to importasmod so we get source code lines\n        # in the tracebacks (otherwise getinspect doesn't find the source code).\n        with pytest.raises(AssertionError) as excinfo:\n            foo()\n        file = io.StringIO()\n        tw = TerminalWriter(file=file)\n        repr = excinfo.getrepr(**reproptions)\n        repr.toterminal(tw)\n        assert file.getvalue()\n\n    def test_traceback_repr_style(self, importasmod, tw_mock):\n        mod = importasmod(\n            \"\"\"\n            def f():\n                g()\n            def g():\n                h()\n            def h():\n                i()\n            def i():\n                raise ValueError()\n        \"\"\"\n        )\n        excinfo = pytest.raises(ValueError, mod.f)\n        excinfo.traceback = excinfo.traceback.filter(excinfo)\n        excinfo.traceback = _pytest._code.Traceback(\n            entry if i not in (1, 2) else entry.with_repr_style(\"short\")\n            for i, entry in enumerate(excinfo.traceback)\n        )\n        r = excinfo.getrepr(style=\"long\")\n        r.toterminal(tw_mock)\n        for line in tw_mock.lines:\n            print(line)\n        assert tw_mock.lines[0] == \"\"\n        assert tw_mock.lines[1] == \"    def f():\"\n        assert tw_mock.lines[2] == \">       g()\"\n        assert tw_mock.lines[3] == \"\"\n        msg = tw_mock.get_write_msg(4)\n        assert msg.endswith(\"mod.py\")\n        assert tw_mock.lines[5] == \":3: \"\n        assert tw_mock.lines[6] == (\"_ \", None)\n        tw_mock.get_write_msg(7)\n        assert tw_mock.lines[8].endswith(\"in g\")\n        assert tw_mock.lines[9] == \"    h()\"\n        tw_mock.get_write_msg(10)\n        assert tw_mock.lines[11].endswith(\"in h\")\n        assert tw_mock.lines[12] == \"    i()\"\n        assert tw_mock.lines[13] == (\"_ \", None)\n        assert tw_mock.lines[14] == \"\"\n        assert tw_mock.lines[15] == \"    def i():\"\n        assert tw_mock.lines[16] == \">       raise ValueError()\"\n        assert tw_mock.lines[17] == \"E       ValueError\"\n        assert tw_mock.lines[18] == \"\"\n        msg = tw_mock.get_write_msg(19)\n        msg.endswith(\"mod.py\")\n        assert tw_mock.lines[20] == \":9: ValueError\"\n\n    def test_exc_chain_repr(self, importasmod, tw_mock):\n        mod = importasmod(\n            \"\"\"\n            class Err(Exception):\n                pass\n            def f():\n                try:\n                    g()\n                except Exception as e:\n                    raise Err() from e\n                finally:\n                    h()\n            def g():\n                raise ValueError()\n\n            def h():\n                if True: raise AttributeError()\n        \"\"\"\n        )\n        excinfo = pytest.raises(AttributeError, mod.f)\n        r = excinfo.getrepr(style=\"long\")\n        r.toterminal(tw_mock)\n        for line in tw_mock.lines:\n            print(line)\n        assert tw_mock.lines[0] == \"\"\n        assert tw_mock.lines[1] == \"    def f():\"\n        assert tw_mock.lines[2] == \"        try:\"\n        assert tw_mock.lines[3] == \">           g()\"\n        assert tw_mock.lines[4] == \"\"\n        line = tw_mock.get_write_msg(5)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[6] == \":6: \"\n        assert tw_mock.lines[7] == (\"_ \", None)\n        assert tw_mock.lines[8] == \"\"\n        assert tw_mock.lines[9] == \"    def g():\"\n        assert tw_mock.lines[10] == \">       raise ValueError()\"\n        assert tw_mock.lines[11] == \"E       ValueError\"\n        assert tw_mock.lines[12] == \"\"\n        line = tw_mock.get_write_msg(13)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[14] == \":12: ValueError\"\n        assert tw_mock.lines[15] == \"\"\n        assert (\n            tw_mock.lines[16]\n            == \"The above exception was the direct cause of the following exception:\"\n        )\n        assert tw_mock.lines[17] == \"\"\n        assert tw_mock.lines[18] == \"    def f():\"\n        assert tw_mock.lines[19] == \"        try:\"\n        assert tw_mock.lines[20] == \"            g()\"\n        assert tw_mock.lines[21] == \"        except Exception as e:\"\n        assert tw_mock.lines[22] == \">           raise Err() from e\"\n        assert tw_mock.lines[23] == \"E           test_exc_chain_repr0.mod.Err\"\n        assert tw_mock.lines[24] == \"\"\n        line = tw_mock.get_write_msg(25)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[26] == \":8: Err\"\n        assert tw_mock.lines[27] == \"\"\n        assert (\n            tw_mock.lines[28]\n            == \"During handling of the above exception, another exception occurred:\"\n        )\n        assert tw_mock.lines[29] == \"\"\n        assert tw_mock.lines[30] == \"    def f():\"\n        assert tw_mock.lines[31] == \"        try:\"\n        assert tw_mock.lines[32] == \"            g()\"\n        assert tw_mock.lines[33] == \"        except Exception as e:\"\n        assert tw_mock.lines[34] == \"            raise Err() from e\"\n        assert tw_mock.lines[35] == \"        finally:\"\n        assert tw_mock.lines[36] == \">           h()\"\n        assert tw_mock.lines[37] == \"\"\n        line = tw_mock.get_write_msg(38)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[39] == \":10: \"\n        assert tw_mock.lines[40] == (\"_ \", None)\n        assert tw_mock.lines[41] == \"\"\n        assert tw_mock.lines[42] == \"    def h():\"\n        # On python 3.11 and greater, check for carets in the traceback.\n        if sys.version_info >= (3, 11):\n            assert tw_mock.lines[43] == \">       if True: raise AttributeError()\"\n            assert tw_mock.lines[44] == \"                 ^^^^^^^^^^^^^^^^^^^^^^\"\n            assert tw_mock.lines[45] == \"E       AttributeError\"\n            assert tw_mock.lines[46] == \"\"\n            line = tw_mock.get_write_msg(47)\n            assert line.endswith(\"mod.py\")\n            assert tw_mock.lines[48] == \":15: AttributeError\"\n        else:\n            assert tw_mock.lines[43] == \">       if True: raise AttributeError()\"\n            assert tw_mock.lines[44] == \"E       AttributeError\"\n            assert tw_mock.lines[45] == \"\"\n            line = tw_mock.get_write_msg(46)\n            assert line.endswith(\"mod.py\")\n            assert tw_mock.lines[47] == \":15: AttributeError\"\n\n    @pytest.mark.parametrize(\"mode\", [\"from_none\", \"explicit_suppress\"])\n    def test_exc_repr_chain_suppression(self, importasmod, mode, tw_mock):\n        \"\"\"Check that exc repr does not show chained exceptions in Python 3.\n        - When the exception is raised with \"from None\"\n        - Explicitly suppressed with \"chain=False\" to ExceptionInfo.getrepr().\n        \"\"\"\n        raise_suffix = \" from None\" if mode == \"from_none\" else \"\"\n        mod = importasmod(\n            f\"\"\"\n            def f():\n                try:\n                    g()\n                except Exception:\n                    raise AttributeError(){raise_suffix}\n            def g():\n                raise ValueError()\n        \"\"\"\n        )\n        excinfo = pytest.raises(AttributeError, mod.f)\n        r = excinfo.getrepr(style=\"long\", chain=mode != \"explicit_suppress\")\n        r.toterminal(tw_mock)\n        for line in tw_mock.lines:\n            print(line)\n        assert tw_mock.lines[0] == \"\"\n        assert tw_mock.lines[1] == \"    def f():\"\n        assert tw_mock.lines[2] == \"        try:\"\n        assert tw_mock.lines[3] == \"            g()\"\n        assert tw_mock.lines[4] == \"        except Exception:\"\n        assert tw_mock.lines[5] == f\">           raise AttributeError(){raise_suffix}\"\n        assert tw_mock.lines[6] == \"E           AttributeError\"\n        assert tw_mock.lines[7] == \"\"\n        line = tw_mock.get_write_msg(8)\n        assert line.endswith(\"mod.py\")\n        assert tw_mock.lines[9] == \":6: AttributeError\"\n        assert len(tw_mock.lines) == 10\n\n    @pytest.mark.parametrize(\n        \"reason, description\",\n        [\n            pytest.param(\n                \"cause\",\n                \"The above exception was the direct cause of the following exception:\",\n                id=\"cause\",\n            ),\n            pytest.param(\n                \"context\",\n                \"During handling of the above exception, another exception occurred:\",\n                id=\"context\",\n            ),\n        ],\n    )\n    def test_exc_chain_repr_without_traceback(self, importasmod, reason, description):\n        \"\"\"\n        Handle representation of exception chains where one of the exceptions doesn't have a\n        real traceback, such as those raised in a subprocess submitted by the multiprocessing\n        module (#1984).\n        \"\"\"\n        exc_handling_code = \" from e\" if reason == \"cause\" else \"\"\n        mod = importasmod(\n            f\"\"\"\n            def f():\n                try:\n                    g()\n                except Exception as e:\n                    raise RuntimeError('runtime problem'){exc_handling_code}\n            def g():\n                raise ValueError('invalid value')\n        \"\"\"\n        )\n\n        with pytest.raises(RuntimeError) as excinfo:\n            mod.f()\n\n        # emulate the issue described in #1984\n        attr = f\"__{reason}__\"\n        getattr(excinfo.value, attr).__traceback__ = None\n\n        r = excinfo.getrepr()\n        file = io.StringIO()\n        tw = TerminalWriter(file=file)\n        tw.hasmarkup = False\n        r.toterminal(tw)\n\n        matcher = LineMatcher(file.getvalue().splitlines())\n        matcher.fnmatch_lines(\n            [\n                \"ValueError: invalid value\",\n                description,\n                \"* except Exception as e:\",\n                \"> * raise RuntimeError('runtime problem')\" + exc_handling_code,\n                \"E *RuntimeError: runtime problem\",\n            ]\n        )\n\n    def test_exc_chain_repr_cycle(self, importasmod, tw_mock):\n        mod = importasmod(\n            \"\"\"\n            class Err(Exception):\n                pass\n            def fail():\n                return 0 / 0\n            def reraise():\n                try:\n                    fail()\n                except ZeroDivisionError as e:\n                    raise Err() from e\n            def unreraise():\n                try:\n                    reraise()\n                except Err as e:\n                    raise e.__cause__\n        \"\"\"\n        )\n        excinfo = pytest.raises(ZeroDivisionError, mod.unreraise)\n        r = excinfo.getrepr(style=\"short\")\n        r.toterminal(tw_mock)\n        out = \"\\n\".join(line for line in tw_mock.lines if isinstance(line, str))\n        # Assert highlighting carets in python3.11+\n        if sys.version_info >= (3, 11):\n            expected_out = textwrap.dedent(\n                \"\"\"\\\n                :13: in unreraise\n                    reraise()\n                :10: in reraise\n                    raise Err() from e\n                E   test_exc_chain_repr_cycle0.mod.Err\n\n                During handling of the above exception, another exception occurred:\n                :15: in unreraise\n                    raise e.__cause__\n                :8: in reraise\n                    fail()\n                :5: in fail\n                    return 0 / 0\n                           ^^^^^\n                E   ZeroDivisionError: division by zero\"\"\"\n            )\n        else:\n            expected_out = textwrap.dedent(\n                \"\"\"\\\n                :13: in unreraise\n                    reraise()\n                :10: in reraise\n                    raise Err() from e\n                E   test_exc_chain_repr_cycle0.mod.Err\n\n                During handling of the above exception, another exception occurred:\n                :15: in unreraise\n                    raise e.__cause__\n                :8: in reraise\n                    fail()\n                :5: in fail\n                    return 0 / 0\n                E   ZeroDivisionError: division by zero\"\"\"\n            )\n        assert out == expected_out\n\n    def test_exec_type_error_filter(self, importasmod):\n        \"\"\"See #7742\"\"\"\n        mod = importasmod(\n            \"\"\"\\\n            def f():\n                exec(\"a = 1\", {}, [])\n            \"\"\"\n        )\n        with pytest.raises(TypeError) as excinfo:\n            mod.f()\n        # previously crashed with `AttributeError: list has no attribute get`\n        excinfo.traceback.filter(excinfo)\n\n\n@pytest.mark.parametrize(\"style\", [\"short\", \"long\"])\n@pytest.mark.parametrize(\"encoding\", [None, \"utf8\", \"utf16\"])\ndef test_repr_traceback_with_unicode(style, encoding):\n    if encoding is None:\n        msg: str | bytes = \"☹\"\n    else:\n        msg = \"☹\".encode(encoding)\n    try:\n        raise RuntimeError(msg)\n    except RuntimeError:\n        e_info = ExceptionInfo.from_current()\n    formatter = FormattedExcinfo(style=style)\n    repr_traceback = formatter.repr_traceback(e_info)\n    assert repr_traceback is not None\n\n\ndef test_cwd_deleted(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import os\n\n        def test(tmp_path):\n            os.chdir(tmp_path)\n            tmp_path.unlink()\n            assert False\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"* 1 failed in *\"])\n    result.stdout.no_fnmatch_line(\"*INTERNALERROR*\")\n    result.stderr.no_fnmatch_line(\"*INTERNALERROR*\")\n\n\ndef test_regression_negative_line_index(pytester: Pytester) -> None:\n    \"\"\"\n    With Python 3.10 alphas, there was an INTERNALERROR reported in\n    https://github.com/pytest-dev/pytest/pull/8227\n    This test ensures it does not regress.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import ast\n        import pytest\n\n\n        def test_literal_eval():\n            with pytest.raises(ValueError, match=\"^$\"):\n                ast.literal_eval(\"pytest\")\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"* 1 failed in *\"])\n    result.stdout.no_fnmatch_line(\"*INTERNALERROR*\")\n    result.stderr.no_fnmatch_line(\"*INTERNALERROR*\")\n\n\n@pytest.mark.usefixtures(\"limited_recursion_depth\")\ndef test_exception_repr_extraction_error_on_recursion():\n    \"\"\"\n    Ensure we can properly detect a recursion error even\n    if some locals raise error on comparison (#2459).\n    \"\"\"\n\n    class numpy_like:\n        def __eq__(self, other):\n            if type(other) is numpy_like:\n                raise ValueError(\n                    \"The truth value of an array \"\n                    \"with more than one element is ambiguous.\"\n                )\n\n    def a(x):\n        return b(numpy_like())\n\n    def b(x):\n        return a(numpy_like())\n\n    with pytest.raises(RuntimeError) as excinfo:\n        a(numpy_like())\n\n    matcher = LineMatcher(str(excinfo.getrepr()).splitlines())\n    matcher.fnmatch_lines(\n        [\n            \"!!! Recursion error detected, but an error occurred locating the origin of recursion.\",\n            \"*The following exception happened*\",\n            \"*ValueError: The truth value of an array*\",\n        ]\n    )\n\n\n@pytest.mark.usefixtures(\"limited_recursion_depth\")\ndef test_no_recursion_index_on_recursion_error():\n    \"\"\"\n    Ensure that we don't break in case we can't find the recursion index\n    during a recursion error (#2486).\n    \"\"\"\n\n    class RecursionDepthError:\n        def __getattr__(self, attr):\n            return getattr(self, \"_\" + attr)\n\n    with pytest.raises(RuntimeError) as excinfo:\n        _ = RecursionDepthError().trigger\n    assert \"maximum recursion\" in str(excinfo.getrepr())\n\n\ndef _exceptiongroup_common(\n    pytester: Pytester,\n    outer_chain: str,\n    inner_chain: str,\n    native: bool,\n) -> None:\n    pre_raise = \"exceptiongroup.\" if not native else \"\"\n    pre_catch = pre_raise if sys.version_info < (3, 11) else \"\"\n    filestr = f\"\"\"\n    {\"import exceptiongroup\" if not native else \"\"}\n    import pytest\n\n    def f(): raise ValueError(\"From f()\")\n    def g(): raise BaseException(\"From g()\")\n\n    def inner(inner_chain):\n        excs = []\n        for callback in [f, g]:\n            try:\n                callback()\n            except BaseException as err:\n                excs.append(err)\n        if excs:\n            if inner_chain == \"none\":\n                raise {pre_raise}BaseExceptionGroup(\"Oops\", excs)\n            try:\n                raise SyntaxError()\n            except SyntaxError as e:\n                if inner_chain == \"from\":\n                    raise {pre_raise}BaseExceptionGroup(\"Oops\", excs) from e\n                else:\n                    raise {pre_raise}BaseExceptionGroup(\"Oops\", excs)\n\n    def outer(outer_chain, inner_chain):\n        try:\n            inner(inner_chain)\n        except {pre_catch}BaseExceptionGroup as e:\n            if outer_chain == \"none\":\n                raise\n            if outer_chain == \"from\":\n                raise IndexError() from e\n            else:\n                raise IndexError()\n\n\n    def test():\n        outer(\"{outer_chain}\", \"{inner_chain}\")\n    \"\"\"\n    pytester.makepyfile(test_excgroup=filestr)\n    result = pytester.runpytest()\n    match_lines = []\n    if inner_chain in (\"another\", \"from\"):\n        match_lines.append(r\"SyntaxError: <no detail available>\")\n\n    match_lines += [\n        r\"  + Exception Group Traceback (most recent call last):\",\n        rf\"  \\| {pre_catch}BaseExceptionGroup: Oops \\(2 sub-exceptions\\)\",\n        r\"    \\| ValueError: From f\\(\\)\",\n        r\"    \\| BaseException: From g\\(\\)\",\n        r\"=* short test summary info =*\",\n    ]\n    if outer_chain in (\"another\", \"from\"):\n        match_lines.append(r\"FAILED test_excgroup.py::test - IndexError\")\n    else:\n        match_lines.append(\n            rf\"FAILED test_excgroup.py::test - {pre_catch}BaseExceptionGroup: Oops \\(2.*\"\n        )\n    result.stdout.re_match_lines(match_lines)\n    # Check for traceback filtering of pytest internals.\n    result.stdout.no_fnmatch_line(\"*, line *, in pytest_pyfunc_call\")\n    result.stdout.no_fnmatch_line(\"*, line *, in pytest_runtest_call\")\n\n\n@pytest.mark.skipif(\n    sys.version_info < (3, 11), reason=\"Native ExceptionGroup not implemented\"\n)\n@pytest.mark.parametrize(\"outer_chain\", [\"none\", \"from\", \"another\"])\n@pytest.mark.parametrize(\"inner_chain\", [\"none\", \"from\", \"another\"])\ndef test_native_exceptiongroup(pytester: Pytester, outer_chain, inner_chain) -> None:\n    _exceptiongroup_common(pytester, outer_chain, inner_chain, native=True)\n\n\n@pytest.mark.parametrize(\"outer_chain\", [\"none\", \"from\", \"another\"])\n@pytest.mark.parametrize(\"inner_chain\", [\"none\", \"from\", \"another\"])\ndef test_exceptiongroup(pytester: Pytester, outer_chain, inner_chain) -> None:\n    # with py>=3.11 does not depend on exceptiongroup, though there is a toxenv for it\n    pytest.importorskip(\"exceptiongroup\")\n    _exceptiongroup_common(pytester, outer_chain, inner_chain, native=False)\n\n\ndef test_exceptiongroup_short_summary_info(pytester: Pytester):\n    pytester.makepyfile(\n        \"\"\"\n        import sys\n\n        if sys.version_info < (3, 11):\n            from exceptiongroup import BaseExceptionGroup, ExceptionGroup\n\n        def test_base() -> None:\n            raise BaseExceptionGroup(\"NOT IN SUMMARY\", [SystemExit(\"a\" * 10)])\n\n        def test_nonbase() -> None:\n            raise ExceptionGroup(\"NOT IN SUMMARY\", [ValueError(\"a\" * 10)])\n\n        def test_nested() -> None:\n            raise ExceptionGroup(\n                \"NOT DISPLAYED\", [\n                    ExceptionGroup(\"NOT IN SUMMARY\", [ValueError(\"a\" * 10)])\n                ]\n            )\n\n        def test_multiple() -> None:\n            raise ExceptionGroup(\n                \"b\" * 10,\n                [\n                    ValueError(\"NOT IN SUMMARY\"),\n                    TypeError(\"NOT IN SUMMARY\"),\n                ]\n            )\n\n        def test_nested_multiple() -> None:\n            raise ExceptionGroup(\n                \"b\" * 10,\n                [\n                    ExceptionGroup(\n                        \"c\" * 10,\n                        [\n                            ValueError(\"NOT IN SUMMARY\"),\n                            TypeError(\"NOT IN SUMMARY\"),\n                        ]\n                    )\n                ]\n            )\n        \"\"\"\n    )\n    # run with -vv to not truncate summary info, default width in tests is very low\n    result = pytester.runpytest(\"-vv\")\n    assert result.ret == 1\n    backport_str = \"exceptiongroup.\" if sys.version_info < (3, 11) else \"\"\n    result.stdout.fnmatch_lines(\n        [\n            \"*= short test summary info =*\",\n            (\n                \"FAILED test_exceptiongroup_short_summary_info.py::test_base - \"\n                \"SystemExit('aaaaaaaaaa') [single exception in BaseExceptionGroup]\"\n            ),\n            (\n                \"FAILED test_exceptiongroup_short_summary_info.py::test_nonbase - \"\n                \"ValueError('aaaaaaaaaa') [single exception in ExceptionGroup]\"\n            ),\n            (\n                \"FAILED test_exceptiongroup_short_summary_info.py::test_nested - \"\n                \"ValueError('aaaaaaaaaa') [single exception in ExceptionGroup]\"\n            ),\n            (\n                \"FAILED test_exceptiongroup_short_summary_info.py::test_multiple - \"\n                f\"{backport_str}ExceptionGroup: bbbbbbbbbb (2 sub-exceptions)\"\n            ),\n            (\n                \"FAILED test_exceptiongroup_short_summary_info.py::test_nested_multiple - \"\n                f\"{backport_str}ExceptionGroup: bbbbbbbbbb (1 sub-exception)\"\n            ),\n            \"*= 5 failed in *\",\n        ]\n    )\n\n\n@pytest.mark.parametrize(\"tbstyle\", (\"long\", \"short\", \"auto\", \"line\", \"native\"))\n@pytest.mark.parametrize(\"group\", (True, False), ids=(\"group\", \"bare\"))\ndef test_all_entries_hidden(pytester: Pytester, tbstyle: str, group: bool) -> None:\n    \"\"\"Regression test for #10903.\"\"\"\n    pytester.makepyfile(\n        f\"\"\"\n        import sys\n        if sys.version_info < (3, 11):\n            from exceptiongroup import ExceptionGroup\n        def test():\n            __tracebackhide__ = True\n            raise {'ExceptionGroup(\"\", [ValueError(\"bar\")])' if group else 'ValueError(\"bar\")'}\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--tb\", tbstyle)\n    assert result.ret == 1\n    if tbstyle != \"line\":\n        result.stdout.fnmatch_lines([\"*ValueError: bar\"])\n    if tbstyle not in (\"line\", \"native\"):\n        result.stdout.fnmatch_lines([\"All traceback entries are hidden.*\"])\n\n\ndef test_hidden_entries_of_chained_exceptions_are_not_shown(pytester: Pytester) -> None:\n    \"\"\"Hidden entries of chained exceptions are not shown (#1904).\"\"\"\n    p = pytester.makepyfile(\n        \"\"\"\n        def g1():\n            __tracebackhide__ = True\n            str.does_not_exist\n\n        def f3():\n            __tracebackhide__ = True\n            1 / 0\n\n        def f2():\n            try:\n                f3()\n            except Exception:\n                g1()\n\n        def f1():\n            __tracebackhide__ = True\n            f2()\n\n        def test():\n            f1()\n        \"\"\"\n    )\n    result = pytester.runpytest(str(p), \"--tb=short\")\n    assert result.ret == 1\n    result.stdout.fnmatch_lines(\n        [\n            \"*.py:11: in f2\",\n            \"    f3()\",\n            \"E   ZeroDivisionError: division by zero\",\n            \"\",\n            \"During handling of the above exception, another exception occurred:\",\n            \"*.py:20: in test\",\n            \"    f1()\",\n            \"*.py:13: in f2\",\n            \"    g1()\",\n            \"E   AttributeError:*'does_not_exist'\",\n        ],\n        consecutive=True,\n    )\n\n\ndef add_note(err: BaseException, msg: str) -> None:\n    \"\"\"Adds a note to an exception inplace.\"\"\"\n    if sys.version_info < (3, 11):\n        err.__notes__ = [*getattr(err, \"__notes__\", []), msg]  # type: ignore[attr-defined]\n    else:\n        err.add_note(msg)\n\n\n@pytest.mark.parametrize(\n    \"error,notes,match\",\n    [\n        (Exception(\"test\"), [], \"test\"),\n        (AssertionError(\"foo\"), [\"bar\"], \"bar\"),\n        (AssertionError(\"foo\"), [\"bar\", \"baz\"], \"bar\"),\n        (AssertionError(\"foo\"), [\"bar\", \"baz\"], \"baz\"),\n        (ValueError(\"foo\"), [\"bar\", \"baz\"], re.compile(r\"bar\\nbaz\", re.MULTILINE)),\n        (ValueError(\"foo\"), [\"bar\", \"baz\"], re.compile(r\"BAZ\", re.IGNORECASE)),\n    ],\n)\ndef test_check_error_notes_success(\n    error: Exception, notes: list[str], match: str\n) -> None:\n    for note in notes:\n        add_note(error, note)\n\n    with pytest.raises(Exception, match=match):\n        raise error\n\n\n@pytest.mark.parametrize(\n    \"error, notes, match\",\n    [\n        (Exception(\"test\"), [], \"foo\"),\n        (AssertionError(\"foo\"), [\"bar\"], \"baz\"),\n        (AssertionError(\"foo\"), [\"bar\"], \"foo\\nbaz\"),\n    ],\n)\ndef test_check_error_notes_failure(\n    error: Exception, notes: list[str], match: str\n) -> None:\n    for note in notes:\n        add_note(error, note)\n\n    with pytest.raises(AssertionError):\n        with pytest.raises(type(error), match=match):\n            raise error\n"
  },
  {
    "path": "testing/code/test_source.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport inspect\nimport linecache\nfrom pathlib import Path\nimport sys\nimport textwrap\nfrom typing import Any\nfrom unittest.mock import patch\n\nfrom _pytest._code import Code\nfrom _pytest._code import Frame\nfrom _pytest._code import getfslineno\nfrom _pytest._code import Source\nfrom _pytest.pathlib import import_path\nimport pytest\n\n\ndef test_source_str_function() -> None:\n    x = Source(\"3\")\n    assert str(x) == \"3\"\n\n    x = Source(\"   3\")\n    assert str(x) == \"3\"\n\n    x = Source(\n        \"\"\"\n        3\n        \"\"\"\n    )\n    assert str(x) == \"\\n3\"\n\n\ndef test_source_from_function() -> None:\n    source = Source(test_source_str_function)\n    assert str(source).startswith(\"def test_source_str_function() -> None:\")\n\n\ndef test_source_from_method() -> None:\n    class TestClass:\n        def test_method(self):\n            pass\n\n    source = Source(TestClass().test_method)\n    assert source.lines == [\"def test_method(self):\", \"    pass\"]\n\n\ndef test_source_from_lines() -> None:\n    lines = [\"a \\n\", \"b\\n\", \"c\"]\n    source = Source(lines)\n    assert source.lines == [\"a \", \"b\", \"c\"]\n\n\ndef test_source_from_inner_function() -> None:\n    def f():\n        raise NotImplementedError()\n\n    source = Source(f)\n    assert str(source).startswith(\"def f():\")\n\n\ndef test_source_strips() -> None:\n    source = Source(\"\")\n    assert source == Source()\n    assert str(source) == \"\"\n    assert source.strip() == source\n\n\ndef test_source_strip_multiline() -> None:\n    source = Source()\n    source.lines = [\"\", \" hello\", \"  \"]\n    source2 = source.strip()\n    assert source2.lines == [\" hello\"]\n\n\nclass TestAccesses:\n    def setup_class(self) -> None:\n        self.source = Source(\n            \"\"\"\\\n            def f(x):\n                pass\n            def g(x):\n                pass\n        \"\"\"\n        )\n\n    def test_getrange(self) -> None:\n        x = self.source[0:2]\n        assert len(x.lines) == 2\n        assert str(x) == \"def f(x):\\n    pass\"\n\n    def test_getrange_step_not_supported(self) -> None:\n        with pytest.raises(IndexError, match=r\"step\"):\n            self.source[::2]\n\n    def test_getline(self) -> None:\n        x = self.source[0]\n        assert x == \"def f(x):\"\n\n    def test_len(self) -> None:\n        assert len(self.source) == 4\n\n    def test_iter(self) -> None:\n        values = [x for x in self.source]\n        assert len(values) == 4\n\n\nclass TestSourceParsing:\n    def setup_class(self) -> None:\n        self.source = Source(\n            \"\"\"\\\n            def f(x):\n                assert (x ==\n                        3 +\n                        4)\n        \"\"\"\n        ).strip()\n\n    def test_getstatement(self) -> None:\n        # print str(self.source)\n        ass = str(self.source[1:])\n        for i in range(1, 4):\n            # print \"trying start in line %r\" % self.source[i]\n            s = self.source.getstatement(i)\n            # x = s.deindent()\n            assert str(s) == ass\n\n    def test_getstatementrange_triple_quoted(self) -> None:\n        # print str(self.source)\n        source = Source(\n            \"\"\"hello('''\n        ''')\"\"\"\n        )\n        s = source.getstatement(0)\n        assert s == source\n        s = source.getstatement(1)\n        assert s == source\n\n    def test_getstatementrange_within_constructs(self) -> None:\n        source = Source(\n            \"\"\"\\\n            try:\n                try:\n                    raise ValueError\n                except SomeThing:\n                    pass\n            finally:\n                42\n        \"\"\"\n        )\n        assert len(source) == 7\n        # check all lineno's that could occur in a traceback\n        # assert source.getstatementrange(0) == (0, 7)\n        # assert source.getstatementrange(1) == (1, 5)\n        assert source.getstatementrange(2) == (2, 3)\n        assert source.getstatementrange(3) == (3, 4)\n        assert source.getstatementrange(4) == (4, 5)\n        # assert source.getstatementrange(5) == (0, 7)\n        assert source.getstatementrange(6) == (6, 7)\n\n    def test_getstatementrange_bug(self) -> None:\n        source = Source(\n            \"\"\"\\\n            try:\n                x = (\n                   y +\n                   z)\n            except:\n                pass\n        \"\"\"\n        )\n        assert len(source) == 6\n        assert source.getstatementrange(2) == (1, 4)\n\n    def test_getstatementrange_bug2(self) -> None:\n        source = Source(\n            \"\"\"\\\n            assert (\n                33\n                ==\n                [\n                  X(3,\n                      b=1, c=2\n                   ),\n                ]\n              )\n        \"\"\"\n        )\n        assert len(source) == 9\n        assert source.getstatementrange(5) == (0, 9)\n\n    def test_getstatementrange_ast_issue58(self) -> None:\n        source = Source(\n            \"\"\"\\\n\n            def test_some():\n                for a in [a for a in\n                    CAUSE_ERROR]: pass\n\n            x = 3\n        \"\"\"\n        )\n        assert getstatement(2, source).lines == source.lines[2:3]\n        assert getstatement(3, source).lines == source.lines[3:4]\n\n    def test_getstatementrange_out_of_bounds_py3(self) -> None:\n        source = Source(\"if xxx:\\n   from .collections import something\")\n        r = source.getstatementrange(1)\n        assert r == (1, 2)\n\n    def test_getstatementrange_with_syntaxerror_issue7(self) -> None:\n        source = Source(\":\")\n        pytest.raises(SyntaxError, lambda: source.getstatementrange(0))\n\n\ndef test_getstartingblock_singleline() -> None:\n    class A:\n        def __init__(self, *args) -> None:\n            frame = sys._getframe(1)\n            self.source = Frame(frame).statement\n\n    x = A(\"x\", \"y\")\n\n    values = [i for i in x.source.lines if i.strip()]\n    assert len(values) == 1\n\n\ndef test_getline_finally() -> None:\n    def c() -> None:\n        pass\n\n    with pytest.raises(TypeError) as excinfo:\n        teardown = None\n        try:\n            c(1)  # type: ignore\n        finally:\n            if teardown:\n                teardown()  # type: ignore[unreachable]\n    source = excinfo.traceback[-1].statement\n    assert str(source).strip() == \"c(1)  # type: ignore\"\n\n\ndef test_getfuncsource_dynamic() -> None:\n    def f():\n        raise NotImplementedError()\n\n    def g():\n        pass  # pragma: no cover\n\n    f_source = Source(f)\n    g_source = Source(g)\n    assert str(f_source).strip() == \"def f():\\n    raise NotImplementedError()\"\n    assert str(g_source).strip() == \"def g():\\n    pass  # pragma: no cover\"\n\n\ndef test_getfuncsource_with_multiline_string() -> None:\n    def f():\n        c = \"\"\"while True:\n    pass\n\"\"\"\n\n    expected = '''\\\n    def f():\n        c = \"\"\"while True:\n    pass\n\"\"\"\n'''\n    assert str(Source(f)) == expected.rstrip()\n\n\ndef test_deindent() -> None:\n    from _pytest._code.source import deindent as deindent\n\n    assert deindent([\"\\tfoo\", \"\\tbar\"]) == [\"foo\", \"bar\"]\n\n    source = \"\"\"\\\n        def f():\n            def g():\n                pass\n    \"\"\"\n    lines = deindent(source.splitlines())\n    assert lines == [\"def f():\", \"    def g():\", \"        pass\"]\n\n\ndef test_source_of_class_at_eof_without_newline(_sys_snapshot, tmp_path: Path) -> None:\n    # this test fails because the implicit inspect.getsource(A) below\n    # does not return the \"x = 1\" last line.\n    source = Source(\n        \"\"\"\n        class A:\n            def method(self):\n                x = 1\n    \"\"\"\n    )\n    path = tmp_path.joinpath(\"a.py\")\n    path.write_text(str(source), encoding=\"utf-8\")\n    mod: Any = import_path(path, root=tmp_path, consider_namespace_packages=False)\n    s2 = Source(mod.A)\n    assert str(source).strip() == str(s2).strip()\n\n\nif True:\n\n    def x():\n        pass\n\n\ndef test_source_fallback() -> None:\n    src = Source(x)\n    expected = \"\"\"def x():\n    pass\"\"\"\n    assert str(src) == expected\n\n\ndef test_findsource_fallback() -> None:\n    from _pytest._code.source import findsource\n\n    src, lineno = findsource(x)\n    assert src is not None\n    assert \"test_findsource_simple\" in str(src)\n    assert src[lineno] == \"    def x():\"\n\n\ndef test_findsource(monkeypatch) -> None:\n    from _pytest._code.source import findsource\n\n    filename = \"<pytest-test_findsource>\"\n    lines = [\"if 1:\\n\", \"    def x():\\n\", \"          pass\\n\"]\n    co = compile(\"\".join(lines), filename, \"exec\")\n\n    monkeypatch.setitem(linecache.cache, filename, (1, None, lines, filename))\n\n    src, lineno = findsource(co)\n    assert src is not None\n    assert \"if 1:\" in str(src)\n\n    d: dict[str, Any] = {}\n    eval(co, d)\n    src, lineno = findsource(d[\"x\"])\n    assert src is not None\n    assert \"if 1:\" in str(src)\n    assert src[lineno] == \"    def x():\"\n\n\ndef test_getfslineno() -> None:\n    def f(x) -> None:\n        raise NotImplementedError()\n\n    fspath, lineno = getfslineno(f)\n\n    assert isinstance(fspath, Path)\n    assert fspath.name == \"test_source.py\"\n    assert lineno == f.__code__.co_firstlineno - 1  # see findsource\n\n    class A:\n        pass\n\n    fspath, lineno = getfslineno(A)\n\n    _, A_lineno = inspect.findsource(A)\n    assert isinstance(fspath, Path)\n    assert fspath.name == \"test_source.py\"\n    assert lineno == A_lineno\n\n    assert getfslineno(3) == (\"\", -1)\n\n    class B:\n        pass\n\n    B.__name__ = B.__qualname__ = \"B2\"\n    # Since Python 3.13 this started working.\n    if sys.version_info >= (3, 13):\n        assert getfslineno(B)[1] != -1\n    else:\n        assert getfslineno(B)[1] == -1\n\n\ndef test_code_of_object_instance_with_call() -> None:\n    class A:\n        pass\n\n    pytest.raises(TypeError, lambda: Source(A()))\n\n    class WithCall:\n        def __call__(self) -> None:\n            pass\n\n    code = Code.from_function(WithCall())\n    assert \"pass\" in str(code.source())\n\n    class Hello:\n        def __call__(self) -> None:\n            pass\n\n    pytest.raises(TypeError, lambda: Code.from_function(Hello))\n\n\ndef getstatement(lineno: int, source) -> Source:\n    from _pytest._code.source import getstatementrange_ast\n\n    src = Source(source)\n    _ast, start, end = getstatementrange_ast(lineno, src)\n    return src[start:end]\n\n\ndef test_oneline() -> None:\n    source = getstatement(0, \"raise ValueError\")\n    assert str(source) == \"raise ValueError\"\n\n\ndef test_comment_and_no_newline_at_end() -> None:\n    from _pytest._code.source import getstatementrange_ast\n\n    source = Source(\n        [\n            \"def test_basic_complex():\",\n            \"    assert 1 == 2\",\n            \"# vim: filetype=pyopencl:fdm=marker\",\n        ]\n    )\n    _ast, _start, end = getstatementrange_ast(1, source)\n    assert end == 2\n\n\ndef test_oneline_and_comment() -> None:\n    source = getstatement(0, \"raise ValueError\\n#hello\")\n    assert str(source) == \"raise ValueError\"\n\n\ndef test_comments() -> None:\n    source = '''def test():\n    \"comment 1\"\n    x = 1\n      # comment 2\n    # comment 3\n\n    assert False\n\n\"\"\"\ncomment 4\n\"\"\"\n'''\n    for line in range(2, 6):\n        assert str(getstatement(line, source)) == \"    x = 1\"\n    for line in range(6, 8):\n        assert str(getstatement(line, source)) == \"    assert False\"\n    for line in range(8, 10):\n        assert str(getstatement(line, source)) == '\"\"\"\\ncomment 4\\n\"\"\"'\n\n\ndef test_comment_in_statement() -> None:\n    source = \"\"\"test(foo=1,\n    # comment 1\n    bar=2)\n\"\"\"\n    for line in range(1, 3):\n        assert (\n            str(getstatement(line, source))\n            == \"test(foo=1,\\n    # comment 1\\n    bar=2)\"\n        )\n\n\ndef test_source_with_decorator() -> None:\n    \"\"\"Test behavior with Source / Code().source with regard to decorators.\"\"\"\n\n    @pytest.mark.foo\n    def deco_mark():\n        assert False\n\n    src = inspect.getsource(deco_mark)\n    assert textwrap.indent(str(Source(deco_mark)), \"    \") + \"\\n\" == src\n    assert src.startswith(\"    @pytest.mark.foo\")\n\n    @pytest.fixture\n    def deco_fixture():\n        assert False\n\n    src = inspect.getsource(deco_fixture._get_wrapped_function())\n    assert src == \"    @pytest.fixture\\n    def deco_fixture():\\n        assert False\\n\"\n    # Make sure the decorator is not a wrapped function\n    assert not str(Source(deco_fixture)).startswith(\"@functools.wraps(function)\")\n    assert (\n        textwrap.indent(str(Source(deco_fixture._get_wrapped_function())), \"    \")\n        + \"\\n\"\n        == src\n    )\n\n\ndef test_single_line_else() -> None:\n    source = getstatement(1, \"if False: 2\\nelse: 3\")\n    assert str(source) == \"else: 3\"\n\n\ndef test_single_line_finally() -> None:\n    source = getstatement(1, \"try: 1\\nfinally: 3\")\n    assert str(source) == \"finally: 3\"\n\n\ndef test_issue55() -> None:\n    source = (\n        \"def round_trip(dinp):\\n  assert 1 == dinp\\n\"\n        'def test_rt():\\n  round_trip(\"\"\"\\n\"\"\")\\n'\n    )\n    s = getstatement(3, source)\n    assert str(s) == '  round_trip(\"\"\"\\n\"\"\")'\n\n\ndef test_multiline() -> None:\n    source = getstatement(\n        0,\n        \"\"\"\\\nraise ValueError(\n    23\n)\nx = 3\n\"\"\",\n    )\n    assert str(source) == \"raise ValueError(\\n    23\\n)\"\n\n\nclass TestTry:\n    def setup_class(self) -> None:\n        self.source = \"\"\"\\\ntry:\n    raise ValueError\nexcept Something:\n    raise IndexError(1)\nelse:\n    raise KeyError()\n\"\"\"\n\n    def test_body(self) -> None:\n        source = getstatement(1, self.source)\n        assert str(source) == \"    raise ValueError\"\n\n    def test_except_line(self) -> None:\n        source = getstatement(2, self.source)\n        assert str(source) == \"except Something:\"\n\n    def test_except_body(self) -> None:\n        source = getstatement(3, self.source)\n        assert str(source) == \"    raise IndexError(1)\"\n\n    def test_else(self) -> None:\n        source = getstatement(5, self.source)\n        assert str(source) == \"    raise KeyError()\"\n\n\nclass TestTryFinally:\n    def setup_class(self) -> None:\n        self.source = \"\"\"\\\ntry:\n    raise ValueError\nfinally:\n    raise IndexError(1)\n\"\"\"\n\n    def test_body(self) -> None:\n        source = getstatement(1, self.source)\n        assert str(source) == \"    raise ValueError\"\n\n    def test_finally(self) -> None:\n        source = getstatement(3, self.source)\n        assert str(source) == \"    raise IndexError(1)\"\n\n\nclass TestIf:\n    def setup_class(self) -> None:\n        self.source = \"\"\"\\\nif 1:\n    y = 3\nelif False:\n    y = 5\nelse:\n    y = 7\n\"\"\"\n\n    def test_body(self) -> None:\n        source = getstatement(1, self.source)\n        assert str(source) == \"    y = 3\"\n\n    def test_elif_clause(self) -> None:\n        source = getstatement(2, self.source)\n        assert str(source) == \"elif False:\"\n\n    def test_elif(self) -> None:\n        source = getstatement(3, self.source)\n        assert str(source) == \"    y = 5\"\n\n    def test_else(self) -> None:\n        source = getstatement(5, self.source)\n        assert str(source) == \"    y = 7\"\n\n\ndef test_semicolon() -> None:\n    s = \"\"\"\\\nhello ; pytest.skip()\n\"\"\"\n    source = getstatement(0, s)\n    assert str(source) == s.strip()\n\n\ndef test_def_online() -> None:\n    s = \"\"\"\\\ndef func(): raise ValueError(42)\n\ndef something():\n    pass\n\"\"\"\n    source = getstatement(0, s)\n    assert str(source) == \"def func(): raise ValueError(42)\"\n\n\ndef test_decorator() -> None:\n    s = \"\"\"\\\ndef foo(f):\n    pass\n\n@foo\ndef bar():\n    pass\n    \"\"\"\n    source = getstatement(3, s)\n    assert \"@foo\" in str(source)\n\n\ndef XXX_test_expression_multiline() -> None:\n    source = \"\"\"\\\nsomething\n'''\n'''\"\"\"\n    result = getstatement(1, source)\n    assert str(result) == \"'''\\n'''\"\n\n\ndef test_getstartingblock_multiline() -> None:\n    class A:\n        def __init__(self, *args):\n            frame = sys._getframe(1)\n            self.source = Frame(frame).statement\n\n    # fmt: off\n    x = A('x',\n          'y'\n          ,\n          'z')\n    # fmt: on\n    values = [i for i in x.source.lines if i.strip()]\n    assert len(values) == 4\n\n\ndef test_patched_compile() -> None:\n    # ensure Source doesn't break\n    # when compile() modifies code dynamically\n    from builtins import compile\n\n    def patched_compile1(_, *args, **kwargs):\n        return compile(\"\", *args, **kwargs)\n\n    with patch(\"builtins.compile\", new=patched_compile1):\n        Source(patched_compile1).getstatement(1)\n\n    # fmt: off\n    def patched_compile2(_, *args, **kwargs):\n\n        # first line of this function (the one above this one) must be empty\n        # LINES must be equal or higher than number of lines of this function\n        LINES = 99\n        return compile(\"\\ndef a():\\n\" + \"\\n\" * LINES + \"    pass\", *args, **kwargs)\n    # fmt: on\n\n    with patch(\"builtins.compile\", new=patched_compile2):\n        Source(patched_compile2).getstatement(1)\n"
  },
  {
    "path": "testing/conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nimport importlib.metadata\nimport re\nimport sys\n\nfrom packaging.version import Version\n\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nif sys.gettrace():\n\n    @pytest.fixture(autouse=True)\n    def restore_tracing():\n        \"\"\"Restore tracing function (when run with Coverage.py).\n\n        https://bugs.python.org/issue37011\n        \"\"\"\n        orig_trace = sys.gettrace()\n        yield\n        if sys.gettrace() != orig_trace:\n            sys.settrace(orig_trace)\n\n\n@pytest.fixture(autouse=True)\ndef set_column_width(monkeypatch: pytest.MonkeyPatch) -> None:\n    \"\"\"\n    Force terminal width to 80: some tests check the formatting of --help, which is sensible\n    to terminal width.\n    \"\"\"\n    monkeypatch.setenv(\"COLUMNS\", \"80\")\n\n\n@pytest.fixture(autouse=True)\ndef reset_colors(monkeypatch: pytest.MonkeyPatch) -> None:\n    \"\"\"\n    Reset all color-related variables to prevent them from affecting internal pytest output\n    in tests that depend on it.\n    \"\"\"\n    monkeypatch.delenv(\"PY_COLORS\", raising=False)\n    monkeypatch.delenv(\"NO_COLOR\", raising=False)\n    monkeypatch.delenv(\"FORCE_COLOR\", raising=False)\n\n\n@pytest.hookimpl(wrapper=True, tryfirst=True)\ndef pytest_collection_modifyitems(items) -> Generator[None]:\n    \"\"\"Prefer faster tests.\n\n    Use a hook wrapper to do this in the beginning, so e.g. --ff still works\n    correctly.\n    \"\"\"\n    fast_items = []\n    slow_items = []\n    slowest_items = []\n    neutral_items = []\n\n    spawn_names = {\"spawn_pytest\", \"spawn\"}\n\n    for item in items:\n        try:\n            fixtures = item.fixturenames\n        except AttributeError:\n            # doctest at least\n            # (https://github.com/pytest-dev/pytest/issues/5070)\n            neutral_items.append(item)\n        else:\n            if \"pytester\" in fixtures:\n                co_names = item.function.__code__.co_names\n                if spawn_names.intersection(co_names):\n                    item.add_marker(pytest.mark.uses_pexpect)\n                    slowest_items.append(item)\n                elif \"runpytest_subprocess\" in co_names:\n                    slowest_items.append(item)\n                else:\n                    slow_items.append(item)\n                item.add_marker(pytest.mark.slow)\n            else:\n                marker = item.get_closest_marker(\"slow\")\n                if marker:\n                    slowest_items.append(item)\n                else:\n                    fast_items.append(item)\n\n    items[:] = fast_items + neutral_items + slow_items + slowest_items\n\n    return (yield)\n\n\n@pytest.fixture\ndef tw_mock():\n    \"\"\"Returns a mock terminal writer\"\"\"\n\n    class TWMock:\n        WRITE = object()\n\n        def __init__(self):\n            self.lines = []\n            self.is_writing = False\n\n        def sep(self, sep, line=None):\n            self.lines.append((sep, line))\n\n        def write(self, msg, **kw):\n            self.lines.append((TWMock.WRITE, msg))\n\n        def _write_source(self, lines, indents=()):\n            if not indents:\n                indents = [\"\"] * len(lines)\n            for indent, line in zip(indents, lines, strict=True):\n                self.line(indent + line)\n\n        def line(self, line, **kw):\n            self.lines.append(line)\n\n        def markup(self, text, **kw):\n            return text\n\n        def get_write_msg(self, idx):\n            assert self.lines[idx][0] == TWMock.WRITE\n            msg = self.lines[idx][1]\n            return msg\n\n        fullwidth = 80\n\n    return TWMock()\n\n\n@pytest.fixture\ndef dummy_yaml_custom_test(pytester: Pytester) -> None:\n    \"\"\"Writes a conftest file that collects and executes a dummy yaml test.\n\n    Taken from the docs, but stripped down to the bare minimum, useful for\n    tests which needs custom items collected.\n    \"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n\n        def pytest_collect_file(parent, file_path):\n            if file_path.suffix == \".yaml\" and file_path.name.startswith(\"test\"):\n                return YamlFile.from_parent(path=file_path, parent=parent)\n\n        class YamlFile(pytest.File):\n            def collect(self):\n                yield YamlItem.from_parent(name=self.path.name, parent=self)\n\n        class YamlItem(pytest.Item):\n            def runtest(self):\n                pass\n    \"\"\"\n    )\n    pytester.makefile(\".yaml\", test1=\"\")\n\n\n@pytest.fixture\ndef pytester(pytester: Pytester, monkeypatch: MonkeyPatch) -> Pytester:\n    monkeypatch.setenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", \"1\")\n    return pytester\n\n\n@pytest.fixture(scope=\"session\")\ndef color_mapping():\n    \"\"\"Returns a utility class which can replace keys in strings in the form \"{NAME}\"\n    by their equivalent ASCII codes in the terminal.\n\n    Used by tests which check the actual colors output by pytest.\n    \"\"\"\n    # https://github.com/pygments/pygments/commit/d24e272894a56a98b1b718d9ac5fabc20124882a\n    pygments_version = Version(importlib.metadata.version(\"pygments\"))\n    pygments_has_kwspace_hl = pygments_version >= Version(\"2.19\")\n\n    class ColorMapping:\n        COLORS = {\n            \"red\": \"\\x1b[31m\",\n            \"green\": \"\\x1b[32m\",\n            \"yellow\": \"\\x1b[33m\",\n            \"light-gray\": \"\\x1b[90m\",\n            \"light-red\": \"\\x1b[91m\",\n            \"light-green\": \"\\x1b[92m\",\n            \"bold\": \"\\x1b[1m\",\n            \"reset\": \"\\x1b[0m\",\n            \"kw\": \"\\x1b[94m\",\n            \"kwspace\": \"\\x1b[90m \\x1b[39;49;00m\" if pygments_has_kwspace_hl else \" \",\n            \"hl-reset\": \"\\x1b[39;49;00m\",\n            \"function\": \"\\x1b[92m\",\n            \"number\": \"\\x1b[94m\",\n            \"str\": \"\\x1b[33m\",\n            \"print\": \"\\x1b[96m\",\n            \"endline\": \"\\x1b[90m\\x1b[39;49;00m\",\n        }\n        RE_COLORS = {k: re.escape(v) for k, v in COLORS.items()}\n        NO_COLORS = {k: \"\" for k in COLORS.keys()}\n\n        @classmethod\n        def format(cls, lines: list[str]) -> list[str]:\n            \"\"\"Straightforward replacement of color names to their ASCII codes.\"\"\"\n            return [line.format(**cls.COLORS) for line in lines]\n\n        @classmethod\n        def format_for_fnmatch(cls, lines: list[str]) -> list[str]:\n            \"\"\"Replace color names for use with LineMatcher.fnmatch_lines\"\"\"\n            return [line.format(**cls.COLORS).replace(\"[\", \"[[]\") for line in lines]\n\n        @classmethod\n        def format_for_rematch(cls, lines: list[str]) -> list[str]:\n            \"\"\"Replace color names for use with LineMatcher.re_match_lines\"\"\"\n            return [line.format(**cls.RE_COLORS) for line in lines]\n\n        @classmethod\n        def strip_colors(cls, lines: list[str]) -> list[str]:\n            \"\"\"Entirely remove every color code\"\"\"\n            return [line.format(**cls.NO_COLORS) for line in lines]\n\n    return ColorMapping\n\n\n@pytest.fixture\ndef mock_timing(monkeypatch: MonkeyPatch):\n    \"\"\"Mocks _pytest.timing with a known object that can be used to control timing in tests\n    deterministically.\n\n    pytest itself should always use functions from `_pytest.timing` instead of `time` directly.\n\n    This then allows us more control over time during testing, if testing code also\n    uses `_pytest.timing` functions.\n\n    Time is static, and only advances through `sleep` calls, thus tests might sleep over large\n    numbers and obtain accurate time() calls at the end, making tests reliable and instant.\n    \"\"\"\n    from _pytest.timing import MockTiming\n\n    result = MockTiming()\n    result.patch(monkeypatch)\n    return result\n\n\n@pytest.fixture(autouse=True)\ndef remove_ci_env_var(monkeypatch: MonkeyPatch, request: pytest.FixtureRequest) -> None:\n    \"\"\"Make the test insensitive if it is running in CI or not.\n\n    Use `@pytest.mark.keep_ci_var` in a test to avoid applying this fixture, letting the test\n    see the real `CI` variable (if present).\n    \"\"\"\n    has_keep_ci_mark = request.node.get_closest_marker(\"keep_ci_var\") is not None\n    if not has_keep_ci_mark:\n        monkeypatch.delenv(\"CI\", raising=False)\n"
  },
  {
    "path": "testing/deprecated_test.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom _pytest import deprecated\nfrom _pytest.pytester import Pytester\nimport pytest\nfrom pytest import PytestDeprecationWarning\n\n\n@pytest.mark.parametrize(\"plugin\", sorted(deprecated.DEPRECATED_EXTERNAL_PLUGINS))\n@pytest.mark.filterwarnings(\"default\")\ndef test_external_plugins_integrated(pytester: Pytester, plugin) -> None:\n    pytester.syspathinsert()\n    pytester.makepyfile(**{plugin: \"\"})\n\n    with pytest.warns(pytest.PytestConfigWarning):\n        pytester.parseconfig(\"-p\", plugin)\n\n\ndef test_hookspec_via_function_attributes_are_deprecated():\n    from _pytest.config import PytestPluginManager\n\n    pm = PytestPluginManager()\n\n    class DeprecatedHookMarkerSpec:\n        def pytest_bad_hook(self):\n            pass\n\n        pytest_bad_hook.historic = False  # type: ignore[attr-defined]\n\n    with pytest.warns(\n        PytestDeprecationWarning,\n        match=r\"Please use the pytest\\.hookspec\\(historic=False\\) decorator\",\n    ) as recorder:\n        pm.add_hookspecs(DeprecatedHookMarkerSpec)\n    (record,) = recorder\n    assert (\n        record.lineno\n        == DeprecatedHookMarkerSpec.pytest_bad_hook.__code__.co_firstlineno\n    )\n    assert record.filename == __file__\n\n\ndef test_hookimpl_via_function_attributes_are_deprecated():\n    from _pytest.config import PytestPluginManager\n\n    pm = PytestPluginManager()\n\n    class DeprecatedMarkImplPlugin:\n        def pytest_runtest_call(self):\n            pass\n\n        pytest_runtest_call.tryfirst = True  # type: ignore[attr-defined]\n\n    with pytest.warns(\n        PytestDeprecationWarning,\n        match=r\"Please use the pytest.hookimpl\\(tryfirst=True\\)\",\n    ) as recorder:\n        pm.register(DeprecatedMarkImplPlugin())\n    (record,) = recorder\n    assert (\n        record.lineno\n        == DeprecatedMarkImplPlugin.pytest_runtest_call.__code__.co_firstlineno\n    )\n    assert record.filename == __file__\n\n\ndef test_yield_fixture_is_deprecated() -> None:\n    with pytest.warns(DeprecationWarning, match=r\"yield_fixture is deprecated\"):\n\n        @pytest.yield_fixture\n        def fix():\n            assert False\n\n\ndef test_private_is_deprecated() -> None:\n    class PrivateInit:\n        def __init__(self, foo: int, *, _ispytest: bool = False) -> None:\n            deprecated.check_ispytest(_ispytest)\n\n    with pytest.warns(\n        pytest.PytestDeprecationWarning, match=\"private pytest class or function\"\n    ):\n        PrivateInit(10)\n\n    # Doesn't warn.\n    PrivateInit(10, _ispytest=True)\n"
  },
  {
    "path": "testing/example_scripts/README.rst",
    "content": "Example test scripts\n=====================\n\n\nThe files in this directory are not direct tests, but rather example test suites that demonstrate certain issues/behaviours.\n\nIn the future we will move part of the content of the acceptance tests here in order to have directly testable code instead of writing out things and then running them in nested pytest sessions/subprocesses.\n\nThis will aid debugging and comprehension.\n"
  },
  {
    "path": "testing/example_scripts/__init__.py",
    "content": ""
  },
  {
    "path": "testing/example_scripts/acceptance/fixture_mock_integration.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Reproduces issue #3774\"\"\"\n\nfrom __future__ import annotations\n\nfrom unittest import mock\n\nimport pytest\n\n\nconfig = {\"mykey\": \"ORIGINAL\"}\n\n\n@pytest.fixture(scope=\"function\")\n@mock.patch.dict(config, {\"mykey\": \"MOCKED\"})\ndef my_fixture():\n    return config[\"mykey\"]\n\n\ndef test_foobar(my_fixture):\n    assert my_fixture == \"MOCKED\"\n"
  },
  {
    "path": "testing/example_scripts/collect/collect_init_tests/pytest.ini",
    "content": "[pytest]\npython_files = *.py\n"
  },
  {
    "path": "testing/example_scripts/collect/collect_init_tests/tests/__init__.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_init():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/collect/collect_init_tests/tests/test_foo.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_foo():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/collect/package_infinite_recursion/__init__.pyi",
    "content": ""
  },
  {
    "path": "testing/example_scripts/collect/package_infinite_recursion/conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef pytest_ignore_collect(collection_path):\n    return False\n"
  },
  {
    "path": "testing/example_scripts/collect/package_infinite_recursion/tests/__init__.py",
    "content": ""
  },
  {
    "path": "testing/example_scripts/collect/package_infinite_recursion/tests/test_basic.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/collect/package_init_given_as_arg/pkg/__init__.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_init():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/collect/package_init_given_as_arg/pkg/test_foo.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_foo():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/config/collect_pytest_prefix/__init__.pyi",
    "content": ""
  },
  {
    "path": "testing/example_scripts/config/collect_pytest_prefix/conftest.py",
    "content": "from __future__ import annotations\n\n\nclass pytest_something:\n    pass\n"
  },
  {
    "path": "testing/example_scripts/config/collect_pytest_prefix/test_foo.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_foo():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/conftest_usageerror/__init__.pyi",
    "content": ""
  },
  {
    "path": "testing/example_scripts/conftest_usageerror/conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef pytest_configure(config):\n    import pytest\n\n    raise pytest.UsageError(\"hello\")\n\n\ndef pytest_unconfigure(config):\n    print(\"pytest_unconfigure_called\")\n"
  },
  {
    "path": "testing/example_scripts/customdirectory/conftest.py",
    "content": "# mypy: allow-untyped-defs\n# content of conftest.py\nfrom __future__ import annotations\n\nimport json\n\nimport pytest\n\n\nclass ManifestDirectory(pytest.Directory):\n    def collect(self):\n        manifest_path = self.path / \"manifest.json\"\n        manifest = json.loads(manifest_path.read_text(encoding=\"utf-8\"))\n        ihook = self.ihook\n        for file in manifest[\"files\"]:\n            yield from ihook.pytest_collect_file(\n                file_path=self.path / file, parent=self\n            )\n\n\n@pytest.hookimpl\ndef pytest_collect_directory(path, parent):\n    if path.joinpath(\"manifest.json\").is_file():\n        return ManifestDirectory.from_parent(parent=parent, path=path)\n    return None\n"
  },
  {
    "path": "testing/example_scripts/customdirectory/pytest.ini",
    "content": ""
  },
  {
    "path": "testing/example_scripts/customdirectory/tests/manifest.json",
    "content": "{\n    \"files\": [\n        \"test_first.py\",\n        \"test_second.py\"\n    ]\n}\n"
  },
  {
    "path": "testing/example_scripts/customdirectory/tests/test_first.py",
    "content": "# mypy: allow-untyped-defs\n# content of test_first.py\nfrom __future__ import annotations\n\n\ndef test_1():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/customdirectory/tests/test_second.py",
    "content": "# mypy: allow-untyped-defs\n# content of test_second.py\nfrom __future__ import annotations\n\n\ndef test_2():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/customdirectory/tests/test_third.py",
    "content": "# mypy: allow-untyped-defs\n# content of test_third.py\nfrom __future__ import annotations\n\n\ndef test_3():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/dataclasses/test_compare_dataclasses.py",
    "content": "from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\n\ndef test_dataclasses() -> None:\n    @dataclass\n    class SimpleDataObject:\n        field_a: int = field()\n        field_b: str = field()\n\n    left = SimpleDataObject(1, \"b\")\n    right = SimpleDataObject(1, \"c\")\n\n    assert left == right\n"
  },
  {
    "path": "testing/example_scripts/dataclasses/test_compare_dataclasses_field_comparison_off.py",
    "content": "from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\n\ndef test_dataclasses_with_attribute_comparison_off() -> None:\n    @dataclass\n    class SimpleDataObject:\n        field_a: int = field()\n        field_b: str = field(compare=False)\n\n    left = SimpleDataObject(1, \"b\")\n    right = SimpleDataObject(1, \"c\")\n\n    assert left == right\n"
  },
  {
    "path": "testing/example_scripts/dataclasses/test_compare_dataclasses_verbose.py",
    "content": "from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\n\ndef test_dataclasses_verbose() -> None:\n    @dataclass\n    class SimpleDataObject:\n        field_a: int = field()\n        field_b: str = field()\n\n    left = SimpleDataObject(1, \"b\")\n    right = SimpleDataObject(1, \"c\")\n\n    assert left == right\n"
  },
  {
    "path": "testing/example_scripts/dataclasses/test_compare_dataclasses_with_custom_eq.py",
    "content": "from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\n\ndef test_dataclasses() -> None:\n    @dataclass\n    class SimpleDataObject:\n        field_a: int = field()\n        field_b: str = field()\n\n        def __eq__(self, o: object, /) -> bool:\n            return super().__eq__(o)\n\n    left = SimpleDataObject(1, \"b\")\n    right = SimpleDataObject(1, \"c\")\n\n    assert left == right\n"
  },
  {
    "path": "testing/example_scripts/dataclasses/test_compare_initvar.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom dataclasses import InitVar\n\n\n@dataclass\nclass Foo:\n    init_only: InitVar[int]\n    real_attr: int\n\n\ndef test_demonstrate():\n    assert Foo(1, 2) == Foo(1, 3)\n"
  },
  {
    "path": "testing/example_scripts/dataclasses/test_compare_recursive_dataclasses.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass S:\n    a: int\n    b: str\n\n\n@dataclass\nclass C:\n    c: S\n    d: S\n\n\n@dataclass\nclass C2:\n    e: C\n    f: S\n\n\n@dataclass\nclass C3:\n    g: S\n    h: C2\n    i: str\n    j: str\n\n\ndef test_recursive_dataclasses():\n    left = C3(\n        S(10, \"ten\"),\n        C2(C(S(1, \"one\"), S(2, \"two\")), S(2, \"three\")),\n        \"equal\",\n        \"left\",\n    )\n    right = C3(\n        S(20, \"xxx\"),\n        C2(C(S(1, \"one\"), S(2, \"yyy\")), S(3, \"three\")),\n        \"equal\",\n        \"right\",\n    )\n\n    assert left == right\n"
  },
  {
    "path": "testing/example_scripts/dataclasses/test_compare_two_different_dataclasses.py",
    "content": "from __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom dataclasses import field\n\n\ndef test_comparing_two_different_data_classes() -> None:\n    @dataclass\n    class SimpleDataObjectOne:\n        field_a: int = field()\n        field_b: str = field()\n\n    @dataclass\n    class SimpleDataObjectTwo:\n        field_a: int = field()\n        field_b: str = field()\n\n    left = SimpleDataObjectOne(1, \"b\")\n    right = SimpleDataObjectTwo(1, \"c\")\n\n    assert left != right  # type: ignore[comparison-overlap]\n"
  },
  {
    "path": "testing/example_scripts/doctest/main_py/__main__.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_this_is_ignored():\n    assert True\n"
  },
  {
    "path": "testing/example_scripts/doctest/main_py/test_normal_module.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_doc():\n    \"\"\"\n    >>> 10 > 5\n    True\n    \"\"\"\n    assert False\n"
  },
  {
    "path": "testing/example_scripts/fixtures/custom_item/__init__.pyi",
    "content": ""
  },
  {
    "path": "testing/example_scripts/fixtures/custom_item/conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\nclass CustomItem(pytest.Item):\n    def runtest(self):\n        pass\n\n\nclass CustomFile(pytest.File):\n    def collect(self):\n        yield CustomItem.from_parent(name=\"foo\", parent=self)\n\n\ndef pytest_collect_file(file_path, parent):\n    return CustomFile.from_parent(path=file_path, parent=parent)\n"
  },
  {
    "path": "testing/example_scripts/fixtures/custom_item/foo/__init__.py",
    "content": ""
  },
  {
    "path": "testing/example_scripts/fixtures/custom_item/foo/test_foo.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub1/__init__.py",
    "content": ""
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub1/conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef arg1(request):\n    with pytest.raises(pytest.FixtureLookupError):\n        request.getfixturevalue(\"arg2\")\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub1/test_in_sub1.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_1(arg1):\n    pass\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub2/__init__.py",
    "content": ""
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub2/conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom _pytest.fixtures import FixtureLookupError\nimport pytest\n\n\n@pytest.fixture\ndef arg2(request):\n    with pytest.raises(FixtureLookupError):\n        request.getfixturevalue(\"arg1\")\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_conftest_funcargs_only_available_in_subdir/sub2/test_in_sub2.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_2(arg2):\n    pass\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_detect_recursive_dependency_error.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef fix1(fix2):\n    return 1\n\n\n@pytest.fixture\ndef fix2(fix1):\n    return 1\n\n\ndef test(fix1):\n    pass\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest/__init__.pyi",
    "content": ""
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest/conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef spam():\n    return \"spam\"\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest/pkg/__init__.py",
    "content": ""
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest/pkg/conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef spam(spam):\n    return spam * 2\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_conftest/pkg/test_spam.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_spam(spam):\n    assert spam == \"spamspam\"\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_module/__init__.pyi",
    "content": ""
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_module/conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef spam():\n    return \"spam\"\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_conftest_module/test_extend_fixture_conftest_module.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef spam(spam):\n    return spam * 2\n\n\ndef test_spam(spam):\n    assert spam == \"spamspam\"\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_extend_fixture_module_class.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef spam():\n    return \"spam\"\n\n\nclass TestSpam:\n    @pytest.fixture\n    def spam(self, spam):\n        return spam * 2\n\n    def test_spam(self, spam):\n        assert spam == \"spamspam\"\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_funcarg_basic.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef some(request):\n    return request.function.__name__\n\n\n@pytest.fixture\ndef other(request):\n    return 42\n\n\ndef test_func(some, other):\n    pass\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_funcarg_lookup_classlevel.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\nclass TestClass:\n    @pytest.fixture\n    def something(self, request):\n        return request.instance\n\n    def test_method(self, something):\n        assert something is self\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_funcarg_lookup_modulelevel.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef something(request):\n    return request.function.__name__\n\n\nclass TestClass:\n    def test_method(self, something):\n        assert something == \"test_method\"\n\n\ndef test_func(something):\n    assert something == \"test_func\"\n"
  },
  {
    "path": "testing/example_scripts/fixtures/fill_fixtures/test_funcarg_lookupfails.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef xyzsomething(request):\n    return 42\n\n\ndef test_func(some):\n    pass\n"
  },
  {
    "path": "testing/example_scripts/fixtures/test_fixture_named_request.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef request():\n    pass\n\n\ndef test():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/fixtures/test_getfixturevalue_dynamic.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.fixture\ndef dynamic():\n    pass\n\n\n@pytest.fixture\ndef a(request):\n    request.getfixturevalue(\"dynamic\")\n\n\n@pytest.fixture\ndef b(a):\n    pass\n\n\ndef test(b, request):\n    assert request.fixturenames == [\"b\", \"request\", \"a\", \"dynamic\"]\n"
  },
  {
    "path": "testing/example_scripts/issue88_initial_file_multinodes/__init__.pyi",
    "content": ""
  },
  {
    "path": "testing/example_scripts/issue88_initial_file_multinodes/conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\nclass MyFile(pytest.File):\n    def collect(self):\n        return [MyItem.from_parent(name=\"hello\", parent=self)]\n\n\ndef pytest_collect_file(file_path, parent):\n    return MyFile.from_parent(path=file_path, parent=parent)\n\n\nclass MyItem(pytest.Item):\n    def runtest(self):\n        raise NotImplementedError()\n"
  },
  {
    "path": "testing/example_scripts/issue88_initial_file_multinodes/test_hello.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_hello():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/issue_519.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pprint\n\nimport pytest\n\n\ndef pytest_generate_tests(metafunc):\n    if \"arg1\" in metafunc.fixturenames:\n        metafunc.parametrize(\"arg1\", [\"arg1v1\", \"arg1v2\"], scope=\"module\")\n\n    if \"arg2\" in metafunc.fixturenames:\n        metafunc.parametrize(\"arg2\", [\"arg2v1\", \"arg2v2\"], scope=\"function\")\n\n\n@pytest.fixture(scope=\"session\")\ndef checked_order():\n    order: list[tuple[str, str, str]] = []\n\n    yield order\n    pprint.pprint(order)\n    assert order == [\n        (\"issue_519.py\", \"fix1\", \"arg1v1\"),\n        (\"test_one[arg1v1-arg2v1]\", \"fix2\", \"arg2v1\"),\n        (\"test_two[arg1v1-arg2v1]\", \"fix2\", \"arg2v1\"),\n        (\"test_one[arg1v1-arg2v2]\", \"fix2\", \"arg2v2\"),\n        (\"test_two[arg1v1-arg2v2]\", \"fix2\", \"arg2v2\"),\n        (\"issue_519.py\", \"fix1\", \"arg1v2\"),\n        (\"test_one[arg1v2-arg2v1]\", \"fix2\", \"arg2v1\"),\n        (\"test_two[arg1v2-arg2v1]\", \"fix2\", \"arg2v1\"),\n        (\"test_one[arg1v2-arg2v2]\", \"fix2\", \"arg2v2\"),\n        (\"test_two[arg1v2-arg2v2]\", \"fix2\", \"arg2v2\"),\n    ]\n\n\n@pytest.fixture(scope=\"module\")\ndef fix1(request, arg1, checked_order):\n    checked_order.append((request.node.name, \"fix1\", arg1))\n    yield \"fix1-\" + arg1\n\n\n@pytest.fixture(scope=\"function\")\ndef fix2(request, fix1, arg2, checked_order):\n    checked_order.append((request.node.name, \"fix2\", arg2))\n    yield \"fix2-\" + arg2 + fix1\n\n\ndef test_one(fix2):\n    pass\n\n\ndef test_two(fix2):\n    pass\n"
  },
  {
    "path": "testing/example_scripts/junit-10.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!--\nThe MIT License (MIT)\n\nCopyright (c) 2014, Gregory Boissinot\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n-->\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n    <xs:simpleType name=\"SUREFIRE_TIME\">\n        <xs:restriction base=\"xs:string\">\n            <xs:pattern value=\"(([0-9]{0,3},)*[0-9]{3}|[0-9]{0,3})*(\\.[0-9]{0,3})?\"/>\n        </xs:restriction>\n    </xs:simpleType>\n\n    <xs:complexType name=\"rerunType\" mixed=\"true\"> <!-- mixed (XML contains text) to be compatible with version previous than 2.22.1 -->\n        <xs:sequence>\n            <xs:element name=\"stackTrace\" type=\"xs:string\" minOccurs=\"0\" /> <!-- optional to be compatible with version previous than 2.22.1 -->\n            <xs:element name=\"system-out\" type=\"xs:string\" minOccurs=\"0\" />\n            <xs:element name=\"system-err\" type=\"xs:string\" minOccurs=\"0\" />\n        </xs:sequence>\n        <xs:attribute name=\"message\" type=\"xs:string\" />\n        <xs:attribute name=\"type\" type=\"xs:string\" use=\"required\" />\n    </xs:complexType>\n\n    <xs:element name=\"failure\">\n        <xs:complexType mixed=\"true\">\n            <xs:attribute name=\"type\" type=\"xs:string\"/>\n            <xs:attribute name=\"message\" type=\"xs:string\"/>\n        </xs:complexType>\n    </xs:element>\n\n    <xs:element name=\"error\">\n        <xs:complexType mixed=\"true\">\n            <xs:attribute name=\"type\" type=\"xs:string\"/>\n            <xs:attribute name=\"message\" type=\"xs:string\"/>\n        </xs:complexType>\n    </xs:element>\n\n    <xs:element name=\"skipped\">\n        <xs:complexType mixed=\"true\">\n            <xs:attribute name=\"type\" type=\"xs:string\"/>\n            <xs:attribute name=\"message\" type=\"xs:string\"/>\n        </xs:complexType>\n    </xs:element>\n\n    <xs:element name=\"properties\">\n        <xs:complexType>\n            <xs:sequence>\n                <xs:element ref=\"property\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n            </xs:sequence>\n        </xs:complexType>\n    </xs:element>\n\n    <xs:element name=\"property\">\n        <xs:complexType>\n            <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\"/>\n            <xs:attribute name=\"value\" type=\"xs:string\" use=\"required\"/>\n        </xs:complexType>\n    </xs:element>\n\n    <xs:element name=\"system-err\" type=\"xs:string\"/>\n    <xs:element name=\"system-out\" type=\"xs:string\"/>\n    <xs:element name=\"rerunFailure\" type=\"rerunType\"/>\n    <xs:element name=\"rerunError\" type=\"rerunType\"/>\n    <xs:element name=\"flakyFailure\" type=\"rerunType\"/>\n    <xs:element name=\"flakyError\" type=\"rerunType\"/>\n\n    <xs:element name=\"testcase\">\n        <xs:complexType>\n            <xs:sequence>\n                <xs:choice minOccurs=\"0\" maxOccurs=\"unbounded\">\n                    <xs:element ref=\"skipped\"/>\n                    <xs:element ref=\"error\"/>\n                    <xs:element ref=\"failure\"/>\n                    <xs:element ref=\"rerunFailure\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n                    <xs:element ref=\"rerunError\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n                    <xs:element ref=\"flakyFailure\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n                    <xs:element ref=\"flakyError\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n                    <xs:element ref=\"system-out\"/>\n                    <xs:element ref=\"system-err\"/>\n                </xs:choice>\n            </xs:sequence>\n            <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\"/>\n            <xs:attribute name=\"time\" type=\"xs:string\"/>\n            <xs:attribute name=\"classname\" type=\"xs:string\"/>\n            <xs:attribute name=\"group\" type=\"xs:string\"/>\n        </xs:complexType>\n    </xs:element>\n\n    <xs:element name=\"testsuite\">\n        <xs:complexType>\n            <xs:choice minOccurs=\"0\" maxOccurs=\"unbounded\">\n                <xs:element ref=\"testsuite\"/>\n                <xs:element ref=\"properties\"/>\n                <xs:element ref=\"testcase\"/>\n                <xs:element ref=\"system-out\"/>\n                <xs:element ref=\"system-err\"/>\n            </xs:choice>\n            <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\"/>\n            <xs:attribute name=\"tests\" type=\"xs:string\" use=\"required\"/>\n            <xs:attribute name=\"failures\" type=\"xs:string\" use=\"required\"/>\n            <xs:attribute name=\"errors\" type=\"xs:string\" use=\"required\"/>\n            <xs:attribute name=\"group\" type=\"xs:string\" />\n            <xs:attribute name=\"time\" type=\"SUREFIRE_TIME\"/>\n            <xs:attribute name=\"skipped\" type=\"xs:string\" />\n            <xs:attribute name=\"timestamp\" type=\"xs:string\" />\n            <xs:attribute name=\"hostname\" type=\"xs:string\" />\n            <xs:attribute name=\"id\" type=\"xs:string\" />\n            <xs:attribute name=\"package\" type=\"xs:string\" />\n            <xs:attribute name=\"file\" type=\"xs:string\"/>\n            <xs:attribute name=\"log\" type=\"xs:string\"/>\n            <xs:attribute name=\"url\" type=\"xs:string\"/>\n            <xs:attribute name=\"version\" type=\"xs:string\"/>\n        </xs:complexType>\n    </xs:element>\n\n    <xs:element name=\"testsuites\">\n        <xs:complexType>\n            <xs:sequence>\n                <xs:element ref=\"testsuite\" minOccurs=\"0\" maxOccurs=\"unbounded\" />\n            </xs:sequence>\n            <xs:attribute name=\"name\" type=\"xs:string\" />\n            <xs:attribute name=\"time\" type=\"SUREFIRE_TIME\"/>\n            <xs:attribute name=\"tests\" type=\"xs:string\" />\n            <xs:attribute name=\"failures\" type=\"xs:string\" />\n            <xs:attribute name=\"errors\" type=\"xs:string\" />\n        </xs:complexType>\n    </xs:element>\n\n</xs:schema>\n"
  },
  {
    "path": "testing/example_scripts/marks/marks_considered_keywords/__init__.pyi",
    "content": ""
  },
  {
    "path": "testing/example_scripts/marks/marks_considered_keywords/conftest.py",
    "content": ""
  },
  {
    "path": "testing/example_scripts/marks/marks_considered_keywords/test_marks_as_keywords.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.mark.foo\ndef test_mark():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/perf_examples/collect_stats/.gitignore",
    "content": "foo_*\n"
  },
  {
    "path": "testing/example_scripts/perf_examples/collect_stats/generate_folders.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport argparse\nimport pathlib\n\n\nHERE = pathlib.Path(__file__).parent\nTEST_CONTENT = (HERE / \"template_test.py\").read_bytes()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"numbers\", nargs=\"*\", type=int)\n\n\ndef generate_folders(root, elements, *more_numbers):\n    fill_len = len(str(elements))\n    if more_numbers:\n        for i in range(elements):\n            new_folder = root.joinpath(f\"foo_{i:0>{fill_len}}\")\n            new_folder.mkdir()\n            new_folder.joinpath(\"__init__.py\").write_bytes(TEST_CONTENT)\n            generate_folders(new_folder, *more_numbers)\n    else:\n        for i in range(elements):\n            new_test = root.joinpath(f\"test_{i:0<{fill_len}}.py\")\n            new_test.write_bytes(TEST_CONTENT)\n\n\nif __name__ == \"__main__\":\n    args = parser.parse_args()\n    generate_folders(HERE, *(args.numbers or (10, 100)))\n"
  },
  {
    "path": "testing/example_scripts/perf_examples/collect_stats/template_test.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_x():\n    pass\n"
  },
  {
    "path": "testing/example_scripts/pytest.ini",
    "content": "[pytest]\n# dummy pytest.ini to ease direct running of example scripts\n"
  },
  {
    "path": "testing/example_scripts/tmpdir/tmp_path_fixture.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\n@pytest.mark.parametrize(\"a\", [r\"qwe/\\abc\"])\ndef test_fixture(tmp_path, a):\n    assert tmp_path.is_dir()\n    assert list(tmp_path.iterdir()) == []\n"
  },
  {
    "path": "testing/example_scripts/unittest/test_parametrized_fixture_error_message.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport unittest\n\nimport pytest\n\n\n@pytest.fixture(params=[1, 2])\ndef two(request):\n    return request.param\n\n\n@pytest.mark.usefixtures(\"two\")\nclass TestSomethingElse(unittest.TestCase):\n    def test_two(self):\n        pass\n"
  },
  {
    "path": "testing/example_scripts/unittest/test_setup_skip.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Skipping an entire subclass with unittest.skip() should *not* call setUp from a base class.\"\"\"\n\nfrom __future__ import annotations\n\nimport unittest\n\n\nclass Base(unittest.TestCase):\n    def setUp(self):\n        assert 0\n\n\n@unittest.skip(\"skip all tests\")\nclass Test(Base):\n    def test_foo(self):\n        assert 0\n"
  },
  {
    "path": "testing/example_scripts/unittest/test_setup_skip_class.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Skipping an entire subclass with unittest.skip() should *not* call setUpClass from a base class.\"\"\"\n\nfrom __future__ import annotations\n\nimport unittest\n\n\nclass Base(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        assert 0\n\n\n@unittest.skip(\"skip all tests\")\nclass Test(Base):\n    def test_foo(self):\n        assert 0\n"
  },
  {
    "path": "testing/example_scripts/unittest/test_setup_skip_module.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"setUpModule is always called, even if all tests in the module are skipped\"\"\"\n\nfrom __future__ import annotations\n\nimport unittest\n\n\ndef setUpModule():\n    assert 0\n\n\n@unittest.skip(\"skip all tests\")\nclass Base(unittest.TestCase):\n    def test(self):\n        assert 0\n"
  },
  {
    "path": "testing/example_scripts/unittest/test_unittest_asyncio.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom unittest import IsolatedAsyncioTestCase\n\n\nteardowns: list[None] = []\n\n\nclass AsyncArguments(IsolatedAsyncioTestCase):\n    async def asyncTearDown(self):\n        teardowns.append(None)\n\n    async def test_something_async(self):\n        async def addition(x, y):\n            return x + y\n\n        self.assertEqual(await addition(2, 2), 4)\n\n    async def test_something_async_fails(self):\n        async def addition(x, y):\n            return x + y\n\n        self.assertEqual(await addition(2, 2), 3)\n\n    def test_teardowns(self):\n        assert len(teardowns) == 2\n"
  },
  {
    "path": "testing/example_scripts/unittest/test_unittest_asynctest.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Issue #7110\"\"\"\n\nfrom __future__ import annotations\n\nimport asyncio\n\nimport asynctest\n\n\nteardowns: list[None] = []\n\n\nclass Test(asynctest.TestCase):\n    async def tearDown(self):\n        teardowns.append(None)\n\n    async def test_error(self):\n        await asyncio.sleep(0)\n        self.fail(\"failing on purpose\")\n\n    async def test_ok(self):\n        await asyncio.sleep(0)\n\n    def test_teardowns(self):\n        assert len(teardowns) == 2\n"
  },
  {
    "path": "testing/example_scripts/unittest/test_unittest_plain_async.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport unittest\n\n\nclass Test(unittest.TestCase):\n    async def test_foo(self):\n        assert False\n"
  },
  {
    "path": "testing/example_scripts/warnings/test_group_warnings_by_message.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport warnings\n\nimport pytest\n\n\ndef func(msg):\n    warnings.warn(UserWarning(msg))\n\n\n@pytest.mark.parametrize(\"i\", range(5))\ndef test_foo(i):\n    func(\"foo\")\n\n\ndef test_foo_1():\n    func(\"foo\")\n\n\n@pytest.mark.parametrize(\"i\", range(5))\ndef test_bar(i):\n    func(\"bar\")\n"
  },
  {
    "path": "testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_1.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport warnings\n\nimport pytest\n\n\ndef func(msg):\n    warnings.warn(UserWarning(msg))\n\n\n@pytest.mark.parametrize(\"i\", range(20))\ndef test_foo(i):\n    func(\"foo\")\n\n\ndef test_foo_1():\n    func(\"foo\")\n\n\n@pytest.mark.parametrize(\"i\", range(20))\ndef test_bar(i):\n    func(\"bar\")\n"
  },
  {
    "path": "testing/example_scripts/warnings/test_group_warnings_by_message_summary/test_2.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom test_1 import func\n\n\ndef test_2():\n    func(\"foo\")\n"
  },
  {
    "path": "testing/examples/test_issue519.py",
    "content": "from __future__ import annotations\n\nfrom _pytest.pytester import Pytester\n\n\ndef test_519(pytester: Pytester) -> None:\n    pytester.copy_example(\"issue_519.py\")\n    res = pytester.runpytest(\"issue_519.py\")\n    res.assert_outcomes(passed=8)\n"
  },
  {
    "path": "testing/freeze/.gitignore",
    "content": "build/\ndist/\n*.spec\n"
  },
  {
    "path": "testing/freeze/create_executable.py",
    "content": "\"\"\"Generate an executable with pytest runner embedded using PyInstaller.\"\"\"\n\nfrom __future__ import annotations\n\n\nif __name__ == \"__main__\":\n    import subprocess\n\n    import pytest\n\n    hidden = []\n    for x in pytest.freeze_includes():\n        hidden.extend([\"--hidden-import\", x])\n    hidden.extend([\"--hidden-import\", \"distutils\"])\n    args = [\"pyinstaller\", \"--noconfirm\", *hidden, \"runtests_script.py\"]\n    subprocess.check_call(\" \".join(args), shell=True)\n"
  },
  {
    "path": "testing/freeze/runtests_script.py",
    "content": "\"\"\"\nThis is the script that is actually frozen into an executable: simply executes\npytest main().\n\"\"\"\n\nfrom __future__ import annotations\n\n\nif __name__ == \"__main__\":\n    import sys\n\n    import pytest\n\n    sys.exit(pytest.main())\n"
  },
  {
    "path": "testing/freeze/tests/test_doctest.txt",
    "content": "\n\nTesting doctest::\n\n    >>> 1 + 1\n    2\n"
  },
  {
    "path": "testing/freeze/tests/test_trivial.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_upper():\n    assert \"foo\".upper() == \"FOO\"\n\n\ndef test_lower():\n    assert \"FOO\".lower() == \"foo\"\n"
  },
  {
    "path": "testing/freeze/tox_run.py",
    "content": "\"\"\"\nCalled by tox.ini: uses the generated executable to run the tests in ./tests/\ndirectory.\n\"\"\"\n\nfrom __future__ import annotations\n\n\nif __name__ == \"__main__\":\n    import os\n    import sys\n\n    executable = os.path.join(os.getcwd(), \"dist\", \"runtests_script\", \"runtests_script\")\n    if sys.platform.startswith(\"win\"):\n        executable += \".exe\"\n    sys.exit(os.system(f\"{executable} tests\"))\n"
  },
  {
    "path": "testing/io/test_pprint.py",
    "content": "from __future__ import annotations\n\nfrom collections import ChainMap\nfrom collections import Counter\nfrom collections import defaultdict\nfrom collections import deque\nfrom collections import OrderedDict\nfrom dataclasses import dataclass\nimport textwrap\nfrom types import MappingProxyType\nfrom types import SimpleNamespace\nfrom typing import Any\n\nfrom _pytest._io.pprint import PrettyPrinter\nimport pytest\n\n\n@dataclass\nclass EmptyDataclass:\n    pass\n\n\n@dataclass\nclass DataclassWithOneItem:\n    foo: str\n\n\n@dataclass\nclass DataclassWithTwoItems:\n    foo: str\n    bar: str\n\n\n@pytest.mark.parametrize(\n    (\"data\", \"expected\"),\n    (\n        pytest.param(\n            EmptyDataclass(),\n            \"EmptyDataclass()\",\n            id=\"dataclass-empty\",\n        ),\n        pytest.param(\n            DataclassWithOneItem(foo=\"bar\"),\n            \"\"\"\n            DataclassWithOneItem(\n                foo='bar',\n            )\n            \"\"\",\n            id=\"dataclass-one-item\",\n        ),\n        pytest.param(\n            DataclassWithTwoItems(foo=\"foo\", bar=\"bar\"),\n            \"\"\"\n            DataclassWithTwoItems(\n                foo='foo',\n                bar='bar',\n            )\n            \"\"\",\n            id=\"dataclass-two-items\",\n        ),\n        pytest.param(\n            {},\n            \"{}\",\n            id=\"dict-empty\",\n        ),\n        pytest.param(\n            {\"one\": 1},\n            \"\"\"\n            {\n                'one': 1,\n            }\n            \"\"\",\n            id=\"dict-one-item\",\n        ),\n        pytest.param(\n            {\"one\": 1, \"two\": 2},\n            \"\"\"\n            {\n                'one': 1,\n                'two': 2,\n            }\n            \"\"\",\n            id=\"dict-two-items\",\n        ),\n        pytest.param(OrderedDict(), \"OrderedDict()\", id=\"ordereddict-empty\"),\n        pytest.param(\n            OrderedDict({\"one\": 1}),\n            \"\"\"\n            OrderedDict({\n                'one': 1,\n            })\n            \"\"\",\n            id=\"ordereddict-one-item\",\n        ),\n        pytest.param(\n            OrderedDict({\"one\": 1, \"two\": 2}),\n            \"\"\"\n            OrderedDict({\n                'one': 1,\n                'two': 2,\n            })\n            \"\"\",\n            id=\"ordereddict-two-items\",\n        ),\n        pytest.param(\n            [],\n            \"[]\",\n            id=\"list-empty\",\n        ),\n        pytest.param(\n            [1],\n            \"\"\"\n            [\n                1,\n            ]\n            \"\"\",\n            id=\"list-one-item\",\n        ),\n        pytest.param(\n            [1, 2],\n            \"\"\"\n            [\n                1,\n                2,\n            ]\n            \"\"\",\n            id=\"list-two-items\",\n        ),\n        pytest.param(\n            tuple(),\n            \"()\",\n            id=\"tuple-empty\",\n        ),\n        pytest.param(\n            (1,),\n            \"\"\"\n            (\n                1,\n            )\n            \"\"\",\n            id=\"tuple-one-item\",\n        ),\n        pytest.param(\n            (1, 2),\n            \"\"\"\n            (\n                1,\n                2,\n            )\n            \"\"\",\n            id=\"tuple-two-items\",\n        ),\n        pytest.param(\n            set(),\n            \"set()\",\n            id=\"set-empty\",\n        ),\n        pytest.param(\n            {1},\n            \"\"\"\n            {\n                1,\n            }\n            \"\"\",\n            id=\"set-one-item\",\n        ),\n        pytest.param(\n            {1, 2},\n            \"\"\"\n            {\n                1,\n                2,\n            }\n            \"\"\",\n            id=\"set-two-items\",\n        ),\n        pytest.param(\n            MappingProxyType({}),\n            \"mappingproxy({})\",\n            id=\"mappingproxy-empty\",\n        ),\n        pytest.param(\n            MappingProxyType({\"one\": 1}),\n            \"\"\"\n            mappingproxy({\n                'one': 1,\n            })\n            \"\"\",\n            id=\"mappingproxy-one-item\",\n        ),\n        pytest.param(\n            MappingProxyType({\"one\": 1, \"two\": 2}),\n            \"\"\"\n            mappingproxy({\n                'one': 1,\n                'two': 2,\n            })\n            \"\"\",\n            id=\"mappingproxy-two-items\",\n        ),\n        pytest.param(\n            SimpleNamespace(),\n            \"namespace()\",\n            id=\"simplenamespace-empty\",\n        ),\n        pytest.param(\n            SimpleNamespace(one=1),\n            \"\"\"\n            namespace(\n                one=1,\n            )\n            \"\"\",\n            id=\"simplenamespace-one-item\",\n        ),\n        pytest.param(\n            SimpleNamespace(one=1, two=2),\n            \"\"\"\n            namespace(\n                one=1,\n                two=2,\n            )\n            \"\"\",\n            id=\"simplenamespace-two-items\",\n        ),\n        pytest.param(\n            defaultdict(str), \"defaultdict(<class 'str'>, {})\", id=\"defaultdict-empty\"\n        ),\n        pytest.param(\n            defaultdict(str, {\"one\": \"1\"}),\n            \"\"\"\n            defaultdict(<class 'str'>, {\n                'one': '1',\n            })\n            \"\"\",\n            id=\"defaultdict-one-item\",\n        ),\n        pytest.param(\n            defaultdict(str, {\"one\": \"1\", \"two\": \"2\"}),\n            \"\"\"\n            defaultdict(<class 'str'>, {\n                'one': '1',\n                'two': '2',\n            })\n            \"\"\",\n            id=\"defaultdict-two-items\",\n        ),\n        pytest.param(\n            Counter(),\n            \"Counter()\",\n            id=\"counter-empty\",\n        ),\n        pytest.param(\n            Counter(\"1\"),\n            \"\"\"\n            Counter({\n                '1': 1,\n            })\n            \"\"\",\n            id=\"counter-one-item\",\n        ),\n        pytest.param(\n            Counter(\"121\"),\n            \"\"\"\n            Counter({\n                '1': 2,\n                '2': 1,\n            })\n            \"\"\",\n            id=\"counter-two-items\",\n        ),\n        pytest.param(ChainMap(), \"ChainMap({})\", id=\"chainmap-empty\"),\n        pytest.param(\n            ChainMap({\"one\": 1, \"two\": 2}),\n            \"\"\"\n            ChainMap(\n                {\n                    'one': 1,\n                    'two': 2,\n                },\n            )\n            \"\"\",\n            id=\"chainmap-one-item\",\n        ),\n        pytest.param(\n            ChainMap({\"one\": 1}, {\"two\": 2}),\n            \"\"\"\n            ChainMap(\n                {\n                    'one': 1,\n                },\n                {\n                    'two': 2,\n                },\n            )\n            \"\"\",\n            id=\"chainmap-two-items\",\n        ),\n        pytest.param(\n            deque(),\n            \"deque([])\",\n            id=\"deque-empty\",\n        ),\n        pytest.param(\n            deque([1]),\n            \"\"\"\n            deque([\n                1,\n            ])\n            \"\"\",\n            id=\"deque-one-item\",\n        ),\n        pytest.param(\n            deque([1, 2]),\n            \"\"\"\n            deque([\n                1,\n                2,\n            ])\n            \"\"\",\n            id=\"deque-two-items\",\n        ),\n        pytest.param(\n            deque([1, 2], maxlen=3),\n            \"\"\"\n            deque(maxlen=3, [\n                1,\n                2,\n            ])\n            \"\"\",\n            id=\"deque-maxlen\",\n        ),\n        pytest.param(\n            {\n                \"chainmap\": ChainMap({\"one\": 1}, {\"two\": 2}),\n                \"counter\": Counter(\"122\"),\n                \"dataclass\": DataclassWithTwoItems(foo=\"foo\", bar=\"bar\"),\n                \"defaultdict\": defaultdict(str, {\"one\": \"1\", \"two\": \"2\"}),\n                \"deque\": deque([1, 2], maxlen=3),\n                \"dict\": {\"one\": 1, \"two\": 2},\n                \"list\": [1, 2],\n                \"mappingproxy\": MappingProxyType({\"one\": 1, \"two\": 2}),\n                \"ordereddict\": OrderedDict({\"one\": 1, \"two\": 2}),\n                \"set\": {1, 2},\n                \"simplenamespace\": SimpleNamespace(one=1, two=2),\n                \"tuple\": (1, 2),\n            },\n            \"\"\"\n            {\n                'chainmap': ChainMap(\n                    {\n                        'one': 1,\n                    },\n                    {\n                        'two': 2,\n                    },\n                ),\n                'counter': Counter({\n                    '2': 2,\n                    '1': 1,\n                }),\n                'dataclass': DataclassWithTwoItems(\n                    foo='foo',\n                    bar='bar',\n                ),\n                'defaultdict': defaultdict(<class 'str'>, {\n                    'one': '1',\n                    'two': '2',\n                }),\n                'deque': deque(maxlen=3, [\n                    1,\n                    2,\n                ]),\n                'dict': {\n                    'one': 1,\n                    'two': 2,\n                },\n                'list': [\n                    1,\n                    2,\n                ],\n                'mappingproxy': mappingproxy({\n                    'one': 1,\n                    'two': 2,\n                }),\n                'ordereddict': OrderedDict({\n                    'one': 1,\n                    'two': 2,\n                }),\n                'set': {\n                    1,\n                    2,\n                },\n                'simplenamespace': namespace(\n                    one=1,\n                    two=2,\n                ),\n                'tuple': (\n                    1,\n                    2,\n                ),\n            }\n            \"\"\",\n            id=\"deep-example\",\n        ),\n    ),\n)\ndef test_consistent_pretty_printer(data: Any, expected: str) -> None:\n    assert PrettyPrinter().pformat(data) == textwrap.dedent(expected).strip()\n"
  },
  {
    "path": "testing/io/test_saferepr.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE\nfrom _pytest._io.saferepr import SafeRepr\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest._io.saferepr import saferepr_unlimited\nimport pytest\n\n\ndef test_simple_repr():\n    assert saferepr(1) == \"1\"\n    assert saferepr(None) == \"None\"\n\n\ndef test_maxsize():\n    s = saferepr(\"x\" * 50, maxsize=25)\n    assert len(s) == 25\n    expected = repr(\"x\" * 10 + \"...\" + \"x\" * 10)\n    assert s == expected\n\n\ndef test_no_maxsize():\n    text = \"x\" * DEFAULT_REPR_MAX_SIZE * 10\n    s = saferepr(text, maxsize=None)\n    expected = repr(text)\n    assert s == expected\n\n\ndef test_maxsize_error_on_instance():\n    class A:\n        def __repr__(self):\n            raise ValueError(\"...\")\n\n    s = saferepr((\"*\" * 50, A()), maxsize=25)\n    assert len(s) == 25\n    assert s[0] == \"(\" and s[-1] == \")\"\n\n\ndef test_exceptions() -> None:\n    class BrokenRepr:\n        def __init__(self, ex):\n            self.ex = ex\n\n        def __repr__(self):\n            raise self.ex\n\n    class BrokenReprException(Exception):\n        __str__ = None  # type: ignore[assignment]\n        __repr__ = None  # type: ignore[assignment]\n\n    assert \"Exception\" in saferepr(BrokenRepr(Exception(\"broken\")))\n    s = saferepr(BrokenReprException(\"really broken\"))\n    assert \"TypeError\" in s\n    assert \"TypeError\" in saferepr(BrokenRepr(\"string\"))\n\n    none = None\n    try:\n        none()  # type: ignore[misc]\n    except BaseException as exc:\n        exp_exc = repr(exc)\n    obj = BrokenRepr(BrokenReprException(\"omg even worse\"))\n    s2 = saferepr(obj)\n    assert s2 == (\n        f\"<[unpresentable exception ({exp_exc!s}) raised in repr()] BrokenRepr object at 0x{id(obj):x}>\"\n    )\n\n\ndef test_baseexception():\n    \"\"\"Test saferepr() with BaseExceptions, which includes pytest outcomes.\"\"\"\n\n    class RaisingOnStrRepr(BaseException):\n        def __init__(self, exc_types):\n            self.exc_types = exc_types\n\n        def raise_exc(self, *args):\n            try:\n                self.exc_type = self.exc_types.pop(0)\n            except IndexError:\n                pass\n            if hasattr(self.exc_type, \"__call__\"):\n                raise self.exc_type(*args)\n            raise self.exc_type\n\n        def __str__(self):  # noqa: PLE0307\n            self.raise_exc(\"__str__\")\n\n        def __repr__(self):\n            self.raise_exc(\"__repr__\")\n\n    class BrokenObj:\n        def __init__(self, exc):\n            self.exc = exc\n\n        def __repr__(self):\n            raise self.exc\n\n        __str__ = __repr__\n\n    baseexc_str = BaseException(\"__str__\")\n    obj = BrokenObj(RaisingOnStrRepr([BaseException]))\n    assert saferepr(obj) == (\n        f\"<[unpresentable exception ({baseexc_str!r}) \"\n        f\"raised in repr()] BrokenObj object at 0x{id(obj):x}>\"\n    )\n    obj = BrokenObj(RaisingOnStrRepr([RaisingOnStrRepr([BaseException])]))\n    assert saferepr(obj) == (\n        f\"<[{baseexc_str!r} raised in repr()] BrokenObj object at 0x{id(obj):x}>\"\n    )\n\n    with pytest.raises(KeyboardInterrupt):\n        saferepr(BrokenObj(KeyboardInterrupt()))\n\n    with pytest.raises(SystemExit):\n        saferepr(BrokenObj(SystemExit()))\n\n    with pytest.raises(KeyboardInterrupt):\n        saferepr(BrokenObj(RaisingOnStrRepr([KeyboardInterrupt])))\n\n    with pytest.raises(SystemExit):\n        saferepr(BrokenObj(RaisingOnStrRepr([SystemExit])))\n\n    with pytest.raises(KeyboardInterrupt):\n        print(saferepr(BrokenObj(RaisingOnStrRepr([BaseException, KeyboardInterrupt]))))\n\n    with pytest.raises(SystemExit):\n        saferepr(BrokenObj(RaisingOnStrRepr([BaseException, SystemExit])))\n\n\ndef test_buggy_builtin_repr():\n    # Simulate a case where a repr for a builtin raises.\n    # reprlib dispatches by type name, so use \"int\".\n\n    class int:\n        def __repr__(self):\n            raise ValueError(\"Buggy repr!\")\n\n    assert \"Buggy\" in saferepr(int())\n\n\ndef test_big_repr():\n    from _pytest._io.saferepr import SafeRepr\n\n    assert len(saferepr(range(1000))) <= len(\"[\" + SafeRepr(0).maxlist * \"1000\" + \"]\")\n\n\ndef test_repr_on_newstyle() -> None:\n    class Function:\n        def __repr__(self):\n            return f\"<{self.name}>\"  # type: ignore[attr-defined]\n\n    assert saferepr(Function())\n\n\ndef test_unicode():\n    val = \"£€\"\n    reprval = \"'£€'\"\n    assert saferepr(val) == reprval\n\n\ndef test_broken_getattribute():\n    \"\"\"saferepr() can create proper representations of classes with\n    broken __getattribute__ (#7145)\n    \"\"\"\n\n    class SomeClass:\n        def __getattribute__(self, attr):\n            raise RuntimeError\n\n        def __repr__(self):\n            raise RuntimeError\n\n    assert saferepr(SomeClass()).startswith(\n        \"<[RuntimeError() raised in repr()] SomeClass object at 0x\"\n    )\n\n\ndef test_saferepr_unlimited():\n    dict5 = {f\"v{i}\": i for i in range(5)}\n    assert saferepr_unlimited(dict5) == \"{'v0': 0, 'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4}\"\n\n    dict_long = {f\"v{i}\": i for i in range(1_000)}\n    r = saferepr_unlimited(dict_long)\n    assert \"...\" not in r\n    assert \"\\n\" not in r\n\n\ndef test_saferepr_unlimited_exc():\n    class A:\n        def __repr__(self):\n            raise ValueError(42)\n\n    assert saferepr_unlimited(A()).startswith(\n        \"<[ValueError(42) raised in repr()] A object at 0x\"\n    )\n\n\ndef test_saferepr_dict_preserves_insertion_order() -> None:\n    d = {\n        \"b\": 2,\n        \"a\": 1,\n        \"d\": 4,\n        \"e\": 5,\n        \"c\": 3,\n    }\n    s = SafeRepr(maxsize=None)\n    s.maxdict = 10\n    assert s.repr(d) == \"{'b': 2, 'a': 1, 'd': 4, 'e': 5, 'c': 3}\"\n\n\ndef test_saferepr_dict_truncation_preserves_insertion_order() -> None:\n    d = {\n        \"b\": 2,\n        \"a\": 1,\n        \"d\": 4,\n        \"e\": 5,\n        \"c\": 3,\n    }\n    s = SafeRepr(maxsize=None)\n    s.maxdict = 1\n    assert s.repr(d) == \"{'b': 2, ...}\"\n\n\ndef test_saferepr_dict_fillvalue_when_level_is_zero() -> None:\n    s = SafeRepr(maxsize=None)\n    assert s.repr_dict({\"a\": 1}, level=0) == \"{...}\"\n\n\ndef test_saferepr_dict_empty() -> None:\n    s = SafeRepr(maxsize=None)\n    assert s.repr_dict({}, level=1) == \"{}\"\n"
  },
  {
    "path": "testing/io/test_terminalwriter.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nimport io\nfrom io import StringIO\nimport os\nfrom pathlib import Path\nimport re\nimport shutil\nimport sys\nfrom unittest import mock\n\nfrom _pytest._io import terminalwriter\nfrom _pytest.monkeypatch import MonkeyPatch\nimport pytest\n\n\n# These tests were initially copied from py 1.8.1.\n\n\ndef test_terminal_width_COLUMNS(monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setenv(\"COLUMNS\", \"42\")\n    assert terminalwriter.get_terminal_width() == 42\n    monkeypatch.delenv(\"COLUMNS\", raising=False)\n\n\ndef test_terminalwriter_width_bogus(monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setattr(shutil, \"get_terminal_size\", mock.Mock(return_value=(10, 10)))\n    monkeypatch.delenv(\"COLUMNS\", raising=False)\n    tw = terminalwriter.TerminalWriter()\n    assert tw.fullwidth == 80\n\n\ndef test_terminalwriter_computes_width(monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setattr(terminalwriter, \"get_terminal_width\", lambda: 42)\n    tw = terminalwriter.TerminalWriter()\n    assert tw.fullwidth == 42\n\n\ndef test_terminalwriter_dumb_term_no_markup(monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setattr(os, \"environ\", {\"TERM\": \"dumb\", \"PATH\": \"\"})\n\n    class MyFile:\n        closed = False\n\n        def isatty(self):\n            return True\n\n    with monkeypatch.context() as m:\n        m.setattr(sys, \"stdout\", MyFile())\n        assert sys.stdout.isatty()\n        tw = terminalwriter.TerminalWriter()\n        assert not tw.hasmarkup\n\n\ndef test_terminalwriter_not_unicode() -> None:\n    \"\"\"If the file doesn't support Unicode, the string is unicode-escaped (#7475).\"\"\"\n    buffer = io.BytesIO()\n    file = io.TextIOWrapper(buffer, encoding=\"cp1252\")\n    tw = terminalwriter.TerminalWriter(file)\n    tw.write(\"hello 🌀 wôrld אבג\", flush=True)\n    assert buffer.getvalue() == rb\"hello \\U0001f300 w\\xf4rld \\u05d0\\u05d1\\u05d2\"\n\n\nwin32 = int(sys.platform == \"win32\")\n\n\nclass TestTerminalWriter:\n    @pytest.fixture(params=[\"path\", \"stringio\"])\n    def tw(self, request, tmp_path: Path) -> Generator[terminalwriter.TerminalWriter]:\n        f: io.TextIOWrapper | StringIO\n        if request.param == \"path\":\n            p = tmp_path.joinpath(\"tmpfile\")\n            f = open(str(p), \"w+\", encoding=\"utf8\")\n            tw = terminalwriter.TerminalWriter(f)\n\n            def getlines():\n                f.flush()\n                with open(str(p), encoding=\"utf8\") as fp:\n                    return fp.readlines()\n\n        elif request.param == \"stringio\":\n            f = io.StringIO()\n            tw = terminalwriter.TerminalWriter(f)\n\n            def getlines():\n                f.seek(0)\n                return f.readlines()\n\n        tw.getlines = getlines  # type: ignore\n        tw.getvalue = lambda: \"\".join(getlines())  # type: ignore\n\n        with f:\n            yield tw\n\n    def test_line(self, tw) -> None:\n        tw.line(\"hello\")\n        lines = tw.getlines()\n        assert len(lines) == 1\n        assert lines[0] == \"hello\\n\"\n\n    def test_line_unicode(self, tw) -> None:\n        msg = \"b\\u00f6y\"\n        tw.line(msg)\n        lines = tw.getlines()\n        assert lines[0] == msg + \"\\n\"\n\n    def test_sep_no_title(self, tw) -> None:\n        tw.sep(\"-\", fullwidth=60)\n        lines = tw.getlines()\n        assert len(lines) == 1\n        assert lines[0] == \"-\" * (60 - win32) + \"\\n\"\n\n    def test_sep_with_title(self, tw) -> None:\n        tw.sep(\"-\", \"hello\", fullwidth=60)\n        lines = tw.getlines()\n        assert len(lines) == 1\n        assert lines[0] == \"-\" * 26 + \" hello \" + \"-\" * (27 - win32) + \"\\n\"\n\n    def test_sep_longer_than_width(self, tw) -> None:\n        tw.sep(\"-\", \"a\" * 10, fullwidth=5)\n        (line,) = tw.getlines()\n        # even though the string is wider than the line, still have a separator\n        assert line == \"- aaaaaaaaaa -\\n\"\n\n    @pytest.mark.skipif(sys.platform == \"win32\", reason=\"win32 has no native ansi\")\n    @pytest.mark.parametrize(\"bold\", (True, False))\n    @pytest.mark.parametrize(\"color\", (\"red\", \"green\"))\n    def test_markup(self, tw, bold: bool, color: str) -> None:\n        text = tw.markup(\"hello\", **{color: True, \"bold\": bold})\n        assert \"hello\" in text\n\n    def test_markup_bad(self, tw) -> None:\n        with pytest.raises(ValueError):\n            tw.markup(\"x\", wronkw=3)\n        with pytest.raises(ValueError):\n            tw.markup(\"x\", wronkw=0)\n\n    def test_line_write_markup(self, tw) -> None:\n        tw.hasmarkup = True\n        tw.line(\"x\", bold=True)\n        tw.write(\"x\\n\", red=True)\n        lines = tw.getlines()\n        if sys.platform != \"win32\":\n            assert len(lines[0]) >= 2, lines\n            assert len(lines[1]) >= 2, lines\n\n    def test_attr_fullwidth(self, tw) -> None:\n        tw.sep(\"-\", \"hello\", fullwidth=70)\n        tw.fullwidth = 70\n        tw.sep(\"-\", \"hello\")\n        lines = tw.getlines()\n        assert len(lines[0]) == len(lines[1])\n\n\n@pytest.mark.skipif(sys.platform == \"win32\", reason=\"win32 has no native ansi\")\ndef test_attr_hasmarkup() -> None:\n    file = io.StringIO()\n    tw = terminalwriter.TerminalWriter(file)\n    assert not tw.hasmarkup\n    tw.hasmarkup = True\n    tw.line(\"hello\", bold=True)\n    s = file.getvalue()\n    assert len(s) > len(\"hello\\n\")\n    assert \"\\x1b[1m\" in s\n    assert \"\\x1b[0m\" in s\n\n\ndef assert_color(expected: bool, default: bool | None = None) -> None:\n    file = io.StringIO()\n    if default is None:\n        default = not expected\n    file.isatty = lambda: default  # type: ignore\n    tw = terminalwriter.TerminalWriter(file=file)\n    assert tw.hasmarkup is expected\n    tw.line(\"hello\", bold=True)\n    s = file.getvalue()\n    if expected:\n        assert len(s) > len(\"hello\\n\")\n        assert \"\\x1b[1m\" in s\n        assert \"\\x1b[0m\" in s\n    else:\n        assert s == \"hello\\n\"\n\n\ndef test_should_do_markup_PY_COLORS_eq_1(monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setitem(os.environ, \"PY_COLORS\", \"1\")\n    assert_color(True)\n\n\ndef test_should_not_do_markup_PY_COLORS_eq_0(monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setitem(os.environ, \"PY_COLORS\", \"0\")\n    assert_color(False)\n\n\ndef test_should_not_do_markup_NO_COLOR(monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setitem(os.environ, \"NO_COLOR\", \"1\")\n    assert_color(False)\n\n\ndef test_should_do_markup_FORCE_COLOR(monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setitem(os.environ, \"FORCE_COLOR\", \"1\")\n    assert_color(True)\n\n\n@pytest.mark.parametrize(\n    [\"NO_COLOR\", \"FORCE_COLOR\", \"expected\"],\n    [\n        (\"1\", \"1\", False),\n        (\"\", \"1\", True),\n        (\"1\", \"\", False),\n    ],\n)\ndef test_NO_COLOR_and_FORCE_COLOR(\n    monkeypatch: MonkeyPatch,\n    NO_COLOR: str,\n    FORCE_COLOR: str,\n    expected: bool,\n) -> None:\n    monkeypatch.setitem(os.environ, \"NO_COLOR\", NO_COLOR)\n    monkeypatch.setitem(os.environ, \"FORCE_COLOR\", FORCE_COLOR)\n    assert_color(expected)\n\n\ndef test_empty_NO_COLOR_and_FORCE_COLOR_ignored(monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setenv(\"TERM\", \"xterm-256color\")\n    monkeypatch.setitem(os.environ, \"NO_COLOR\", \"\")\n    monkeypatch.setitem(os.environ, \"FORCE_COLOR\", \"\")\n    assert_color(True, True)\n    assert_color(False, False)\n\n\nclass TestTerminalWriterLineWidth:\n    def test_init(self) -> None:\n        tw = terminalwriter.TerminalWriter()\n        assert tw.width_of_current_line == 0\n\n    def test_update(self) -> None:\n        tw = terminalwriter.TerminalWriter()\n        tw.write(\"hello world\")\n        assert tw.width_of_current_line == 11\n\n    def test_update_with_newline(self) -> None:\n        tw = terminalwriter.TerminalWriter()\n        tw.write(\"hello\\nworld\")\n        assert tw.width_of_current_line == 5\n\n    def test_update_with_wide_text(self) -> None:\n        tw = terminalwriter.TerminalWriter()\n        tw.write(\"乇乂ㄒ尺卂 ㄒ卄丨匚匚\")\n        assert tw.width_of_current_line == 21  # 5*2 + 1 + 5*2\n\n    def test_composed(self) -> None:\n        tw = terminalwriter.TerminalWriter()\n        text = \"café food\"\n        assert len(text) == 9\n        tw.write(text)\n        assert tw.width_of_current_line == 9\n\n    def test_combining(self) -> None:\n        tw = terminalwriter.TerminalWriter()\n        text = \"café food\"\n        assert len(text) == 10\n        tw.write(text)\n        assert tw.width_of_current_line == 9\n\n\n@pytest.mark.parametrize(\n    (\"has_markup\", \"code_highlight\", \"expected\"),\n    [\n        pytest.param(\n            True,\n            True,\n            \"{reset}{kw}assert{hl-reset} {number}0{hl-reset}{endline}\\n\",\n            id=\"with markup and code_highlight\",\n        ),\n        pytest.param(\n            True,\n            False,\n            \"assert 0\\n\",\n            id=\"with markup but no code_highlight\",\n        ),\n        pytest.param(\n            False,\n            True,\n            \"assert 0\\n\",\n            id=\"without markup but with code_highlight\",\n        ),\n        pytest.param(\n            False,\n            False,\n            \"assert 0\\n\",\n            id=\"neither markup nor code_highlight\",\n        ),\n    ],\n)\ndef test_code_highlight(has_markup, code_highlight, expected, color_mapping):\n    f = io.StringIO()\n    tw = terminalwriter.TerminalWriter(f)\n    tw.hasmarkup = has_markup\n    tw.code_highlight = code_highlight\n    tw._write_source([\"assert 0\"])\n\n    assert f.getvalue().splitlines(keepends=True) == color_mapping.format([expected])\n\n    with pytest.raises(\n        ValueError,\n        match=re.escape(\"indents size (2) should have same size as lines (1)\"),\n    ):\n        tw._write_source([\"assert 0\"], [\" \", \" \"])\n\n\ndef test_highlight_empty_source() -> None:\n    \"\"\"Don't crash trying to highlight empty source code.\n\n    Issue #11758.\n    \"\"\"\n    f = io.StringIO()\n    tw = terminalwriter.TerminalWriter(f)\n    tw.hasmarkup = True\n    tw.code_highlight = True\n    tw._write_source([])\n\n    assert f.getvalue() == \"\"\n"
  },
  {
    "path": "testing/io/test_wcwidth.py",
    "content": "from __future__ import annotations\n\nfrom _pytest._io.wcwidth import wcswidth\nfrom _pytest._io.wcwidth import wcwidth\nimport pytest\n\n\n@pytest.mark.parametrize(\n    (\"c\", \"expected\"),\n    [\n        (\"\\0\", 0),\n        (\"\\n\", -1),\n        (\"a\", 1),\n        (\"1\", 1),\n        (\"א\", 1),\n        (\"\\u200b\", 0),\n        (\"\\u1abe\", 0),\n        (\"\\u0591\", 0),\n        (\"🉐\", 2),\n        (\"＄\", 2),  # noqa: RUF001\n    ],\n)\ndef test_wcwidth(c: str, expected: int) -> None:\n    assert wcwidth(c) == expected\n\n\n@pytest.mark.parametrize(\n    (\"s\", \"expected\"),\n    [\n        (\"\", 0),\n        (\"hello, world!\", 13),\n        (\"hello, world!\\n\", -1),\n        (\"0123456789\", 10),\n        (\"שלום, עולם!\", 11),\n        (\"שְבֻעָיים\", 6),\n        (\"🉐🉐🉐\", 6),\n    ],\n)\ndef test_wcswidth(s: str, expected: int) -> None:\n    assert wcswidth(s) == expected\n"
  },
  {
    "path": "testing/logging/test_fixture.py",
    "content": "# mypy: disable-error-code=\"attr-defined\"\n# mypy: disallow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Iterator\nimport logging\n\nfrom _pytest.logging import caplog_records_key\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nlogger = logging.getLogger(__name__)\nsublogger = logging.getLogger(__name__ + \".baz\")\n\n\n@pytest.fixture(autouse=True)\ndef cleanup_disabled_logging() -> Iterator[None]:\n    \"\"\"Simple fixture that ensures that a test doesn't disable logging.\n\n    This is necessary because ``logging.disable()`` is global, so a test disabling logging\n    and not cleaning up after will break every test that runs after it.\n\n    This behavior was moved to a fixture so that logging will be un-disabled even if the test fails an assertion.\n    \"\"\"\n    yield\n    logging.disable(logging.NOTSET)\n\n\ndef test_fixture_help(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--fixtures\")\n    result.stdout.fnmatch_lines([\"*caplog*\"])\n\n\ndef test_change_level(caplog: pytest.LogCaptureFixture) -> None:\n    caplog.set_level(logging.INFO)\n    logger.debug(\"handler DEBUG level\")\n    logger.info(\"handler INFO level\")\n\n    caplog.set_level(logging.CRITICAL, logger=sublogger.name)\n    sublogger.warning(\"logger WARNING level\")\n    sublogger.critical(\"logger CRITICAL level\")\n\n    assert \"DEBUG\" not in caplog.text\n    assert \"INFO\" in caplog.text\n    assert \"WARNING\" not in caplog.text\n    assert \"CRITICAL\" in caplog.text\n\n\ndef test_change_level_logging_disabled(caplog: pytest.LogCaptureFixture) -> None:\n    logging.disable(logging.CRITICAL)\n    assert logging.root.manager.disable == logging.CRITICAL\n    caplog.set_level(logging.WARNING)\n    logger.info(\"handler INFO level\")\n    logger.warning(\"handler WARNING level\")\n\n    caplog.set_level(logging.CRITICAL, logger=sublogger.name)\n    sublogger.warning(\"logger SUB_WARNING level\")\n    sublogger.critical(\"logger SUB_CRITICAL level\")\n\n    assert \"INFO\" not in caplog.text\n    assert \"WARNING\" in caplog.text\n    assert \"SUB_WARNING\" not in caplog.text\n    assert \"SUB_CRITICAL\" in caplog.text\n\n\ndef test_change_level_undo(pytester: Pytester) -> None:\n    \"\"\"Ensure that 'set_level' is undone after the end of the test.\n\n    Tests the logging output themselves (affected both by logger and handler levels).\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        def test1(caplog):\n            caplog.set_level(logging.INFO)\n            # using + operator here so fnmatch_lines doesn't match the code in the traceback\n            logging.info('log from ' + 'test1')\n            assert 0\n\n        def test2(caplog):\n            # using + operator here so fnmatch_lines doesn't match the code in the traceback\n            logging.info('log from ' + 'test2')\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*log from test1*\", \"*2 failed in *\"])\n    result.stdout.no_fnmatch_line(\"*log from test2*\")\n\n\ndef test_change_disabled_level_undo(pytester: Pytester) -> None:\n    \"\"\"Ensure that '_force_enable_logging' in 'set_level' is undone after the end of the test.\n\n    Tests the logging output themselves (affected by disabled logging level).\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        def test1(caplog):\n            logging.disable(logging.CRITICAL)\n            caplog.set_level(logging.INFO)\n            # using + operator here so fnmatch_lines doesn't match the code in the traceback\n            logging.info('log from ' + 'test1')\n            assert 0\n\n        def test2(caplog):\n            # using + operator here so fnmatch_lines doesn't match the code in the traceback\n            # use logging.warning because we need a level that will show up if logging.disabled\n            # isn't reset to ``CRITICAL`` after test1.\n            logging.warning('log from ' + 'test2')\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*log from test1*\", \"*2 failed in *\"])\n    result.stdout.no_fnmatch_line(\"*log from test2*\")\n\n\ndef test_change_level_undoes_handler_level(pytester: Pytester) -> None:\n    \"\"\"Ensure that 'set_level' is undone after the end of the test (handler).\n\n    Issue #7569. Tests the handler level specifically.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        def test1(caplog):\n            assert caplog.handler.level == 0\n            caplog.set_level(9999)\n            caplog.set_level(41)\n            assert caplog.handler.level == 41\n\n        def test2(caplog):\n            assert caplog.handler.level == 0\n\n        def test3(caplog):\n            assert caplog.handler.level == 0\n            caplog.set_level(43)\n            assert caplog.handler.level == 43\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=3)\n\n\ndef test_with_statement_at_level(caplog: pytest.LogCaptureFixture) -> None:\n    with caplog.at_level(logging.INFO):\n        logger.debug(\"handler DEBUG level\")\n        logger.info(\"handler INFO level\")\n\n        with caplog.at_level(logging.CRITICAL, logger=sublogger.name):\n            sublogger.warning(\"logger WARNING level\")\n            sublogger.critical(\"logger CRITICAL level\")\n\n    assert \"DEBUG\" not in caplog.text\n    assert \"INFO\" in caplog.text\n    assert \"WARNING\" not in caplog.text\n    assert \"CRITICAL\" in caplog.text\n\n\ndef test_with_statement_at_level_logging_disabled(\n    caplog: pytest.LogCaptureFixture,\n) -> None:\n    logging.disable(logging.CRITICAL)\n    assert logging.root.manager.disable == logging.CRITICAL\n    with caplog.at_level(logging.WARNING):\n        logger.debug(\"handler DEBUG level\")\n        logger.info(\"handler INFO level\")\n        logger.warning(\"handler WARNING level\")\n        logger.error(\"handler ERROR level\")\n        logger.critical(\"handler CRITICAL level\")\n\n        assert logging.root.manager.disable == logging.INFO\n\n        with caplog.at_level(logging.CRITICAL, logger=sublogger.name):\n            sublogger.warning(\"logger SUB_WARNING level\")\n            sublogger.critical(\"logger SUB_CRITICAL level\")\n\n    assert \"DEBUG\" not in caplog.text\n    assert \"INFO\" not in caplog.text\n    assert \"WARNING\" in caplog.text\n    assert \"ERROR\" in caplog.text\n    assert \" CRITICAL\" in caplog.text\n    assert \"SUB_WARNING\" not in caplog.text\n    assert \"SUB_CRITICAL\" in caplog.text\n    assert logging.root.manager.disable == logging.CRITICAL\n\n\ndef test_with_statement_filtering(caplog: pytest.LogCaptureFixture) -> None:\n    class TestFilter(logging.Filter):\n        def filter(self, record: logging.LogRecord) -> bool:\n            record.msg = \"filtered handler call\"\n            return True\n\n    with caplog.at_level(logging.INFO):\n        with caplog.filtering(TestFilter()):\n            logger.info(\"handler call\")\n        logger.info(\"handler call\")\n\n    filtered_tuple, unfiltered_tuple = caplog.record_tuples\n    assert filtered_tuple == (\"test_fixture\", 20, \"filtered handler call\")\n    assert unfiltered_tuple == (\"test_fixture\", 20, \"handler call\")\n\n\n@pytest.mark.parametrize(\n    \"level_str,expected_disable_level\",\n    [\n        (\"CRITICAL\", logging.ERROR),\n        (\"ERROR\", logging.WARNING),\n        (\"WARNING\", logging.INFO),\n        (\"INFO\", logging.DEBUG),\n        (\"DEBUG\", logging.NOTSET),\n        (\"NOTSET\", logging.NOTSET),\n        (\"NOTVALIDLEVEL\", logging.NOTSET),\n    ],\n)\ndef test_force_enable_logging_level_string(\n    caplog: pytest.LogCaptureFixture, level_str: str, expected_disable_level: int\n) -> None:\n    \"\"\"Test _force_enable_logging using a level string.\n\n    ``expected_disable_level`` is one level below ``level_str`` because the disabled log level\n    always needs to be *at least* one level lower than the level that caplog is trying to capture.\n    \"\"\"\n    test_logger = logging.getLogger(\"test_str_level_force_enable\")\n    # Emulate a testing environment where all logging is disabled.\n    logging.disable(logging.CRITICAL)\n    # Make sure all logging is disabled.\n    assert not test_logger.isEnabledFor(logging.CRITICAL)\n    # Un-disable logging for `level_str`.\n    caplog._force_enable_logging(level_str, test_logger)\n    # Make sure that the disabled level is now one below the requested logging level.\n    # We don't use `isEnabledFor` here because that also checks the level set by\n    # `logging.setLevel()` which is irrelevant to `logging.disable()`.\n    assert test_logger.manager.disable == expected_disable_level\n\n\ndef test_log_access(caplog: pytest.LogCaptureFixture) -> None:\n    caplog.set_level(logging.INFO)\n    logger.info(\"boo %s\", \"arg\")\n    assert caplog.records[0].levelname == \"INFO\"\n    assert caplog.records[0].msg == \"boo %s\"\n    assert \"boo arg\" in caplog.text\n\n\ndef test_messages(caplog: pytest.LogCaptureFixture) -> None:\n    caplog.set_level(logging.INFO)\n    logger.info(\"boo %s\", \"arg\")\n    logger.info(\"bar %s\\nbaz %s\", \"arg1\", \"arg2\")\n    assert \"boo arg\" == caplog.messages[0]\n    assert \"bar arg1\\nbaz arg2\" == caplog.messages[1]\n    assert caplog.text.count(\"\\n\") > len(caplog.messages)\n    assert len(caplog.text.splitlines()) > len(caplog.messages)\n\n    try:\n        raise Exception(\"test\")\n    except Exception:\n        logger.exception(\"oops\")\n\n    assert \"oops\" in caplog.text\n    assert \"oops\" in caplog.messages[-1]\n    # Tracebacks are stored in the record and not added until the formatter or handler.\n    assert \"Exception\" in caplog.text\n    assert \"Exception\" not in caplog.messages[-1]\n\n\ndef test_record_tuples(caplog: pytest.LogCaptureFixture) -> None:\n    caplog.set_level(logging.INFO)\n    logger.info(\"boo %s\", \"arg\")\n\n    assert caplog.record_tuples == [(__name__, logging.INFO, \"boo arg\")]\n\n\ndef test_unicode(caplog: pytest.LogCaptureFixture) -> None:\n    caplog.set_level(logging.INFO)\n    logger.info(\"bū\")\n    assert caplog.records[0].levelname == \"INFO\"\n    assert caplog.records[0].msg == \"bū\"\n    assert \"bū\" in caplog.text\n\n\ndef test_clear(caplog: pytest.LogCaptureFixture) -> None:\n    caplog.set_level(logging.INFO)\n    logger.info(\"bū\")\n    assert len(caplog.records)\n    assert caplog.text\n    caplog.clear()\n    assert not len(caplog.records)\n    assert not caplog.text\n\n\n@pytest.fixture\ndef logging_during_setup_and_teardown(\n    caplog: pytest.LogCaptureFixture,\n) -> Iterator[None]:\n    caplog.set_level(\"INFO\")\n    logger.info(\"a_setup_log\")\n    yield\n    logger.info(\"a_teardown_log\")\n    assert [x.message for x in caplog.get_records(\"teardown\")] == [\"a_teardown_log\"]\n\n\ndef private_assert_caplog_records_is_setup_call(\n    caplog: pytest.LogCaptureFixture,\n) -> None:\n    # This reaches into private API, don't use this type of thing in real tests!\n    caplog_records = caplog._item.stash[caplog_records_key]\n    assert set(caplog_records) == {\"setup\", \"call\"}\n\n\ndef test_captures_for_all_stages(\n    caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None\n) -> None:\n    assert not caplog.records\n    assert not caplog.get_records(\"call\")\n    logger.info(\"a_call_log\")\n    assert [x.message for x in caplog.get_records(\"call\")] == [\"a_call_log\"]\n\n    assert [x.message for x in caplog.get_records(\"setup\")] == [\"a_setup_log\"]\n\n    private_assert_caplog_records_is_setup_call(caplog)\n\n\ndef test_clear_for_call_stage(\n    caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None\n) -> None:\n    logger.info(\"a_call_log\")\n    assert [x.message for x in caplog.get_records(\"call\")] == [\"a_call_log\"]\n    assert [x.message for x in caplog.get_records(\"setup\")] == [\"a_setup_log\"]\n    private_assert_caplog_records_is_setup_call(caplog)\n\n    caplog.clear()\n\n    assert caplog.get_records(\"call\") == []\n    assert [x.message for x in caplog.get_records(\"setup\")] == [\"a_setup_log\"]\n    private_assert_caplog_records_is_setup_call(caplog)\n\n    logging.info(\"a_call_log_after_clear\")\n    assert [x.message for x in caplog.get_records(\"call\")] == [\"a_call_log_after_clear\"]\n    assert [x.message for x in caplog.get_records(\"setup\")] == [\"a_setup_log\"]\n    private_assert_caplog_records_is_setup_call(caplog)\n\n\ndef test_ini_controls_global_log_level(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_level_override(request, caplog):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_level == logging.ERROR\n            logger = logging.getLogger('catchlog')\n            logger.warning(\"WARNING message won't be shown\")\n            logger.error(\"ERROR message will be shown\")\n            assert 'WARNING' not in caplog.text\n            assert 'ERROR' in caplog.text\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_level=ERROR\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n\n\ndef test_can_override_global_log_level(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_level_override(request, caplog):\n            logger = logging.getLogger('catchlog')\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_level == logging.WARNING\n\n            logger.info(\"INFO message won't be shown\")\n\n            caplog.set_level(logging.INFO, logger.name)\n\n            with caplog.at_level(logging.DEBUG, logger.name):\n                logger.debug(\"DEBUG message will be shown\")\n\n            logger.debug(\"DEBUG message won't be shown\")\n\n            with caplog.at_level(logging.CRITICAL, logger.name):\n                logger.warning(\"WARNING message won't be shown\")\n\n            logger.debug(\"DEBUG message won't be shown\")\n            logger.info(\"INFO message will be shown\")\n\n            assert \"message won't be shown\" not in caplog.text\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_level=WARNING\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n    assert result.ret == 0\n\n\ndef test_captures_despite_exception(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_level_override(request, caplog):\n            logger = logging.getLogger('catchlog')\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_level == logging.WARNING\n\n            logger.error(\"ERROR message \" + \"will be shown\")\n\n            with caplog.at_level(logging.DEBUG, logger.name):\n                logger.debug(\"DEBUG message \" + \"won't be shown\")\n                raise Exception()\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_level=WARNING\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*ERROR message will be shown*\"])\n    result.stdout.no_fnmatch_line(\"*DEBUG message won't be shown*\")\n    assert result.ret == 1\n\n\ndef test_log_report_captures_according_to_config_option_upon_failure(\n    pytester: Pytester,\n) -> None:\n    \"\"\"Test that upon failure:\n    (1) `caplog` succeeded to capture the DEBUG message and assert on it => No `Exception` is raised.\n    (2) The `DEBUG` message does NOT appear in the `Captured log call` report.\n    (3) The stdout, `INFO`, and `WARNING` messages DO appear in the test reports due to `--log-level=INFO`.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n\n        def function_that_logs():\n            logging.debug('DEBUG log ' + 'message')\n            logging.info('INFO log ' + 'message')\n            logging.warning('WARNING log ' + 'message')\n            print('Print ' + 'message')\n\n        def test_that_fails(request, caplog):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_level == logging.INFO\n\n            with caplog.at_level(logging.DEBUG):\n                function_that_logs()\n\n            if 'DEBUG log ' + 'message' not in caplog.text:\n                raise Exception('caplog failed to ' + 'capture DEBUG')\n\n            assert False\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"--log-level=INFO\")\n    result.stdout.no_fnmatch_line(\"*Exception: caplog failed to capture DEBUG*\")\n    result.stdout.no_fnmatch_line(\"*DEBUG log message*\")\n    result.stdout.fnmatch_lines(\n        [\"*Print message*\", \"*INFO log message*\", \"*WARNING log message*\"]\n    )\n    assert result.ret == 1\n"
  },
  {
    "path": "testing/logging/test_formatter.py",
    "content": "from __future__ import annotations\n\nimport logging\nfrom typing import Any\n\nfrom _pytest._io import TerminalWriter\nfrom _pytest.logging import ColoredLevelFormatter\n\n\ndef test_coloredlogformatter() -> None:\n    logfmt = \"%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s\"\n\n    record = logging.LogRecord(\n        name=\"dummy\",\n        level=logging.INFO,\n        pathname=\"dummypath\",\n        lineno=10,\n        msg=\"Test Message\",\n        args=(),\n        exc_info=None,\n    )\n\n    tw = TerminalWriter()\n    tw.hasmarkup = True\n    formatter = ColoredLevelFormatter(tw, logfmt)\n    output = formatter.format(record)\n    assert output == (\n        \"dummypath                   10 \\x1b[32mINFO    \\x1b[0m Test Message\"\n    )\n\n    tw.hasmarkup = False\n    formatter = ColoredLevelFormatter(tw, logfmt)\n    output = formatter.format(record)\n    assert output == (\"dummypath                   10 INFO     Test Message\")\n\n\ndef test_coloredlogformatter_with_width_precision() -> None:\n    logfmt = \"%(filename)-25s %(lineno)4d %(levelname)-8.8s %(message)s\"\n\n    record = logging.LogRecord(\n        name=\"dummy\",\n        level=logging.INFO,\n        pathname=\"dummypath\",\n        lineno=10,\n        msg=\"Test Message\",\n        args=(),\n        exc_info=None,\n    )\n\n    tw = TerminalWriter()\n    tw.hasmarkup = True\n    formatter = ColoredLevelFormatter(tw, logfmt)\n    output = formatter.format(record)\n    assert output == (\n        \"dummypath                   10 \\x1b[32mINFO    \\x1b[0m Test Message\"\n    )\n\n    tw.hasmarkup = False\n    formatter = ColoredLevelFormatter(tw, logfmt)\n    output = formatter.format(record)\n    assert output == (\"dummypath                   10 INFO     Test Message\")\n\n\ndef test_multiline_message() -> None:\n    from _pytest.logging import PercentStyleMultiline\n\n    logfmt = \"%(filename)-25s %(lineno)4d %(levelname)-8s %(message)s\"\n\n    record: Any = logging.LogRecord(\n        name=\"dummy\",\n        level=logging.INFO,\n        pathname=\"dummypath\",\n        lineno=10,\n        msg=\"Test Message line1\\nline2\",\n        args=(),\n        exc_info=None,\n    )\n    # this is called by logging.Formatter.format\n    record.message = record.getMessage()\n\n    ai_on_style = PercentStyleMultiline(logfmt, True)\n    output = ai_on_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\n\"\n        \"                                        line2\"\n    )\n\n    ai_off_style = PercentStyleMultiline(logfmt, False)\n    output = ai_off_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\nline2\"\n    )\n\n    ai_none_style = PercentStyleMultiline(logfmt, None)\n    output = ai_none_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\nline2\"\n    )\n\n    record.auto_indent = False\n    output = ai_on_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\nline2\"\n    )\n\n    record.auto_indent = True\n    output = ai_off_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\n\"\n        \"                                        line2\"\n    )\n\n    record.auto_indent = \"False\"\n    output = ai_on_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\nline2\"\n    )\n\n    record.auto_indent = \"True\"\n    output = ai_off_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\n\"\n        \"                                        line2\"\n    )\n\n    # bad string values default to False\n    record.auto_indent = \"junk\"\n    output = ai_off_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\nline2\"\n    )\n\n    # anything other than string or int will default to False\n    record.auto_indent = dict()\n    output = ai_off_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\nline2\"\n    )\n\n    record.auto_indent = \"5\"\n    output = ai_off_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\n     line2\"\n    )\n\n    record.auto_indent = 5\n    output = ai_off_style.format(record)\n    assert output == (\n        \"dummypath                   10 INFO     Test Message line1\\n     line2\"\n    )\n\n\ndef test_colored_short_level() -> None:\n    logfmt = \"%(levelname).1s %(message)s\"\n\n    record = logging.LogRecord(\n        name=\"dummy\",\n        level=logging.INFO,\n        pathname=\"dummypath\",\n        lineno=10,\n        msg=\"Test Message\",\n        args=(),\n        exc_info=None,\n    )\n\n    class ColorConfig:\n        class option:\n            pass\n\n    tw = TerminalWriter()\n    tw.hasmarkup = True\n    formatter = ColoredLevelFormatter(tw, logfmt)\n    output = formatter.format(record)\n    # the I (of INFO) is colored\n    assert output == (\"\\x1b[32mI\\x1b[0m Test Message\")\n"
  },
  {
    "path": "testing/logging/test_reporting.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport io\nimport os\nimport re\nfrom typing import cast\n\nfrom _pytest.capture import CaptureManager\nfrom _pytest.config import ExitCode\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.pytester import Pytester\nfrom _pytest.terminal import TerminalReporter\nimport pytest\n\n\ndef test_nothing_logged(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import sys\n\n        def test_foo():\n            sys.stdout.write('text going to stdout')\n            sys.stderr.write('text going to stderr')\n            assert False\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 1\n    result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", \"text going to stdout\"])\n    result.stdout.fnmatch_lines([\"*- Captured stderr call -*\", \"text going to stderr\"])\n    with pytest.raises(pytest.fail.Exception):\n        result.stdout.fnmatch_lines([\"*- Captured *log call -*\"])\n\n\ndef test_messages_logged(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import sys\n        import logging\n\n        logger = logging.getLogger(__name__)\n\n        def test_foo():\n            sys.stdout.write('text going to stdout')\n            sys.stderr.write('text going to stderr')\n            logger.info('text going to logger')\n            assert False\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--log-level=INFO\")\n    assert result.ret == 1\n    result.stdout.fnmatch_lines([\"*- Captured *log call -*\", \"*text going to logger*\"])\n    result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", \"text going to stdout\"])\n    result.stdout.fnmatch_lines([\"*- Captured stderr call -*\", \"text going to stderr\"])\n\n\ndef test_root_logger_affected(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n        logger = logging.getLogger()\n\n        def test_foo():\n            logger.info('info text ' + 'going to logger')\n            logger.warning('warning text ' + 'going to logger')\n            logger.error('error text ' + 'going to logger')\n\n            assert 0\n    \"\"\"\n    )\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n    result = pytester.runpytest(\"--log-level=ERROR\", \"--log-file=pytest.log\")\n    assert result.ret == 1\n\n    # The capture log calls in the stdout section only contain the\n    # logger.error msg, because of --log-level=ERROR.\n    result.stdout.fnmatch_lines([\"*error text going to logger*\"])\n    stdout = result.stdout.str()\n    assert \"warning text going to logger\" not in stdout\n    assert \"info text going to logger\" not in stdout\n\n    # The log file should only contain the error log messages and\n    # not the warning or info ones, because the root logger is set to\n    # ERROR using --log-level=ERROR.\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert \"info text going to logger\" not in contents\n        assert \"warning text going to logger\" not in contents\n        assert \"error text going to logger\" in contents\n\n\ndef test_log_cli_level_log_level_interaction(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n        logger = logging.getLogger()\n\n        def test_foo():\n            logger.debug('debug text ' + 'going to logger')\n            logger.info('info text ' + 'going to logger')\n            logger.warning('warning text ' + 'going to logger')\n            logger.error('error text ' + 'going to logger')\n            assert 0\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"--log-cli-level=INFO\", \"--log-level=ERROR\")\n    assert result.ret == 1\n\n    result.stdout.fnmatch_lines(\n        [\n            \"*-- live log call --*\",\n            \"*INFO*info text going to logger\",\n            \"*WARNING*warning text going to logger\",\n            \"*ERROR*error text going to logger\",\n            \"=* 1 failed in *=\",\n        ]\n    )\n    result.stdout.no_re_match_line(\"DEBUG\")\n\n\ndef test_setup_logging(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        logger = logging.getLogger(__name__)\n\n        def setup_function(function):\n            logger.info('text going to logger from setup')\n\n        def test_foo():\n            logger.info('text going to logger from call')\n            assert False\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--log-level=INFO\")\n    assert result.ret == 1\n    result.stdout.fnmatch_lines(\n        [\n            \"*- Captured *log setup -*\",\n            \"*text going to logger from setup*\",\n            \"*- Captured *log call -*\",\n            \"*text going to logger from call*\",\n        ]\n    )\n\n\ndef test_teardown_logging(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        logger = logging.getLogger(__name__)\n\n        def test_foo():\n            logger.info('text going to logger from call')\n\n        def teardown_function(function):\n            logger.info('text going to logger from teardown')\n            assert False\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--log-level=INFO\")\n    assert result.ret == 1\n    result.stdout.fnmatch_lines(\n        [\n            \"*- Captured *log call -*\",\n            \"*text going to logger from call*\",\n            \"*- Captured *log teardown -*\",\n            \"*text going to logger from teardown*\",\n        ]\n    )\n\n\n@pytest.mark.parametrize(\"enabled\", [True, False])\ndef test_log_cli_enabled_disabled(pytester: Pytester, enabled: bool) -> None:\n    msg = \"critical message logged by test\"\n    pytester.makepyfile(\n        f\"\"\"\n        import logging\n        def test_log_cli():\n            logging.critical(\"{msg}\")\n    \"\"\"\n    )\n    if enabled:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            log_cli=true\n        \"\"\"\n        )\n    result = pytester.runpytest()\n    if enabled:\n        result.stdout.fnmatch_lines(\n            [\n                \"test_log_cli_enabled_disabled.py::test_log_cli \",\n                \"*-- live log call --*\",\n                \"CRITICAL *test_log_cli_enabled_disabled.py* critical message logged by test\",\n                \"PASSED*\",\n            ]\n        )\n    else:\n        assert msg not in result.stdout.str()\n\n\ndef test_log_cli_default_level(pytester: Pytester) -> None:\n    # Default log file level\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_cli(request):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_cli_handler.level == logging.NOTSET\n            logging.getLogger('catchlog').info(\"INFO message won't be shown\")\n            logging.getLogger('catchlog').warning(\"WARNING message will be shown\")\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_cli=true\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n\n    # fnmatch_lines does an assertion internally\n    result.stdout.fnmatch_lines(\n        [\n            \"test_log_cli_default_level.py::test_log_cli \",\n            \"WARNING*test_log_cli_default_level.py* message will be shown*\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*INFO message won't be shown*\")\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n\n\ndef test_log_cli_default_level_multiple_tests(\n    pytester: Pytester, request: FixtureRequest\n) -> None:\n    \"\"\"Ensure we reset the first newline added by the live logger between tests\"\"\"\n    filename = request.node.name + \".py\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        def test_log_1():\n            logging.warning(\"log message from test_log_1\")\n\n        def test_log_2():\n            logging.warning(\"log message from test_log_2\")\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_cli=true\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            f\"{filename}::test_log_1 \",\n            \"*WARNING*log message from test_log_1*\",\n            \"PASSED *50%*\",\n            f\"{filename}::test_log_2 \",\n            \"*WARNING*log message from test_log_2*\",\n            \"PASSED *100%*\",\n            \"=* 2 passed in *=\",\n        ]\n    )\n\n\ndef test_log_cli_default_level_sections(\n    pytester: Pytester, request: FixtureRequest\n) -> None:\n    \"\"\"Check that with live logging enable we are printing the correct headers during\n    start/setup/call/teardown/finish.\"\"\"\n    filename = request.node.name + \".py\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n        import logging\n\n        def pytest_runtest_logstart():\n            logging.warning('>>>>> START >>>>>')\n\n        def pytest_runtest_logfinish():\n            logging.warning('<<<<< END <<<<<<<')\n    \"\"\"\n    )\n\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n\n        @pytest.fixture\n        def fix(request):\n            logging.warning(\"log message from setup of {}\".format(request.node.name))\n            yield\n            logging.warning(\"log message from teardown of {}\".format(request.node.name))\n\n        def test_log_1(fix):\n            logging.warning(\"log message from test_log_1\")\n\n        def test_log_2(fix):\n            logging.warning(\"log message from test_log_2\")\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_cli=true\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            f\"{filename}::test_log_1 \",\n            \"*-- live log start --*\",\n            \"*WARNING* >>>>> START >>>>>*\",\n            \"*-- live log setup --*\",\n            \"*WARNING*log message from setup of test_log_1*\",\n            \"*-- live log call --*\",\n            \"*WARNING*log message from test_log_1*\",\n            \"PASSED *50%*\",\n            \"*-- live log teardown --*\",\n            \"*WARNING*log message from teardown of test_log_1*\",\n            \"*-- live log finish --*\",\n            \"*WARNING* <<<<< END <<<<<<<*\",\n            f\"{filename}::test_log_2 \",\n            \"*-- live log start --*\",\n            \"*WARNING* >>>>> START >>>>>*\",\n            \"*-- live log setup --*\",\n            \"*WARNING*log message from setup of test_log_2*\",\n            \"*-- live log call --*\",\n            \"*WARNING*log message from test_log_2*\",\n            \"PASSED *100%*\",\n            \"*-- live log teardown --*\",\n            \"*WARNING*log message from teardown of test_log_2*\",\n            \"*-- live log finish --*\",\n            \"*WARNING* <<<<< END <<<<<<<*\",\n            \"=* 2 passed in *=\",\n        ]\n    )\n\n\ndef test_live_logs_unknown_sections(\n    pytester: Pytester, request: FixtureRequest\n) -> None:\n    \"\"\"Check that with live logging enable we are printing the correct headers during\n    start/setup/call/teardown/finish.\"\"\"\n    filename = request.node.name + \".py\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n        import logging\n\n        def pytest_runtest_protocol(item, nextitem):\n            logging.warning('Unknown Section!')\n\n        def pytest_runtest_logstart():\n            logging.warning('>>>>> START >>>>>')\n\n        def pytest_runtest_logfinish():\n            logging.warning('<<<<< END <<<<<<<')\n    \"\"\"\n    )\n\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n\n        @pytest.fixture\n        def fix(request):\n            logging.warning(\"log message from setup of {}\".format(request.node.name))\n            yield\n            logging.warning(\"log message from teardown of {}\".format(request.node.name))\n\n        def test_log_1(fix):\n            logging.warning(\"log message from test_log_1\")\n\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_cli=true\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"*WARNING*Unknown Section*\",\n            f\"{filename}::test_log_1 \",\n            \"*WARNING* >>>>> START >>>>>*\",\n            \"*-- live log setup --*\",\n            \"*WARNING*log message from setup of test_log_1*\",\n            \"*-- live log call --*\",\n            \"*WARNING*log message from test_log_1*\",\n            \"PASSED *100%*\",\n            \"*-- live log teardown --*\",\n            \"*WARNING*log message from teardown of test_log_1*\",\n            \"*WARNING* <<<<< END <<<<<<<*\",\n            \"=* 1 passed in *=\",\n        ]\n    )\n\n\ndef test_sections_single_new_line_after_test_outcome(\n    pytester: Pytester, request: FixtureRequest\n) -> None:\n    \"\"\"Check that only a single new line is written between log messages during\n    teardown/finish.\"\"\"\n    filename = request.node.name + \".py\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n        import logging\n\n        def pytest_runtest_logstart():\n            logging.warning('>>>>> START >>>>>')\n\n        def pytest_runtest_logfinish():\n            logging.warning('<<<<< END <<<<<<<')\n            logging.warning('<<<<< END <<<<<<<')\n    \"\"\"\n    )\n\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n\n        @pytest.fixture\n        def fix(request):\n            logging.warning(\"log message from setup of {}\".format(request.node.name))\n            yield\n            logging.warning(\"log message from teardown of {}\".format(request.node.name))\n            logging.warning(\"log message from teardown of {}\".format(request.node.name))\n\n        def test_log_1(fix):\n            logging.warning(\"log message from test_log_1\")\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_cli=true\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            f\"{filename}::test_log_1 \",\n            \"*-- live log start --*\",\n            \"*WARNING* >>>>> START >>>>>*\",\n            \"*-- live log setup --*\",\n            \"*WARNING*log message from setup of test_log_1*\",\n            \"*-- live log call --*\",\n            \"*WARNING*log message from test_log_1*\",\n            \"PASSED *100%*\",\n            \"*-- live log teardown --*\",\n            \"*WARNING*log message from teardown of test_log_1*\",\n            \"*-- live log finish --*\",\n            \"*WARNING* <<<<< END <<<<<<<*\",\n            \"*WARNING* <<<<< END <<<<<<<*\",\n            \"=* 1 passed in *=\",\n        ]\n    )\n    assert (\n        re.search(\n            r\"(.+)live log teardown(.+)\\nWARNING(.+)\\nWARNING(.+)\",\n            result.stdout.str(),\n            re.MULTILINE,\n        )\n        is not None\n    )\n    assert (\n        re.search(\n            r\"(.+)live log finish(.+)\\nWARNING(.+)\\nWARNING(.+)\",\n            result.stdout.str(),\n            re.MULTILINE,\n        )\n        is not None\n    )\n\n\ndef test_log_cli_level(pytester: Pytester) -> None:\n    # Default log file level\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_cli(request):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_cli_handler.level == logging.INFO\n            logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n            logging.getLogger('catchlog').info(\"This log message will be shown\")\n            print('PASSED')\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_cli=true\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"-s\", \"--log-cli-level=INFO\")\n\n    # fnmatch_lines does an assertion internally\n    result.stdout.fnmatch_lines(\n        [\n            \"*test_log_cli_level.py*This log message will be shown\",\n            \"PASSED\",  # 'PASSED' on its own line because the log message prints a new line\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*This log message won't be shown*\")\n\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n\n    result = pytester.runpytest(\"-s\", \"--log-level=INFO\")\n\n    # fnmatch_lines does an assertion internally\n    result.stdout.fnmatch_lines(\n        [\n            \"*test_log_cli_level.py* This log message will be shown\",\n            \"PASSED\",  # 'PASSED' on its own line because the log message prints a new line\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*This log message won't be shown*\")\n\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n\n\ndef test_log_cli_ini_level(pytester: Pytester) -> None:\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_cli=true\n        log_cli_level = INFO\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_cli(request):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_cli_handler.level == logging.INFO\n            logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n            logging.getLogger('catchlog').info(\"This log message will be shown\")\n            print('PASSED')\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"-s\")\n\n    # fnmatch_lines does an assertion internally\n    result.stdout.fnmatch_lines(\n        [\n            \"*test_log_cli_ini_level.py* This log message will be shown\",\n            \"PASSED\",  # 'PASSED' on its own line because the log message prints a new line\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*This log message won't be shown*\")\n\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n\n\n@pytest.mark.parametrize(\n    \"cli_args\",\n    [\"\", \"--log-level=WARNING\", \"--log-file-level=WARNING\", \"--log-cli-level=WARNING\"],\n)\ndef test_log_cli_auto_enable(pytester: Pytester, cli_args: str) -> None:\n    \"\"\"Check that live logs are enabled if --log-level or --log-cli-level is passed on the CLI.\n\n    It should not be auto enabled if the same configs are set on the configuration file.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        def test_log_1():\n            logging.info(\"log message from test_log_1 not to be shown\")\n            logging.warning(\"log message from test_log_1\")\n\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_level=INFO\n        log_cli_level=INFO\n    \"\"\"\n    )\n\n    result = pytester.runpytest(cli_args)\n    stdout = result.stdout.str()\n    if cli_args == \"--log-cli-level=WARNING\":\n        result.stdout.fnmatch_lines(\n            [\n                \"*::test_log_1 \",\n                \"*-- live log call --*\",\n                \"*WARNING*log message from test_log_1*\",\n                \"PASSED *100%*\",\n                \"=* 1 passed in *=\",\n            ]\n        )\n        assert \"INFO\" not in stdout\n    else:\n        result.stdout.fnmatch_lines(\n            [\"*test_log_cli_auto_enable*100%*\", \"=* 1 passed in *=\"]\n        )\n        assert \"INFO\" not in stdout\n        assert \"WARNING\" not in stdout\n\n\ndef test_log_file_cli(pytester: Pytester) -> None:\n    # Default log file level\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_file(request):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_file_handler.level == logging.WARNING\n            logging.getLogger('catchlog').info(\"This log message won't be shown\")\n            logging.getLogger('catchlog').warning(\"This log message will be shown\")\n            print('PASSED')\n    \"\"\"\n    )\n\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    result = pytester.runpytest(\n        \"-s\", f\"--log-file={log_file}\", \"--log-file-level=WARNING\"\n    )\n\n    # fnmatch_lines does an assertion internally\n    result.stdout.fnmatch_lines([\"test_log_file_cli.py PASSED\"])\n\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert \"This log message will be shown\" in contents\n        assert \"This log message won't be shown\" not in contents\n\n\ndef test_log_file_mode_cli(pytester: Pytester) -> None:\n    # Default log file level\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_file(request):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_file_handler.level == logging.WARNING\n            logging.getLogger('catchlog').info(\"This log message won't be shown\")\n            logging.getLogger('catchlog').warning(\"This log message will be shown\")\n            print('PASSED')\n    \"\"\"\n    )\n\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    with open(log_file, mode=\"w\", encoding=\"utf-8\") as wfh:\n        wfh.write(\"A custom header\\n\")\n\n    result = pytester.runpytest(\n        \"-s\",\n        f\"--log-file={log_file}\",\n        \"--log-file-mode=a\",\n        \"--log-file-level=WARNING\",\n    )\n\n    # fnmatch_lines does an assertion internally\n    result.stdout.fnmatch_lines([\"test_log_file_mode_cli.py PASSED\"])\n\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert \"A custom header\" in contents\n        assert \"This log message will be shown\" in contents\n        assert \"This log message won't be shown\" not in contents\n\n\ndef test_log_file_mode_cli_invalid(pytester: Pytester) -> None:\n    # Default log file level\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_file(request):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_file_handler.level == logging.WARNING\n            logging.getLogger('catchlog').info(\"This log message won't be shown\")\n            logging.getLogger('catchlog').warning(\"This log message will be shown\")\n    \"\"\"\n    )\n\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    result = pytester.runpytest(\n        \"-s\",\n        f\"--log-file={log_file}\",\n        \"--log-file-mode=b\",\n        \"--log-file-level=WARNING\",\n    )\n\n    # make sure that we get a '4' exit code for the testsuite\n    assert result.ret == ExitCode.USAGE_ERROR\n\n\ndef test_log_file_cli_level(pytester: Pytester) -> None:\n    # Default log file level\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_file(request):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_file_handler.level == logging.INFO\n            logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n            logging.getLogger('catchlog').info(\"This log message will be shown\")\n            print('PASSED')\n    \"\"\"\n    )\n\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    result = pytester.runpytest(\"-s\", f\"--log-file={log_file}\", \"--log-file-level=INFO\")\n\n    # fnmatch_lines does an assertion internally\n    result.stdout.fnmatch_lines([\"test_log_file_cli_level.py PASSED\"])\n\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert \"This log message will be shown\" in contents\n        assert \"This log message won't be shown\" not in contents\n\n\ndef test_log_level_not_changed_by_default(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n        def test_log_file():\n            assert logging.getLogger().level == logging.WARNING\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-s\")\n    result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n\ndef test_log_file_ini(pytester: Pytester) -> None:\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        log_file={log_file}\n        log_file_level=WARNING\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_file(request):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_file_handler.level == logging.WARNING\n            logging.getLogger('catchlog').info(\"This log message won't be shown\")\n            logging.getLogger('catchlog').warning(\"This log message will be shown\")\n            print('PASSED')\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"-s\")\n\n    # fnmatch_lines does an assertion internally\n    result.stdout.fnmatch_lines([\"test_log_file_ini.py PASSED\"])\n\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert \"This log message will be shown\" in contents\n        assert \"This log message won't be shown\" not in contents\n\n\ndef test_log_file_mode_ini(pytester: Pytester) -> None:\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        log_file={log_file}\n        log_file_mode=a\n        log_file_level=WARNING\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_file(request):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_file_handler.level == logging.WARNING\n            logging.getLogger('catchlog').info(\"This log message won't be shown\")\n            logging.getLogger('catchlog').warning(\"This log message will be shown\")\n            print('PASSED')\n    \"\"\"\n    )\n\n    with open(log_file, mode=\"w\", encoding=\"utf-8\") as wfh:\n        wfh.write(\"A custom header\\n\")\n\n    result = pytester.runpytest(\"-s\")\n\n    # fnmatch_lines does an assertion internally\n    result.stdout.fnmatch_lines([\"test_log_file_mode_ini.py PASSED\"])\n\n    assert result.ret == ExitCode.OK\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert \"A custom header\" in contents\n        assert \"This log message will be shown\" in contents\n        assert \"This log message won't be shown\" not in contents\n\n\ndef test_log_file_ini_level(pytester: Pytester) -> None:\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        log_file={log_file}\n        log_file_level = INFO\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        def test_log_file(request):\n            plugin = request.config.pluginmanager.getplugin('logging-plugin')\n            assert plugin.log_file_handler.level == logging.INFO\n            logging.getLogger('catchlog').debug(\"This log message won't be shown\")\n            logging.getLogger('catchlog').info(\"This log message will be shown\")\n            print('PASSED')\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"-s\")\n\n    # fnmatch_lines does an assertion internally\n    result.stdout.fnmatch_lines([\"test_log_file_ini_level.py PASSED\"])\n\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert \"This log message will be shown\" in contents\n        assert \"This log message won't be shown\" not in contents\n\n\ndef test_log_file_unicode(pytester: Pytester) -> None:\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        log_file={log_file}\n        log_file_level = INFO\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\\\n        import logging\n\n        def test_log_file():\n            logging.getLogger('catchlog').info(\"Normal message\")\n            logging.getLogger('catchlog').info(\"├\")\n            logging.getLogger('catchlog').info(\"Another normal message\")\n        \"\"\"\n    )\n\n    result = pytester.runpytest()\n\n    # make sure that we get a '0' exit code for the testsuite\n    assert result.ret == 0\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert \"Normal message\" in contents\n        assert \"├\" in contents\n        assert \"Another normal message\" in contents\n\n\n@pytest.mark.parametrize(\"has_capture_manager\", [True, False])\ndef test_live_logging_suspends_capture(\n    has_capture_manager: bool, request: FixtureRequest\n) -> None:\n    \"\"\"Test that capture manager is suspended when we emitting messages for live logging.\n\n    This tests the implementation calls instead of behavior because it is difficult/impossible to do it using\n    ``pytester`` facilities because they do their own capturing.\n\n    We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin\n    is installed.\n    \"\"\"\n    import contextlib\n    from functools import partial\n    import logging\n\n    from _pytest.logging import _LiveLoggingStreamHandler\n\n    class MockCaptureManager:\n        calls = []\n\n        @contextlib.contextmanager\n        def global_and_fixture_disabled(self):\n            self.calls.append(\"enter disabled\")\n            yield\n            self.calls.append(\"exit disabled\")\n\n    class DummyTerminal(io.StringIO):\n        def section(self, *args, **kwargs):\n            pass\n\n    out_file = cast(TerminalReporter, DummyTerminal())\n    capture_manager = (\n        cast(CaptureManager, MockCaptureManager()) if has_capture_manager else None\n    )\n    handler = _LiveLoggingStreamHandler(out_file, capture_manager)\n    handler.set_when(\"call\")\n\n    logger = logging.getLogger(__name__ + \".test_live_logging_suspends_capture\")\n    logger.addHandler(handler)\n    request.addfinalizer(partial(logger.removeHandler, handler))\n\n    logger.critical(\"some message\")\n    if has_capture_manager:\n        assert MockCaptureManager.calls == [\"enter disabled\", \"exit disabled\"]\n    else:\n        assert MockCaptureManager.calls == []\n    assert cast(io.StringIO, out_file).getvalue() == \"\\nsome message\\n\"\n\n\ndef test_collection_live_logging(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        logging.getLogger().info(\"Normal message\")\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"--log-cli-level=INFO\")\n    result.stdout.fnmatch_lines(\n        [\"*--- live log collection ---*\", \"*Normal message*\", \"collected 0 items\"]\n    )\n\n\n@pytest.mark.parametrize(\"verbose\", [\"\", \"-q\", \"-qq\"])\ndef test_collection_collect_only_live_logging(pytester: Pytester, verbose: str) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_simple():\n            pass\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"--collect-only\", \"--log-cli-level=INFO\", verbose)\n\n    expected_lines = []\n\n    if not verbose:\n        expected_lines.extend(\n            [\n                \"*collected 1 item*\",\n                \"*<Module test_collection_collect_only_live_logging.py>*\",\n                \"*1 test collected*\",\n            ]\n        )\n    elif verbose == \"-q\":\n        result.stdout.no_fnmatch_line(\"*collected 1 item**\")\n        expected_lines.extend(\n            [\n                \"*test_collection_collect_only_live_logging.py::test_simple*\",\n                \"1 test collected in [0-9].[0-9][0-9]s\",\n            ]\n        )\n    elif verbose == \"-qq\":\n        result.stdout.no_fnmatch_line(\"*collected 1 item**\")\n        expected_lines.extend([\"*test_collection_collect_only_live_logging.py: 1*\"])\n\n    result.stdout.fnmatch_lines(expected_lines)\n\n\ndef test_collection_logging_to_file(pytester: Pytester) -> None:\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        log_file={log_file}\n        log_file_level = INFO\n        \"\"\"\n    )\n\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        logging.getLogger().info(\"Normal message\")\n\n        def test_simple():\n            logging.getLogger().debug(\"debug message in test_simple\")\n            logging.getLogger().info(\"info message in test_simple\")\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n\n    result.stdout.no_fnmatch_line(\"*--- live log collection ---*\")\n\n    assert result.ret == 0\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert \"Normal message\" in contents\n        assert \"debug message in test_simple\" not in contents\n        assert \"info message in test_simple\" in contents\n\n\ndef test_log_in_hooks(pytester: Pytester) -> None:\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        log_file={log_file}\n        log_file_level = INFO\n        log_cli=true\n        \"\"\"\n    )\n    pytester.makeconftest(\n        \"\"\"\n        import logging\n\n        def pytest_runtestloop(session):\n            logging.info('runtestloop')\n\n        def pytest_sessionstart(session):\n            logging.info('sessionstart')\n\n        def pytest_sessionfinish(session, exitstatus):\n            logging.info('sessionfinish')\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*sessionstart*\", \"*runtestloop*\", \"*sessionfinish*\"])\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert \"sessionstart\" in contents\n        assert \"runtestloop\" in contents\n        assert \"sessionfinish\" in contents\n\n\ndef test_log_in_runtest_logreport(pytester: Pytester) -> None:\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        log_file={log_file}\n        log_file_level = INFO\n        log_cli=true\n        \"\"\"\n    )\n    pytester.makeconftest(\n        \"\"\"\n        import logging\n        logger = logging.getLogger(__name__)\n\n        def pytest_runtest_logreport(report):\n            logger.info(\"logreport\")\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n            def test_first():\n                assert True\n        \"\"\"\n    )\n    pytester.runpytest()\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert contents.count(\"logreport\") == 3\n\n\ndef test_log_set_path(pytester: Pytester) -> None:\n    report_dir_base = str(pytester.path)\n\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_file_level = DEBUG\n        log_cli=true\n        \"\"\"\n    )\n    pytester.makeconftest(\n        f\"\"\"\n            import os\n            import pytest\n            @pytest.hookimpl(wrapper=True, tryfirst=True)\n            def pytest_runtest_setup(item):\n                config = item.config\n                logging_plugin = config.pluginmanager.get_plugin(\"logging-plugin\")\n                report_file = os.path.join({report_dir_base!r}, item._request.node.name)\n                logging_plugin.set_log_path(report_file)\n                return (yield)\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n            import logging\n            logger = logging.getLogger(\"testcase-logger\")\n            def test_first():\n                logger.info(\"message from test 1\")\n                assert True\n\n            def test_second():\n                logger.debug(\"message from test 2\")\n                assert True\n        \"\"\"\n    )\n    pytester.runpytest()\n    with open(os.path.join(report_dir_base, \"test_first\"), encoding=\"utf-8\") as rfh:\n        content = rfh.read()\n        assert \"message from test 1\" in content\n\n    with open(os.path.join(report_dir_base, \"test_second\"), encoding=\"utf-8\") as rfh:\n        content = rfh.read()\n        assert \"message from test 2\" in content\n\n\ndef test_log_set_path_with_log_file_mode(pytester: Pytester) -> None:\n    report_dir_base = str(pytester.path)\n\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_file_level = DEBUG\n        log_cli=true\n        log_file_mode=a\n        \"\"\"\n    )\n    pytester.makeconftest(\n        f\"\"\"\n            import os\n            import pytest\n            @pytest.hookimpl(wrapper=True, tryfirst=True)\n            def pytest_runtest_setup(item):\n                config = item.config\n                logging_plugin = config.pluginmanager.get_plugin(\"logging-plugin\")\n                report_file = os.path.join({report_dir_base!r}, item._request.node.name)\n                logging_plugin.set_log_path(report_file)\n                return (yield)\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n            import logging\n            logger = logging.getLogger(\"testcase-logger\")\n            def test_first():\n                logger.info(\"message from test 1\")\n                assert True\n\n            def test_second():\n                logger.debug(\"message from test 2\")\n                assert True\n        \"\"\"\n    )\n\n    test_first_log_file = os.path.join(report_dir_base, \"test_first\")\n    test_second_log_file = os.path.join(report_dir_base, \"test_second\")\n    with open(test_first_log_file, mode=\"w\", encoding=\"utf-8\") as wfh:\n        wfh.write(\"A custom header for test 1\\n\")\n\n    with open(test_second_log_file, mode=\"w\", encoding=\"utf-8\") as wfh:\n        wfh.write(\"A custom header for test 2\\n\")\n\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.OK\n\n    with open(test_first_log_file, encoding=\"utf-8\") as rfh:\n        content = rfh.read()\n        assert \"A custom header for test 1\" in content\n        assert \"message from test 1\" in content\n\n    with open(test_second_log_file, encoding=\"utf-8\") as rfh:\n        content = rfh.read()\n        assert \"A custom header for test 2\" in content\n        assert \"message from test 2\" in content\n\n\ndef test_colored_captured_log(pytester: Pytester) -> None:\n    \"\"\"Test that the level names of captured log messages of a failing test\n    are colored.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        logger = logging.getLogger(__name__)\n\n        def test_foo():\n            logger.info('text going to logger from call')\n            assert False\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--log-level=INFO\", \"--color=yes\")\n    assert result.ret == 1\n    result.stdout.fnmatch_lines(\n        [\n            \"*-- Captured log call --*\",\n            \"\\x1b[32mINFO    \\x1b[0m*text going to logger from call\",\n        ]\n    )\n\n\ndef test_colored_ansi_esc_caplogtext(pytester: Pytester) -> None:\n    \"\"\"Make sure that caplog.text does not contain ANSI escape sequences.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        logger = logging.getLogger(__name__)\n\n        def test_foo(caplog):\n            logger.info('text going to logger from call')\n            assert '\\x1b' not in caplog.text\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--log-level=INFO\", \"--color=yes\")\n    assert result.ret == 0\n\n\ndef test_logging_emit_error(pytester: Pytester) -> None:\n    \"\"\"An exception raised during emit() should fail the test.\n\n    The default behavior of logging is to print \"Logging error\"\n    to stderr with the call stack and some extra details.\n\n    pytest overrides this behavior to propagate the exception.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        def test_bad_log():\n            logging.warning('oops', 'first', 2)\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(failed=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"====* FAILURES *====\",\n            \"*not all arguments converted during string formatting*\",\n        ]\n    )\n\n\ndef test_logging_emit_error_supressed(pytester: Pytester) -> None:\n    \"\"\"If logging is configured to silently ignore errors, pytest\n    doesn't propagate errors either.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        def test_bad_log(monkeypatch):\n            monkeypatch.setattr(logging, 'raiseExceptions', False)\n            logging.warning('oops', 'first', 2)\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=1)\n\n\ndef test_log_file_cli_subdirectories_are_successfully_created(\n    pytester: Pytester,\n) -> None:\n    path = pytester.makepyfile(\"\"\" def test_logger(): pass \"\"\")\n    expected = os.path.join(os.path.dirname(str(path)), \"foo\", \"bar\")\n    result = pytester.runpytest(\"--log-file=foo/bar/logf.log\")\n    assert \"logf.log\" in os.listdir(expected)\n    assert result.ret == ExitCode.OK\n\n\ndef test_disable_loggers(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n        import os\n        disabled_log = logging.getLogger('disabled')\n        test_log = logging.getLogger('test')\n        def test_logger_propagation(caplog):\n            with caplog.at_level(logging.DEBUG):\n                disabled_log.warning(\"no log; no stderr\")\n                test_log.debug(\"Visible text!\")\n                assert caplog.record_tuples == [('test', 10, 'Visible text!')]\n         \"\"\"\n    )\n    result = pytester.runpytest(\"--log-disable=disabled\", \"-s\")\n    assert result.ret == ExitCode.OK\n    assert not result.stderr.lines\n\n\ndef test_disable_loggers_does_not_propagate(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n    import logging\n    import os\n\n    parent_logger = logging.getLogger(\"parent\")\n    child_logger = parent_logger.getChild(\"child\")\n\n    def test_logger_propagation_to_parent(caplog):\n            with caplog.at_level(logging.DEBUG):\n                parent_logger.warning(\"some parent logger message\")\n                child_logger.warning(\"some child logger message\")\n                assert len(caplog.record_tuples) == 1\n                assert caplog.record_tuples[0][0] == \"parent\"\n                assert caplog.record_tuples[0][2] == \"some parent logger message\"\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"--log-disable=parent.child\", \"-s\")\n    assert result.ret == ExitCode.OK\n    assert not result.stderr.lines\n\n\ndef test_log_disabling_works_with_log_cli(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n    import logging\n    disabled_log = logging.getLogger('disabled')\n    test_log = logging.getLogger('test')\n\n    def test_log_cli_works(caplog):\n        test_log.info(\"Visible text!\")\n        disabled_log.warning(\"This string will be suppressed.\")\n    \"\"\"\n    )\n    result = pytester.runpytest(\n        \"--log-cli-level=DEBUG\",\n        \"--log-disable=disabled\",\n    )\n    assert result.ret == ExitCode.OK\n    result.stdout.fnmatch_lines(\n        \"INFO     test:test_log_disabling_works_with_log_cli.py:6 Visible text!\"\n    )\n    result.stdout.no_fnmatch_line(\n        \"WARNING  disabled:test_log_disabling_works_with_log_cli.py:7 This string will be suppressed.\"\n    )\n    assert not result.stderr.lines\n\n\ndef test_without_date_format_log(pytester: Pytester) -> None:\n    \"\"\"Check that date is not printed by default.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        logger = logging.getLogger(__name__)\n\n        def test_foo():\n            logger.warning('text')\n            assert False\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 1\n    result.stdout.fnmatch_lines(\n        [\"WARNING  test_without_date_format_log:test_without_date_format_log.py:6 text\"]\n    )\n\n\ndef test_date_format_log(pytester: Pytester) -> None:\n    \"\"\"Check that log_date_format affects output.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        logger = logging.getLogger(__name__)\n\n        def test_foo():\n            logger.warning('text')\n            assert False\n        \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_format=%(asctime)s; %(levelname)s; %(message)s\n        log_date_format=%Y-%m-%d %H:%M:%S\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 1\n    result.stdout.re_match_lines([r\"^[0-9-]{10} [0-9:]{8}; WARNING; text\"])\n\n\ndef test_date_format_percentf_log(pytester: Pytester) -> None:\n    \"\"\"Make sure that microseconds are printed in log.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        logger = logging.getLogger(__name__)\n\n        def test_foo():\n            logger.warning('text')\n            assert False\n        \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_format=%(asctime)s; %(levelname)s; %(message)s\n        log_date_format=%Y-%m-%d %H:%M:%S.%f\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 1\n    result.stdout.re_match_lines([r\"^[0-9-]{10} [0-9:]{8}.[0-9]{6}; WARNING; text\"])\n\n\ndef test_date_format_percentf_tz_log(pytester: Pytester) -> None:\n    \"\"\"Make sure that timezone and microseconds are properly formatted together.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n\n        logger = logging.getLogger(__name__)\n\n        def test_foo():\n            logger.warning('text')\n            assert False\n        \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        log_format=%(asctime)s; %(levelname)s; %(message)s\n        log_date_format=%Y-%m-%d %H:%M:%S.%f%z\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 1\n    result.stdout.re_match_lines(\n        [r\"^[0-9-]{10} [0-9:]{8}.[0-9]{6}[+-][0-9\\.]+; WARNING; text\"]\n    )\n\n\ndef test_log_file_cli_fallback_options(pytester: Pytester) -> None:\n    \"\"\"Make sure that fallback values for log-file formats and level works.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n        logger = logging.getLogger()\n\n        def test_foo():\n            logger.info('info text going to logger')\n            logger.warning('warning text going to logger')\n            logger.error('error text going to logger')\n\n            assert 0\n    \"\"\"\n    )\n    log_file = str(pytester.path.joinpath(\"pytest.log\"))\n    result = pytester.runpytest(\n        \"--log-level=ERROR\",\n        \"--log-format=%(asctime)s %(message)s\",\n        \"--log-date-format=%H:%M\",\n        \"--log-file=pytest.log\",\n    )\n    assert result.ret == 1\n\n    # The log file should only contain the error log messages\n    # not the warning or info ones and the format and date format\n    # should match the formats provided using --log-format and --log-date-format\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert re.match(r\"[0-9]{2}:[0-9]{2} error text going to logger\\s*\", contents)\n        assert \"info text going to logger\" not in contents\n        assert \"warning text going to logger\" not in contents\n        assert \"error text going to logger\" in contents\n\n    # Try with a different format and date format to make sure that the formats\n    # are being used\n    result = pytester.runpytest(\n        \"--log-level=ERROR\",\n        \"--log-format=%(asctime)s : %(message)s\",\n        \"--log-date-format=%H:%M:%S\",\n        \"--log-file=pytest.log\",\n    )\n    assert result.ret == 1\n\n    # The log file should only contain the error log messages\n    # not the warning or info ones and the format and date format\n    # should match the formats provided using --log-format and --log-date-format\n    assert os.path.isfile(log_file)\n    with open(log_file, encoding=\"utf-8\") as rfh:\n        contents = rfh.read()\n        assert re.match(\n            r\"[0-9]{2}:[0-9]{2}:[0-9]{2} : error text going to logger\\s*\", contents\n        )\n        assert \"info text going to logger\" not in contents\n        assert \"warning text going to logger\" not in contents\n        assert \"error text going to logger\" in contents\n"
  },
  {
    "path": "testing/plugins_integration/.gitignore",
    "content": "*.html\nassets/\n"
  },
  {
    "path": "testing/plugins_integration/README.rst",
    "content": "This directory contains tests and support files for smoke testing popular plugins against the current pytest version.\n\nThe objective is to gauge if any intentional or unintentional changes in pytest break plugins.\n\nAs a rule of thumb, we should add plugins here:\n\n1. That are used at large. This might be subjective in some cases, but if answer is yes to\n   the question: *if a new release of pytest causes pytest-X to break, will this break a ton of test suites out there?*.\n2. That don't have large external dependencies: such as external services.\n\nBesides adding the plugin as dependency, we should also add a quick test which uses some\nminimal part of the plugin, a smoke test. Also consider reusing one of the existing tests if that's\npossible.\n"
  },
  {
    "path": "testing/plugins_integration/bdd_wallet.feature",
    "content": "Feature: Buy things with apple\n\n    Scenario: Buy fruits\n        Given A wallet with 50\n\n        When I buy some apples for 1\n        And I buy some bananas for 2\n\n        Then I have 47 left\n"
  },
  {
    "path": "testing/plugins_integration/bdd_wallet.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom pytest_bdd import given\nfrom pytest_bdd import scenario\nfrom pytest_bdd import then\nfrom pytest_bdd import when\n\nimport pytest\n\n\n@scenario(\"bdd_wallet.feature\", \"Buy fruits\")\ndef test_publish():\n    pass\n\n\n@pytest.fixture\ndef wallet():\n    class Wallet:\n        amount = 0\n\n    return Wallet()\n\n\n@given(\"A wallet with 50\")\ndef fill_wallet(wallet):\n    wallet.amount = 50\n\n\n@when(\"I buy some apples for 1\")\ndef buy_apples(wallet):\n    wallet.amount -= 1\n\n\n@when(\"I buy some bananas for 2\")\ndef buy_bananas(wallet):\n    wallet.amount -= 2\n\n\n@then(\"I have 47 left\")\ndef check(wallet):\n    assert wallet.amount == 47\n"
  },
  {
    "path": "testing/plugins_integration/django_settings.py",
    "content": "from __future__ import annotations\n\n\nSECRET_KEY = \"mysecret\"\n"
  },
  {
    "path": "testing/plugins_integration/pytest.ini",
    "content": "[pytest]\nstrict_markers = True\nasyncio_mode = strict\nfilterwarnings =\n    error::pytest.PytestWarning\n    ignore:usefixtures.* without arguments has no effect:pytest.PytestWarning\n    ignore:.*.fspath is deprecated and will be replaced by .*.path.*:pytest.PytestDeprecationWarning\n"
  },
  {
    "path": "testing/plugins_integration/pytest_anyio_integration.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport anyio\n\nimport pytest\n\n\n@pytest.mark.anyio\nasync def test_sleep():\n    await anyio.sleep(0)\n"
  },
  {
    "path": "testing/plugins_integration/pytest_asyncio_integration.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport asyncio\n\nimport pytest\n\n\n@pytest.mark.asyncio\nasync def test_sleep():\n    await asyncio.sleep(0)\n"
  },
  {
    "path": "testing/plugins_integration/pytest_mock_integration.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\n\ndef test_mocker(mocker):\n    mocker.MagicMock()\n"
  },
  {
    "path": "testing/plugins_integration/pytest_rerunfailures_integration.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\n\nclass MyTestCase(unittest.TestCase):\n    first_time = True\n\n    def test_fail_the_first_time(self) -> None:\n        \"\"\"Regression test for issue #12424.\"\"\"\n        if self.first_time:\n            type(self).first_time = False\n            self.fail()\n"
  },
  {
    "path": "testing/plugins_integration/pytest_trio_integration.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport trio\n\nimport pytest\n\n\n@pytest.mark.trio\nasync def test_sleep():\n    await trio.sleep(0)\n"
  },
  {
    "path": "testing/plugins_integration/pytest_twisted_integration.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest_twisted\nfrom twisted.internet.task import deferLater\n\n\ndef sleep():\n    import twisted.internet.reactor\n\n    return deferLater(clock=twisted.internet.reactor, delay=0)\n\n\n@pytest_twisted.inlineCallbacks\ndef test_inlineCallbacks():\n    yield sleep()\n\n\n@pytest_twisted.ensureDeferred\nasync def test_inlineCallbacks_async():\n    await sleep()\n"
  },
  {
    "path": "testing/plugins_integration/requirements.txt",
    "content": "anyio[trio]==4.12.1\ndjango==6.0.3\npytest-asyncio==1.3.0\npytest-bdd==8.1.0\npytest-cov==7.0.0\npytest-django==4.12.0\npytest-flakes==4.0.5\npytest-html==4.2.0\npytest-mock==3.15.1\npytest-rerunfailures==16.1\npytest-sugar==1.1.1\npytest-trio==0.8.0\npytest-twisted==1.14.3\ntwisted==25.5.0\npytest-xvfb==3.1.1\n"
  },
  {
    "path": "testing/plugins_integration/simple_integration.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport pytest\n\n\ndef test_foo():\n    assert True\n\n\n@pytest.mark.parametrize(\"i\", range(3))\ndef test_bar(i):\n    assert True\n"
  },
  {
    "path": "testing/python/approx.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom contextlib import contextmanager\nimport decimal\nfrom decimal import Decimal\nfrom fractions import Fraction\nfrom math import inf\nfrom math import nan\nfrom math import sqrt\nimport operator\nfrom operator import eq\nfrom operator import ne\nimport re\n\nfrom _pytest.pytester import Pytester\nfrom _pytest.python_api import _recursive_sequence_map\nimport pytest\nfrom pytest import approx\n\n\n@pytest.fixture\ndef mocked_doctest_runner(monkeypatch):\n    import doctest\n\n    class MockedPdb:\n        def __init__(self, out):\n            pass\n\n        def set_trace(self):\n            raise NotImplementedError(\"not used\")\n\n        def reset(self):\n            pass\n\n        def set_continue(self):\n            pass\n\n    monkeypatch.setattr(\"doctest._OutputRedirectingPdb\", MockedPdb)\n\n    class MyDocTestRunner(doctest.DocTestRunner):\n        def report_failure(self, out, test, example, got):\n            raise AssertionError(\n                f\"'{example.source.strip()}' evaluates to '{got.strip()}', not '{example.want.strip()}'\"\n            )\n\n    return MyDocTestRunner()\n\n\n@contextmanager\ndef temporary_verbosity(config, verbosity=0):\n    original_verbosity = config.getoption(\"verbose\")\n    config.option.verbose = verbosity\n    try:\n        yield\n    finally:\n        config.option.verbose = original_verbosity\n\n\n@pytest.fixture\ndef assert_approx_raises_regex(pytestconfig):\n    def do_assert(lhs, rhs, expected_message, verbosity_level=0):\n        import re\n\n        with temporary_verbosity(pytestconfig, verbosity_level):\n            with pytest.raises(AssertionError) as e:\n                assert lhs == approx(rhs)\n\n        nl = \"\\n\"\n        obtained_message = str(e.value).splitlines()[1:]\n        assert len(obtained_message) == len(expected_message), (\n            \"Regex message length doesn't match obtained.\\n\"\n            \"Obtained:\\n\"\n            f\"{nl.join(obtained_message)}\\n\\n\"\n            \"Expected regex:\\n\"\n            f\"{nl.join(expected_message)}\\n\\n\"\n        )\n\n        for i, (obtained_line, expected_line) in enumerate(\n            zip(obtained_message, expected_message, strict=True)\n        ):\n            regex = re.compile(expected_line)\n            assert regex.match(obtained_line) is not None, (\n                \"Unexpected error message:\\n\"\n                f\"{nl.join(obtained_message)}\\n\\n\"\n                \"Did not match regex:\\n\"\n                f\"{nl.join(expected_message)}\\n\\n\"\n                f\"With verbosity level = {verbosity_level}, on line {i}\"\n            )\n\n    return do_assert\n\n\nSOME_FLOAT = r\"[+-]?((?:([0-9]*[.])?[0-9]+(e-?[0-9]+)?)|inf|nan)\\s*\"\nSOME_INT = r\"[0-9]+\\s*\"\nSOME_TOLERANCE = rf\"({SOME_FLOAT}|[+-]?[0-9]+(\\.[0-9]+)?[eE][+-]?[0-9]+\\s*)\"\n\n\nclass TestApprox:\n    def test_error_messages_native_dtypes(self, assert_approx_raises_regex):\n        # Treat bool exactly.\n        assert_approx_raises_regex(\n            {\"a\": 1.0, \"b\": True},\n            {\"a\": 1.0, \"b\": False},\n            [\n                \"\",\n                \"  comparison failed. Mismatched elements: 1 / 2:\",\n                f\"  Max absolute difference: {SOME_FLOAT}\",\n                f\"  Max relative difference: {SOME_FLOAT}\",\n                r\"  Index\\s+\\| Obtained\\s+\\| Expected\",\n                r\".*(True|False)\\s+\",\n            ],\n        )\n        assert_approx_raises_regex(\n            2.0,\n            1.0,\n            [\n                \"\",\n                \"  comparison failed\",\n                f\"  Obtained: {SOME_FLOAT}\",\n                f\"  Expected: {SOME_FLOAT} ± {SOME_TOLERANCE}\",\n            ],\n        )\n\n        assert_approx_raises_regex(\n            {\"a\": 1.0, \"b\": 1000.0, \"c\": 1000000.0},\n            {\n                \"a\": 2.0,\n                \"b\": 1000.0,\n                \"c\": 3000000.0,\n            },\n            [\n                r\"\",\n                r\"  comparison failed. Mismatched elements: 2 / 3:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                rf\"  Max relative difference: {SOME_FLOAT}\",\n                r\"  Index \\| Obtained\\s+\\| Expected\\s+\",\n                rf\"  a     \\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_TOLERANCE}\",\n                rf\"  c     \\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_TOLERANCE}\",\n            ],\n        )\n\n        assert_approx_raises_regex(\n            {\"a\": 1.0, \"b\": None, \"c\": None},\n            {\n                \"a\": None,\n                \"b\": 1000.0,\n                \"c\": None,\n            },\n            [\n                r\"\",\n                r\"  comparison failed. Mismatched elements: 2 / 3:\",\n                r\"  Max absolute difference: -inf\",\n                r\"  Max relative difference: -inf\",\n                r\"  Index \\| Obtained\\s+\\| Expected\\s+\",\n                rf\"  a     \\| {SOME_FLOAT} \\| None\",\n                rf\"  b     \\| None\\s+\\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n            ],\n        )\n\n        assert_approx_raises_regex(\n            [1.0, 2.0, 3.0, 4.0],\n            [1.0, 3.0, 3.0, 5.0],\n            [\n                r\"\",\n                r\"  comparison failed. Mismatched elements: 2 / 4:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                rf\"  Max relative difference: {SOME_FLOAT}\",\n                r\"  Index \\| Obtained\\s+\\| Expected   \",\n                rf\"  1     \\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n                rf\"  3     \\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n            ],\n        )\n\n        assert_approx_raises_regex(\n            (1, 2.2, 4),\n            (1, 3.2, 4),\n            [\n                r\"\",\n                r\"  comparison failed. Mismatched elements: 1 / 3:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                rf\"  Max relative difference: {SOME_FLOAT}\",\n                r\"  Index \\| Obtained\\s+\\| Expected   \",\n                rf\"  1     \\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n            ],\n        )\n\n        # Specific test for comparison with 0.0 (relative diff will be 'inf')\n        assert_approx_raises_regex(\n            [0.0],\n            [1.0],\n            [\n                r\"\",\n                r\"  comparison failed. Mismatched elements: 1 / 1:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                r\"  Max relative difference: inf\",\n                r\"  Index \\| Obtained\\s+\\| Expected   \",\n                rf\"\\s*0\\s*\\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n            ],\n        )\n\n    def test_error_messages_numpy_dtypes(self, assert_approx_raises_regex):\n        np = pytest.importorskip(\"numpy\")\n\n        a = np.linspace(0, 100, 20)\n        b = np.linspace(0, 100, 20)\n        a[10] += 0.5\n        assert_approx_raises_regex(\n            a,\n            b,\n            [\n                r\"\",\n                r\"  comparison failed. Mismatched elements: 1 / 20:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                rf\"  Max relative difference: {SOME_FLOAT}\",\n                r\"  Index \\| Obtained\\s+\\| Expected\",\n                rf\"  \\(10,\\) \\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n            ],\n        )\n\n        assert_approx_raises_regex(\n            np.array(\n                [\n                    [[1.1987311, 12412342.3], [3.214143244, 1423412423415.677]],\n                    [[1, 2], [3, 219371297321973]],\n                ]\n            ),\n            np.array(\n                [\n                    [[1.12313, 12412342.3], [3.214143244, 534523542345.677]],\n                    [[1, 2], [3, 7]],\n                ]\n            ),\n            [\n                r\"\",\n                r\"  comparison failed. Mismatched elements: 3 / 8:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                rf\"  Max relative difference: {SOME_FLOAT}\",\n                r\"  Index\\s+\\| Obtained\\s+\\| Expected\\s+\",\n                rf\"  \\(0, 0, 0\\) \\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n                rf\"  \\(0, 1, 1\\) \\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n                rf\"  \\(1, 1, 1\\) \\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n            ],\n        )\n\n        # Specific test for comparison with 0.0 (relative diff will be 'inf')\n        assert_approx_raises_regex(\n            np.array([0.0]),\n            np.array([1.0]),\n            [\n                r\"\",\n                r\"  comparison failed. Mismatched elements: 1 / 1:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                r\"  Max relative difference: inf\",\n                r\"  Index \\| Obtained\\s+\\| Expected   \",\n                rf\"\\s*\\(0,\\)\\s*\\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n            ],\n        )\n\n    def test_error_messages_invalid_args(self, assert_approx_raises_regex):\n        np = pytest.importorskip(\"numpy\")\n        with pytest.raises(AssertionError) as e:\n            assert np.array([[1.2, 3.4], [4.0, 5.0]]) == pytest.approx(\n                np.array([[4.0], [5.0]])\n            )\n        message = \"\\n\".join(str(e.value).split(\"\\n\")[1:])\n        assert message == \"\\n\".join(\n            [\n                \"  \",\n                \"  Impossible to compare arrays with different shapes.\",\n                \"  Shapes: (2, 1) and (2, 2)\",\n            ]\n        )\n\n        with pytest.raises(AssertionError) as e:\n            assert [1.0, 2.0, 3.0] == pytest.approx([4.0, 5.0])\n        message = \"\\n\".join(str(e.value).split(\"\\n\")[1:])\n        assert message == \"\\n\".join(\n            [\n                \"  \",\n                \"  Impossible to compare lists with different sizes.\",\n                \"  Lengths: 2 and 3\",\n            ]\n        )\n\n    def test_error_messages_with_different_verbosity(self, assert_approx_raises_regex):\n        np = pytest.importorskip(\"numpy\")\n        for v in [0, 1, 2]:\n            # Verbosity level doesn't affect the error message for scalars\n            assert_approx_raises_regex(\n                2.0,\n                1.0,\n                [\n                    \"\",\n                    \"  comparison failed\",\n                    f\"  Obtained: {SOME_FLOAT}\",\n                    f\"  Expected: {SOME_FLOAT} ± {SOME_FLOAT}\",\n                ],\n                verbosity_level=v,\n            )\n\n        a = np.linspace(1, 101, 20)\n        b = np.linspace(2, 102, 20)\n        assert_approx_raises_regex(\n            a,\n            b,\n            [\n                r\"^  $\",\n                r\"^  comparison failed. Mismatched elements: 20 / 20:$\",\n                rf\"^  Max absolute difference: {SOME_FLOAT}$\",\n                rf\"^  Max relative difference: {SOME_FLOAT}$\",\n                r\"^  Index \\| Obtained\\s+\\| Expected\\s+$\",\n                rf\"^  \\(0,\\)\\s+\\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}$\",\n                rf\"^  \\(1,\\)\\s+\\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}\\.\\.\\.$\",\n                \"^  $\",\n                rf\"^  ...Full output truncated \\({SOME_INT} lines hidden\\), use '-vv' to show$\",\n            ],\n            verbosity_level=0,\n        )\n\n        assert_approx_raises_regex(\n            a,\n            b,\n            [\n                r\"  \",\n                r\"  comparison failed. Mismatched elements: 20 / 20:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                rf\"  Max relative difference: {SOME_FLOAT}\",\n                r\"  Index \\| Obtained\\s+\\| Expected\",\n            ]\n            + [\n                rf\"  \\({i},\\)\\s+\\| {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\"\n                for i in range(20)\n            ],\n            verbosity_level=2,\n        )\n\n    def test_repr_string(self):\n        assert repr(approx(1.0)) == \"1.0 ± 1.0e-06\"\n        assert repr(approx([1.0, 2.0])) == \"approx([1.0 ± 1.0e-06, 2.0 ± 2.0e-06])\"\n        assert repr(approx((1.0, 2.0))) == \"approx((1.0 ± 1.0e-06, 2.0 ± 2.0e-06))\"\n        assert repr(approx(inf)) == \"inf\"\n        assert repr(approx(1.0, rel=nan)) == \"1.0 ± ???\"\n        assert repr(approx(1.0, rel=inf)) == \"1.0 ± inf\"\n\n        # Dictionaries aren't ordered, so we need to check both orders.\n        assert repr(approx({\"a\": 1.0, \"b\": 2.0})) in (\n            \"approx({'a': 1.0 ± 1.0e-06, 'b': 2.0 ± 2.0e-06})\",\n            \"approx({'b': 2.0 ± 2.0e-06, 'a': 1.0 ± 1.0e-06})\",\n        )\n\n        assert repr(approx(42, abs=1)) == \"42 ± 1\"\n        assert repr(approx(5, rel=0.01)) == \"5 ± 0.05\"\n        assert repr(approx(24000, abs=500)) == \"24000 ± 500\"\n        assert repr(approx(1500, abs=555)) == \"1500 ± 555\"\n\n    def test_repr_complex_numbers(self):\n        assert repr(approx(inf + 1j)) == \"(inf+1j)\"\n        assert repr(approx(1.0j, rel=inf)) == \"1j ± inf\"\n\n        # can't compute a sensible tolerance\n        assert repr(approx(nan + 1j)) == \"(nan+1j) ± ???\"\n\n        assert repr(approx(1.0j)) == \"1j ± 1.0e-06 ∠ ±180°\"\n\n        # relative tolerance is scaled to |3+4j| = 5\n        assert repr(approx(3 + 4 * 1j)) == \"(3+4j) ± 5.0e-06 ∠ ±180°\"\n\n        # absolute tolerance is not scaled\n        assert repr(approx(3.3 + 4.4 * 1j, abs=0.02)) == \"(3.3+4.4j) ± 0.02 ∠ ±180°\"\n\n    @pytest.mark.parametrize(\n        \"value, expected_repr_string\",\n        [\n            (5.0, \"approx(5.0 ± 5.0e-06)\"),\n            ([5.0], \"approx([5.0 ± 5.0e-06])\"),\n            ([[5.0]], \"approx([[5.0 ± 5.0e-06]])\"),\n            ([[5.0, 6.0]], \"approx([[5.0 ± 5.0e-06, 6.0 ± 6.0e-06]])\"),\n            ([[5.0], [6.0]], \"approx([[5.0 ± 5.0e-06], [6.0 ± 6.0e-06]])\"),\n        ],\n    )\n    def test_repr_nd_array(self, value, expected_repr_string):\n        \"\"\"Make sure that arrays of all different dimensions are repr'd correctly.\"\"\"\n        np = pytest.importorskip(\"numpy\")\n        np_array = np.array(value)\n        assert repr(approx(np_array)) == expected_repr_string\n\n    def test_bool(self):\n        with pytest.raises(AssertionError) as err:\n            assert approx(1)\n\n        assert err.match(r\"approx\\(\\) is not supported in a boolean context\")\n\n    def test_mixed_sequence(self, assert_approx_raises_regex) -> None:\n        \"\"\"Approx should work on sequences that also contain non-numbers (#13010).\"\"\"\n        assert_approx_raises_regex(\n            [1.1, 2, \"word\"],\n            [1.0, 2, \"different\"],\n            [\n                \"\",\n                r\"  comparison failed. Mismatched elements: 2 / 3:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                rf\"  Max relative difference: {SOME_FLOAT}\",\n                r\"  Index \\| Obtained\\s+\\| Expected\\s+\",\n                r\"\\s*0\\s*\\|\\s*1\\.1\\s*\\|\\s*1\\.0\\s*±\\s*1\\.0e\\-06\\s*\",\n                r\"\\s*2\\s*\\|\\s*word\\s*\\|\\s*different\\s*\",\n            ],\n            verbosity_level=2,\n        )\n        assert_approx_raises_regex(\n            [1.1, 2, \"word\"],\n            [1.0, 2, \"word\"],\n            [\n                \"\",\n                r\"  comparison failed. Mismatched elements: 1 / 3:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                rf\"  Max relative difference: {SOME_FLOAT}\",\n                r\"  Index \\| Obtained\\s+\\| Expected\\s+\",\n                r\"\\s*0\\s*\\|\\s*1\\.1\\s*\\|\\s*1\\.0\\s*±\\s*1\\.0e\\-06\\s*\",\n            ],\n            verbosity_level=2,\n        )\n        assert [1.1, 2, \"word\"] == pytest.approx([1.1, 2, \"word\"])\n\n    def test_operator_overloading(self):\n        assert 1 == approx(1, rel=1e-6, abs=1e-12)\n        assert not (1 != approx(1, rel=1e-6, abs=1e-12))\n        assert 10 != approx(1, rel=1e-6, abs=1e-12)\n        assert not (10 == approx(1, rel=1e-6, abs=1e-12))\n\n    def test_exactly_equal(self):\n        examples = [\n            (2.0, 2.0),\n            (0.1e200, 0.1e200),\n            (1.123e-300, 1.123e-300),\n            (12345, 12345.0),\n            (0.0, -0.0),\n            (345678, 345678),\n            (Decimal(\"1.0001\"), Decimal(\"1.0001\")),\n            (Fraction(1, 3), Fraction(-1, -3)),\n        ]\n        for a, x in examples:\n            assert a == approx(x)\n\n    def test_opposite_sign(self):\n        examples = [(eq, 1e-100, -1e-100), (ne, 1e100, -1e100)]\n        for op, a, x in examples:\n            assert op(a, approx(x))\n\n    def test_zero_tolerance(self):\n        within_1e10 = [(1.1e-100, 1e-100), (-1.1e-100, -1e-100)]\n        for a, x in within_1e10:\n            assert x == approx(x, rel=0.0, abs=0.0)\n            assert a != approx(x, rel=0.0, abs=0.0)\n            assert a == approx(x, rel=0.0, abs=5e-101)\n            assert a != approx(x, rel=0.0, abs=5e-102)\n            assert a == approx(x, rel=5e-1, abs=0.0)\n            assert a != approx(x, rel=5e-2, abs=0.0)\n\n    @pytest.mark.parametrize(\n        (\"rel\", \"abs\"),\n        [\n            (-1e100, None),\n            (None, -1e100),\n            (1e100, -1e100),\n            (-1e100, 1e100),\n            (-1e100, -1e100),\n        ],\n    )\n    def test_negative_tolerance(self, rel: float | None, abs: float | None) -> None:\n        # Negative tolerances are not allowed.\n        with pytest.raises(ValueError):\n            1.1 == approx(1, rel, abs)\n\n    def test_negative_tolerance_message(self):\n        # Error message for negative tolerance should include the value.\n        with pytest.raises(ValueError, match=\"-3\"):\n            0 == approx(1, abs=-3)\n        with pytest.raises(ValueError, match=\"-3\"):\n            0 == approx(1, rel=-3)\n\n    def test_inf_tolerance(self):\n        # Everything should be equal if the tolerance is infinite.\n        large_diffs = [(1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10)]\n        for a, x in large_diffs:\n            assert a != approx(x, rel=0.0, abs=0.0)\n            assert a == approx(x, rel=inf, abs=0.0)\n            assert a == approx(x, rel=0.0, abs=inf)\n            assert a == approx(x, rel=inf, abs=inf)\n\n    def test_inf_tolerance_expecting_zero(self) -> None:\n        # If the relative tolerance is zero but the expected value is infinite,\n        # the actual tolerance is a NaN, which should be an error.\n        with pytest.raises(ValueError):\n            1 == approx(0, rel=inf, abs=0.0)\n        with pytest.raises(ValueError):\n            1 == approx(0, rel=inf, abs=inf)\n\n    def test_nan_tolerance(self) -> None:\n        with pytest.raises(ValueError):\n            1.1 == approx(1, rel=nan)\n        with pytest.raises(ValueError):\n            1.1 == approx(1, abs=nan)\n        with pytest.raises(ValueError):\n            1.1 == approx(1, rel=nan, abs=nan)\n\n    def test_reasonable_defaults(self):\n        # Whatever the defaults are, they should work for numbers close to 1\n        # than have a small amount of floating-point error.\n        assert 0.1 + 0.2 == approx(0.3)\n\n    def test_default_tolerances(self):\n        # This tests the defaults as they are currently set.  If you change the\n        # defaults, this test will fail but you should feel free to change it.\n        # None of the other tests (except the doctests) should be affected by\n        # the choice of defaults.\n        examples = [\n            # Relative tolerance used.\n            (eq, 1e100 + 1e94, 1e100),\n            (ne, 1e100 + 2e94, 1e100),\n            (eq, 1e0 + 1e-6, 1e0),\n            (ne, 1e0 + 2e-6, 1e0),\n            # Absolute tolerance used.\n            (eq, 1e-100, +1e-106),\n            (eq, 1e-100, +2e-106),\n            (eq, 1e-100, 0),\n        ]\n        for op, a, x in examples:\n            assert op(a, approx(x))\n\n    def test_custom_tolerances(self):\n        assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e0)\n        assert 1e8 + 1e0 == approx(1e8, rel=5e-9, abs=5e0)\n        assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e-1)\n        assert 1e8 + 1e0 != approx(1e8, rel=5e-9, abs=5e-1)\n\n        assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-8)\n        assert 1e0 + 1e-8 == approx(1e0, rel=5e-9, abs=5e-8)\n        assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-9)\n        assert 1e0 + 1e-8 != approx(1e0, rel=5e-9, abs=5e-9)\n\n        assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-16)\n        assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-9, abs=5e-16)\n        assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-17)\n        assert 1e-8 + 1e-16 != approx(1e-8, rel=5e-9, abs=5e-17)\n\n    def test_relative_tolerance(self):\n        within_1e8_rel = [(1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8)]\n        for a, x in within_1e8_rel:\n            assert a == approx(x, rel=5e-8, abs=0.0)\n            assert a != approx(x, rel=5e-9, abs=0.0)\n\n    def test_absolute_tolerance(self):\n        within_1e8_abs = [(1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8)]\n        for a, x in within_1e8_abs:\n            assert a == approx(x, rel=0, abs=5e-8)\n            assert a != approx(x, rel=0, abs=5e-9)\n\n    def test_expecting_zero(self):\n        examples = [\n            (ne, 1e-6, 0.0),\n            (ne, -1e-6, 0.0),\n            (eq, 1e-12, 0.0),\n            (eq, -1e-12, 0.0),\n            (ne, 2e-12, 0.0),\n            (ne, -2e-12, 0.0),\n            (ne, inf, 0.0),\n            (ne, nan, 0.0),\n        ]\n        for op, a, x in examples:\n            assert op(a, approx(x, rel=0.0, abs=1e-12))\n            assert op(a, approx(x, rel=1e-6, abs=1e-12))\n\n    def test_expecting_inf(self):\n        examples = [\n            (eq, inf, inf),\n            (eq, -inf, -inf),\n            (ne, inf, -inf),\n            (ne, 0.0, inf),\n            (ne, nan, inf),\n        ]\n        for op, a, x in examples:\n            assert op(a, approx(x))\n\n    def test_expecting_nan(self):\n        examples = [\n            (eq, nan, nan),\n            (eq, -nan, -nan),\n            (eq, nan, -nan),\n            (ne, 0.0, nan),\n            (ne, inf, nan),\n        ]\n        for op, a, x in examples:\n            # Nothing is equal to NaN by default.\n            assert a != approx(x)\n\n            # If ``nan_ok=True``, then NaN is equal to NaN.\n            assert op(a, approx(x, nan_ok=True))\n\n    def test_int(self):\n        within_1e6 = [(1000001, 1000000), (-1000001, -1000000)]\n        for a, x in within_1e6:\n            assert a == approx(x, rel=5e-6, abs=0)\n            assert a != approx(x, rel=5e-7, abs=0)\n            assert approx(x, rel=5e-6, abs=0) == a\n            assert approx(x, rel=5e-7, abs=0) != a\n\n    def test_decimal(self):\n        within_1e6 = [\n            (Decimal(\"1.000001\"), Decimal(\"1.0\")),\n            (Decimal(\"-1.000001\"), Decimal(\"-1.0\")),\n        ]\n        for a, x in within_1e6:\n            assert a == approx(x)\n            assert a == approx(x, rel=Decimal(\"5e-6\"), abs=0)\n            assert a != approx(x, rel=Decimal(\"5e-7\"), abs=0)\n            assert approx(x, rel=Decimal(\"5e-6\"), abs=0) == a\n            assert approx(x, rel=Decimal(\"5e-7\"), abs=0) != a\n\n    def test_fraction(self):\n        within_1e6 = [\n            (1 + Fraction(1, 1000000), Fraction(1)),\n            (-1 - Fraction(-1, 1000000), Fraction(-1)),\n        ]\n        for a, x in within_1e6:\n            assert a == approx(x, rel=5e-6, abs=0)\n            assert a != approx(x, rel=5e-7, abs=0)\n            assert approx(x, rel=5e-6, abs=0) == a\n            assert approx(x, rel=5e-7, abs=0) != a\n\n    def test_complex(self):\n        within_1e6 = [\n            (1.000001 + 1.0j, 1.0 + 1.0j),\n            (1.0 + 1.000001j, 1.0 + 1.0j),\n            (-1.000001 + 1.0j, -1.0 + 1.0j),\n            (1.0 - 1.000001j, 1.0 - 1.0j),\n        ]\n        for a, x in within_1e6:\n            assert a == approx(x, rel=5e-6, abs=0)\n            assert a != approx(x, rel=5e-7, abs=0)\n            assert approx(x, rel=5e-6, abs=0) == a\n            assert approx(x, rel=5e-7, abs=0) != a\n\n    def test_expecting_bool(self) -> None:\n        assert True == approx(True)  # noqa: E712\n        assert False == approx(False)  # noqa: E712\n        assert True != approx(False)  # noqa: E712\n        assert True != approx(False, abs=2)  # noqa: E712\n        assert 1 != approx(True)\n\n    def test_expecting_bool_numpy(self) -> None:\n        \"\"\"Check approx comparing with numpy.bool (#13047).\"\"\"\n        np = pytest.importorskip(\"numpy\")\n        assert np.False_ != approx(True)\n        assert np.True_ != approx(False)\n        assert np.True_ == approx(True)\n        assert np.False_ == approx(False)\n        assert np.True_ != approx(False, abs=2)\n\n    def test_list(self):\n        actual = [1 + 1e-7, 2 + 1e-8]\n        expected = [1, 2]\n\n        # Return false if any element is outside the tolerance.\n        assert actual == approx(expected, rel=5e-7, abs=0)\n        assert actual != approx(expected, rel=5e-8, abs=0)\n        assert approx(expected, rel=5e-7, abs=0) == actual\n        assert approx(expected, rel=5e-8, abs=0) != actual\n\n    def test_list_decimal(self):\n        actual = [Decimal(\"1.000001\"), Decimal(\"2.000001\")]\n        expected = [Decimal(\"1\"), Decimal(\"2\")]\n\n        assert actual == approx(expected)\n\n    def test_list_wrong_len(self):\n        assert [1, 2] != approx([1])\n        assert [1, 2] != approx([1, 2, 3])\n\n    def test_tuple(self):\n        actual = (1 + 1e-7, 2 + 1e-8)\n        expected = (1, 2)\n\n        # Return false if any element is outside the tolerance.\n        assert actual == approx(expected, rel=5e-7, abs=0)\n        assert actual != approx(expected, rel=5e-8, abs=0)\n        assert approx(expected, rel=5e-7, abs=0) == actual\n        assert approx(expected, rel=5e-8, abs=0) != actual\n\n    def test_tuple_wrong_len(self):\n        assert (1, 2) != approx((1,))\n        assert (1, 2) != approx((1, 2, 3))\n\n    def test_tuple_vs_other(self):\n        assert 1 != approx((1,))\n\n    def test_dict(self):\n        actual = {\"a\": 1 + 1e-7, \"b\": 2 + 1e-8}\n        # Dictionaries became ordered in python3.6, so switch up the order here\n        # to make sure it doesn't matter.\n        expected = {\"b\": 2, \"a\": 1}\n\n        # Return false if any element is outside the tolerance.\n        assert actual == approx(expected, rel=5e-7, abs=0)\n        assert actual != approx(expected, rel=5e-8, abs=0)\n        assert approx(expected, rel=5e-7, abs=0) == actual\n        assert approx(expected, rel=5e-8, abs=0) != actual\n\n    def test_dict_decimal(self):\n        actual = {\"a\": Decimal(\"1.000001\"), \"b\": Decimal(\"2.000001\")}\n        # Dictionaries became ordered in python3.6, so switch up the order here\n        # to make sure it doesn't matter.\n        expected = {\"b\": Decimal(\"2\"), \"a\": Decimal(\"1\")}\n\n        assert actual == approx(expected)\n\n    def test_dict_wrong_len(self):\n        assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1})\n        assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1, \"c\": 2})\n        assert {\"a\": 1, \"b\": 2} != approx({\"a\": 1, \"b\": 2, \"c\": 3})\n\n    def test_dict_nonnumeric(self):\n        assert {\"a\": 1.0, \"b\": None} == pytest.approx({\"a\": 1.0, \"b\": None})\n        assert {\"a\": 1.0, \"b\": 1} != pytest.approx({\"a\": 1.0, \"b\": None})\n        assert {\"a\": 1.0, \"b\": True} != pytest.approx({\"a\": 1.0, \"b\": False}, abs=2)\n\n    def test_dict_vs_other(self):\n        assert 1 != approx({\"a\": 0})\n\n    def test_dict_for_div_by_zero(self, assert_approx_raises_regex):\n        assert_approx_raises_regex(\n            {\"foo\": 42.0},\n            {\"foo\": 0.0},\n            [\n                r\"\",\n                r\"  comparison failed. Mismatched elements: 1 / 1:\",\n                rf\"  Max absolute difference: {SOME_FLOAT}\",\n                r\"  Max relative difference: inf\",\n                r\"  Index \\| Obtained\\s+\\| Expected   \",\n                rf\"  foo   | {SOME_FLOAT} \\| {SOME_FLOAT} ± {SOME_FLOAT}\",\n            ],\n        )\n\n    def test_dict_differing_lengths(self, assert_approx_raises_regex):\n        assert_approx_raises_regex(\n            {\"a\": 0},\n            {\"a\": 0, \"b\": 1},\n            [\n                \"  \",\n                r\"  Impossible to compare mappings with different sizes\\.\",\n                r\"  Lengths: 2 and 1\",\n            ],\n        )\n\n    def test_numpy_array(self):\n        np = pytest.importorskip(\"numpy\")\n\n        actual = np.array([1 + 1e-7, 2 + 1e-8])\n        expected = np.array([1, 2])\n\n        # Return false if any element is outside the tolerance.\n        assert actual == approx(expected, rel=5e-7, abs=0)\n        assert actual != approx(expected, rel=5e-8, abs=0)\n        assert approx(expected, rel=5e-7, abs=0) == expected\n        assert approx(expected, rel=5e-8, abs=0) != actual\n\n        # Should be able to compare lists with numpy arrays.\n        assert list(actual) == approx(expected, rel=5e-7, abs=0)\n        assert list(actual) != approx(expected, rel=5e-8, abs=0)\n        assert actual == approx(list(expected), rel=5e-7, abs=0)\n        assert actual != approx(list(expected), rel=5e-8, abs=0)\n\n    def test_numpy_tolerance_args(self):\n        \"\"\"\n        Check that numpy rel/abs args are handled correctly\n        for comparison against an np.array\n        Check both sides of the operator, hopefully it doesn't impact things.\n        Test all permutations of where the approx and np.array() can show up\n        \"\"\"\n        np = pytest.importorskip(\"numpy\")\n        expected = 100.0\n        actual = 99.0\n        abs_diff = expected - actual\n        rel_diff = (expected - actual) / expected\n\n        tests = [\n            (eq, abs_diff, 0),\n            (eq, 0, rel_diff),\n            (ne, 0, rel_diff / 2.0),  # rel diff fail\n            (ne, abs_diff / 2.0, 0),  # abs diff fail\n        ]\n\n        for op, _abs, _rel in tests:\n            assert op(np.array(actual), approx(expected, abs=_abs, rel=_rel))  # a, b\n            assert op(approx(expected, abs=_abs, rel=_rel), np.array(actual))  # b, a\n\n            assert op(actual, approx(np.array(expected), abs=_abs, rel=_rel))  # a, b\n            assert op(approx(np.array(expected), abs=_abs, rel=_rel), actual)  # b, a\n\n            assert op(np.array(actual), approx(np.array(expected), abs=_abs, rel=_rel))\n            assert op(approx(np.array(expected), abs=_abs, rel=_rel), np.array(actual))\n\n    def test_numpy_expecting_nan(self):\n        np = pytest.importorskip(\"numpy\")\n        examples = [\n            (eq, nan, nan),\n            (eq, -nan, -nan),\n            (eq, nan, -nan),\n            (ne, 0.0, nan),\n            (ne, inf, nan),\n        ]\n        for op, a, x in examples:\n            # Nothing is equal to NaN by default.\n            assert np.array(a) != approx(x)\n            assert a != approx(np.array(x))\n\n            # If ``nan_ok=True``, then NaN is equal to NaN.\n            assert op(np.array(a), approx(x, nan_ok=True))\n            assert op(a, approx(np.array(x), nan_ok=True))\n\n    def test_numpy_expecting_inf(self):\n        np = pytest.importorskip(\"numpy\")\n        examples = [\n            (eq, inf, inf),\n            (eq, -inf, -inf),\n            (ne, inf, -inf),\n            (ne, 0.0, inf),\n            (ne, nan, inf),\n        ]\n        for op, a, x in examples:\n            assert op(np.array(a), approx(x))\n            assert op(a, approx(np.array(x)))\n            assert op(np.array(a), approx(np.array(x)))\n\n    def test_numpy_array_wrong_shape(self):\n        np = pytest.importorskip(\"numpy\")\n\n        a12 = np.array([[1, 2]])\n        a21 = np.array([[1], [2]])\n\n        assert a12 != approx(a21)\n        assert a21 != approx(a12)\n\n    def test_numpy_array_implicit_conversion(self):\n        np = pytest.importorskip(\"numpy\")\n\n        class ImplicitArray:\n            \"\"\"Type which is implicitly convertible to a numpy array.\"\"\"\n\n            def __init__(self, vals):\n                self.vals = vals\n\n            def __array__(self, dtype=None, copy=None):\n                return np.array(self.vals)\n\n        vec1 = ImplicitArray([1.0, 2.0, 3.0])\n        vec2 = ImplicitArray([1.0, 2.0, 4.0])\n        # see issue #12114 for test case\n        assert vec1 != approx(vec2)\n\n    def test_numpy_array_protocol(self):\n        \"\"\"\n        array-like objects such as tensorflow's DeviceArray are handled like ndarray.\n        See issue #8132\n        \"\"\"\n        np = pytest.importorskip(\"numpy\")\n\n        class DeviceArray:\n            def __init__(self, value, size):\n                self.value = value\n                self.size = size\n\n            def __array__(self):\n                return self.value * np.ones(self.size)\n\n        class DeviceScalar:\n            def __init__(self, value):\n                self.value = value\n\n            def __array__(self):\n                return np.array(self.value)\n\n        expected = 1\n        actual = 1 + 1e-6\n        assert approx(expected) == DeviceArray(actual, size=1)\n        assert approx(expected) == DeviceArray(actual, size=2)\n        assert approx(expected) == DeviceScalar(actual)\n        assert approx(DeviceScalar(expected)) == actual\n        assert approx(DeviceScalar(expected)) == DeviceScalar(actual)\n\n    def test_doctests(self, mocked_doctest_runner) -> None:\n        import doctest\n\n        parser = doctest.DocTestParser()\n        assert approx.__doc__ is not None\n        test = parser.get_doctest(\n            approx.__doc__, {\"approx\": approx}, approx.__name__, None, None\n        )\n        mocked_doctest_runner.run(test)\n\n    def test_unicode_plus_minus(self, pytester: Pytester) -> None:\n        \"\"\"\n        Comparing approx instances inside lists should not produce an error in the detailed diff.\n        Integration test for issue #2111.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_foo():\n                assert [3] == [pytest.approx(4)]\n        \"\"\"\n        )\n        expected = \"4.0e-06\"\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [f\"*At index 0 diff: 3 != 4 ± {expected}\", \"=* 1 failed in *=\"]\n        )\n\n    @pytest.mark.parametrize(\n        \"x, name\",\n        [\n            pytest.param([[1]], \"data structures\", id=\"nested-list\"),\n            pytest.param({\"key\": {\"key\": 1}}, \"dictionaries\", id=\"nested-dict\"),\n        ],\n    )\n    def test_expected_value_type_error(self, x, name):\n        with pytest.raises(\n            TypeError,\n            match=rf\"pytest.approx\\(\\) does not support nested {name}:\",\n        ):\n            approx(x)\n\n    @pytest.mark.parametrize(\n        \"x\",\n        [\n            pytest.param(None),\n            pytest.param(\"string\"),\n            pytest.param([\"string\"], id=\"nested-str\"),\n            pytest.param({\"key\": \"string\"}, id=\"dict-with-string\"),\n        ],\n    )\n    def test_nonnumeric_okay_if_equal(self, x):\n        assert x == approx(x)\n\n    @pytest.mark.parametrize(\n        \"x\",\n        [\n            pytest.param(\"string\"),\n            pytest.param([\"string\"], id=\"nested-str\"),\n            pytest.param({\"key\": \"string\"}, id=\"dict-with-string\"),\n        ],\n    )\n    def test_nonnumeric_false_if_unequal(self, x):\n        \"\"\"For non-numeric types, x != pytest.approx(y) reduces to x != y\"\"\"\n        assert \"ab\" != approx(\"abc\")\n        assert [\"ab\"] != approx([\"abc\"])\n        # in particular, both of these should return False\n        assert {\"a\": 1.0} != approx({\"a\": None})\n        assert {\"a\": None} != approx({\"a\": 1.0})\n\n        assert 1.0 != approx(None)\n        assert None != approx(1.0)  # noqa: E711\n\n        assert 1.0 != approx([None])\n        assert None != approx([1.0])  # noqa: E711\n\n    def test_nonnumeric_dict_repr(self):\n        \"\"\"Dicts with non-numerics and infinites have no tolerances\"\"\"\n        x1 = {\"foo\": 1.0000005, \"bar\": None, \"foobar\": inf}\n        assert (\n            repr(approx(x1))\n            == \"approx({'foo': 1.0000005 ± 1.0e-06, 'bar': None, 'foobar': inf})\"\n        )\n\n    def test_nonnumeric_list_repr(self):\n        \"\"\"Lists with non-numerics and infinites have no tolerances\"\"\"\n        x1 = [1.0000005, None, inf]\n        assert repr(approx(x1)) == \"approx([1.0000005 ± 1.0e-06, None, inf])\"\n\n    @pytest.mark.parametrize(\n        \"op\",\n        [\n            pytest.param(operator.le, id=\"<=\"),\n            pytest.param(operator.lt, id=\"<\"),\n            pytest.param(operator.ge, id=\">=\"),\n            pytest.param(operator.gt, id=\">\"),\n        ],\n    )\n    def test_comparison_operator_type_error(self, op):\n        \"\"\"pytest.approx should raise TypeError for operators other than == and != (#2003).\"\"\"\n        with pytest.raises(TypeError):\n            op(1, approx(1, rel=1e-6, abs=1e-12))\n\n    def test_numpy_array_with_scalar(self):\n        np = pytest.importorskip(\"numpy\")\n\n        actual = np.array([1 + 1e-7, 1 - 1e-8])\n        expected = 1.0\n\n        assert actual == approx(expected, rel=5e-7, abs=0)\n        assert actual != approx(expected, rel=5e-8, abs=0)\n        assert approx(expected, rel=5e-7, abs=0) == actual\n        assert approx(expected, rel=5e-8, abs=0) != actual\n\n    def test_numpy_scalar_with_array(self):\n        np = pytest.importorskip(\"numpy\")\n\n        actual = 1.0\n        expected = np.array([1 + 1e-7, 1 - 1e-8])\n\n        assert actual == approx(expected, rel=5e-7, abs=0)\n        assert actual != approx(expected, rel=5e-8, abs=0)\n        assert approx(expected, rel=5e-7, abs=0) == actual\n        assert approx(expected, rel=5e-8, abs=0) != actual\n\n    def test_generic_ordered_sequence(self):\n        class MySequence:\n            def __getitem__(self, i):\n                return [1, 2, 3, 4][i]\n\n            def __len__(self):\n                return 4\n\n        expected = MySequence()\n        assert [1, 2, 3, 4] == approx(expected, abs=1e-4)\n\n        expected_repr = \"approx([1 ± 1.0e-06, 2 ± 2.0e-06, 3 ± 3.0e-06, 4 ± 4.0e-06])\"\n        assert repr(approx(expected)) == expected_repr\n\n    def test_decimal_approx_repr(self, monkeypatch) -> None:\n        monkeypatch.setitem(decimal.getcontext().traps, decimal.FloatOperation, True)\n        approx_obj = pytest.approx(decimal.Decimal(\"2.60\"))\n        assert decimal.Decimal(\"2.600001\") == approx_obj\n\n    def test_allow_ordered_sequences_only(self) -> None:\n        \"\"\"pytest.approx() should raise an error on unordered sequences (#9692).\"\"\"\n        with pytest.raises(TypeError, match=\"only supports ordered sequences\"):\n            assert {1, 2, 3} == approx({1, 2, 3})\n\n    def test_strange_sequence(self):\n        \"\"\"https://github.com/pytest-dev/pytest/issues/11797\"\"\"\n        a = MyVec3(1, 2, 3)\n        b = MyVec3(0, 1, 2)\n\n        # this would trigger the error inside the test\n        pytest.approx(a, abs=0.5)._repr_compare(b)\n\n        assert b == pytest.approx(a, abs=2)\n        assert b != pytest.approx(a, abs=0.5)\n\n    def test_approx_dicts_with_mismatch_on_keys(self) -> None:\n        \"\"\"https://github.com/pytest-dev/pytest/issues/13816\"\"\"\n        expected = {\"a\": 1, \"b\": 3}\n        actual = {\"a\": 1, \"c\": 3}\n\n        with pytest.raises(\n            AssertionError,\n            match=re.escape(\n                \"comparison failed.\\n  Mappings has different keys: \"\n                \"expected dict_keys(['a', 'b']) but got dict_keys(['a', 'c'])\"\n            ),\n        ):\n            assert actual == approx(expected)\n\n    def test_approx_on_unordered_mapping_with_mismatch(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"https://github.com/pytest-dev/pytest/issues/12444\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def test_approx_on_unordered_mapping_with_mismatch():\n                expected = {\"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4}\n                actual = {\"d\": 4, \"c\": 5, \"a\": 8, \"b\": 2}\n                assert actual == pytest.approx(expected)\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(failed=1)\n        result.stdout.fnmatch_lines(\n            [\n                \"*comparison failed.**Mismatched elements: 2 / 4:*\",\n                \"*Max absolute difference: 7*\",\n                \"*Index | Obtained | Expected *\",\n                \"* a * | 8 * | 1 *\",\n                \"* c * | 5 * | 3 *\",\n            ]\n        )\n\n    def test_approx_on_unordered_mapping_matching(self, pytester: Pytester) -> None:\n        \"\"\"https://github.com/pytest-dev/pytest/issues/12444\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_approx_on_unordered_mapping_matching():\n                expected = {\"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4}\n                actual = {\"d\": 4, \"c\": 3, \"a\": 1, \"b\": 2}\n                assert actual == pytest.approx(expected)\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(passed=1)\n\n\nclass MyVec3:  # incomplete\n    \"\"\"sequence like\"\"\"\n\n    _x: int\n    _y: int\n    _z: int\n\n    def __init__(self, x: int, y: int, z: int):\n        self._x, self._y, self._z = x, y, z\n\n    def __repr__(self) -> str:\n        return f\"<MyVec3 {self._x} {self._y} {self._z}>\"\n\n    def __len__(self) -> int:\n        return 3\n\n    def __getitem__(self, key: int) -> int:\n        if key == 0:\n            return self._x\n        if key == 1:\n            return self._y\n        if key == 2:\n            return self._z\n        raise IndexError(key)\n\n\nclass TestRecursiveSequenceMap:\n    def test_map_over_scalar(self):\n        assert _recursive_sequence_map(sqrt, 16) == 4\n\n    def test_map_over_empty_list(self):\n        assert _recursive_sequence_map(sqrt, []) == []\n\n    def test_map_over_list(self):\n        assert _recursive_sequence_map(sqrt, [4, 16, 25, 676]) == [2, 4, 5, 26]\n\n    def test_map_over_tuple(self):\n        assert _recursive_sequence_map(sqrt, (4, 16, 25, 676)) == (2, 4, 5, 26)\n\n    def test_map_over_nested_lists(self):\n        assert _recursive_sequence_map(sqrt, [4, [25, 64], [[49]]]) == [\n            2,\n            [5, 8],\n            [[7]],\n        ]\n\n    def test_map_over_mixed_sequence(self):\n        assert _recursive_sequence_map(sqrt, [4, (25, 64), [49]]) == [\n            2,\n            (5, 8),\n            [7],\n        ]\n\n    def test_map_over_sequence_like(self):\n        assert _recursive_sequence_map(int, MyVec3(1, 2, 3)) == [1, 2, 3]\n"
  },
  {
    "path": "testing/python/collect.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport os\nimport sys\nimport textwrap\nfrom typing import Any\n\nimport _pytest._code\nfrom _pytest.config import ExitCode\nfrom _pytest.main import Session\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.nodes import Collector\nfrom _pytest.pytester import Pytester\nfrom _pytest.python import Class\nfrom _pytest.python import Function\nimport pytest\n\n\nclass TestModule:\n    def test_failing_import(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\"import alksdjalskdjalkjals\")\n        pytest.raises(Collector.CollectError, modcol.collect)\n\n    def test_import_duplicate(self, pytester: Pytester) -> None:\n        a = pytester.mkdir(\"a\")\n        b = pytester.mkdir(\"b\")\n        p1 = a.joinpath(\"test_whatever.py\")\n        p1.touch()\n        p2 = b.joinpath(\"test_whatever.py\")\n        p2.touch()\n        # ensure we don't have it imported already\n        sys.modules.pop(p1.stem, None)\n\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*import*mismatch*\",\n                \"*imported*test_whatever*\",\n                f\"*{p1}*\",\n                \"*not the same*\",\n                f\"*{p2}*\",\n                \"*HINT*\",\n            ]\n        )\n\n    def test_import_prepend_append(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        root1 = pytester.mkdir(\"root1\")\n        root2 = pytester.mkdir(\"root2\")\n        root1.joinpath(\"x456.py\").touch()\n        root2.joinpath(\"x456.py\").touch()\n        p = root2.joinpath(\"test_x456.py\")\n        monkeypatch.syspath_prepend(str(root1))\n        p.write_text(\n            textwrap.dedent(\n                f\"\"\"\\\n                import x456\n                def test():\n                    assert x456.__file__.startswith({str(root2)!r})\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        with monkeypatch.context() as mp:\n            mp.chdir(root2)\n            reprec = pytester.inline_run(\"--import-mode=append\")\n            reprec.assertoutcome(passed=0, failed=1)\n            reprec = pytester.inline_run()\n            reprec.assertoutcome(passed=1)\n\n    def test_syntax_error_in_module(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\"this is a syntax error\")\n        pytest.raises(modcol.CollectError, modcol.collect)\n        pytest.raises(modcol.CollectError, modcol.collect)\n\n    def test_module_considers_pluginmanager_at_import(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\"pytest_plugins='xasdlkj',\")\n        pytest.raises(ImportError, lambda: modcol.obj)\n\n    def test_invalid_test_module_name(self, pytester: Pytester) -> None:\n        a = pytester.mkdir(\"a\")\n        a.joinpath(\"test_one.part1.py\").touch()\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"ImportError while importing test module*test_one.part1*\",\n                \"Hint: make sure your test modules/packages have valid Python names.\",\n            ]\n        )\n\n    @pytest.mark.parametrize(\"verbose\", [0, 1, 2])\n    def test_show_traceback_import_error(\n        self, pytester: Pytester, verbose: int\n    ) -> None:\n        \"\"\"Import errors when collecting modules should display the traceback (#1976).\n\n        With low verbosity we omit pytest and internal modules, otherwise show all traceback entries.\n        \"\"\"\n        pytester.makepyfile(\n            foo_traceback_import_error=\"\"\"\n               from bar_traceback_import_error import NOT_AVAILABLE\n           \"\"\",\n            bar_traceback_import_error=\"\",\n        )\n        pytester.makepyfile(\n            \"\"\"\n               import foo_traceback_import_error\n        \"\"\"\n        )\n        args = (\"-v\",) * verbose\n        result = pytester.runpytest(*args)\n        result.stdout.fnmatch_lines(\n            [\n                \"ImportError while importing test module*\",\n                \"Traceback:\",\n                \"*from bar_traceback_import_error import NOT_AVAILABLE\",\n                \"*cannot import name *NOT_AVAILABLE*\",\n            ]\n        )\n        assert result.ret == 2\n\n        stdout = result.stdout.str()\n        if verbose == 2:\n            assert \"_pytest\" in stdout\n        else:\n            assert \"_pytest\" not in stdout\n\n    def test_show_traceback_import_error_unicode(self, pytester: Pytester) -> None:\n        \"\"\"Check test modules collected which raise ImportError with unicode messages\n        are handled properly (#2336).\n        \"\"\"\n        pytester.makepyfile(\"raise ImportError('Something bad happened ☺')\")\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"ImportError while importing test module*\",\n                \"Traceback:\",\n                \"*raise ImportError*Something bad happened*\",\n            ]\n        )\n        assert result.ret == 2\n\n\nclass TestClass:\n    def test_class_with_init_warning(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            class TestClass1(object):\n                def __init__(self):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*cannot collect test class 'TestClass1' because it has \"\n                \"a __init__ constructor (from: test_class_with_init_warning.py)\"\n            ]\n        )\n\n    def test_class_with_new_warning(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            class TestClass1(object):\n                def __new__(self):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*cannot collect test class 'TestClass1' because it has \"\n                \"a __new__ constructor (from: test_class_with_new_warning.py)\"\n            ]\n        )\n\n    def test_class_subclassobject(self, pytester: Pytester) -> None:\n        pytester.getmodulecol(\n            \"\"\"\n            class test(object):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*collected 0*\"])\n\n    def test_static_method(self, pytester: Pytester) -> None:\n        \"\"\"Support for collecting staticmethod tests (#2528, #2699)\"\"\"\n        pytester.getmodulecol(\n            \"\"\"\n            import pytest\n            class Test(object):\n                @staticmethod\n                def test_something():\n                    pass\n\n                @pytest.fixture\n                def fix(self):\n                    return 1\n\n                @staticmethod\n                def test_fix(fix):\n                    assert fix == 1\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*collected 2 items*\", \"*2 passed in*\"])\n\n    def test_setup_teardown_class_as_classmethod(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_mod1=\"\"\"\n            class TestClassMethod(object):\n                @classmethod\n                def setup_class(cls):\n                    pass\n                def test_1(self):\n                    pass\n                @classmethod\n                def teardown_class(cls):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_issue1035_obj_has_getattr(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            class Chameleon(object):\n                def __getattr__(self, name):\n                    return True\n            chameleon = Chameleon()\n        \"\"\"\n        )\n        colitems = modcol.collect()\n        assert len(colitems) == 0\n\n    def test_issue1579_namedtuple(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import collections\n\n            TestCase = collections.namedtuple('TestCase', ['a'])\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            \"*cannot collect test class 'TestCase' \"\n            \"because it has a __new__ constructor*\"\n        )\n\n    def test_issue2234_property(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            class TestCase(object):\n                @property\n                def prop(self):\n                    raise NotImplementedError()\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n    def test_does_not_discover_properties(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #12446.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\\\n            class TestCase:\n                @property\n                def oops(self):\n                    raise SystemExit('do not call me!')\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n    def test_does_not_discover_instance_descriptors(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #12446.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\\\n            # not `@property`, but it acts like one\n            # this should cover the case of things like `@cached_property` / etc.\n            class MyProperty:\n                def __init__(self, func):\n                    self._func = func\n                def __get__(self, inst, owner):\n                    if inst is None:\n                        return self\n                    else:\n                        return self._func.__get__(inst, owner)()\n\n            class TestCase:\n                @MyProperty\n                def oops(self):\n                    raise SystemExit('do not call me!')\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n    def test_abstract_class_is_not_collected(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #12275 (non-unittest version).\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import abc\n\n            class TestBase(abc.ABC):\n                @abc.abstractmethod\n                def abstract1(self): pass\n\n                @abc.abstractmethod\n                def abstract2(self): pass\n\n                def test_it(self): pass\n\n            class TestPartial(TestBase):\n                def abstract1(self): pass\n\n            class TestConcrete(TestPartial):\n                def abstract2(self): pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.OK\n        result.assert_outcomes(passed=1)\n\n\nclass TestFunction:\n    def test_getmodulecollector(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\"def test_func(): pass\")\n        modcol = item.getparent(pytest.Module)\n        assert isinstance(modcol, pytest.Module)\n        assert hasattr(modcol.obj, \"test_func\")\n\n    @pytest.mark.filterwarnings(\"default\")\n    def test_function_as_object_instance_ignored(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            class A(object):\n                def __call__(self, tmp_path):\n                    0/0\n\n            test_a = A()\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 0 items\",\n                \"*test_function_as_object_instance_ignored.py:2: \"\n                \"*cannot collect 'test_a' because it is not a function.\",\n            ]\n        )\n\n    @staticmethod\n    def make_function(pytester: Pytester, **kwargs: Any) -> Any:\n        from _pytest.fixtures import FixtureManager\n\n        config = pytester.parseconfigure()\n        session = Session.from_config(config)\n        session._fixturemanager = FixtureManager(session)\n\n        return pytest.Function.from_parent(parent=session, **kwargs)\n\n    def test_function_equality(self, pytester: Pytester) -> None:\n        def func1():\n            pass\n\n        def func2():\n            pass\n\n        f1 = self.make_function(pytester, name=\"name\", callobj=func1)\n        assert f1 == f1\n        f2 = self.make_function(\n            pytester, name=\"name\", callobj=func2, originalname=\"foobar\"\n        )\n        assert f1 != f2\n\n    def test_repr_produces_actual_test_id(self, pytester: Pytester) -> None:\n        f = self.make_function(\n            pytester, name=r\"test[\\xe5]\", callobj=self.test_repr_produces_actual_test_id\n        )\n        assert repr(f) == r\"<Function test[\\xe5]>\"\n\n    def test_issue197_parametrize_emptyset(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.parametrize('arg', [])\n            def test_function(arg):\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(skipped=1)\n\n    def test_single_tuple_unwraps_values(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.parametrize(('arg',), [(1,)])\n            def test_function(arg):\n                assert arg == 1\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_issue213_parametrize_value_no_equal(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            class A(object):\n                def __eq__(self, other):\n                    raise ValueError(\"not possible\")\n            @pytest.mark.parametrize('arg', [A()])\n            def test_function(arg):\n                assert arg.__class__.__name__ == \"A\"\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"--fulltrace\")\n        reprec.assertoutcome(passed=1)\n\n    def test_parametrize_with_non_hashable_values(self, pytester: Pytester) -> None:\n        \"\"\"Test parametrization with non-hashable values.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            archival_mapping = {\n                '1.0': {'tag': '1.0'},\n                '1.2.2a1': {'tag': 'release-1.2.2a1'},\n            }\n\n            import pytest\n            @pytest.mark.parametrize('key value'.split(),\n                                     archival_mapping.items())\n            def test_archival_to_version(key, value):\n                assert key in archival_mapping\n                assert value == archival_mapping[key]\n        \"\"\"\n        )\n        rec = pytester.inline_run()\n        rec.assertoutcome(passed=2)\n\n    def test_parametrize_with_non_hashable_values_indirect(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test parametrization with non-hashable values with indirect parametrization.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            archival_mapping = {\n                '1.0': {'tag': '1.0'},\n                '1.2.2a1': {'tag': 'release-1.2.2a1'},\n            }\n\n            import pytest\n\n            @pytest.fixture\n            def key(request):\n                return request.param\n\n            @pytest.fixture\n            def value(request):\n                return request.param\n\n            @pytest.mark.parametrize('key value'.split(),\n                                     archival_mapping.items(), indirect=True)\n            def test_archival_to_version(key, value):\n                assert key in archival_mapping\n                assert value == archival_mapping[key]\n        \"\"\"\n        )\n        rec = pytester.inline_run()\n        rec.assertoutcome(passed=2)\n\n    def test_parametrize_overrides_fixture(self, pytester: Pytester) -> None:\n        \"\"\"Test parametrization when parameter overrides existing fixture with same name.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def value():\n                return 'value'\n\n            @pytest.mark.parametrize('value',\n                                     ['overridden'])\n            def test_overridden_via_param(value):\n                assert value == 'overridden'\n\n            @pytest.mark.parametrize('somevalue', ['overridden'])\n            def test_not_overridden(value, somevalue):\n                assert value == 'value'\n                assert somevalue == 'overridden'\n\n            @pytest.mark.parametrize('other,value', [('foo', 'overridden')])\n            def test_overridden_via_multiparam(other, value):\n                assert other == 'foo'\n                assert value == 'overridden'\n        \"\"\"\n        )\n        rec = pytester.inline_run()\n        rec.assertoutcome(passed=3)\n\n    def test_parametrize_overrides_parametrized_fixture(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test parametrization when parameter overrides existing parametrized fixture with same name.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[1, 2])\n            def value(request):\n                return request.param\n\n            @pytest.mark.parametrize('value',\n                                     ['overridden'])\n            def test_overridden_via_param(value):\n                assert value == 'overridden'\n        \"\"\"\n        )\n        rec = pytester.inline_run()\n        rec.assertoutcome(passed=1)\n\n    def test_parametrize_overrides_parametrized_fixture_with_unrelated_indirect(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test parametrization when parameter overrides existing parametrized fixture with same name,\n        and there is an unrelated indirect param.\n\n        Regression test for #13974.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[\"a\", \"b\"])\n            def target(request):\n                return request.param\n\n            @pytest.fixture\n            def val(request):\n                return int(request.param)\n\n            @pytest.mark.parametrize(\n                [\"val\", \"target\"],\n                [\n                    (\"1\", 1),\n                    (\"2\", 2),\n                ],\n                indirect=[\"val\"],\n            )\n            def test(val, target):\n                assert val == target\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n        result.assert_outcomes(passed=2)\n\n    def test_parametrize_overrides_indirect_dependency_fixture(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test parametrization when parameter overrides a fixture that a test indirectly depends on\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            fix3_instantiated = False\n\n            @pytest.fixture\n            def fix1(fix2):\n               return fix2 + '1'\n\n            @pytest.fixture\n            def fix2(fix3):\n               return fix3 + '2'\n\n            @pytest.fixture\n            def fix3():\n               global fix3_instantiated\n               fix3_instantiated = True\n               return '3'\n\n            @pytest.mark.parametrize('fix2', ['2'])\n            def test_it(fix1):\n               assert fix1 == '21'\n               assert not fix3_instantiated\n        \"\"\"\n        )\n        rec = pytester.inline_run()\n        rec.assertoutcome(passed=1)\n\n    def test_parametrize_with_mark(self, pytester: Pytester) -> None:\n        items = pytester.getitems(\n            \"\"\"\n            import pytest\n            @pytest.mark.foo\n            @pytest.mark.parametrize('arg', [\n                1,\n                pytest.param(2, marks=[pytest.mark.baz, pytest.mark.bar])\n            ])\n            def test_function(arg):\n                pass\n        \"\"\"\n        )\n        keywords = [item.keywords for item in items]\n        assert (\n            \"foo\" in keywords[0]\n            and \"bar\" not in keywords[0]\n            and \"baz\" not in keywords[0]\n        )\n        assert \"foo\" in keywords[1] and \"bar\" in keywords[1] and \"baz\" in keywords[1]\n\n    def test_parametrize_with_empty_string_arguments(self, pytester: Pytester) -> None:\n        items = pytester.getitems(\n            \"\"\"\\\n            import pytest\n\n            @pytest.mark.parametrize('v', ('', ' '))\n            @pytest.mark.parametrize('w', ('', ' '))\n            def test(v, w): ...\n            \"\"\"\n        )\n        names = {item.name for item in items}\n        assert names == {\"test[-]\", \"test[ -]\", \"test[- ]\", \"test[ - ]\"}\n\n    def test_function_equality_with_callspec(self, pytester: Pytester) -> None:\n        items = pytester.getitems(\n            \"\"\"\n            import pytest\n            @pytest.mark.parametrize('arg', [1,2])\n            def test_function(arg):\n                pass\n        \"\"\"\n        )\n        assert items[0] != items[1]\n        assert not (items[0] == items[1])\n\n    def test_pyfunc_call(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\"def test_func(): raise ValueError\")\n        config = item.config\n\n        class MyPlugin1:\n            def pytest_pyfunc_call(self):\n                raise ValueError\n\n        class MyPlugin2:\n            def pytest_pyfunc_call(self):\n                return True\n\n        config.pluginmanager.register(MyPlugin1())\n        config.pluginmanager.register(MyPlugin2())\n        config.hook.pytest_runtest_setup(item=item)\n        config.hook.pytest_pyfunc_call(pyfuncitem=item)\n\n    def test_multiple_parametrize(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            import pytest\n            @pytest.mark.parametrize('x', [0, 1])\n            @pytest.mark.parametrize('y', [2, 3])\n            def test1(x, y):\n                pass\n        \"\"\"\n        )\n        colitems = modcol.collect()\n        assert colitems[0].name == \"test1[2-0]\"\n        assert colitems[1].name == \"test1[2-1]\"\n        assert colitems[2].name == \"test1[3-0]\"\n        assert colitems[3].name == \"test1[3-1]\"\n\n    def test_issue751_multiple_parametrize_with_ids(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            import pytest\n            @pytest.mark.parametrize('x', [0], ids=['c'])\n            @pytest.mark.parametrize('y', [0, 1], ids=['a', 'b'])\n            class Test(object):\n                def test1(self, x, y):\n                    pass\n                def test2(self, x, y):\n                    pass\n        \"\"\"\n        )\n        colitems = modcol.collect()[0].collect()\n        assert colitems[0].name == \"test1[a-c]\"\n        assert colitems[1].name == \"test1[b-c]\"\n        assert colitems[2].name == \"test2[a-c]\"\n        assert colitems[3].name == \"test2[b-c]\"\n\n    def test_parametrize_skipif(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            m = pytest.mark.skipif('True')\n\n            @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n            def test_skip_if(x):\n                assert x < 2\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 2 passed, 1 skipped in *\"])\n\n    def test_parametrize_skip(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            m = pytest.mark.skip('')\n\n            @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n            def test_skip(x):\n                assert x < 2\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 2 passed, 1 skipped in *\"])\n\n    def test_parametrize_skipif_no_skip(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            m = pytest.mark.skipif('False')\n\n            @pytest.mark.parametrize('x', [0, 1, m(2)])\n            def test_skipif_no_skip(x):\n                assert x < 2\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 1 failed, 2 passed in *\"])\n\n    def test_parametrize_xfail(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            m = pytest.mark.xfail('True')\n\n            @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n            def test_xfail(x):\n                assert x < 2\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 2 passed, 1 xfailed in *\"])\n\n    def test_parametrize_passed(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            m = pytest.mark.xfail('True')\n\n            @pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])\n            def test_xfail(x):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 2 passed, 1 xpassed in *\"])\n\n    def test_parametrize_xfail_passed(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            m = pytest.mark.xfail('False')\n\n            @pytest.mark.parametrize('x', [0, 1, m(2)])\n            def test_passed(x):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 3 passed in *\"])\n\n    def test_function_originalname(self, pytester: Pytester) -> None:\n        items = pytester.getitems(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize('arg', [1,2])\n            def test_func(arg):\n                pass\n\n            def test_no_param():\n                pass\n        \"\"\"\n        )\n        originalnames = []\n        for x in items:\n            assert isinstance(x, pytest.Function)\n            originalnames.append(x.originalname)\n        assert originalnames == [\n            \"test_func\",\n            \"test_func\",\n            \"test_no_param\",\n        ]\n\n    def test_function_with_square_brackets(self, pytester: Pytester) -> None:\n        \"\"\"Check that functions with square brackets don't cause trouble.\"\"\"\n        p1 = pytester.makepyfile(\n            \"\"\"\n            locals()[\"test_foo[name]\"] = lambda: None\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-v\", str(p1))\n        result.stdout.fnmatch_lines(\n            [\n                \"test_function_with_square_brackets.py::test_foo[[]name[]] PASSED *\",\n                \"*= 1 passed in *\",\n            ]\n        )\n\n\nclass TestSorting:\n    def test_check_equality(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            def test_pass(): pass\n            def test_fail(): assert 0\n        \"\"\"\n        )\n        fn1 = pytester.collect_by_name(modcol, \"test_pass\")\n        assert isinstance(fn1, pytest.Function)\n        fn2 = pytester.collect_by_name(modcol, \"test_pass\")\n        assert isinstance(fn2, pytest.Function)\n\n        assert fn1 == fn2\n        assert fn1 != modcol\n        assert hash(fn1) == hash(fn2)\n\n        fn3 = pytester.collect_by_name(modcol, \"test_fail\")\n        assert isinstance(fn3, pytest.Function)\n        assert not (fn1 == fn3)\n        assert fn1 != fn3\n\n        for fn in fn1, fn2, fn3:\n            assert fn != 3  # type: ignore[comparison-overlap]\n            assert fn != modcol\n            assert fn != [1, 2, 3]  # type: ignore[comparison-overlap]\n            assert [1, 2, 3] != fn  # type: ignore[comparison-overlap]\n            assert modcol != fn\n\n    def test_allow_sane_sorting_for_decorators(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            def dec(f):\n                g = lambda: f(2)\n                g.place_as = f\n                return g\n\n\n            def test_b(y):\n                pass\n            test_b = dec(test_b)\n\n            def test_a(y):\n                pass\n            test_a = dec(test_a)\n        \"\"\"\n        )\n        colitems = modcol.collect()\n        assert len(colitems) == 2\n        assert [item.name for item in colitems] == [\"test_b\", \"test_a\"]\n\n    def test_ordered_by_definition_order(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n            class Test1:\n                def test_foo(self): pass\n                def test_bar(self): pass\n            class Test2:\n                def test_foo(self): pass\n                test_bar = Test1.test_bar\n            class Test3(Test2):\n                def test_baz(self): pass\n            \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*Class Test1*\",\n                \"*Function test_foo*\",\n                \"*Function test_bar*\",\n                \"*Class Test2*\",\n                # previously the order was flipped due to Test1.test_bar reference\n                \"*Function test_foo*\",\n                \"*Function test_bar*\",\n                \"*Class Test3*\",\n                \"*Function test_foo*\",\n                \"*Function test_bar*\",\n                \"*Function test_baz*\",\n            ]\n        )\n\n\nclass TestConftestCustomization:\n    def test_pytest_pycollect_module(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            class MyModule(pytest.Module):\n                pass\n            def pytest_pycollect_makemodule(module_path, parent):\n                if module_path.name == \"test_xyz.py\":\n                    return MyModule.from_parent(path=module_path, parent=parent)\n        \"\"\"\n        )\n        pytester.makepyfile(\"def test_some(): pass\")\n        pytester.makepyfile(test_xyz=\"def test_func(): pass\")\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines([\"*<Module*test_pytest*\", \"*<MyModule*xyz*\"])\n\n    def test_customized_pymakemodule_issue205_subdir(self, pytester: Pytester) -> None:\n        b = pytester.path.joinpath(\"a\", \"b\")\n        b.mkdir(parents=True)\n        b.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n                @pytest.hookimpl(wrapper=True)\n                def pytest_pycollect_makemodule():\n                    mod = yield\n                    mod.obj.hello = \"world\"\n                    return mod\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        b.joinpath(\"test_module.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                def test_hello():\n                    assert hello == \"world\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_customized_pymakeitem(self, pytester: Pytester) -> None:\n        b = pytester.path.joinpath(\"a\", \"b\")\n        b.mkdir(parents=True)\n        b.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n                @pytest.hookimpl(wrapper=True)\n                def pytest_pycollect_makeitem():\n                    result = yield\n                    if result:\n                        for func in result:\n                            func._some123 = \"world\"\n                    return result\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        b.joinpath(\"test_module.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n\n                @pytest.fixture()\n                def obj(request):\n                    return request.node._some123\n                def test_hello(obj):\n                    assert obj == \"world\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_pytest_pycollect_makeitem(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            class MyFunction(pytest.Function):\n                pass\n            def pytest_pycollect_makeitem(collector, name, obj):\n                if name == \"some\":\n                    return MyFunction.from_parent(name=name, parent=collector)\n        \"\"\"\n        )\n        pytester.makepyfile(\"def some(): pass\")\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines([\"*MyFunction*some*\"])\n\n    def test_issue2369_collect_module_fileext(self, pytester: Pytester) -> None:\n        \"\"\"Ensure we can collect files with weird file extensions as Python\n        modules (#2369)\"\"\"\n        # Implement a little meta path finder to import files containing\n        # Python source code whose file extension is \".narf\".\n        pytester.makeconftest(\n            \"\"\"\n            import sys\n            import os.path\n            from importlib.util import spec_from_loader\n            from importlib.machinery import SourceFileLoader\n            from _pytest.python import Module\n\n            class MetaPathFinder:\n                def find_spec(self, fullname, path, target=None):\n                    if os.path.exists(fullname + \".narf\"):\n                        return spec_from_loader(\n                            fullname,\n                            SourceFileLoader(fullname, fullname + \".narf\"),\n                        )\n            sys.meta_path.append(MetaPathFinder())\n\n            def pytest_collect_file(file_path, parent):\n                if file_path.suffix == \".narf\":\n                    return Module.from_parent(path=file_path, parent=parent)\n            \"\"\"\n        )\n        pytester.makefile(\n            \".narf\",\n            \"\"\"\\\n            def test_something():\n                assert 1 + 1 == 2\"\"\",\n        )\n        # Use runpytest_subprocess, since we're futzing with sys.meta_path.\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_early_ignored_attributes(self, pytester: Pytester) -> None:\n        \"\"\"Builtin attributes should be ignored early on, even if\n        configuration would otherwise allow them.\n\n        This tests a performance optimization, not correctness, really,\n        although it tests PytestCollectionWarning is not raised, while\n        it would have been raised otherwise.\n        \"\"\"\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            python_classes=*\n            python_functions=*\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            class TestEmpty:\n                pass\n            test_empty = TestEmpty()\n            def test_real():\n                pass\n        \"\"\"\n        )\n        items, rec = pytester.inline_genitems()\n        assert rec.ret == 0\n        assert len(items) == 1\n\n\ndef test_setup_only_available_in_subdir(pytester: Pytester) -> None:\n    sub1 = pytester.mkpydir(\"sub1\")\n    sub2 = pytester.mkpydir(\"sub2\")\n    sub1.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            import pytest\n            def pytest_runtest_setup(item):\n                assert item.path.stem == \"test_in_sub1\"\n            def pytest_runtest_call(item):\n                assert item.path.stem == \"test_in_sub1\"\n            def pytest_runtest_teardown(item):\n                assert item.path.stem == \"test_in_sub1\"\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    sub2.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            import pytest\n            def pytest_runtest_setup(item):\n                assert item.path.stem == \"test_in_sub2\"\n            def pytest_runtest_call(item):\n                assert item.path.stem == \"test_in_sub2\"\n            def pytest_runtest_teardown(item):\n                assert item.path.stem == \"test_in_sub2\"\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    sub1.joinpath(\"test_in_sub1.py\").write_text(\"def test_1(): pass\", encoding=\"utf-8\")\n    sub2.joinpath(\"test_in_sub2.py\").write_text(\"def test_2(): pass\", encoding=\"utf-8\")\n    result = pytester.runpytest(\"-v\", \"-s\")\n    result.assert_outcomes(passed=2)\n\n\ndef test_modulecol_roundtrip(pytester: Pytester) -> None:\n    modcol = pytester.getmodulecol(\"pass\", withinit=False)\n    trail = modcol.nodeid\n    newcol = modcol.session.perform_collect([trail], genitems=0)[0]\n    assert modcol.name == newcol.name\n\n\nclass TestTracebackCutting:\n    def test_skip_simple(self):\n        with pytest.raises(pytest.skip.Exception) as excinfo:\n            pytest.skip(\"xxx\")\n        if sys.version_info >= (3, 11):\n            assert excinfo.traceback[-1].frame.code.raw.co_qualname == \"_Skip.__call__\"\n        assert excinfo.traceback[-1].ishidden(excinfo)\n        assert excinfo.traceback[-2].frame.code.name == \"test_skip_simple\"\n        assert not excinfo.traceback[-2].ishidden(excinfo)\n\n    def test_traceback_argsetup(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def hello(request):\n                raise ValueError(\"xyz\")\n        \"\"\"\n        )\n        p = pytester.makepyfile(\"def test(hello): pass\")\n        result = pytester.runpytest(p)\n        assert result.ret != 0\n        out = result.stdout.str()\n        assert \"xyz\" in out\n        assert \"conftest.py:5: ValueError\" in out\n        numentries = out.count(\"_ _ _\")  # separator for traceback entries\n        assert numentries == 0\n\n        result = pytester.runpytest(\"--fulltrace\", p)\n        out = result.stdout.str()\n        assert \"conftest.py:5: ValueError\" in out\n        numentries = out.count(\"_ _ _ _\")  # separator for traceback entries\n        assert numentries > 3\n\n    def test_traceback_error_during_import(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            x = 1\n            x = 2\n            x = 17\n            asd\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret != 0\n        out = result.stdout.str()\n        assert \"x = 1\" not in out\n        assert \"x = 2\" not in out\n        result.stdout.fnmatch_lines([\" *asd*\", \"E*NameError*\"])\n        result = pytester.runpytest(\"--fulltrace\")\n        out = result.stdout.str()\n        assert \"x = 1\" in out\n        assert \"x = 2\" in out\n        result.stdout.fnmatch_lines([\">*asd*\", \"E*NameError*\"])\n\n    def test_traceback_filter_error_during_fixture_collection(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Integration test for issue #995.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def fail_me(func):\n                ns = {}\n                exec('def w(): raise ValueError(\"fail me\")', ns)\n                return ns['w']\n\n            @pytest.fixture(scope='class')\n            @fail_me\n            def fail_fixture():\n                pass\n\n            def test_failing_fixture(fail_fixture):\n               pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret != 0\n        out = result.stdout.str()\n        assert \"INTERNALERROR>\" not in out\n        result.stdout.fnmatch_lines([\"*ValueError: fail me*\", \"* 1 error in *\"])\n\n    def test_filter_traceback_generated_code(self) -> None:\n        \"\"\"Test that filter_traceback() works with the fact that\n        _pytest._code.code.Code.path attribute might return an str object.\n\n        In this case, one of the entries on the traceback was produced by\n        dynamically generated code.\n        See: https://bitbucket.org/pytest-dev/py/issues/71\n        This fixes #995.\n        \"\"\"\n        from _pytest._code import filter_traceback\n\n        tb = None\n        try:\n            ns: dict[str, Any] = {}\n            exec(\"def foo(): raise ValueError\", ns)\n            ns[\"foo\"]()\n        except ValueError:\n            _, _, tb = sys.exc_info()\n\n        assert tb is not None\n        traceback = _pytest._code.Traceback(tb)\n        assert isinstance(traceback[-1].path, str)\n        assert not filter_traceback(traceback[-1])\n\n    def test_filter_traceback_path_no_longer_valid(self, pytester: Pytester) -> None:\n        \"\"\"Test that filter_traceback() works with the fact that\n        _pytest._code.code.Code.path attribute might return an str object.\n\n        In this case, one of the files in the traceback no longer exists.\n        This fixes #1133.\n        \"\"\"\n        from _pytest._code import filter_traceback\n\n        pytester.syspathinsert()\n        pytester.makepyfile(\n            filter_traceback_entry_as_str=\"\"\"\n            def foo():\n                raise ValueError\n        \"\"\"\n        )\n        tb = None\n        try:\n            import filter_traceback_entry_as_str\n\n            filter_traceback_entry_as_str.foo()\n        except ValueError:\n            _, _, tb = sys.exc_info()\n\n        assert tb is not None\n        pytester.path.joinpath(\"filter_traceback_entry_as_str.py\").unlink()\n        traceback = _pytest._code.Traceback(tb)\n        assert isinstance(traceback[-1].path, str)\n        assert filter_traceback(traceback[-1])\n\n\nclass TestReportInfo:\n    def test_itemreport_reportinfo(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            class MyFunction(pytest.Function):\n                def reportinfo(self):\n                    return \"ABCDE\", 42, \"custom\"\n            def pytest_pycollect_makeitem(collector, name, obj):\n                if name == \"test_func\":\n                    return MyFunction.from_parent(name=name, parent=collector)\n        \"\"\"\n        )\n        item = pytester.getitem(\"def test_func(): pass\")\n        item.config.pluginmanager.getplugin(\"runner\")\n        assert item.location == (\"ABCDE\", 42, \"custom\")\n\n    def test_func_reportinfo(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\"def test_func(): pass\")\n        path, lineno, modpath = item.reportinfo()\n        assert os.fspath(path) == str(item.path)\n        assert lineno == 0\n        assert modpath == \"test_func\"\n\n    def test_class_reportinfo(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            # lineno 0\n            class TestClass(object):\n                def test_hello(self): pass\n        \"\"\"\n        )\n        classcol = pytester.collect_by_name(modcol, \"TestClass\")\n        assert isinstance(classcol, Class)\n        path, lineno, msg = classcol.reportinfo()\n        assert os.fspath(path) == str(modcol.path)\n        assert lineno == 1\n        assert msg == \"TestClass\"\n\n    @pytest.mark.filterwarnings(\n        \"ignore:usage of Generator.Function is deprecated, please use pytest.Function instead\"\n    )\n    def test_reportinfo_with_nasty_getattr(self, pytester: Pytester) -> None:\n        # https://github.com/pytest-dev/pytest/issues/1204\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            # lineno 0\n            class TestClass:\n                def __getattr__(self, name):\n                    return \"this is not an int\"\n\n                def __class_getattr__(cls, name):\n                    return \"this is not an int\"\n\n                def intest_foo(self):\n                    pass\n\n                def test_bar(self):\n                    pass\n        \"\"\"\n        )\n        classcol = pytester.collect_by_name(modcol, \"TestClass\")\n        assert isinstance(classcol, Class)\n        _path, _lineno, _msg = classcol.reportinfo()\n        func = next(iter(classcol.collect()))\n        assert isinstance(func, Function)\n        _path, _lineno, _msg = func.reportinfo()\n\n\ndef test_customized_python_discovery(pytester: Pytester) -> None:\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        python_files=check_*.py\n        python_classes=Check\n        python_functions=check\n    \"\"\"\n    )\n    p = pytester.makepyfile(\n        \"\"\"\n        def check_simple():\n            pass\n        class CheckMyApp(object):\n            def check_meth(self):\n                pass\n    \"\"\"\n    )\n    p2 = p.with_name(p.name.replace(\"test\", \"check\"))\n    p.rename(p2)\n    result = pytester.runpytest(\"--collect-only\", \"-s\")\n    result.stdout.fnmatch_lines(\n        [\"*check_customized*\", \"*check_simple*\", \"*CheckMyApp*\", \"*check_meth*\"]\n    )\n\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_customized_python_discovery_functions(pytester: Pytester) -> None:\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        python_functions=_test\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        def _test_underscore():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--collect-only\", \"-s\")\n    result.stdout.fnmatch_lines([\"*_test_underscore*\"])\n\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_unorderable_types(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        class TestJoinEmpty(object):\n            pass\n\n        def make_test():\n            class Test(object):\n                pass\n            Test.__name__ = \"TestFoo\"\n            return Test\n        TestFoo = make_test()\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.no_fnmatch_line(\"*TypeError*\")\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\n@pytest.mark.filterwarnings(\"default::pytest.PytestCollectionWarning\")\ndef test_dont_collect_non_function_callable(pytester: Pytester) -> None:\n    \"\"\"Test for issue https://github.com/pytest-dev/pytest/issues/331\n\n    In this case an INTERNALERROR occurred trying to report the failure of\n    a test like this one because pytest failed to get the source lines.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        class Oh(object):\n            def __call__(self):\n                pass\n\n        test_a = Oh()\n\n        def test_real():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"*collected 1 item*\",\n            \"*test_dont_collect_non_function_callable.py:2: *cannot collect 'test_a' because it is not a function*\",\n            \"*1 passed, 1 warning in *\",\n        ]\n    )\n\n\ndef test_class_injection_does_not_break_collection(pytester: Pytester) -> None:\n    \"\"\"Tests whether injection during collection time will terminate testing.\n\n    In this case the error should not occur if the TestClass itself\n    is modified during collection time, and the original method list\n    is still used for collection.\n    \"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        from test_inject import TestClass\n        def pytest_generate_tests(metafunc):\n            TestClass.changed_var = {}\n    \"\"\"\n    )\n    pytester.makepyfile(\n        test_inject='''\n         class TestClass(object):\n            def test_injection(self):\n                \"\"\"Test being parametrized.\"\"\"\n                pass\n    '''\n    )\n    result = pytester.runpytest()\n    assert (\n        \"RuntimeError: dictionary changed size during iteration\"\n        not in result.stdout.str()\n    )\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_syntax_error_with_non_ascii_chars(pytester: Pytester) -> None:\n    \"\"\"Fix decoding issue while formatting SyntaxErrors during collection (#578).\"\"\"\n    pytester.makepyfile(\"☃\")\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*SyntaxError*\", \"*1 error in*\"])\n\n\ndef test_collect_error_with_fulltrace(pytester: Pytester) -> None:\n    pytester.makepyfile(\"assert 0\")\n    result = pytester.runpytest(\"--fulltrace\")\n    result.stdout.fnmatch_lines(\n        [\n            \"collected 0 items / 1 error\",\n            \"\",\n            \"*= ERRORS =*\",\n            \"*_ ERROR collecting test_collect_error_with_fulltrace.py _*\",\n            \"\",\n            \">   assert 0\",\n            \"E   assert 0\",\n            \"\",\n            \"test_collect_error_with_fulltrace.py:1: AssertionError\",\n            \"*! Interrupted: 1 error during collection !*\",\n        ]\n    )\n\n\ndef test_skip_duplicates_by_default(pytester: Pytester) -> None:\n    \"\"\"Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)\n\n    Ignore duplicate directories.\n    \"\"\"\n    a = pytester.mkdir(\"a\")\n    fh = a.joinpath(\"test_a.py\")\n    fh.write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            import pytest\n            def test_real():\n                pass\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    result = pytester.runpytest(str(a), str(a))\n    result.stdout.fnmatch_lines([\"*collected 1 item*\"])\n\n\ndef test_keep_duplicates(pytester: Pytester) -> None:\n    \"\"\"Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)\n\n    Use --keep-duplicates to collect tests from duplicate directories.\n    \"\"\"\n    a = pytester.mkdir(\"a\")\n    fh = a.joinpath(\"test_a.py\")\n    fh.write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            import pytest\n            def test_real():\n                pass\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    result = pytester.runpytest(\"--keep-duplicates\", str(a), str(a))\n    result.stdout.fnmatch_lines([\"*collected 2 item*\"])\n\n\ndef test_package_collection_infinite_recursion(pytester: Pytester) -> None:\n    pytester.copy_example(\"collect/package_infinite_recursion\")\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_package_collection_init_given_as_argument(pytester: Pytester) -> None:\n    \"\"\"Regression test for #3749, #8976, #9263, #9313.\n\n    Specifying an __init__.py file directly should collect only the __init__.py\n    Module, not the entire package.\n    \"\"\"\n    p = pytester.copy_example(\"collect/package_init_given_as_arg\")\n    items, _hookrecorder = pytester.inline_genitems(p / \"pkg\" / \"__init__.py\")\n    assert len(items) == 1\n    assert items[0].name == \"test_init\"\n\n\ndef test_package_with_modules(pytester: Pytester) -> None:\n    \"\"\"\n    .\n    └── root\n        ├── __init__.py\n        ├── sub1\n        │   ├── __init__.py\n        │   └── sub1_1\n        │       ├── __init__.py\n        │       └── test_in_sub1.py\n        └── sub2\n            └── test\n                └── test_in_sub2.py\n\n    \"\"\"\n    root = pytester.mkpydir(\"root\")\n    sub1 = root.joinpath(\"sub1\")\n    sub1_test = sub1.joinpath(\"sub1_1\")\n    sub1_test.mkdir(parents=True)\n    for d in (sub1, sub1_test):\n        d.joinpath(\"__init__.py\").touch()\n\n    sub2 = root.joinpath(\"sub2\")\n    sub2_test = sub2.joinpath(\"test\")\n    sub2_test.mkdir(parents=True)\n\n    sub1_test.joinpath(\"test_in_sub1.py\").write_text(\n        \"def test_1(): pass\", encoding=\"utf-8\"\n    )\n    sub2_test.joinpath(\"test_in_sub2.py\").write_text(\n        \"def test_2(): pass\", encoding=\"utf-8\"\n    )\n\n    # Execute from .\n    result = pytester.runpytest(\"-v\", \"-s\")\n    result.assert_outcomes(passed=2)\n\n    # Execute from . with one argument \"root\"\n    result = pytester.runpytest(\"-v\", \"-s\", \"root\")\n    result.assert_outcomes(passed=2)\n\n    # Chdir into package's root and execute with no args\n    os.chdir(root)\n    result = pytester.runpytest(\"-v\", \"-s\")\n    result.assert_outcomes(passed=2)\n\n\ndef test_package_ordering(pytester: Pytester) -> None:\n    \"\"\"\n    .\n    └── root\n        ├── Test_root.py\n        ├── __init__.py\n        ├── sub1\n        │   ├── Test_sub1.py\n        │   └── __init__.py\n        └── sub2\n            └── test\n                └── test_sub2.py\n\n    \"\"\"\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        python_files=*.py\n    \"\"\"\n    )\n    root = pytester.mkpydir(\"root\")\n    sub1 = root.joinpath(\"sub1\")\n    sub1.mkdir()\n    sub1.joinpath(\"__init__.py\").touch()\n    sub2 = root.joinpath(\"sub2\")\n    sub2_test = sub2.joinpath(\"test\")\n    sub2_test.mkdir(parents=True)\n\n    root.joinpath(\"Test_root.py\").write_text(\"def test_1(): pass\", encoding=\"utf-8\")\n    sub1.joinpath(\"Test_sub1.py\").write_text(\"def test_2(): pass\", encoding=\"utf-8\")\n    sub2_test.joinpath(\"test_sub2.py\").write_text(\n        \"def test_3(): pass\", encoding=\"utf-8\"\n    )\n\n    # Execute from .\n    result = pytester.runpytest(\"-v\", \"-s\")\n    result.assert_outcomes(passed=3)\n\n\ndef test_collection_hierarchy(pytester: Pytester) -> None:\n    \"\"\"A general test checking that a filesystem hierarchy is collected as\n    expected in various scenarios.\n\n    top/\n    ├── aaa\n    │   ├── pkg\n    │   │   ├── __init__.py\n    │   │   └── test_pkg.py\n    │   └── test_aaa.py\n    ├── test_a.py\n    ├── test_b\n    │   ├── __init__.py\n    │   └── test_b.py\n    ├── test_c.py\n    └── zzz\n        ├── dir\n        │   └── test_dir.py\n        ├── __init__.py\n        └── test_zzz.py\n    \"\"\"\n    pytester.makepyfile(\n        **{\n            \"top/aaa/test_aaa.py\": \"def test_it(): pass\",\n            \"top/aaa/pkg/__init__.py\": \"\",\n            \"top/aaa/pkg/test_pkg.py\": \"def test_it(): pass\",\n            \"top/test_a.py\": \"def test_it(): pass\",\n            \"top/test_b/__init__.py\": \"\",\n            \"top/test_b/test_b.py\": \"def test_it(): pass\",\n            \"top/test_c.py\": \"def test_it(): pass\",\n            \"top/zzz/__init__.py\": \"\",\n            \"top/zzz/test_zzz.py\": \"def test_it(): pass\",\n            \"top/zzz/dir/test_dir.py\": \"def test_it(): pass\",\n        }\n    )\n\n    full = [\n        \"<Dir test_collection_hierarchy*>\",\n        \"  <Dir top>\",\n        \"    <Dir aaa>\",\n        \"      <Package pkg>\",\n        \"        <Module test_pkg.py>\",\n        \"          <Function test_it>\",\n        \"      <Module test_aaa.py>\",\n        \"        <Function test_it>\",\n        \"    <Module test_a.py>\",\n        \"      <Function test_it>\",\n        \"    <Package test_b>\",\n        \"      <Module test_b.py>\",\n        \"        <Function test_it>\",\n        \"    <Module test_c.py>\",\n        \"      <Function test_it>\",\n        \"    <Package zzz>\",\n        \"      <Dir dir>\",\n        \"        <Module test_dir.py>\",\n        \"          <Function test_it>\",\n        \"      <Module test_zzz.py>\",\n        \"        <Function test_it>\",\n    ]\n    result = pytester.runpytest(\"--collect-only\")\n    result.stdout.fnmatch_lines(full, consecutive=True)\n    result = pytester.runpytest(\"top\", \"--collect-only\")\n    result.stdout.fnmatch_lines(full, consecutive=True)\n    result = pytester.runpytest(\"top\", \"top\", \"--collect-only\")\n    result.stdout.fnmatch_lines(full, consecutive=True)\n\n    result = pytester.runpytest(\n        \"top/aaa\", \"top/aaa/pkg\", \"--collect-only\", \"--keep-duplicates\"\n    )\n    result.stdout.fnmatch_lines(\n        [\n            \"<Dir test_collection_hierarchy*>\",\n            \"  <Dir top>\",\n            \"    <Dir aaa>\",\n            \"      <Package pkg>\",\n            \"        <Module test_pkg.py>\",\n            \"          <Function test_it>\",\n            \"      <Module test_aaa.py>\",\n            \"        <Function test_it>\",\n            \"      <Package pkg>\",\n            \"        <Module test_pkg.py>\",\n            \"          <Function test_it>\",\n        ],\n        consecutive=True,\n    )\n\n    result = pytester.runpytest(\n        \"top/aaa/pkg\", \"top/aaa\", \"--collect-only\", \"--keep-duplicates\"\n    )\n    result.stdout.fnmatch_lines(\n        [\n            \"<Dir test_collection_hierarchy*>\",\n            \"  <Dir top>\",\n            \"    <Dir aaa>\",\n            \"      <Package pkg>\",\n            \"        <Module test_pkg.py>\",\n            \"          <Function test_it>\",\n            \"          <Function test_it>\",\n            \"      <Module test_aaa.py>\",\n            \"        <Function test_it>\",\n        ],\n        consecutive=True,\n    )\n"
  },
  {
    "path": "testing/python/fixtures.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom itertools import zip_longest\nimport os\nfrom pathlib import Path\nimport sys\nimport textwrap\n\nfrom _pytest.compat import getfuncargnames\nfrom _pytest.config import ExitCode\nfrom _pytest.fixtures import deduplicate_names\nfrom _pytest.fixtures import TopRequest\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import get_public_names\nfrom _pytest.pytester import Pytester\nfrom _pytest.python import Function\nimport pytest\n\n\ndef test_getfuncargnames_functions():\n    \"\"\"Test getfuncargnames for normal functions\"\"\"\n\n    def f():\n        raise NotImplementedError()\n\n    assert not getfuncargnames(f)\n\n    def g(arg):\n        raise NotImplementedError()\n\n    assert getfuncargnames(g) == (\"arg\",)\n\n    def h(arg1, arg2=\"hello\"):\n        raise NotImplementedError()\n\n    assert getfuncargnames(h) == (\"arg1\",)\n\n    def j(arg1, arg2, arg3=\"hello\"):\n        raise NotImplementedError()\n\n    assert getfuncargnames(j) == (\"arg1\", \"arg2\")\n\n\ndef test_getfuncargnames_methods():\n    \"\"\"Test getfuncargnames for normal methods\"\"\"\n\n    class A:\n        def f(self, arg1, arg2=\"hello\"):\n            raise NotImplementedError()\n\n        def g(self, /, arg1, arg2=\"hello\"):\n            raise NotImplementedError()\n\n        def h(self, *, arg1, arg2=\"hello\"):\n            raise NotImplementedError()\n\n        def j(self, arg1, *, arg2, arg3=\"hello\"):\n            raise NotImplementedError()\n\n        def k(self, /, arg1, *, arg2, arg3=\"hello\"):\n            raise NotImplementedError()\n\n    assert getfuncargnames(A().f) == (\"arg1\",)\n    assert getfuncargnames(A().g) == (\"arg1\",)\n    assert getfuncargnames(A().h) == (\"arg1\",)\n    assert getfuncargnames(A().j) == (\"arg1\", \"arg2\")\n    assert getfuncargnames(A().k) == (\"arg1\", \"arg2\")\n\n\ndef test_getfuncargnames_staticmethod():\n    \"\"\"Test getfuncargnames for staticmethods\"\"\"\n\n    class A:\n        @staticmethod\n        def static(arg1, arg2, x=1):\n            raise NotImplementedError()\n\n    assert getfuncargnames(A.static, cls=A) == (\"arg1\", \"arg2\")\n\n\ndef test_getfuncargnames_staticmethod_inherited() -> None:\n    \"\"\"Test getfuncargnames for inherited staticmethods (#8061)\"\"\"\n\n    class A:\n        @staticmethod\n        def static(arg1, arg2, x=1):\n            raise NotImplementedError()\n\n    class B(A):\n        pass\n\n    assert getfuncargnames(B.static, cls=B) == (\"arg1\", \"arg2\")\n\n\n@pytest.mark.skipif(\n    sys.version_info >= (3, 13),\n    reason=\"\"\"\\\nIn python 3.13, this will raise FutureWarning:\nfunctools.partial will be a method descriptor in future Python versions;\nwrap it in staticmethod() if you want to preserve the old behavior\n\nBut the wrapped 'functools.partial' is tested by 'test_getfuncargnames_staticmethod_partial' below.\n\"\"\",\n)\ndef test_getfuncargnames_partial():\n    \"\"\"Check getfuncargnames for methods defined with functools.partial (#5701)\"\"\"\n    import functools\n\n    def check(arg1, arg2, i):\n        raise NotImplementedError()\n\n    class T:\n        test_ok = functools.partial(check, i=2)\n\n    values = getfuncargnames(T().test_ok, name=\"test_ok\")\n    assert values == (\"arg1\", \"arg2\")\n\n\ndef test_getfuncargnames_staticmethod_partial():\n    \"\"\"Check getfuncargnames for staticmethods defined with functools.partial (#5701)\"\"\"\n    import functools\n\n    def check(arg1, arg2, i):\n        raise NotImplementedError()\n\n    class T:\n        test_ok = staticmethod(functools.partial(check, i=2))\n\n    values = getfuncargnames(T().test_ok, name=\"test_ok\")\n    assert values == (\"arg1\", \"arg2\")\n\n\n@pytest.mark.pytester_example_path(\"fixtures/fill_fixtures\")\nclass TestFillFixtures:\n    def test_funcarg_lookupfails(self, pytester: Pytester) -> None:\n        pytester.copy_example()\n        result = pytester.runpytest()  # \"--collect-only\")\n        assert result.ret != 0\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *def test_func(some)*\n            *fixture*some*not found*\n            *xyzsomething*\n            \"\"\"\n        )\n\n    def test_detect_recursive_dependency_error(self, pytester: Pytester) -> None:\n        pytester.copy_example()\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\"*recursive dependency involving fixture 'fix1' detected*\"]\n        )\n\n    def test_funcarg_basic(self, pytester: Pytester) -> None:\n        pytester.copy_example()\n        item = pytester.getitem(Path(\"test_funcarg_basic.py\"))\n        assert isinstance(item, Function)\n        # Execute's item's setup, which fills fixtures.\n        item.session._setupstate.setup(item)\n        del item.funcargs[\"request\"]\n        assert len(get_public_names(item.funcargs)) == 2\n        assert item.funcargs[\"some\"] == \"test_func\"\n        assert item.funcargs[\"other\"] == 42\n\n    def test_funcarg_lookup_modulelevel(self, pytester: Pytester) -> None:\n        pytester.copy_example()\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_funcarg_lookup_classlevel(self, pytester: Pytester) -> None:\n        p = pytester.copy_example()\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_conftest_funcargs_only_available_in_subdir(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.copy_example()\n        result = pytester.runpytest(\"-v\")\n        result.assert_outcomes(passed=2)\n\n    def test_extend_fixture_module_class(self, pytester: Pytester) -> None:\n        testfile = pytester.copy_example()\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n        result = pytester.runpytest(testfile)\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_extend_fixture_conftest_module(self, pytester: Pytester) -> None:\n        p = pytester.copy_example()\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n        result = pytester.runpytest(str(next(Path(str(p)).rglob(\"test_*.py\"))))\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_extend_fixture_conftest_conftest(self, pytester: Pytester) -> None:\n        p = pytester.copy_example()\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n        result = pytester.runpytest(str(next(Path(str(p)).rglob(\"test_*.py\"))))\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_extend_fixture_conftest_plugin(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            testplugin=\"\"\"\n            import pytest\n\n            @pytest.fixture\n            def foo():\n                return 7\n        \"\"\"\n        )\n        pytester.syspathinsert()\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            pytest_plugins = 'testplugin'\n\n            @pytest.fixture\n            def foo(foo):\n                return foo + 7\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo(foo):\n                assert foo == 14\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\")\n        assert result.ret == 0\n\n    def test_extend_fixture_plugin_plugin(self, pytester: Pytester) -> None:\n        # Two plugins should extend each order in loading order\n        pytester.makepyfile(\n            testplugin0=\"\"\"\n            import pytest\n\n            @pytest.fixture\n            def foo():\n                return 7\n        \"\"\"\n        )\n        pytester.makepyfile(\n            testplugin1=\"\"\"\n            import pytest\n\n            @pytest.fixture\n            def foo(foo):\n                return foo + 7\n        \"\"\"\n        )\n        pytester.syspathinsert()\n        pytester.makepyfile(\n            \"\"\"\n            pytest_plugins = ['testplugin0', 'testplugin1']\n\n            def test_foo(foo):\n                assert foo == 14\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_override_parametrized_fixture_conftest_module(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test override of the parametrized fixture with non-parametrized one on the test module level.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[1, 2, 3])\n            def spam(request):\n                return request.param\n        \"\"\"\n        )\n        testfile = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def spam():\n                return 'spam'\n\n            def test_spam(spam):\n                assert spam == 'spam'\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n        result = pytester.runpytest(testfile)\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_override_parametrized_fixture_conftest_conftest(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test override of the parametrized fixture with non-parametrized one on the conftest level.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[1, 2, 3])\n            def spam(request):\n                return request.param\n        \"\"\"\n        )\n        subdir = pytester.mkpydir(\"subdir\")\n        subdir.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n\n                @pytest.fixture\n                def spam():\n                    return 'spam'\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        testfile = subdir.joinpath(\"test_spam.py\")\n        testfile.write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                def test_spam(spam):\n                    assert spam == \"spam\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n        result = pytester.runpytest(testfile)\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_override_non_parametrized_fixture_conftest_module(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test override of the non-parametrized fixture with parametrized one on the test module level.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def spam():\n                return 'spam'\n        \"\"\"\n        )\n        testfile = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[1, 2, 3])\n            def spam(request):\n                return request.param\n\n            params = {'spam': 1}\n\n            def test_spam(spam):\n                assert spam == params['spam']\n                params['spam'] += 1\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*3 passed*\"])\n        result = pytester.runpytest(testfile)\n        result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n    def test_override_non_parametrized_fixture_conftest_conftest(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test override of the non-parametrized fixture with parametrized one on the conftest level.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def spam():\n                return 'spam'\n        \"\"\"\n        )\n        subdir = pytester.mkpydir(\"subdir\")\n        subdir.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n\n                @pytest.fixture(params=[1, 2, 3])\n                def spam(request):\n                    return request.param\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        testfile = subdir.joinpath(\"test_spam.py\")\n        testfile.write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                params = {'spam': 1}\n\n                def test_spam(spam):\n                    assert spam == params['spam']\n                    params['spam'] += 1\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*3 passed*\"])\n        result = pytester.runpytest(testfile)\n        result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n    def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test override of the autouse fixture with parametrized one on the conftest level.\n        This test covers the issue explained in issue 1601\n        \"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(autouse=True)\n            def spam():\n                return 'spam'\n        \"\"\"\n        )\n        subdir = pytester.mkpydir(\"subdir\")\n        subdir.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n\n                @pytest.fixture(params=[1, 2, 3])\n                def spam(request):\n                    return request.param\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        testfile = subdir.joinpath(\"test_spam.py\")\n        testfile.write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                params = {'spam': 1}\n\n                def test_spam(spam):\n                    assert spam == params['spam']\n                    params['spam'] += 1\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*3 passed*\"])\n        result = pytester.runpytest(testfile)\n        result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n    def test_override_fixture_reusing_super_fixture_parametrization(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Override a fixture at a lower level, reusing the higher-level fixture that\n        is parametrized (#1953).\n        \"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[1, 2])\n            def foo(request):\n                return request.param\n            \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def foo(foo):\n                return foo * 2\n\n            def test_spam(foo):\n                assert foo in (2, 4)\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n    def test_override_parametrize_fixture_and_indirect(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Override a fixture at a lower level, reusing the higher-level fixture that\n        is parametrized, while also using indirect parametrization.\n        \"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[1, 2])\n            def foo(request):\n                return request.param\n            \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def foo(foo):\n                return foo * 2\n\n            @pytest.fixture\n            def bar(request):\n                return request.param * 100\n\n            @pytest.mark.parametrize(\"bar\", [42], indirect=True)\n            def test_spam(bar, foo):\n                assert bar == 4200\n                assert foo in (2, 4)\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n    def test_override_top_level_fixture_reusing_super_fixture_parametrization(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Same as the above test, but with another level of overwriting.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=['unused', 'unused'])\n            def foo(request):\n                return request.param\n            \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[1, 2])\n            def foo(request):\n                return request.param\n\n            class Test:\n\n                @pytest.fixture\n                def foo(self, foo):\n                    return foo * 2\n\n                def test_spam(self, foo):\n                    assert foo in (2, 4)\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n    def test_override_parametrized_fixture_with_new_parametrized_fixture(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Overriding a parametrized fixture, while also parametrizing the new fixture and\n        simultaneously requesting the overwritten fixture as parameter, yields the same value\n        as ``request.param``.\n        \"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=['ignored', 'ignored'])\n            def foo(request):\n                return request.param\n            \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[10, 20])\n            def foo(foo, request):\n                assert request.param == foo\n                return foo * 2\n\n            def test_spam(foo):\n                assert foo in (20, 40)\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n    @pytest.mark.xfail(reason=\"not handled currently\")\n    def test_override_parametrized_fixture_via_transitive_fixture(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test that overriding a parametrized fixture works even the super\n        fixture is requested only transitively.\n\n        Regression test for #7737.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[1, 2])\n            def foo(request):\n                return request.param\n\n            @pytest.fixture\n            def bar(foo):\n                return foo\n\n            class TestIt:\n                @pytest.fixture\n                def foo(self, bar):\n                    return bar * 2\n\n                def test_it(self, foo):\n                    pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.OK\n        result.assert_outcomes(passed=2)\n\n    def test_autouse_fixture_plugin(self, pytester: Pytester) -> None:\n        # A fixture from a plugin has no baseid set, which screwed up\n        # the autouse fixture handling.\n        pytester.makepyfile(\n            testplugin=\"\"\"\n            import pytest\n\n            @pytest.fixture(autouse=True)\n            def foo(request):\n                request.function.foo = 7\n        \"\"\"\n        )\n        pytester.syspathinsert()\n        pytester.makepyfile(\n            \"\"\"\n            pytest_plugins = 'testplugin'\n\n            def test_foo(request):\n                assert request.function.foo == 7\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_funcarg_lookup_error(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def a_fixture(): pass\n\n            @pytest.fixture\n            def b_fixture(): pass\n\n            @pytest.fixture\n            def c_fixture(): pass\n\n            @pytest.fixture\n            def d_fixture(): pass\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_lookup_error(unknown):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*ERROR at setup of test_lookup_error*\",\n                \"  def test_lookup_error(unknown):*\",\n                \"E       fixture 'unknown' not found\",\n                \">       available fixtures:*a_fixture,*b_fixture,*c_fixture,*d_fixture*monkeypatch,*\",\n                # sorted\n                \">       use 'py*test --fixtures *' for help on them.\",\n                \"*1 error*\",\n            ]\n        )\n        result.stdout.no_fnmatch_line(\"*INTERNAL*\")\n\n    def test_fixture_excinfo_leak(self, pytester: Pytester) -> None:\n        # on python2 sys.excinfo would leak into fixture executions\n        pytester.makepyfile(\n            \"\"\"\n            import sys\n            import traceback\n            import pytest\n\n            @pytest.fixture\n            def leak():\n                if sys.exc_info()[0]:  # python3 bug :)\n                    traceback.print_exc()\n                #fails\n                assert sys.exc_info() == (None, None, None)\n\n            def test_leak(leak):\n                if sys.exc_info()[0]:  # python3 bug :)\n                    traceback.print_exc()\n                assert sys.exc_info() == (None, None, None)\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n\nclass TestRequestBasic:\n    def test_request_attributes(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def something(request): pass\n            def test_func(something): pass\n        \"\"\"\n        )\n        assert isinstance(item, Function)\n        req = TopRequest(item, _ispytest=True)\n        assert req.function == item.obj\n        assert req.keywords == item.keywords\n        assert hasattr(req.module, \"test_func\")\n        assert req.cls is None\n        assert req.function.__name__ == \"test_func\"\n        assert req.config == item.config\n        assert repr(req).find(req.function.__name__) != -1\n\n    def test_request_attributes_method(self, pytester: Pytester) -> None:\n        (item,) = pytester.getitems(\n            \"\"\"\n            import pytest\n            class TestB(object):\n\n                @pytest.fixture\n                def something(self, request):\n                    return 1\n                def test_func(self, something):\n                    pass\n        \"\"\"\n        )\n        assert isinstance(item, Function)\n        req = item._request\n        assert req.cls.__name__ == \"TestB\"\n        assert req.instance.__class__ == req.cls\n\n    def test_request_contains_funcarg_arg2fixturedefs(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def something(request):\n                pass\n            class TestClass(object):\n                def test_method(self, something):\n                    pass\n        \"\"\"\n        )\n        (item1,) = pytester.genitems([modcol])\n        assert isinstance(item1, Function)\n        assert item1.name == \"test_method\"\n        arg2fixturedefs = TopRequest(item1, _ispytest=True)._arg2fixturedefs\n        assert len(arg2fixturedefs) == 1\n        assert arg2fixturedefs[\"something\"][0].argname == \"something\"\n\n    @pytest.mark.skipif(\n        hasattr(sys, \"pypy_version_info\"),\n        reason=\"this method of test doesn't work on pypy\",\n    )\n    def test_request_garbage(self, pytester: Pytester) -> None:\n        try:\n            import xdist  # noqa: F401\n        except ImportError:\n            pass\n        else:\n            pytest.xfail(\"this test is flaky when executed with xdist\")\n        pytester.makepyfile(\n            \"\"\"\n            import sys\n            import pytest\n            from _pytest.fixtures import RequestFixtureDef\n            import gc\n\n            @pytest.fixture(autouse=True)\n            def something(request):\n                original = gc.get_debug()\n                gc.set_debug(gc.DEBUG_SAVEALL)\n                gc.collect()\n\n                yield\n\n                try:\n                    gc.collect()\n                    leaked = [x for _ in gc.garbage if isinstance(_, RequestFixtureDef)]\n                    assert leaked == []\n                finally:\n                    gc.set_debug(original)\n\n            def test_func():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n    def test_getfixturevalue_recursive(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def something(request):\n                return 1\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def something(request):\n                return request.getfixturevalue(\"something\") + 1\n            def test_func(something):\n                assert something == 2\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_getfixturevalue_teardown(self, pytester: Pytester) -> None:\n        \"\"\"\n        Issue #1895\n\n        `test_inner` requests `inner` fixture, which in turn requests `resource`\n        using `getfixturevalue`. `test_func` then requests `resource`.\n\n        `resource` is teardown before `inner` because the fixture mechanism won't consider\n        `inner` dependent on `resource` when it is used via `getfixturevalue`: `test_func`\n        will then cause the `resource`'s finalizer to be called first because of this.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='session')\n            def resource():\n                r = ['value']\n                yield r\n                r.pop()\n\n            @pytest.fixture(scope='session')\n            def inner(request):\n                resource = request.getfixturevalue('resource')\n                assert resource == ['value']\n                yield\n                assert resource == ['value']\n\n            def test_inner(inner):\n                pass\n\n            def test_func(resource):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 2 passed in *\"])\n\n    def test_getfixturevalue_teardown_previously_requested_does_not_warn(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test that requesting a fixture during teardown that was previously\n        requested is OK (#12882).\n\n        Note: this is still kinda dubious so don't let this test lock you in to\n        allowing this behavior forever...\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def fix(request, tmp_path):\n                yield\n                assert request.getfixturevalue(\"tmp_path\") == tmp_path\n\n            def test_it(fix):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-Werror\")\n        result.assert_outcomes(passed=1)\n\n    def test_getfixturevalue_teardown_new_fixture_deprecated(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test that requesting a fixture during teardown that was not\n        previously requested raises a deprecation warning (#12882).\n\n        Note: this is a case that previously worked but will become a hard\n        error after the deprecation is completed.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"session\")\n            def resource():\n                return \"value\"\n\n            @pytest.fixture\n            def fix(request):\n                yield\n                with pytest.warns(\n                    pytest.PytestRemovedIn10Warning,\n                    match=r'Calling request\\\\.getfixturevalue\\\\(\"resource\"\\\\) during teardown is deprecated',\n                ):\n                    assert request.getfixturevalue(\"resource\") == \"value\"\n\n            def test_it(fix):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(passed=1)\n\n    def test_getfixturevalue_teardown_new_inactive_fixture_errors(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test that requesting a fixture during teardown that was not\n        previously requested raises an error (#12882).\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def fix(request):\n                yield\n                request.getfixturevalue(\"tmp_path\")\n\n            def test_it(fix):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(passed=1, errors=1)\n        result.stdout.fnmatch_lines(\n            [\n                (\n                    '*The fixture value for \"tmp_path\" is not available during '\n                    \"teardown because it was not previously requested.*\"\n                ),\n            ]\n        )\n\n    def test_getfixturevalue_teardown_new_inactive_fixture_errors_top_request(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test that requesting a fixture during teardown that was not\n        previously requested raises an error (tricky case) (#12882).\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def test_it(request):\n                request.addfinalizer(lambda: request.getfixturevalue(\"tmp_path\"))\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(passed=1, errors=1)\n        result.stdout.fnmatch_lines(\n            [\n                (\n                    '*The fixture value for \"tmp_path\" is not available during '\n                    \"teardown because it was not previously requested.*\"\n                ),\n            ]\n        )\n\n    def test_getfixturevalue(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def something(request):\n                return 1\n\n            values = [2]\n            @pytest.fixture\n            def other(request):\n                return values.pop()\n\n            def test_func(something): pass\n        \"\"\"\n        )\n        assert isinstance(item, Function)\n        req = item._request\n\n        # Execute item's setup.\n        item.session._setupstate.setup(item)\n\n        with pytest.raises(pytest.FixtureLookupError):\n            req.getfixturevalue(\"notexists\")\n        val = req.getfixturevalue(\"something\")\n        assert val == 1\n        val = req.getfixturevalue(\"something\")\n        assert val == 1\n        val2 = req.getfixturevalue(\"other\")\n        assert val2 == 2\n        val2 = req.getfixturevalue(\"other\")  # see about caching\n        assert val2 == 2\n        assert item.funcargs[\"something\"] == 1\n        assert len(get_public_names(item.funcargs)) == 2\n        assert \"request\" in item.funcargs\n\n    def test_request_addfinalizer(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            teardownlist = []\n            @pytest.fixture\n            def something(request):\n                request.addfinalizer(lambda: teardownlist.append(1))\n            def test_func(something): pass\n        \"\"\"\n        )\n        assert isinstance(item, Function)\n        item.session._setupstate.setup(item)\n        item._request._fillfixtures()\n        # successively check finalization calls\n        parent = item.getparent(pytest.Module)\n        assert parent is not None\n        teardownlist = parent.obj.teardownlist\n        ss = item.session._setupstate\n        assert not teardownlist\n        ss.teardown_exact(None)\n        print(ss.stack)\n        assert teardownlist == [1]\n\n    def test_request_addfinalizer_failing_setup(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = [1]\n            @pytest.fixture\n            def myfix(request):\n                request.addfinalizer(values.pop)\n                assert 0\n            def test_fix(myfix):\n                pass\n            def test_finalizer_ran():\n                assert not values\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(failed=1, passed=1)\n\n    def test_request_addfinalizer_failing_setup_module(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = [1, 2]\n            @pytest.fixture(scope=\"module\")\n            def myfix(request):\n                request.addfinalizer(values.pop)\n                request.addfinalizer(values.pop)\n                assert 0\n            def test_fix(myfix):\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        mod = reprec.getcalls(\"pytest_runtest_setup\")[0].item.module\n        assert not mod.values\n\n    def test_request_addfinalizer_partial_setup_failure(\n        self, pytester: Pytester\n    ) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture\n            def something(request):\n                request.addfinalizer(lambda: values.append(None))\n            def test_func(something, missingarg):\n                pass\n            def test_second():\n                assert len(values) == 1\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines(\n            [\"*1 error*\"]  # XXX the whole module collection fails\n        )\n\n    def test_request_subrequest_addfinalizer_exceptions(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"\n        Ensure exceptions raised during teardown by finalizers are suppressed\n        until all finalizers are called, then re-raised together in an\n        exception group (#2440)\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            def _excepts(where):\n                raise Exception('Error in %s fixture' % where)\n            @pytest.fixture\n            def subrequest(request):\n                return request\n            @pytest.fixture\n            def something(subrequest):\n                subrequest.addfinalizer(lambda: values.append(1))\n                subrequest.addfinalizer(lambda: values.append(2))\n                subrequest.addfinalizer(lambda: _excepts('something'))\n            @pytest.fixture\n            def excepts(subrequest):\n                subrequest.addfinalizer(lambda: _excepts('excepts'))\n                subrequest.addfinalizer(lambda: values.append(3))\n            def test_first(something, excepts):\n                pass\n            def test_second():\n                assert values == [3, 2, 1]\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(passed=2, errors=1)\n        result.stdout.fnmatch_lines(\n            [\n                '  | *ExceptionGroup: errors while tearing down fixture \"subrequest\" of <Function test_first> (2 sub-exceptions)',  # noqa: E501\n                \"  +-+---------------- 1 ----------------\",\n                \"    | Exception: Error in something fixture\",\n                \"    +---------------- 2 ----------------\",\n                \"    | Exception: Error in excepts fixture\",\n                \"    +------------------------------------\",\n            ],\n        )\n\n    def test_request_getmodulepath(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\"def test_somefunc(): pass\")\n        (item,) = pytester.genitems([modcol])\n        assert isinstance(item, Function)\n        req = TopRequest(item, _ispytest=True)\n        assert req.path == modcol.path\n\n    def test_request_fixturenames(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            from _pytest.pytester import get_public_names\n            @pytest.fixture()\n            def arg1():\n                pass\n            @pytest.fixture()\n            def farg(arg1):\n                pass\n            @pytest.fixture(autouse=True)\n            def sarg(tmp_path):\n                pass\n            def test_function(request, farg):\n                assert set(get_public_names(request.fixturenames)) == \\\n                       set([\"sarg\", \"arg1\", \"request\", \"farg\",\n                            \"tmp_path\", \"tmp_path_factory\"])\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_request_fixturenames_dynamic_fixture(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #3057\"\"\"\n        pytester.copy_example(\"fixtures/test_getfixturevalue_dynamic.py\")\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_setupdecorator_and_xunit(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(scope='module', autouse=True)\n            def setup_module():\n                values.append(\"module\")\n            @pytest.fixture(autouse=True)\n            def setup_function():\n                values.append(\"function\")\n\n            def test_func():\n                pass\n\n            class TestClass(object):\n                @pytest.fixture(scope=\"class\", autouse=True)\n                def setup_class(self):\n                    values.append(\"class\")\n                @pytest.fixture(autouse=True)\n                def setup_method(self):\n                    values.append(\"method\")\n                def test_method(self):\n                    pass\n            def test_all():\n                assert values == [\"module\", \"function\", \"class\",\n                             \"function\", \"method\", \"function\"]\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-v\")\n        reprec.assertoutcome(passed=3)\n\n    def test_fixtures_sub_subdir_normalize_sep(self, pytester: Pytester) -> None:\n        # this tests that normalization of nodeids takes place\n        b = pytester.path.joinpath(\"tests\", \"unit\")\n        b.mkdir(parents=True)\n        b.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n                @pytest.fixture\n                def arg1():\n                    pass\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        p = b.joinpath(\"test_module.py\")\n        p.write_text(\"def test_func(arg1): pass\", encoding=\"utf-8\")\n        result = pytester.runpytest(p, \"--fixtures\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *fixtures defined*conftest*\n            *arg1*\n        \"\"\"\n        )\n\n    def test_show_fixtures_color_yes(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\"def test_this(): assert 1\")\n        result = pytester.runpytest(\"--color=yes\", \"--fixtures\")\n        assert \"\\x1b[32mtmp_path\" in result.stdout.str()\n\n    def test_newstyle_with_request(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture()\n            def arg(request):\n                pass\n            def test_1(arg):\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_setupcontext_no_param(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(params=[1,2])\n            def arg(request):\n                return request.param\n\n            @pytest.fixture(autouse=True)\n            def mysetup(request, arg):\n                assert not hasattr(request, \"param\")\n            def test_1(arg):\n                assert arg in (1,2)\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n\nclass TestRequestSessionScoped:\n    @pytest.fixture(scope=\"session\")\n    def session_request(self, request):\n        return request\n\n    @pytest.mark.parametrize(\"name\", [\"path\", \"module\"])\n    def test_session_scoped_unavailable_attributes(self, session_request, name):\n        with pytest.raises(\n            AttributeError,\n            match=f\"{name} not available in session-scoped context\",\n        ):\n            getattr(session_request, name)\n\n\nclass TestRequestMarking:\n    def test_applymarker(self, pytester: Pytester) -> None:\n        item1, _item2 = pytester.getitems(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def something(request):\n                pass\n            class TestClass(object):\n                def test_func1(self, something):\n                    pass\n                def test_func2(self, something):\n                    pass\n        \"\"\"\n        )\n        assert isinstance(item1, Function)\n        req1 = TopRequest(item1, _ispytest=True)\n        assert \"xfail\" not in item1.keywords\n        req1.applymarker(pytest.mark.xfail)\n        assert \"xfail\" in item1.keywords\n        assert \"skipif\" not in item1.keywords\n        req1.applymarker(pytest.mark.skipif)\n        assert \"skipif\" in item1.keywords\n        with pytest.raises(ValueError):\n            req1.applymarker(42)  # type: ignore[arg-type]\n\n    def test_accesskeywords(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture()\n            def keywords(request):\n                return request.keywords\n            @pytest.mark.XYZ\n            def test_function(keywords):\n                assert keywords[\"XYZ\"]\n                assert \"abc\" not in keywords\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_accessmarker_dynamic(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            @pytest.fixture()\n            def keywords(request):\n                return request.keywords\n\n            @pytest.fixture(scope=\"class\", autouse=True)\n            def marking(request):\n                request.applymarker(pytest.mark.XYZ(\"hello\"))\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_fun1(keywords):\n                assert keywords[\"XYZ\"] is not None\n                assert \"abc\" not in keywords\n            def test_fun2(keywords):\n                assert keywords[\"XYZ\"] is not None\n                assert \"abc\" not in keywords\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n\nclass TestFixtureUsages:\n    def test_noargfixturedec(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def arg1():\n                return 1\n\n            def test_func(arg1):\n                assert arg1 == 1\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_receives_funcargs(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture()\n            def arg1():\n                return 1\n\n            @pytest.fixture()\n            def arg2(arg1):\n                return arg1 + 1\n\n            def test_add(arg2):\n                assert arg2 == 2\n            def test_all(arg1, arg2):\n                assert arg1 == 1\n                assert arg2 == 2\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_receives_funcargs_scope_mismatch(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"function\")\n            def arg1():\n                return 1\n\n            @pytest.fixture(scope=\"module\")\n            def arg2(arg1):\n                return arg1 + 1\n\n            def test_add(arg2):\n                assert arg2 == 2\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*ScopeMismatch*Requesting fixture stack*\",\n                \"test_receives_funcargs_scope_mismatch.py:6:  def arg2(arg1)\",\n                \"Requested fixture:\",\n                \"test_receives_funcargs_scope_mismatch.py:2:  def arg1()\",\n                \"*1 error*\",\n            ]\n        )\n\n    def test_receives_funcargs_scope_mismatch_issue660(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"function\")\n            def arg1():\n                return 1\n\n            @pytest.fixture(scope=\"module\")\n            def arg2(arg1):\n                return arg1 + 1\n\n            def test_add(arg1, arg2):\n                assert arg2 == 2\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*ScopeMismatch*Requesting fixture stack*\",\n                \"* def arg2(arg1)\",\n                \"Requested fixture:\",\n                \"* def arg1()\",\n                \"*1 error*\",\n            ],\n        )\n\n    def test_invalid_scope(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"functions\")\n            def badscope():\n                pass\n\n            def test_nothing(badscope):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest_inprocess()\n        result.stdout.fnmatch_lines(\n            \"*Fixture 'badscope' from test_invalid_scope.py got an unexpected scope value 'functions'\"\n        )\n\n    @pytest.mark.parametrize(\"scope\", [\"function\", \"session\"])\n    def test_parameters_without_eq_semantics(self, scope, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            f\"\"\"\n            class NoEq1:  # fails on `a == b` statement\n                def __eq__(self, _):\n                    raise RuntimeError\n\n            class NoEq2:  # fails on `if a == b:` statement\n                def __eq__(self, _):\n                    class NoBool:\n                        def __bool__(self):\n                            raise RuntimeError\n                    return NoBool()\n\n            import pytest\n            @pytest.fixture(params=[NoEq1(), NoEq2()], scope={scope!r})\n            def no_eq(request):\n                return request.param\n\n            def test1(no_eq):\n                pass\n\n            def test2(no_eq):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*4 passed*\"])\n\n    def test_funcarg_parametrized_and_used_twice(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(params=[1,2])\n            def arg1(request):\n                values.append(1)\n                return request.param\n\n            @pytest.fixture()\n            def arg2(arg1):\n                return arg1 + 1\n\n            def test_add(arg1, arg2):\n                assert arg2 == arg1 + 1\n                assert len(values) == arg1\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n    def test_factory_uses_unknown_funcarg_as_dependency_error(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture()\n            def fail(missing):\n                return\n\n            @pytest.fixture()\n            def call_fail(fail):\n                return\n\n            def test_missing(call_fail):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *pytest.fixture()*\n            *def call_fail(fail)*\n            *pytest.fixture()*\n            *def fail*\n            *fixture*'missing'*not found*\n        \"\"\"\n        )\n\n    def test_factory_setup_as_classes_fails(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            class arg1(object):\n                def __init__(self, request):\n                    self.x = 1\n            arg1 = pytest.fixture()(arg1)\n\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        values = reprec.getfailedcollections()\n        assert len(values) == 1\n\n    def test_usefixtures_marker(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            values = []\n\n            @pytest.fixture(scope=\"class\")\n            def myfix(request):\n                request.cls.hello = \"world\"\n                values.append(1)\n\n            class TestClass(object):\n                def test_one(self):\n                    assert self.hello == \"world\"\n                    assert len(values) == 1\n                def test_two(self):\n                    assert self.hello == \"world\"\n                    assert len(values) == 1\n            pytest.mark.usefixtures(\"myfix\")(TestClass)\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_empty_usefixtures_marker(self, pytester: Pytester) -> None:\n        \"\"\"Empty usefixtures() marker issues a warning (#12439).\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.usefixtures()\n            def test_one():\n                assert 1 == 1\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            \"*PytestWarning: usefixtures() in test_empty_usefixtures_marker.py::test_one\"\n            \" without arguments has no effect\"\n        )\n\n    def test_usefixtures_ini(self, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            usefixtures = myfix\n        \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"class\")\n            def myfix(request):\n                request.cls.hello = \"world\"\n\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            class TestClass(object):\n                def test_one(self):\n                    assert self.hello == \"world\"\n                def test_two(self):\n                    assert self.hello == \"world\"\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_usefixtures_seen_in_showmarkers(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"--markers\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *usefixtures(fixturename1*mark tests*fixtures*\n        \"\"\"\n        )\n\n    def test_request_instance_issue203(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            class TestClass(object):\n                @pytest.fixture\n                def setup1(self, request):\n                    assert self == request.instance\n                    self.arg1 = 1\n                def test_hello(self, setup1):\n                    assert self.arg1 == 1\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_fixture_parametrized_with_iterator(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            values = []\n            def f():\n                yield 1\n                yield 2\n            dec = pytest.fixture(scope=\"module\", params=f())\n\n            @dec\n            def arg(request):\n                return request.param\n            @dec\n            def arg2(request):\n                return request.param\n\n            def test_1(arg):\n                values.append(arg)\n            def test_2(arg2):\n                values.append(arg2*10)\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-v\")\n        reprec.assertoutcome(passed=4)\n        values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n        assert values == [1, 2, 10, 20]\n\n    def test_setup_functions_as_fixtures(self, pytester: Pytester) -> None:\n        \"\"\"Ensure setup_* methods obey fixture scope rules (#517, #3094).\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            DB_INITIALIZED = None\n\n            @pytest.fixture(scope=\"session\", autouse=True)\n            def db():\n                global DB_INITIALIZED\n                DB_INITIALIZED = True\n                yield\n                DB_INITIALIZED = False\n\n            def setup_module():\n                assert DB_INITIALIZED\n\n            def teardown_module():\n                assert DB_INITIALIZED\n\n            class TestClass(object):\n\n                def setup_method(self, method):\n                    assert DB_INITIALIZED\n\n                def teardown_method(self, method):\n                    assert DB_INITIALIZED\n\n                def test_printer_1(self):\n                    pass\n\n                def test_printer_2(self):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 2 passed in *\"])\n\n    def test_parameterized_fixture_caching(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #12600.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            from itertools import count\n\n            CACHE_MISSES = count(0)\n\n            def pytest_generate_tests(metafunc):\n                if \"my_fixture\" in metafunc.fixturenames:\n                    # Use unique objects for parametrization (as opposed to small strings\n                    # and small integers which are singletons).\n                    metafunc.parametrize(\"my_fixture\", [[1], [2]], indirect=True)\n\n            @pytest.fixture(scope='session')\n            def my_fixture(request):\n                next(CACHE_MISSES)\n\n            def test1(my_fixture):\n                pass\n\n            def test2(my_fixture):\n                pass\n\n            def teardown_module():\n                assert next(CACHE_MISSES) == 2\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.no_fnmatch_line(\"* ERROR at teardown *\")\n\n    def test_unwrapping_pytest_fixture(self, pytester: Pytester) -> None:\n        \"\"\"Ensure the unwrap method on `FixtureFunctionDefinition` correctly wraps and unwraps methods and functions\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            import inspect\n\n            class FixtureFunctionDefTestClass:\n                def __init__(self) -> None:\n                    self.i = 10\n\n                @pytest.fixture\n                def fixture_function_def_test_method(self):\n                    return self.i\n\n\n            @pytest.fixture\n            def fixture_function_def_test_func():\n                return 9\n\n\n            def test_get_wrapped_func_returns_method():\n                obj = FixtureFunctionDefTestClass()\n                wrapped_function_result = (\n                    obj.fixture_function_def_test_method._get_wrapped_function()\n                )\n                assert inspect.ismethod(wrapped_function_result)\n                assert wrapped_function_result() == 10\n\n\n            def test_get_wrapped_func_returns_function():\n                assert fixture_function_def_test_func._get_wrapped_function()() == 9\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(passed=2)\n\n    def test_fixture_wrapped_looks_liked_wrapped_function(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Ensure that `FixtureFunctionDefinition` behaves like the function it wrapped.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def fixture_function_def_test_func():\n                return 9\n            fixture_function_def_test_func.__doc__ = \"documentation\"\n\n            def test_fixture_has_same_doc():\n                assert fixture_function_def_test_func.__doc__ == \"documentation\"\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(passed=1)\n\n\nclass TestFixtureManagerParseFactories:\n    @pytest.fixture\n    def pytester(self, pytester: Pytester) -> Pytester:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def hello(request):\n                return \"conftest\"\n\n            @pytest.fixture\n            def fm(request):\n                return request._fixturemanager\n\n            @pytest.fixture\n            def item(request):\n                return request._pyfuncitem\n        \"\"\"\n        )\n        return pytester\n\n    def test_parsefactories_evil_objects_issue214(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            class A(object):\n                def __call__(self):\n                    pass\n                def __getattr__(self, name):\n                    raise RuntimeError()\n            a = A()\n            def test_hello():\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1, failed=0)\n\n    def test_parsefactories_conftest(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_hello(item, fm):\n                for name in (\"fm\", \"hello\", \"item\"):\n                    faclist = fm.getfixturedefs(name, item)\n                    assert len(faclist) == 1\n                    fac = faclist[0]\n                    assert fac.func.__name__ == name\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(passed=1)\n\n    def test_parsefactories_conftest_and_module_and_class(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n            import pytest\n\n            @pytest.fixture\n            def hello(request):\n                return \"module\"\n            class TestClass(object):\n                @pytest.fixture\n                def hello(self, request):\n                    return \"class\"\n                def test_hello(self, item, fm):\n                    faclist = fm.getfixturedefs(\"hello\", item)\n                    print(faclist)\n                    assert len(faclist) == 3\n\n                    assert faclist[0].func(item._request) == \"conftest\"\n                    assert faclist[1].func(item._request) == \"module\"\n                    assert faclist[2].func(item._request) == \"class\"\n            \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(passed=1)\n\n    def test_parsefactories_relative_node_ids(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        # example mostly taken from:\n        # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html\n        runner = pytester.mkdir(\"runner\")\n        package = pytester.mkdir(\"package\")\n        package.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            import pytest\n            @pytest.fixture\n            def one():\n                return 1\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        package.joinpath(\"test_x.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                def test_x(one):\n                    assert one == 1\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        sub = package.joinpath(\"sub\")\n        sub.mkdir()\n        sub.joinpath(\"__init__.py\").touch()\n        sub.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n                @pytest.fixture\n                def one():\n                    return 2\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        sub.joinpath(\"test_y.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                def test_x(one):\n                    assert one == 2\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n        with monkeypatch.context() as mp:\n            mp.chdir(runner)\n            reprec = pytester.inline_run(\"..\")\n            reprec.assertoutcome(passed=2)\n\n    def test_package_xunit_fixture(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            __init__=\"\"\"\\\n            values = []\n        \"\"\"\n        )\n        package = pytester.mkdir(\"package\")\n        package.joinpath(\"__init__.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                from .. import values\n                def setup_module():\n                    values.append(\"package\")\n                def teardown_module():\n                    values[:] = []\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        package.joinpath(\"test_x.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                from .. import values\n                def test_x():\n                    assert values == [\"package\"]\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        package = pytester.mkdir(\"package2\")\n        package.joinpath(\"__init__.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                from .. import values\n                def setup_module():\n                    values.append(\"package2\")\n                def teardown_module():\n                    values[:] = []\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        package.joinpath(\"test_x.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                from .. import values\n                def test_x():\n                    assert values == [\"package2\"]\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_package_fixture_complex(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            __init__=\"\"\"\\\n            values = []\n        \"\"\"\n        )\n        pytester.syspathinsert(pytester.path.name)\n        package = pytester.mkdir(\"package\")\n        package.joinpath(\"__init__.py\").write_text(\"\", encoding=\"utf-8\")\n        package.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n                from .. import values\n                @pytest.fixture(scope=\"package\")\n                def one():\n                    values.append(\"package\")\n                    yield values\n                    values.pop()\n                @pytest.fixture(scope=\"package\", autouse=True)\n                def two():\n                    values.append(\"package-auto\")\n                    yield values\n                    values.pop()\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        package.joinpath(\"test_x.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                from .. import values\n                def test_package_autouse():\n                    assert values == [\"package-auto\"]\n                def test_package(one):\n                    assert values == [\"package-auto\", \"package\"]\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_collect_custom_items(self, pytester: Pytester) -> None:\n        pytester.copy_example(\"fixtures/custom_item\")\n        result = pytester.runpytest(\"foo\")\n        result.stdout.fnmatch_lines([\"*passed*\"])\n\n\nclass TestAutouseDiscovery:\n    @pytest.fixture\n    def pytester(self, pytester: Pytester) -> Pytester:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            @pytest.fixture(autouse=True)\n            def perfunction(request, tmp_path):\n                pass\n\n            @pytest.fixture()\n            def arg1(tmp_path):\n                pass\n            @pytest.fixture(autouse=True)\n            def perfunction2(arg1):\n                pass\n\n            @pytest.fixture\n            def fm(request):\n                return request._fixturemanager\n\n            @pytest.fixture\n            def item(request):\n                return request._pyfuncitem\n        \"\"\"\n        )\n        return pytester\n\n    def test_parsefactories_conftest(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            from _pytest.pytester import get_public_names\n            def test_check_setup(item, fm):\n                autousenames = list(fm._getautousenames(item))\n                assert len(get_public_names(autousenames)) == 2\n                assert \"perfunction2\" in autousenames\n                assert \"perfunction\" in autousenames\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(passed=1)\n\n    def test_two_classes_separated_autouse(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            class TestA(object):\n                values = []\n                @pytest.fixture(autouse=True)\n                def setup1(self):\n                    self.values.append(1)\n                def test_setup1(self):\n                    assert self.values == [1]\n            class TestB(object):\n                values = []\n                @pytest.fixture(autouse=True)\n                def setup2(self):\n                    self.values.append(1)\n                def test_setup2(self):\n                    assert self.values == [1]\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_setup_at_classlevel(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            class TestClass(object):\n                @pytest.fixture(autouse=True)\n                def permethod(self, request):\n                    request.instance.funcname = request.function.__name__\n                def test_method1(self):\n                    assert self.funcname == \"test_method1\"\n                def test_method2(self):\n                    assert self.funcname == \"test_method2\"\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(passed=2)\n\n    @pytest.mark.xfail(reason=\"'enabled' feature not implemented\")\n    def test_setup_enabled_functionnode(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def enabled(parentnode, markers):\n                return \"needsdb\" in markers\n\n            @pytest.fixture(params=[1,2])\n            def db(request):\n                return request.param\n\n            @pytest.fixture(enabled=enabled, autouse=True)\n            def createdb(db):\n                pass\n\n            def test_func1(request):\n                assert \"db\" not in request.fixturenames\n\n            @pytest.mark.needsdb\n            def test_func2(request):\n                assert \"db\" in request.fixturenames\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(passed=2)\n\n    def test_callables_nocode(self, pytester: Pytester) -> None:\n        \"\"\"An imported mock.call would break setup/factory discovery due to\n        it being callable and __code__ not being a code object.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n           class _call(tuple):\n               def __call__(self, *k, **kw):\n                   pass\n               def __getattr__(self, k):\n                   return self\n\n           call = _call()\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(failed=0, passed=0)\n\n    def test_autouse_in_conftests(self, pytester: Pytester) -> None:\n        a = pytester.mkdir(\"a\")\n        b = pytester.mkdir(\"a1\")\n        conftest = pytester.makeconftest(\n            \"\"\"\n            import pytest\n            @pytest.fixture(autouse=True)\n            def hello():\n                xxx\n        \"\"\"\n        )\n        conftest.rename(a.joinpath(conftest.name))\n        a.joinpath(\"test_something.py\").write_text(\n            \"def test_func(): pass\", encoding=\"utf-8\"\n        )\n        b.joinpath(\"test_otherthing.py\").write_text(\n            \"def test_func(): pass\", encoding=\"utf-8\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *1 passed*1 error*\n        \"\"\"\n        )\n\n    def test_autouse_in_module_and_two_classes(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(autouse=True)\n            def append1():\n                values.append(\"module\")\n            def test_x():\n                assert values == [\"module\"]\n\n            class TestA(object):\n                @pytest.fixture(autouse=True)\n                def append2(self):\n                    values.append(\"A\")\n                def test_hello(self):\n                    assert values == [\"module\", \"module\", \"A\"], values\n            class TestA2(object):\n                def test_world(self):\n                    assert values == [\"module\", \"module\", \"A\", \"module\"], values\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=3)\n\n\nclass TestAutouseManagement:\n    def test_autouse_conftest_mid_directory(self, pytester: Pytester) -> None:\n        pkgdir = pytester.mkpydir(\"xyz123\")\n        pkgdir.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n                @pytest.fixture(autouse=True)\n                def app():\n                    import sys\n                    sys._myapp = \"hello\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        sub = pkgdir.joinpath(\"tests\")\n        sub.mkdir()\n        t = sub.joinpath(\"test_app.py\")\n        t.touch()\n        t.write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import sys\n                def test_app():\n                    assert sys._myapp == \"hello\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(passed=1)\n\n    def test_funcarg_and_setup(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(scope=\"module\")\n            def arg():\n                values.append(1)\n                return 0\n            @pytest.fixture(scope=\"module\", autouse=True)\n            def something(arg):\n                values.append(2)\n\n            def test_hello(arg):\n                assert len(values) == 2\n                assert values == [1,2]\n                assert arg == 0\n\n            def test_hello2(arg):\n                assert len(values) == 2\n                assert values == [1,2]\n                assert arg == 0\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_uses_parametrized_resource(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(params=[1,2])\n            def arg(request):\n                return request.param\n\n            @pytest.fixture(autouse=True)\n            def something(arg):\n                values.append(arg)\n\n            def test_hello():\n                if len(values) == 1:\n                    assert values == [1]\n                elif len(values) == 2:\n                    assert values == [1, 2]\n                else:\n                    0/0\n\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(passed=2)\n\n    def test_session_parametrized_function(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            values = []\n\n            @pytest.fixture(scope=\"session\", params=[1,2])\n            def arg(request):\n               return request.param\n\n            @pytest.fixture(scope=\"function\", autouse=True)\n            def append(request, arg):\n                if request.function.__name__ == \"test_some\":\n                    values.append(arg)\n\n            def test_some():\n                pass\n\n            def test_result(arg):\n                assert len(values) == arg\n                assert values[:arg] == [1,2][:arg]\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-v\", \"-s\")\n        reprec.assertoutcome(passed=4)\n\n    def test_class_function_parametrization_finalization(\n        self, pytester: Pytester\n    ) -> None:\n        p = pytester.makeconftest(\n            \"\"\"\n            import pytest\n            import pprint\n\n            values = []\n\n            @pytest.fixture(scope=\"function\", params=[1,2])\n            def farg(request):\n                return request.param\n\n            @pytest.fixture(scope=\"class\", params=list(\"ab\"))\n            def carg(request):\n                return request.param\n\n            @pytest.fixture(scope=\"function\", autouse=True)\n            def append(request, farg, carg):\n                def fin():\n                    values.append(\"fin_%s%s\" % (carg, farg))\n                request.addfinalizer(fin)\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            class TestClass(object):\n                def test_1(self):\n                    pass\n            class TestClass2(object):\n                def test_2(self):\n                    pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-v\", \"-s\", \"--confcutdir\", pytester.path)\n        reprec.assertoutcome(passed=8)\n        config = reprec.getcalls(\"pytest_unconfigure\")[0].config\n        values = config.pluginmanager._getconftestmodules(p)[0].values\n        assert values == [\"fin_a1\", \"fin_a2\", \"fin_b1\", \"fin_b2\"] * 2\n\n    def test_scope_ordering(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(scope=\"function\", autouse=True)\n            def fappend2():\n                values.append(2)\n            @pytest.fixture(scope=\"class\", autouse=True)\n            def classappend3():\n                values.append(3)\n            @pytest.fixture(scope=\"module\", autouse=True)\n            def mappend():\n                values.append(1)\n\n            class TestHallo(object):\n                def test_method(self):\n                    assert values == [1,3,2]\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_parametrization_setup_teardown_ordering(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            def pytest_generate_tests(metafunc):\n                if metafunc.cls is None:\n                    assert metafunc.function is test_finish\n                if metafunc.cls is not None:\n                    metafunc.parametrize(\"item\", [1,2], scope=\"class\")\n            class TestClass(object):\n                @pytest.fixture(scope=\"class\", autouse=True)\n                def addteardown(self, item, request):\n                    values.append(\"setup-%d\" % item)\n                    request.addfinalizer(lambda: values.append(\"teardown-%d\" % item))\n                def test_step1(self, item):\n                    values.append(\"step1-%d\" % item)\n                def test_step2(self, item):\n                    values.append(\"step2-%d\" % item)\n\n            def test_finish():\n                print(values)\n                assert values == [\"setup-1\", \"step1-1\", \"step2-1\", \"teardown-1\",\n                             \"setup-2\", \"step1-2\", \"step2-2\", \"teardown-2\",]\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(passed=5)\n\n    def test_ordering_autouse_before_explicit(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            values = []\n            @pytest.fixture(autouse=True)\n            def fix1():\n                values.append(1)\n            @pytest.fixture()\n            def arg1():\n                values.append(2)\n            def test_hello(arg1):\n                assert values == [1,2]\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    @pytest.mark.parametrize(\"param1\", [\"\", \"params=[1]\"], ids=[\"p00\", \"p01\"])\n    @pytest.mark.parametrize(\"param2\", [\"\", \"params=[1]\"], ids=[\"p10\", \"p11\"])\n    def test_ordering_dependencies_torndown_first(\n        self, pytester: Pytester, param1, param2\n    ) -> None:\n        \"\"\"#226\"\"\"\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest\n            values = []\n            @pytest.fixture({param1})\n            def arg1(request):\n                request.addfinalizer(lambda: values.append(\"fin1\"))\n                values.append(\"new1\")\n            @pytest.fixture({param2})\n            def arg2(request, arg1):\n                request.addfinalizer(lambda: values.append(\"fin2\"))\n                values.append(\"new2\")\n\n            def test_arg(arg2):\n                pass\n            def test_check():\n                assert values == [\"new1\", \"new2\", \"fin2\", \"fin1\"]\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        reprec.assertoutcome(passed=2)\n\n    def test_reordering_catastrophic_performance(self, pytester: Pytester) -> None:\n        \"\"\"Check that a certain high-scope parametrization pattern doesn't cause\n        a catasrophic slowdown.\n\n        Regression test for #12355.\n        \"\"\"\n        pytester.makepyfile(\"\"\"\n            import pytest\n\n            params = tuple(\"abcdefghijklmnopqrstuvwxyz\")\n            @pytest.mark.parametrize(params, [range(len(params))] * 3, scope=\"module\")\n            def test_parametrize(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z):\n                pass\n        \"\"\")\n\n        result = pytester.runpytest()\n\n        result.assert_outcomes(passed=3)\n\n\nclass TestFixtureMarker:\n    def test_parametrize(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(params=[\"a\", \"b\", \"c\"])\n            def arg(request):\n                return request.param\n            values = []\n            def test_param(arg):\n                values.append(arg)\n            def test_result():\n                assert values == list(\"abc\")\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=4)\n\n    def test_multiple_parametrization_issue_736(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[1,2,3])\n            def foo(request):\n                return request.param\n\n            @pytest.mark.parametrize('foobar', [4,5,6])\n            def test_issue(foo, foobar):\n                assert foo in [1,2,3]\n                assert foobar in [4,5,6]\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=9)\n\n    @pytest.mark.parametrize(\n        \"param_args\",\n        [\"'fixt, val'\", \"'fixt,val'\", \"['fixt', 'val']\", \"('fixt', 'val')\"],\n    )\n    def test_override_parametrized_fixture_issue_979(\n        self, pytester: Pytester, param_args\n    ) -> None:\n        \"\"\"Make sure a parametrized argument can override a parametrized fixture.\n\n        This was a regression introduced in the fix for #736.\n        \"\"\"\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest\n\n            @pytest.fixture(params=[1, 2])\n            def fixt(request):\n                return request.param\n\n            @pytest.mark.parametrize({param_args}, [(3, 'x'), (4, 'x')])\n            def test_foo(fixt, val):\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_scope_session(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(scope=\"module\")\n            def arg():\n                values.append(1)\n                return 1\n\n            def test_1(arg):\n                assert arg == 1\n            def test_2(arg):\n                assert arg == 1\n                assert len(values) == 1\n            class TestClass(object):\n                def test3(self, arg):\n                    assert arg == 1\n                    assert len(values) == 1\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=3)\n\n    def test_scope_session_exc(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(scope=\"session\")\n            def fix():\n                values.append(1)\n                pytest.skip('skipping')\n\n            def test_1(fix):\n                pass\n            def test_2(fix):\n                pass\n            def test_last():\n                assert values == [1]\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(skipped=2, passed=1)\n\n    def test_scope_session_exc_two_fix(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            m = []\n            @pytest.fixture(scope=\"session\")\n            def a():\n                values.append(1)\n                pytest.skip('skipping')\n            @pytest.fixture(scope=\"session\")\n            def b(a):\n                m.append(1)\n\n            def test_1(b):\n                pass\n            def test_2(b):\n                pass\n            def test_last():\n                assert values == [1]\n                assert m == []\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(skipped=2, passed=1)\n\n    def test_scope_exc(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_foo=\"\"\"\n                def test_foo(fix):\n                    pass\n            \"\"\",\n            test_bar=\"\"\"\n                def test_bar(fix):\n                    pass\n            \"\"\",\n            conftest=\"\"\"\n                import pytest\n                reqs = []\n                @pytest.fixture(scope=\"session\")\n                def fix(request):\n                    reqs.append(1)\n                    pytest.skip()\n                @pytest.fixture\n                def req_list():\n                    return reqs\n            \"\"\",\n            test_real=\"\"\"\n                def test_last(req_list):\n                    assert req_list == [1]\n            \"\"\",\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(skipped=2, passed=1)\n\n    def test_scope_module_uses_session(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(scope=\"module\")\n            def arg():\n                values.append(1)\n                return 1\n\n            def test_1(arg):\n                assert arg == 1\n            def test_2(arg):\n                assert arg == 1\n                assert len(values) == 1\n            class TestClass(object):\n                def test3(self, arg):\n                    assert arg == 1\n                    assert len(values) == 1\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=3)\n\n    def test_scope_module_and_finalizer(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            finalized_list = []\n            created_list = []\n            @pytest.fixture(scope=\"module\")\n            def arg(request):\n                created_list.append(1)\n                assert request.scope == \"module\"\n                request.addfinalizer(lambda: finalized_list.append(1))\n            @pytest.fixture\n            def created(request):\n                return len(created_list)\n            @pytest.fixture\n            def finalized(request):\n                return len(finalized_list)\n        \"\"\"\n        )\n        pytester.makepyfile(\n            test_mod1=\"\"\"\n                def test_1(arg, created, finalized):\n                    assert created == 1\n                    assert finalized == 0\n                def test_2(arg, created, finalized):\n                    assert created == 1\n                    assert finalized == 0\"\"\",\n            test_mod2=\"\"\"\n                def test_3(arg, created, finalized):\n                    assert created == 2\n                    assert finalized == 1\"\"\",\n            test_mode3=\"\"\"\n                def test_4(arg, created, finalized):\n                    assert created == 3\n                    assert finalized == 2\n            \"\"\",\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=4)\n\n    def test_scope_mismatch_various(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            finalized = []\n            created = []\n            @pytest.fixture(scope=\"function\")\n            def arg(request):\n                pass\n        \"\"\"\n        )\n        pytester.makepyfile(\n            test_mod1=\"\"\"\n                import pytest\n                @pytest.fixture(scope=\"session\")\n                def arg(request):\n                    request.getfixturevalue(\"arg\")\n                def test_1(arg):\n                    pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret != 0\n        result.stdout.fnmatch_lines(\n            [\"*ScopeMismatch*You tried*function*session*request*\"]\n        )\n\n    def test_scope_mismatch_already_computed_dynamic(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_it=\"\"\"\n                import pytest\n\n                @pytest.fixture(scope=\"function\")\n                def fixfunc(): pass\n\n                @pytest.fixture(scope=\"module\")\n                def fixmod(fixfunc): pass\n\n                def test_it(request, fixfunc):\n                    request.getfixturevalue(\"fixmod\")\n            \"\"\",\n        )\n\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.TESTS_FAILED\n        result.stdout.fnmatch_lines(\n            [\n                \"*ScopeMismatch*Requesting fixture stack*\",\n                \"test_it.py:6:  def fixmod(fixfunc)\",\n                \"Requested fixture:\",\n                \"test_it.py:3:  def fixfunc()\",\n            ]\n        )\n\n    def test_dynamic_scope(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n\n            def pytest_addoption(parser):\n                parser.addoption(\"--extend-scope\", action=\"store_true\", default=False)\n\n\n            def dynamic_scope(fixture_name, config):\n                if config.getoption(\"--extend-scope\"):\n                    return \"session\"\n                return \"function\"\n\n\n            @pytest.fixture(scope=dynamic_scope)\n            def dynamic_fixture(calls=[]):\n                calls.append(\"call\")\n                return len(calls)\n\n        \"\"\"\n        )\n\n        pytester.makepyfile(\n            \"\"\"\n            def test_first(dynamic_fixture):\n                assert dynamic_fixture == 1\n\n\n            def test_second(dynamic_fixture):\n                assert dynamic_fixture == 2\n\n        \"\"\"\n        )\n\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n        reprec = pytester.inline_run(\"--extend-scope\")\n        reprec.assertoutcome(passed=1, failed=1)\n\n    def test_dynamic_scope_bad_return(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def dynamic_scope(**_):\n                return \"wrong-scope\"\n\n            @pytest.fixture(scope=dynamic_scope)\n            def fixture():\n                pass\n\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            \"Fixture 'fixture' from test_dynamic_scope_bad_return.py \"\n            \"got an unexpected scope value 'wrong-scope'\"\n        )\n\n    def test_register_only_with_mark(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            @pytest.fixture()\n            def arg():\n                return 1\n        \"\"\"\n        )\n        pytester.makepyfile(\n            test_mod1=\"\"\"\n                import pytest\n                @pytest.fixture()\n                def arg(arg):\n                    return arg + 1\n                def test_1(arg):\n                    assert arg == 2\n            \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_parametrize_and_scope(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"module\", params=[\"a\", \"b\", \"c\"])\n            def arg(request):\n                return request.param\n            values = []\n            def test_param(arg):\n                values.append(arg)\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-v\")\n        reprec.assertoutcome(passed=3)\n        values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n        assert len(values) == 3\n        assert \"a\" in values\n        assert \"b\" in values\n        assert \"c\" in values\n\n    def test_scope_mismatch(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"function\")\n            def arg(request):\n                pass\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"session\")\n            def arg(arg):\n                pass\n            def test_mismatch(arg):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*ScopeMismatch*\", \"*1 error*\"])\n\n    def test_parametrize_separated_order(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"module\", params=[1, 2])\n            def arg(request):\n                return request.param\n\n            values = []\n            def test_1(arg):\n                values.append(arg)\n            def test_2(arg):\n                values.append(arg)\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-v\")\n        reprec.assertoutcome(passed=4)\n        values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n        assert values == [1, 1, 2, 2]\n\n    def test_module_parametrized_ordering(self, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style=classic\n        \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"session\", params=\"s1 s2\".split())\n            def sarg():\n                pass\n            @pytest.fixture(scope=\"module\", params=\"m1 m2\".split())\n            def marg():\n                pass\n        \"\"\"\n        )\n        pytester.makepyfile(\n            test_mod1=\"\"\"\n            def test_func(sarg):\n                pass\n            def test_func1(marg):\n                pass\n        \"\"\",\n            test_mod2=\"\"\"\n            def test_func2(sarg):\n                pass\n            def test_func3(sarg, marg):\n                pass\n            def test_func3b(sarg, marg):\n                pass\n            def test_func4(marg):\n                pass\n        \"\"\",\n        )\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            test_mod1.py::test_func[s1] PASSED\n            test_mod2.py::test_func2[s1] PASSED\n            test_mod2.py::test_func3[s1-m1] PASSED\n            test_mod2.py::test_func3b[s1-m1] PASSED\n            test_mod2.py::test_func3[s1-m2] PASSED\n            test_mod2.py::test_func3b[s1-m2] PASSED\n            test_mod1.py::test_func[s2] PASSED\n            test_mod2.py::test_func2[s2] PASSED\n            test_mod2.py::test_func3[s2-m1] PASSED\n            test_mod2.py::test_func3b[s2-m1] PASSED\n            test_mod2.py::test_func4[m1] PASSED\n            test_mod2.py::test_func3[s2-m2] PASSED\n            test_mod2.py::test_func3b[s2-m2] PASSED\n            test_mod2.py::test_func4[m2] PASSED\n            test_mod1.py::test_func1[m1] PASSED\n            test_mod1.py::test_func1[m2] PASSED\n        \"\"\"\n        )\n\n    def test_dynamic_parametrized_ordering(self, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style=classic\n        \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            def pytest_configure(config):\n                class DynamicFixturePlugin(object):\n                    @pytest.fixture(scope='session', params=['flavor1', 'flavor2'])\n                    def flavor(self, request):\n                        return request.param\n                config.pluginmanager.register(DynamicFixturePlugin(), 'flavor-fixture')\n\n            @pytest.fixture(scope='session', params=['vxlan', 'vlan'])\n            def encap(request):\n                return request.param\n\n            @pytest.fixture(scope='session', autouse='True')\n            def reprovision(request, flavor, encap):\n                pass\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test(reprovision):\n                pass\n            def test2(reprovision):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            test_dynamic_parametrized_ordering.py::test[flavor1-vxlan] PASSED\n            test_dynamic_parametrized_ordering.py::test2[flavor1-vxlan] PASSED\n            test_dynamic_parametrized_ordering.py::test[flavor1-vlan] PASSED\n            test_dynamic_parametrized_ordering.py::test2[flavor1-vlan] PASSED\n            test_dynamic_parametrized_ordering.py::test[flavor2-vlan] PASSED\n            test_dynamic_parametrized_ordering.py::test2[flavor2-vlan] PASSED\n            test_dynamic_parametrized_ordering.py::test[flavor2-vxlan] PASSED\n            test_dynamic_parametrized_ordering.py::test2[flavor2-vxlan] PASSED\n        \"\"\"\n        )\n\n    def test_class_ordering(self, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style=classic\n        \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            values = []\n\n            @pytest.fixture(scope=\"function\", params=[1,2])\n            def farg(request):\n                return request.param\n\n            @pytest.fixture(scope=\"class\", params=list(\"ab\"))\n            def carg(request):\n                return request.param\n\n            @pytest.fixture(scope=\"function\", autouse=True)\n            def append(request, farg, carg):\n                def fin():\n                    values.append(\"fin_%s%s\" % (carg, farg))\n                request.addfinalizer(fin)\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            class TestClass2(object):\n                def test_1(self):\n                    pass\n                def test_2(self):\n                    pass\n            class TestClass(object):\n                def test_3(self):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-vs\")\n        result.stdout.re_match_lines(\n            r\"\"\"\n            test_class_ordering.py::TestClass2::test_1\\[a-1\\] PASSED\n            test_class_ordering.py::TestClass2::test_1\\[a-2\\] PASSED\n            test_class_ordering.py::TestClass2::test_2\\[a-1\\] PASSED\n            test_class_ordering.py::TestClass2::test_2\\[a-2\\] PASSED\n            test_class_ordering.py::TestClass2::test_1\\[b-1\\] PASSED\n            test_class_ordering.py::TestClass2::test_1\\[b-2\\] PASSED\n            test_class_ordering.py::TestClass2::test_2\\[b-1\\] PASSED\n            test_class_ordering.py::TestClass2::test_2\\[b-2\\] PASSED\n            test_class_ordering.py::TestClass::test_3\\[a-1\\] PASSED\n            test_class_ordering.py::TestClass::test_3\\[a-2\\] PASSED\n            test_class_ordering.py::TestClass::test_3\\[b-1\\] PASSED\n            test_class_ordering.py::TestClass::test_3\\[b-2\\] PASSED\n        \"\"\"\n        )\n\n    def test_parametrize_separated_order_higher_scope_first(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"function\", params=[1, 2])\n            def arg(request):\n                param = request.param\n                request.addfinalizer(lambda: values.append(\"fin:%s\" % param))\n                values.append(\"create:%s\" % param)\n                return request.param\n\n            @pytest.fixture(scope=\"module\", params=[\"mod1\", \"mod2\"])\n            def modarg(request):\n                param = request.param\n                request.addfinalizer(lambda: values.append(\"fin:%s\" % param))\n                values.append(\"create:%s\" % param)\n                return request.param\n\n            values = []\n            def test_1(arg):\n                values.append(\"test1\")\n            def test_2(modarg):\n                values.append(\"test2\")\n            def test_3(arg, modarg):\n                values.append(\"test3\")\n            def test_4(modarg, arg):\n                values.append(\"test4\")\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-v\")\n        reprec.assertoutcome(passed=12)\n        values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n        expected = [\n            \"create:1\",\n            \"test1\",\n            \"fin:1\",\n            \"create:2\",\n            \"test1\",\n            \"fin:2\",\n            \"create:mod1\",\n            \"test2\",\n            \"create:1\",\n            \"test3\",\n            \"fin:1\",\n            \"create:2\",\n            \"test3\",\n            \"fin:2\",\n            \"create:1\",\n            \"test4\",\n            \"fin:1\",\n            \"create:2\",\n            \"test4\",\n            \"fin:2\",\n            \"fin:mod1\",\n            \"create:mod2\",\n            \"test2\",\n            \"create:1\",\n            \"test3\",\n            \"fin:1\",\n            \"create:2\",\n            \"test3\",\n            \"fin:2\",\n            \"create:1\",\n            \"test4\",\n            \"fin:1\",\n            \"create:2\",\n            \"test4\",\n            \"fin:2\",\n            \"fin:mod2\",\n        ]\n        import pprint\n\n        pprint.pprint(list(zip_longest(values, expected)))\n        assert values == expected\n\n    def test_parametrized_fixture_teardown_order(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(params=[1,2], scope=\"class\")\n            def param1(request):\n                return request.param\n\n            values = []\n\n            class TestClass(object):\n                @classmethod\n                @pytest.fixture(scope=\"class\", autouse=True)\n                def setup1(self, request, param1):\n                    values.append(1)\n                    request.addfinalizer(self.teardown1)\n                @classmethod\n                def teardown1(self):\n                    assert values.pop() == 1\n                @pytest.fixture(scope=\"class\", autouse=True)\n                def setup2(self, request, param1):\n                    values.append(2)\n                    request.addfinalizer(self.teardown2)\n                @classmethod\n                def teardown2(self):\n                    assert values.pop() == 2\n                def test(self):\n                    pass\n\n            def test_finish():\n                assert not values\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *3 passed*\n        \"\"\"\n        )\n        assert result.ret == 0\n\n    def test_fixture_finalizer(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            import sys\n\n            @pytest.fixture\n            def browser(request):\n\n                def finalize():\n                    sys.stdout.write_text('Finalized', encoding='utf-8')\n                request.addfinalizer(finalize)\n                return {}\n        \"\"\"\n        )\n        b = pytester.mkdir(\"subdir\")\n        b.joinpath(\"test_overridden_fixture_finalizer.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n                @pytest.fixture\n                def browser(browser):\n                    browser['visited'] = True\n                    return browser\n\n                def test_browser(browser):\n                    assert browser['visited'] is True\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        reprec = pytester.runpytest(\"-s\")\n        for test in [\"test_browser\"]:\n            reprec.stdout.fnmatch_lines([\"*Finalized*\"])\n\n    def test_class_scope_with_normal_tests(self, pytester: Pytester) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            class Box(object):\n                value = 0\n\n            @pytest.fixture(scope='class')\n            def a(request):\n                Box.value += 1\n                return Box.value\n\n            def test_a(a):\n                assert a == 1\n\n            class Test1(object):\n                def test_b(self, a):\n                    assert a == 2\n\n            class Test2(object):\n                def test_c(self, a):\n                    assert a == 3\"\"\"\n        )\n        reprec = pytester.inline_run(testpath)\n        for test in [\"test_a\", \"test_b\", \"test_c\"]:\n            assert reprec.matchreport(test).passed\n\n    def test_request_is_clean(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(params=[1, 2])\n            def fix(request):\n                request.addfinalizer(lambda: values.append(request.param))\n            def test_fix(fix):\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-s\")\n        values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n        assert values == [1, 2]\n\n    def test_parametrize_separated_lifecycle(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            values = []\n            @pytest.fixture(scope=\"module\", params=[1, 2])\n            def arg(request):\n                x = request.param\n                request.addfinalizer(lambda: values.append(\"fin%s\" % x))\n                return request.param\n            def test_1(arg):\n                values.append(arg)\n            def test_2(arg):\n                values.append(arg)\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-vs\")\n        reprec.assertoutcome(passed=4)\n        values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n        import pprint\n\n        pprint.pprint(values)\n        # assert len(values) == 6\n        assert values[0] == values[1] == 1\n        assert values[2] == \"fin1\"\n        assert values[3] == values[4] == 2\n        assert values[5] == \"fin2\"\n\n    def test_parametrize_function_scoped_finalizers_called(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"function\", params=[1, 2])\n            def arg(request):\n                x = request.param\n                request.addfinalizer(lambda: values.append(\"fin%s\" % x))\n                return request.param\n\n            values = []\n            def test_1(arg):\n                values.append(arg)\n            def test_2(arg):\n                values.append(arg)\n            def test_3():\n                assert len(values) == 8\n                assert values == [1, \"fin1\", 2, \"fin2\", 1, \"fin1\", 2, \"fin2\"]\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-v\")\n        reprec.assertoutcome(passed=5)\n\n    @pytest.mark.parametrize(\"scope\", [\"session\", \"function\", \"module\"])\n    def test_finalizer_order_on_parametrization(\n        self, scope, pytester: Pytester\n    ) -> None:\n        \"\"\"#246\"\"\"\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest\n            values = []\n\n            @pytest.fixture(scope={scope!r}, params=[\"1\"])\n            def fix1(request):\n                return request.param\n\n            @pytest.fixture(scope={scope!r})\n            def fix2(request, base):\n                def cleanup_fix2():\n                    assert not values, \"base should not have been finalized\"\n                request.addfinalizer(cleanup_fix2)\n\n            @pytest.fixture(scope={scope!r})\n            def base(request, fix1):\n                def cleanup_base():\n                    values.append(\"fin_base\")\n                    print(\"finalizing base\")\n                request.addfinalizer(cleanup_base)\n\n            def test_begin():\n                pass\n            def test_baz(base, fix2):\n                pass\n            def test_other():\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-lvs\")\n        reprec.assertoutcome(passed=3)\n\n    def test_class_scope_parametrization_ordering(self, pytester: Pytester) -> None:\n        \"\"\"#396\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            values = []\n            @pytest.fixture(params=[\"John\", \"Doe\"], scope=\"class\")\n            def human(request):\n                request.addfinalizer(lambda: values.append(\"fin %s\" % request.param))\n                return request.param\n\n            class TestGreetings(object):\n                def test_hello(self, human):\n                    values.append(\"test_hello\")\n\n            class TestMetrics(object):\n                def test_name(self, human):\n                    values.append(\"test_name\")\n\n                def test_population(self, human):\n                    values.append(\"test_population\")\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=6)\n        values = reprec.getcalls(\"pytest_runtest_call\")[0].item.module.values\n        assert values == [\n            \"test_hello\",\n            \"fin John\",\n            \"test_hello\",\n            \"fin Doe\",\n            \"test_name\",\n            \"test_population\",\n            \"fin John\",\n            \"test_name\",\n            \"test_population\",\n            \"fin Doe\",\n        ]\n\n    def test_parametrize_setup_function(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"module\", params=[1, 2])\n            def arg(request):\n                return request.param\n\n            @pytest.fixture(scope=\"module\", autouse=True)\n            def mysetup(request, arg):\n                request.addfinalizer(lambda: values.append(\"fin%s\" % arg))\n                values.append(\"setup%s\" % arg)\n\n            values = []\n            def test_1(arg):\n                values.append(arg)\n            def test_2(arg):\n                values.append(arg)\n            def test_3():\n                import pprint\n                pprint.pprint(values)\n                if arg == 1:\n                    assert values == [\"setup1\", 1, 1, ]\n                elif arg == 2:\n                    assert values == [\"setup1\", 1, 1, \"fin1\",\n                                 \"setup2\", 2, 2, ]\n\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-v\")\n        reprec.assertoutcome(passed=6)\n\n    def test_fixture_marked_function_not_collected_as_test(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def test_app():\n                return 1\n\n            def test_something(test_app):\n                assert test_app == 1\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_params_and_ids(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[object(), object()],\n                            ids=['alpha', 'beta'])\n            def fix(request):\n                return request.param\n\n            def test_foo(fix):\n                assert 1\n        \"\"\"\n        )\n        res = pytester.runpytest(\"-v\")\n        res.stdout.fnmatch_lines([\"*test_foo*alpha*\", \"*test_foo*beta*\"])\n\n    def test_params_and_ids_yieldfixture(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[object(), object()], ids=['alpha', 'beta'])\n            def fix(request):\n                 yield request.param\n\n            def test_foo(fix):\n                assert 1\n        \"\"\"\n        )\n        res = pytester.runpytest(\"-v\")\n        res.stdout.fnmatch_lines([\"*test_foo*alpha*\", \"*test_foo*beta*\"])\n\n    def test_deterministic_fixture_collection(\n        self, pytester: Pytester, monkeypatch\n    ) -> None:\n        \"\"\"#920\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"module\",\n                            params=[\"A\",\n                                    \"B\",\n                                    \"C\"])\n            def A(request):\n                return request.param\n\n            @pytest.fixture(scope=\"module\",\n                            params=[\"DDDDDDDDD\", \"EEEEEEEEEEEE\", \"FFFFFFFFFFF\", \"banansda\"])\n            def B(request, A):\n                return request.param\n\n            def test_foo(B):\n                # Something funky is going on here.\n                # Despite specified seeds, on what is collected,\n                # sometimes we get unexpected passes. hashing B seems\n                # to help?\n                assert hash(B) or True\n            \"\"\"\n        )\n        monkeypatch.setenv(\"PYTHONHASHSEED\", \"1\")\n        out1 = pytester.runpytest_subprocess(\"-v\")\n        monkeypatch.setenv(\"PYTHONHASHSEED\", \"2\")\n        out2 = pytester.runpytest_subprocess(\"-v\")\n        output1 = [\n            line\n            for line in out1.outlines\n            if line.startswith(\"test_deterministic_fixture_collection.py::test_foo\")\n        ]\n        output2 = [\n            line\n            for line in out2.outlines\n            if line.startswith(\"test_deterministic_fixture_collection.py::test_foo\")\n        ]\n        assert len(output1) == 12\n        assert output1 == output2\n\n\nclass TestRequestScopeAccess:\n    pytestmark = pytest.mark.parametrize(\n        (\"scope\", \"ok\", \"error\"),\n        [\n            [\"session\", \"\", \"path class function module\"],\n            [\"module\", \"module path\", \"cls function\"],\n            [\"class\", \"module path cls\", \"function\"],\n            [\"function\", \"module path cls function\", \"\"],\n        ],\n    )\n\n    def test_setup(self, pytester: Pytester, scope, ok, error) -> None:\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest\n            @pytest.fixture(scope={scope!r}, autouse=True)\n            def myscoped(request):\n                for x in {ok.split()}:\n                    assert hasattr(request, x)\n                for x in {error.split()}:\n                    pytest.raises(AttributeError, lambda:\n                        getattr(request, x))\n                assert request.session\n                assert request.config\n            def test_func():\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-l\")\n        reprec.assertoutcome(passed=1)\n\n    def test_funcarg(self, pytester: Pytester, scope, ok, error) -> None:\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest\n            @pytest.fixture(scope={scope!r})\n            def arg(request):\n                for x in {ok.split()!r}:\n                    assert hasattr(request, x)\n                for x in {error.split()!r}:\n                    pytest.raises(AttributeError, lambda:\n                        getattr(request, x))\n                assert request.session\n                assert request.config\n            def test_func(arg):\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n\nclass TestErrors:\n    def test_subfactory_missing_funcarg(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture()\n            def gen(qwe123):\n                return 1\n            def test_something(gen):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret != 0\n        result.stdout.fnmatch_lines(\n            [\"*def gen(qwe123):*\", \"*fixture*qwe123*not found*\", \"*1 error*\"]\n        )\n\n    def test_issue498_fixture_finalizer_failing(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def fix1(request):\n                def f():\n                    raise KeyError\n                request.addfinalizer(f)\n                return object()\n\n            values = []\n            def test_1(fix1):\n                values.append(fix1)\n            def test_2(fix1):\n                values.append(fix1)\n            def test_3():\n                assert values[0] != values[1]\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *ERROR*teardown*test_1*\n            *KeyError*\n            *ERROR*teardown*test_2*\n            *KeyError*\n            *3 pass*2 errors*\n        \"\"\"\n        )\n\n    def test_setupfunc_missing_funcarg(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(autouse=True)\n            def gen(qwe123):\n                return 1\n            def test_something():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret != 0\n        result.stdout.fnmatch_lines(\n            [\"*def gen(qwe123):*\", \"*fixture*qwe123*not found*\", \"*1 error*\"]\n        )\n\n    def test_cached_exception_doesnt_get_longer(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #12204.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"session\")\n            def bad(): 1 / 0\n\n            def test_1(bad): pass\n            def test_2(bad): pass\n            def test_3(bad): pass\n            \"\"\"\n        )\n\n        result = pytester.runpytest_inprocess(\"--tb=native\")\n        assert result.ret == ExitCode.TESTS_FAILED\n        failures = result.reprec.getfailures()  # type: ignore[attr-defined]\n        assert len(failures) == 3\n        lines1 = failures[1].longrepr.reprtraceback.reprentries[0].lines\n        lines2 = failures[2].longrepr.reprtraceback.reprentries[0].lines\n        assert len(lines1) == len(lines2)\n\n\nclass TestShowFixtures:\n    def test_funcarg_compat(self, pytester: Pytester) -> None:\n        config = pytester.parseconfigure(\"--funcargs\")\n        assert config.option.showfixtures\n\n    def test_show_help(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"--fixtures\", \"--help\")\n        assert not result.ret\n\n    def test_show_fixtures(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"--fixtures\")\n        result.stdout.fnmatch_lines(\n            [\n                \"tmp_path_factory [[]session scope[]] -- .../_pytest/tmpdir.py:*\",\n                \"*for the test session*\",\n                \"tmp_path -- .../_pytest/tmpdir.py:*\",\n                \"*temporary directory*\",\n            ]\n        )\n\n    def test_show_fixtures_verbose(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"--fixtures\", \"-v\")\n        result.stdout.fnmatch_lines(\n            [\n                \"tmp_path_factory [[]session scope[]] -- .../_pytest/tmpdir.py:*\",\n                \"*for the test session*\",\n                \"tmp_path -- .../_pytest/tmpdir.py:*\",\n                \"*temporary directory*\",\n            ]\n        )\n\n    def test_show_fixtures_testmodule(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            '''\n            import pytest\n            @pytest.fixture\n            def _arg0():\n                \"\"\" hidden \"\"\"\n            @pytest.fixture\n            def arg1():\n                \"\"\"  hello world \"\"\"\n        '''\n        )\n        result = pytester.runpytest(\"--fixtures\", p)\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *tmp_path -- *\n            *fixtures defined from*\n            *arg1 -- test_show_fixtures_testmodule.py:6*\n            *hello world*\n        \"\"\"\n        )\n        result.stdout.no_fnmatch_line(\"*arg0*\")\n\n    @pytest.mark.parametrize(\"testmod\", [True, False])\n    def test_show_fixtures_conftest(self, pytester: Pytester, testmod) -> None:\n        pytester.makeconftest(\n            '''\n            import pytest\n            @pytest.fixture\n            def arg1():\n                \"\"\"  hello world \"\"\"\n        '''\n        )\n        if testmod:\n            pytester.makepyfile(\n                \"\"\"\n                def test_hello():\n                    pass\n            \"\"\"\n            )\n        result = pytester.runpytest(\"--fixtures\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *tmp_path*\n            *fixtures defined from*conftest*\n            *arg1*\n            *hello world*\n        \"\"\"\n        )\n\n    def test_show_fixtures_trimmed_doc(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            textwrap.dedent(\n                '''\\\n                import pytest\n                @pytest.fixture\n                def arg1():\n                    \"\"\"\n                    line1\n                    line2\n\n                    \"\"\"\n                @pytest.fixture\n                def arg2():\n                    \"\"\"\n                    line1\n                    line2\n\n                    \"\"\"\n                '''\n            )\n        )\n        result = pytester.runpytest(\"--fixtures\", p)\n        result.stdout.fnmatch_lines(\n            textwrap.dedent(\n                \"\"\"\\\n                * fixtures defined from test_show_fixtures_trimmed_doc *\n                arg2 -- test_show_fixtures_trimmed_doc.py:10\n                    line1\n                    line2\n                arg1 -- test_show_fixtures_trimmed_doc.py:3\n                    line1\n                    line2\n                \"\"\"\n            )\n        )\n\n    def test_show_fixtures_indented_doc(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            textwrap.dedent(\n                '''\\\n                import pytest\n                @pytest.fixture\n                def fixture1():\n                    \"\"\"\n                    line1\n                        indented line\n                    \"\"\"\n                '''\n            )\n        )\n        result = pytester.runpytest(\"--fixtures\", p)\n        result.stdout.fnmatch_lines(\n            textwrap.dedent(\n                \"\"\"\\\n                * fixtures defined from test_show_fixtures_indented_doc *\n                fixture1 -- test_show_fixtures_indented_doc.py:3\n                    line1\n                        indented line\n                \"\"\"\n            )\n        )\n\n    def test_show_fixtures_indented_doc_first_line_unindented(\n        self, pytester: Pytester\n    ) -> None:\n        p = pytester.makepyfile(\n            textwrap.dedent(\n                '''\\\n                import pytest\n                @pytest.fixture\n                def fixture1():\n                    \"\"\"line1\n                    line2\n                        indented line\n                    \"\"\"\n                '''\n            )\n        )\n        result = pytester.runpytest(\"--fixtures\", p)\n        result.stdout.fnmatch_lines(\n            textwrap.dedent(\n                \"\"\"\\\n                * fixtures defined from test_show_fixtures_indented_doc_first_line_unindented *\n                fixture1 -- test_show_fixtures_indented_doc_first_line_unindented.py:3\n                    line1\n                    line2\n                        indented line\n                \"\"\"\n            )\n        )\n\n    def test_show_fixtures_indented_in_class(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            textwrap.dedent(\n                '''\\\n                import pytest\n                class TestClass(object):\n                    @pytest.fixture\n                    def fixture1(self):\n                        \"\"\"line1\n                        line2\n                            indented line\n                        \"\"\"\n                '''\n            )\n        )\n        result = pytester.runpytest(\"--fixtures\", p)\n        result.stdout.fnmatch_lines(\n            textwrap.dedent(\n                \"\"\"\\\n                * fixtures defined from test_show_fixtures_indented_in_class *\n                fixture1 -- test_show_fixtures_indented_in_class.py:4\n                    line1\n                    line2\n                        indented line\n                \"\"\"\n            )\n        )\n\n    def test_show_fixtures_different_files(self, pytester: Pytester) -> None:\n        \"\"\"`--fixtures` only shows fixtures from first file (#833).\"\"\"\n        pytester.makepyfile(\n            test_a='''\n            import pytest\n\n            @pytest.fixture\n            def fix_a():\n                \"\"\"Fixture A\"\"\"\n                pass\n\n            def test_a(fix_a):\n                pass\n        '''\n        )\n        pytester.makepyfile(\n            test_b='''\n            import pytest\n\n            @pytest.fixture\n            def fix_b():\n                \"\"\"Fixture B\"\"\"\n                pass\n\n            def test_b(fix_b):\n                pass\n        '''\n        )\n        result = pytester.runpytest(\"--fixtures\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            * fixtures defined from test_a *\n            fix_a -- test_a.py:4\n                Fixture A\n\n            * fixtures defined from test_b *\n            fix_b -- test_b.py:4\n                Fixture B\n        \"\"\"\n        )\n\n    def test_show_fixtures_with_same_name(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            '''\n            import pytest\n            @pytest.fixture\n            def arg1():\n                \"\"\"Hello World in conftest.py\"\"\"\n                return \"Hello World\"\n        '''\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo(arg1):\n                assert arg1 == \"Hello World\"\n        \"\"\"\n        )\n        pytester.makepyfile(\n            '''\n            import pytest\n            @pytest.fixture\n            def arg1():\n                \"\"\"Hi from test module\"\"\"\n                return \"Hi\"\n            def test_bar(arg1):\n                assert arg1 == \"Hi\"\n        '''\n        )\n        result = pytester.runpytest(\"--fixtures\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            * fixtures defined from conftest *\n            arg1 -- conftest.py:3\n                Hello World in conftest.py\n\n            * fixtures defined from test_show_fixtures_with_same_name *\n            arg1 -- test_show_fixtures_with_same_name.py:3\n                Hi from test module\n        \"\"\"\n        )\n\n    def test_fixture_disallow_twice(self):\n        \"\"\"Test that applying @pytest.fixture twice generates an error (#2334).\"\"\"\n        with pytest.raises(ValueError):\n\n            @pytest.fixture\n            @pytest.fixture\n            def foo():\n                raise NotImplementedError()\n\n\nclass TestContextManagerFixtureFuncs:\n    def test_simple(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def arg1():\n                print(\"setup\")\n                yield 1\n                print(\"teardown\")\n            def test_1(arg1):\n                print(\"test1\", arg1)\n            def test_2(arg1):\n                print(\"test2\", arg1)\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *setup*\n            *test1 1*\n            *teardown*\n            *setup*\n            *test2 1*\n            *teardown*\n        \"\"\"\n        )\n\n    def test_scoped(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"module\")\n            def arg1():\n                print(\"setup\")\n                yield 1\n                print(\"teardown\")\n            def test_1(arg1):\n                print(\"test1\", arg1)\n            def test_2(arg1):\n                print(\"test2\", arg1)\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *setup*\n            *test1 1*\n            *test2 1*\n            *teardown*\n        \"\"\"\n        )\n\n    def test_setup_exception(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"module\")\n            def arg1():\n                pytest.fail(\"setup\")\n                yield 1\n            def test_1(arg1):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *pytest.fail*setup*\n            *1 error*\n        \"\"\"\n        )\n\n    def test_teardown_exception(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"module\")\n            def arg1():\n                yield 1\n                pytest.fail(\"teardown\")\n            def test_1(arg1):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *pytest.fail*teardown*\n            *1 passed*1 error*\n        \"\"\"\n        )\n\n    def test_yields_more_than_one(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"module\")\n            def arg1():\n                yield 1\n                yield 2\n            def test_1(arg1):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *fixture function*\n            *test_yields*:2*\n        \"\"\"\n        )\n\n    def test_custom_name(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(name='meow')\n            def arg1():\n                return 'mew'\n            def test_1(meow):\n                print(meow)\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\")\n        result.stdout.fnmatch_lines([\"*mew*\"])\n\n\nclass TestParameterizedSubRequest:\n    def test_call_from_fixture(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_call_from_fixture=\"\"\"\n            import pytest\n\n            @pytest.fixture(params=[0, 1, 2])\n            def fix_with_param(request):\n                return request.param\n\n            @pytest.fixture\n            def get_named_fixture(request):\n                return request.getfixturevalue('fix_with_param')\n\n            def test_foo(request, get_named_fixture):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"The requested fixture has no parameter defined for test:\",\n                \"    test_call_from_fixture.py::test_foo\",\n                \"Requested fixture 'fix_with_param' defined in:\",\n                \"test_call_from_fixture.py:4\",\n                \"Requested here:\",\n                \"test_call_from_fixture.py:9\",\n                \"*1 error in*\",\n            ]\n        )\n\n    def test_call_from_test(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_call_from_test=\"\"\"\n            import pytest\n\n            @pytest.fixture(params=[0, 1, 2])\n            def fix_with_param(request):\n                return request.param\n\n            def test_foo(request):\n                request.getfixturevalue('fix_with_param')\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"The requested fixture has no parameter defined for test:\",\n                \"    test_call_from_test.py::test_foo\",\n                \"Requested fixture 'fix_with_param' defined in:\",\n                \"test_call_from_test.py:4\",\n                \"Requested here:\",\n                \"test_call_from_test.py:8\",\n                \"*1 failed*\",\n            ]\n        )\n\n    def test_external_fixture(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(params=[0, 1, 2])\n            def fix_with_param(request):\n                return request.param\n            \"\"\"\n        )\n\n        pytester.makepyfile(\n            test_external_fixture=\"\"\"\n            def test_foo(request):\n                request.getfixturevalue('fix_with_param')\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"The requested fixture has no parameter defined for test:\",\n                \"    test_external_fixture.py::test_foo\",\n                \"\",\n                \"Requested fixture 'fix_with_param' defined in:\",\n                \"conftest.py:4\",\n                \"Requested here:\",\n                \"test_external_fixture.py:2\",\n                \"*1 failed*\",\n            ]\n        )\n\n    def test_non_relative_path(self, pytester: Pytester) -> None:\n        tests_dir = pytester.mkdir(\"tests\")\n        fixdir = pytester.mkdir(\"fixtures\")\n        fixfile = fixdir.joinpath(\"fix.py\")\n        fixfile.write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n\n                @pytest.fixture(params=[0, 1, 2])\n                def fix_with_param(request):\n                    return request.param\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        testfile = tests_dir.joinpath(\"test_foos.py\")\n        testfile.write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                from fix import fix_with_param\n\n                def test_foo(request):\n                    request.getfixturevalue('fix_with_param')\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        os.chdir(tests_dir)\n        pytester.syspathinsert(fixdir)\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"The requested fixture has no parameter defined for test:\",\n                \"    test_foos.py::test_foo\",\n                \"\",\n                \"Requested fixture 'fix_with_param' defined in:\",\n                f\"{fixfile}:4\",\n                \"Requested here:\",\n                \"test_foos.py:4\",\n                \"*1 failed*\",\n            ]\n        )\n\n        # With non-overlapping rootdir, passing tests_dir.\n        rootdir = pytester.mkdir(\"rootdir\")\n        os.chdir(rootdir)\n        result = pytester.runpytest(\"--rootdir\", rootdir, tests_dir)\n        result.stdout.fnmatch_lines(\n            [\n                \"The requested fixture has no parameter defined for test:\",\n                \"    test_foos.py::test_foo\",\n                \"\",\n                \"Requested fixture 'fix_with_param' defined in:\",\n                f\"{fixfile}:4\",\n                \"Requested here:\",\n                f\"{testfile}:4\",\n                \"*1 failed*\",\n            ]\n        )\n\n\ndef test_pytest_fixture_setup_and_post_finalizer_hook(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_fixture_setup(fixturedef, request):\n            print('ROOT setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n        def pytest_fixture_post_finalizer(fixturedef, request):\n            print('ROOT finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n    \"\"\"\n    )\n    pytester.makepyfile(\n        **{\n            \"tests/conftest.py\": \"\"\"\n            def pytest_fixture_setup(fixturedef, request):\n                print('TESTS setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n            def pytest_fixture_post_finalizer(fixturedef, request):\n                print('TESTS finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))\n        \"\"\",\n            \"tests/test_hooks.py\": \"\"\"\n            import pytest\n\n            @pytest.fixture()\n            def my_fixture():\n                return 'some'\n\n            def test_func(my_fixture):\n                print('TEST test_func')\n                assert my_fixture == 'some'\n        \"\"\",\n        }\n    )\n    result = pytester.runpytest(\"-s\")\n    assert result.ret == 0\n    result.stdout.fnmatch_lines(\n        [\n            \"*TESTS setup hook called for my_fixture from test_func*\",\n            \"*ROOT setup hook called for my_fixture from test_func*\",\n            \"*TEST test_func*\",\n            \"*TESTS finalizer hook called for my_fixture from test_func*\",\n            \"*ROOT finalizer hook called for my_fixture from test_func*\",\n        ]\n    )\n\n\ndef test_fixture_post_finalizer_called_once(pytester: Pytester) -> None:\n    \"\"\"Test that pytest_fixture_post_finalizer is called only once per fixture teardown.\n\n    When a fixture depends on multiple parametrized fixtures and all their parameters\n    change at the same time, the dependent fixture should be torn down only once,\n    and pytest_fixture_post_finalizer should be called only once for it.\n    \"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n\n        finalizer_calls = []\n\n        def pytest_fixture_post_finalizer(fixturedef, request):\n            finalizer_calls.append(fixturedef.argname)\n\n        @pytest.fixture(autouse=True)\n        def check_finalizer_calls(request):\n            yield\n            # After each test, verify no duplicate finalizer calls.\n            if finalizer_calls:\n                assert len(finalizer_calls) == len(set(finalizer_calls)), (\n                    f\"Duplicate finalizer calls detected: {finalizer_calls}\"\n                )\n                finalizer_calls.clear()\n        \"\"\"\n    )\n    pytester.makepyfile(\n        test_fixtures=\"\"\"\n        import pytest\n\n        @pytest.fixture(scope=\"session\")\n        def foo(request):\n            return request.param\n\n        @pytest.fixture(scope=\"session\")\n        def bar(request):\n            return request.param\n\n        @pytest.fixture(scope=\"session\")\n        def baz(foo, bar):\n            return f\"{foo}-{bar}\"\n\n        @pytest.mark.parametrize(\"foo,bar\", [(1, 1)], indirect=True)\n        def test_first(foo, bar, baz):\n            assert foo == 1\n            assert bar == 1\n            assert baz == \"1-1\"\n\n        @pytest.mark.parametrize(\"foo,bar\", [(2, 2)], indirect=True)\n        def test_second(foo, bar, baz):\n            assert foo == 2\n            assert bar == 2\n            assert baz == \"2-2\"\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    # The test passes, which means no duplicate finalizer calls were detected\n    # by the check_finalizer_calls autouse fixture.\n    result.assert_outcomes(passed=2)\n\n\ndef test_fixture_post_finalizer_hook_exception(pytester: Pytester) -> None:\n    \"\"\"Test that exceptions in pytest_fixture_post_finalizer hook are caught.\n\n    Also verifies that the fixture cache is properly reset even when the\n    post_finalizer hook raises an exception, so the fixture can be rebuilt\n    in subsequent tests.\n    \"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n\n        def pytest_fixture_post_finalizer(fixturedef, request):\n            if \"test_first\" in request.node.nodeid:\n                raise RuntimeError(\"Error in post finalizer hook\")\n\n        @pytest.fixture\n        def my_fixture(request):\n            yield request.node.nodeid\n        \"\"\"\n    )\n    pytester.makepyfile(\n        test_fixtures=\"\"\"\n        def test_first(my_fixture):\n            assert \"test_first\" in my_fixture\n\n        def test_second(my_fixture):\n            assert \"test_second\" in my_fixture\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\", \"--setup-show\")\n    result.assert_outcomes(passed=2, errors=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"*test_first*PASSED\",\n            \"*test_first*ERROR\",\n            \"*RuntimeError: Error in post finalizer hook*\",\n        ]\n    )\n    # Verify fixture is setup twice (rebuilt for test_second despite error).\n    result.stdout.fnmatch_lines(\n        [\n            \"test_fixtures.py::test_first \",\n            \"        SETUP    F my_fixture\",\n            \"        test_fixtures.py::test_first (fixtures used: my_fixture, request)PASSED\",\n            \"test_fixtures.py::test_first ERROR\",\n            \"test_fixtures.py::test_second \",\n            \"        SETUP    F my_fixture\",\n            \"        test_fixtures.py::test_second (fixtures used: my_fixture, request)PASSED\",\n            \"        TEARDOWN F my_fixture\",\n        ],\n        consecutive=True,\n    )\n\n\nclass TestScopeOrdering:\n    \"\"\"Class of tests that ensure fixtures are ordered based on their scopes (#2405)\"\"\"\n\n    @pytest.mark.parametrize(\"variant\", [\"mark\", \"autouse\"])\n    def test_func_closure_module_auto(\n        self, pytester: Pytester, variant, monkeypatch\n    ) -> None:\n        \"\"\"Semantically identical to the example posted in #2405 when ``use_mark=True``\"\"\"\n        monkeypatch.setenv(\"FIXTURE_ACTIVATION_VARIANT\", variant)\n        pytester.makepyfile(\n            \"\"\"\n            import warnings\n            import os\n            import pytest\n            VAR = 'FIXTURE_ACTIVATION_VARIANT'\n            VALID_VARS = ('autouse', 'mark')\n\n            VARIANT = os.environ.get(VAR)\n            if VARIANT is None or VARIANT not in VALID_VARS:\n                warnings.warn(\"{!r} is not  in {}, assuming autouse\".format(VARIANT, VALID_VARS) )\n                variant = 'mark'\n\n            @pytest.fixture(scope='module', autouse=VARIANT == 'autouse')\n            def m1(): pass\n\n            if VARIANT=='mark':\n                pytestmark = pytest.mark.usefixtures('m1')\n\n            @pytest.fixture(scope='function', autouse=True)\n            def f1(): pass\n\n            def test_func(m1):\n                pass\n        \"\"\"\n        )\n        items, _ = pytester.inline_genitems()\n        assert isinstance(items[0], Function)\n        request = TopRequest(items[0], _ispytest=True)\n        assert request.fixturenames == \"m1 f1\".split()\n\n    def test_func_closure_with_native_fixtures(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"Sanity check that verifies the order returned by the closures and the actual fixture execution order:\n        The execution order may differ because of fixture inter-dependencies.\n        \"\"\"\n        monkeypatch.setattr(pytest, \"FIXTURE_ORDER\", [], raising=False)\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            FIXTURE_ORDER = pytest.FIXTURE_ORDER\n\n            @pytest.fixture(scope=\"session\")\n            def s1():\n                FIXTURE_ORDER.append('s1')\n\n            @pytest.fixture(scope=\"package\")\n            def p1():\n                FIXTURE_ORDER.append('p1')\n\n            @pytest.fixture(scope=\"module\")\n            def m1():\n                FIXTURE_ORDER.append('m1')\n\n            @pytest.fixture(scope='session')\n            def my_tmp_path_factory():\n                FIXTURE_ORDER.append('my_tmp_path_factory')\n\n            @pytest.fixture\n            def my_tmp_path(my_tmp_path_factory):\n                FIXTURE_ORDER.append('my_tmp_path')\n\n            @pytest.fixture\n            def f1(my_tmp_path):\n                FIXTURE_ORDER.append('f1')\n\n            @pytest.fixture\n            def f2():\n                FIXTURE_ORDER.append('f2')\n\n            def test_foo(f1, p1, m1, f2, s1): pass\n        \"\"\"\n        )\n        items, _ = pytester.inline_genitems()\n        assert isinstance(items[0], Function)\n        request = TopRequest(items[0], _ispytest=True)\n        # order of fixtures based on their scope and position in the parameter list\n        assert (\n            request.fixturenames\n            == \"s1 my_tmp_path_factory p1 m1 f1 f2 my_tmp_path\".split()\n        )\n        pytester.runpytest()\n        # actual fixture execution differs: dependent fixtures must be created first (\"my_tmp_path\")\n        FIXTURE_ORDER = pytest.FIXTURE_ORDER  # type: ignore[attr-defined]\n        assert FIXTURE_ORDER == \"s1 my_tmp_path_factory p1 m1 my_tmp_path f1 f2\".split()\n\n    def test_func_closure_module(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='module')\n            def m1(): pass\n\n            @pytest.fixture(scope='function')\n            def f1(): pass\n\n            def test_func(f1, m1):\n                pass\n        \"\"\"\n        )\n        items, _ = pytester.inline_genitems()\n        assert isinstance(items[0], Function)\n        request = TopRequest(items[0], _ispytest=True)\n        assert request.fixturenames == \"m1 f1\".split()\n\n    def test_func_closure_scopes_reordered(self, pytester: Pytester) -> None:\n        \"\"\"Test ensures that fixtures are ordered by scope regardless of the order of the parameters, although\n        fixtures of same scope keep the declared order\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='session')\n            def s1(): pass\n\n            @pytest.fixture(scope='module')\n            def m1(): pass\n\n            @pytest.fixture(scope='function')\n            def f1(): pass\n\n            @pytest.fixture(scope='function')\n            def f2(): pass\n\n            class Test:\n\n                @pytest.fixture(scope='class')\n                def c1(cls): pass\n\n                def test_func(self, f2, f1, c1, m1, s1):\n                    pass\n        \"\"\"\n        )\n        items, _ = pytester.inline_genitems()\n        assert isinstance(items[0], Function)\n        request = TopRequest(items[0], _ispytest=True)\n        assert request.fixturenames == \"s1 m1 c1 f2 f1\".split()\n\n    def test_func_closure_same_scope_closer_root_first(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Auto-use fixtures of same scope are ordered by closer-to-root first\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='module', autouse=True)\n            def m_conf(): pass\n        \"\"\"\n        )\n        pytester.makepyfile(\n            **{\n                \"sub/conftest.py\": \"\"\"\n                import pytest\n\n                @pytest.fixture(scope='package', autouse=True)\n                def p_sub(): pass\n\n                @pytest.fixture(scope='module', autouse=True)\n                def m_sub(): pass\n            \"\"\",\n                \"sub/__init__.py\": \"\",\n                \"sub/test_func.py\": \"\"\"\n                import pytest\n\n                @pytest.fixture(scope='module', autouse=True)\n                def m_test(): pass\n\n                @pytest.fixture(scope='function')\n                def f1(): pass\n\n                def test_func(m_test, f1):\n                    pass\n        \"\"\",\n            }\n        )\n        items, _ = pytester.inline_genitems()\n        assert isinstance(items[0], Function)\n        request = TopRequest(items[0], _ispytest=True)\n        assert request.fixturenames == \"p_sub m_conf m_sub m_test f1\".split()\n\n    def test_func_closure_all_scopes_complex(self, pytester: Pytester) -> None:\n        \"\"\"Complex test involving all scopes and mixing autouse with normal fixtures\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='session')\n            def s1(): pass\n\n            @pytest.fixture(scope='package', autouse=True)\n            def p1(): pass\n        \"\"\"\n        )\n        pytester.makepyfile(**{\"__init__.py\": \"\"})\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='module', autouse=True)\n            def m1(): pass\n\n            @pytest.fixture(scope='module')\n            def m2(s1): pass\n\n            @pytest.fixture(scope='function')\n            def f1(): pass\n\n            @pytest.fixture(scope='function')\n            def f2(): pass\n\n            class Test:\n\n                @pytest.fixture(scope='class', autouse=True)\n                def c1(self):\n                    pass\n\n                def test_func(self, f2, f1, m2):\n                    pass\n        \"\"\"\n        )\n        items, _ = pytester.inline_genitems()\n        assert isinstance(items[0], Function)\n        request = TopRequest(items[0], _ispytest=True)\n        assert request.fixturenames == \"s1 p1 m1 m2 c1 f2 f1\".split()\n\n    def test_parametrized_package_scope_reordering(self, pytester: Pytester) -> None:\n        \"\"\"A parameterized package-scoped fixture correctly reorders items to\n        minimize setups & teardowns.\n\n        Regression test for #12328.\n        \"\"\"\n        pytester.makepyfile(\n            __init__=\"\",\n            conftest=\"\"\"\n                import pytest\n                @pytest.fixture(scope=\"package\", params=[\"a\", \"b\"])\n                def fix(request):\n                    return request.param\n            \"\"\",\n            test_1=\"def test1(fix): pass\",\n            test_2=\"def test2(fix): pass\",\n        )\n\n        result = pytester.runpytest(\"--setup-plan\")\n        assert result.ret == ExitCode.OK\n        result.stdout.fnmatch_lines(\n            [\n                \"  SETUP    P fix['a']\",\n                \"        test_1.py::test1[a] (fixtures used: fix, request)\",\n                \"        test_2.py::test2[a] (fixtures used: fix, request)\",\n                \"  TEARDOWN P fix['a']\",\n                \"  SETUP    P fix['b']\",\n                \"        test_1.py::test1[b] (fixtures used: fix, request)\",\n                \"        test_2.py::test2[b] (fixtures used: fix, request)\",\n                \"  TEARDOWN P fix['b']\",\n            ],\n        )\n\n    def test_multiple_packages(self, pytester: Pytester) -> None:\n        \"\"\"Complex test involving multiple package fixtures. Make sure teardowns\n        are executed in order.\n        .\n        └── root\n            ├── __init__.py\n            ├── sub1\n            │   ├── __init__.py\n            │   ├── conftest.py\n            │   └── test_1.py\n            └── sub2\n                ├── __init__.py\n                ├── conftest.py\n                └── test_2.py\n        \"\"\"\n        root = pytester.mkdir(\"root\")\n        root.joinpath(\"__init__.py\").write_text(\"values = []\", encoding=\"utf-8\")\n        sub1 = root.joinpath(\"sub1\")\n        sub1.mkdir()\n        sub1.joinpath(\"__init__.py\").touch()\n        sub1.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            import pytest\n            from .. import values\n            @pytest.fixture(scope=\"package\")\n            def fix():\n                values.append(\"pre-sub1\")\n                yield values\n                assert values.pop() == \"pre-sub1\"\n        \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        sub1.joinpath(\"test_1.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            from .. import values\n            def test_1(fix):\n                assert values == [\"pre-sub1\"]\n        \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        sub2 = root.joinpath(\"sub2\")\n        sub2.mkdir()\n        sub2.joinpath(\"__init__.py\").touch()\n        sub2.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            import pytest\n            from .. import values\n            @pytest.fixture(scope=\"package\")\n            def fix():\n                values.append(\"pre-sub2\")\n                yield values\n                assert values.pop() == \"pre-sub2\"\n        \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        sub2.joinpath(\"test_2.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            from .. import values\n            def test_2(fix):\n                assert values == [\"pre-sub2\"]\n        \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_class_fixture_self_instance(self, pytester: Pytester) -> None:\n        \"\"\"Check that plugin classes which implement fixtures receive the plugin instance\n        as self (see #2270).\n        \"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            def pytest_configure(config):\n                config.pluginmanager.register(MyPlugin())\n\n            class MyPlugin():\n                def __init__(self):\n                    self.arg = 1\n\n                @pytest.fixture(scope='function')\n                def myfix(self):\n                    assert isinstance(self, MyPlugin)\n                    return self.arg\n        \"\"\"\n        )\n\n        pytester.makepyfile(\n            \"\"\"\n            class TestClass(object):\n                def test_1(self, myfix):\n                    assert myfix == 1\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n\ndef test_call_fixture_function_error():\n    \"\"\"Check if an error is raised if a fixture function is called directly (#4545)\"\"\"\n\n    @pytest.fixture\n    def fix():\n        raise NotImplementedError()\n\n    with pytest.raises(pytest.fail.Exception):\n        assert fix() == 1\n\n\ndef test_fixture_double_decorator(pytester: Pytester) -> None:\n    \"\"\"Check if an error is raised when using @pytest.fixture twice.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        @pytest.fixture\n        def fixt():\n            pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(errors=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"E * ValueError: @pytest.fixture is being applied more than once to the same function 'fixt'\"\n        ]\n    )\n\n\ndef test_fixture_class(pytester: Pytester) -> None:\n    \"\"\"Check if an error is raised when using @pytest.fixture on a class.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        class A:\n            pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(errors=1)\n\n\ndef test_fixture_param_shadowing(pytester: Pytester) -> None:\n    \"\"\"Parametrized arguments would be shadowed if a fixture with the same name also exists (#5036)\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture(params=['a', 'b'])\n        def argroot(request):\n            return request.param\n\n        @pytest.fixture\n        def arg(argroot):\n            return argroot\n\n        # This should only be parametrized directly\n        @pytest.mark.parametrize(\"arg\", [1])\n        def test_direct(arg):\n            assert arg == 1\n\n        # This should be parametrized based on the fixtures\n        def test_normal_fixture(arg):\n            assert isinstance(arg, str)\n\n        # Indirect should still work:\n\n        @pytest.fixture\n        def arg2(request):\n            return 2*request.param\n\n        @pytest.mark.parametrize(\"arg2\", [1], indirect=True)\n        def test_indirect(arg2):\n            assert arg2 == 2\n    \"\"\"\n    )\n    # Only one test should have run\n    result = pytester.runpytest(\"-v\")\n    result.assert_outcomes(passed=4)\n    result.stdout.fnmatch_lines([\"*::test_direct[[]1[]]*\"])\n    result.stdout.fnmatch_lines([\"*::test_normal_fixture[[]a[]]*\"])\n    result.stdout.fnmatch_lines([\"*::test_normal_fixture[[]b[]]*\"])\n    result.stdout.fnmatch_lines([\"*::test_indirect[[]1[]]*\"])\n\n\ndef test_fixture_named_request(pytester: Pytester) -> None:\n    pytester.copy_example(\"fixtures/test_fixture_named_request.py\")\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"*'request' is a reserved word for fixtures, use another name:\",\n            \"  *test_fixture_named_request.py:8\",\n        ]\n    )\n\n\ndef test_indirect_fixture_does_not_break_scope(pytester: Pytester) -> None:\n    \"\"\"Ensure that fixture scope is respected when using indirect fixtures (#570)\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        instantiated  = []\n\n        @pytest.fixture(scope=\"session\")\n        def fixture_1(request):\n            instantiated.append((\"fixture_1\", request.param))\n\n\n        @pytest.fixture(scope=\"session\")\n        def fixture_2(request):\n            instantiated.append((\"fixture_2\", request.param))\n\n\n        scenarios = [\n            (\"A\", \"a1\"),\n            (\"A\", \"a2\"),\n            (\"B\", \"b1\"),\n            (\"B\", \"b2\"),\n            (\"C\", \"c1\"),\n            (\"C\", \"c2\"),\n        ]\n\n        @pytest.mark.parametrize(\n            \"fixture_1,fixture_2\", scenarios, indirect=[\"fixture_1\", \"fixture_2\"]\n        )\n        def test_create_fixtures(fixture_1, fixture_2):\n            pass\n\n\n        def test_check_fixture_instantiations():\n            assert instantiated == [\n                ('fixture_1', 'A'),\n                ('fixture_2', 'a1'),\n                ('fixture_2', 'a2'),\n                ('fixture_1', 'B'),\n                ('fixture_2', 'b1'),\n                ('fixture_2', 'b2'),\n                ('fixture_1', 'C'),\n                ('fixture_2', 'c1'),\n                ('fixture_2', 'c2'),\n            ]\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=7)\n\n\ndef test_fixture_parametrization_nparray(pytester: Pytester) -> None:\n    pytest.importorskip(\"numpy\")\n\n    pytester.makepyfile(\n        \"\"\"\n        from numpy import linspace\n        from pytest import fixture\n\n        @fixture(params=linspace(1, 10, 10))\n        def value(request):\n            return request.param\n\n        def test_bug(value):\n            assert value == value\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=10)\n\n\ndef test_fixture_arg_ordering(pytester: Pytester) -> None:\n    \"\"\"\n    This test describes how fixtures in the same scope but without explicit dependencies\n    between them are created. While users should make dependencies explicit, often\n    they rely on this order, so this test exists to catch regressions in this regard.\n    See #6540 and #6492.\n    \"\"\"\n    p1 = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        suffixes = []\n\n        @pytest.fixture\n        def fix_1(): suffixes.append(\"fix_1\")\n        @pytest.fixture\n        def fix_2(): suffixes.append(\"fix_2\")\n        @pytest.fixture\n        def fix_3(): suffixes.append(\"fix_3\")\n        @pytest.fixture\n        def fix_4(): suffixes.append(\"fix_4\")\n        @pytest.fixture\n        def fix_5(): suffixes.append(\"fix_5\")\n\n        @pytest.fixture\n        def fix_combined(fix_1, fix_2, fix_3, fix_4, fix_5): pass\n\n        def test_suffix(fix_combined):\n            assert suffixes == [\"fix_1\", \"fix_2\", \"fix_3\", \"fix_4\", \"fix_5\"]\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-vv\", str(p1))\n    assert result.ret == 0\n\n\ndef test_yield_fixture_with_no_value(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.fixture(name='custom')\n        def empty_yield():\n            if False:\n                yield\n\n        def test_fixt(custom):\n            pass\n        \"\"\"\n    )\n    expected = \"E               ValueError: custom did not yield a value\"\n    result = pytester.runpytest()\n    result.assert_outcomes(errors=1)\n    result.stdout.fnmatch_lines([expected])\n    assert result.ret == ExitCode.TESTS_FAILED\n\n\ndef test_deduplicate_names() -> None:\n    items = deduplicate_names(\"abacd\")\n    assert items == (\"a\", \"b\", \"c\", \"d\")\n    items = deduplicate_names((*items, \"g\", \"f\", \"g\", \"e\", \"b\"))\n    assert items == (\"a\", \"b\", \"c\", \"d\", \"g\", \"f\", \"e\")\n\n\ndef test_staticmethod_classmethod_fixture_instance(pytester: Pytester) -> None:\n    \"\"\"Ensure that static and class methods get and have access to a fresh\n    instance.\n\n    This also ensures `setup_method` works well with static and class methods.\n\n    Regression test for #12065.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        class Test:\n            ran_setup_method = False\n            ran_fixture = False\n\n            def setup_method(self):\n                assert not self.ran_setup_method\n                self.ran_setup_method = True\n\n            @pytest.fixture(autouse=True)\n            def fixture(self):\n                assert not self.ran_fixture\n                self.ran_fixture = True\n\n            def test_method(self):\n                assert self.ran_setup_method\n                assert self.ran_fixture\n\n            @staticmethod\n            def test_1(request):\n                assert request.instance.ran_setup_method\n                assert request.instance.ran_fixture\n\n            @classmethod\n            def test_2(cls, request):\n                assert request.instance.ran_setup_method\n                assert request.instance.ran_fixture\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.OK\n    result.assert_outcomes(passed=3)\n\n\ndef test_scoped_fixture_caching(pytester: Pytester) -> None:\n    \"\"\"Make sure setup and finalization is only run once when using scoped fixture\n    multiple times.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        from __future__ import annotations\n\n        from typing import Generator\n\n        import pytest\n        executed: list[str] = []\n        @pytest.fixture(scope=\"class\")\n        def fixture_1() -> Generator[None, None, None]:\n            executed.append(\"fix setup\")\n            yield\n            executed.append(\"fix teardown\")\n\n\n        class TestFixtureCaching:\n            def test_1(self, fixture_1: None) -> None:\n                assert executed == [\"fix setup\"]\n\n            def test_2(self, fixture_1: None) -> None:\n                assert executed == [\"fix setup\"]\n\n\n        def test_expected_setup_and_teardown() -> None:\n            assert executed == [\"fix setup\", \"fix teardown\"]\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n\n\ndef test_scoped_fixture_caching_exception(pytester: Pytester) -> None:\n    \"\"\"Make sure setup & finalization is only run once for scoped fixture, with a cached exception.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        from __future__ import annotations\n\n        import pytest\n        executed_crash: list[str] = []\n\n\n        @pytest.fixture(scope=\"class\")\n        def fixture_crash(request: pytest.FixtureRequest) -> None:\n            executed_crash.append(\"fix_crash setup\")\n\n            def my_finalizer() -> None:\n                executed_crash.append(\"fix_crash teardown\")\n\n            request.addfinalizer(my_finalizer)\n\n            raise Exception(\"foo\")\n\n\n        class TestFixtureCachingException:\n            @pytest.mark.xfail\n            def test_crash_1(self, fixture_crash: None) -> None:\n                ...\n\n            @pytest.mark.xfail\n            def test_crash_2(self, fixture_crash: None) -> None:\n                ...\n\n\n        def test_crash_expected_setup_and_teardown() -> None:\n            assert executed_crash == [\"fix_crash setup\", \"fix_crash teardown\"]\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n\n\ndef test_scoped_fixture_teardown_order(pytester: Pytester) -> None:\n    \"\"\"\n    Make sure teardowns happen in reverse order of setup with scoped fixtures, when\n    a later test only depends on a subset of scoped fixtures.\n\n    Regression test for https://github.com/pytest-dev/pytest/issues/1489\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        from typing import Generator\n\n        import pytest\n\n\n        last_executed = \"\"\n\n\n        @pytest.fixture(scope=\"module\")\n        def fixture_1() -> Generator[None, None, None]:\n            global last_executed\n            assert last_executed == \"\"\n            last_executed = \"fixture_1_setup\"\n            yield\n            assert last_executed == \"fixture_2_teardown\"\n            last_executed = \"fixture_1_teardown\"\n\n\n        @pytest.fixture(scope=\"module\")\n        def fixture_2() -> Generator[None, None, None]:\n            global last_executed\n            assert last_executed == \"fixture_1_setup\"\n            last_executed = \"fixture_2_setup\"\n            yield\n            assert last_executed == \"run_test\"\n            last_executed = \"fixture_2_teardown\"\n\n\n        def test_fixture_teardown_order(fixture_1: None, fixture_2: None) -> None:\n            global last_executed\n            assert last_executed == \"fixture_2_setup\"\n            last_executed = \"run_test\"\n\n\n        def test_2(fixture_1: None) -> None:\n            # This would previously queue an additional teardown of fixture_1,\n            # despite fixture_1's value being cached, which caused fixture_1 to be\n            # torn down before fixture_2 - violating the rule that teardowns should\n            # happen in reverse order of setup.\n            pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n\n\ndef test_subfixture_teardown_order(pytester: Pytester) -> None:\n    \"\"\"\n    Make sure fixtures don't re-register their finalization in parent fixtures multiple\n    times, causing ordering failure in their teardowns.\n\n    Regression test for #12135\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        execution_order = []\n\n        @pytest.fixture(scope=\"class\")\n        def fixture_1():\n            ...\n\n        @pytest.fixture(scope=\"class\")\n        def fixture_2(fixture_1):\n            execution_order.append(\"setup 2\")\n            yield\n            execution_order.append(\"teardown 2\")\n\n        @pytest.fixture(scope=\"class\")\n        def fixture_3(fixture_1):\n            execution_order.append(\"setup 3\")\n            yield\n            execution_order.append(\"teardown 3\")\n\n        class TestFoo:\n            def test_initialize_fixtures(self, fixture_2, fixture_3):\n                ...\n\n            # This would previously reschedule fixture_2's finalizer in the parent fixture,\n            # causing it to be torn down before fixture 3.\n            def test_reschedule_fixture_2(self, fixture_2):\n                ...\n\n            # Force finalization directly on fixture_1\n            # Otherwise the cleanup would sequence 3&2 before 1 as normal.\n            @pytest.mark.parametrize(\"fixture_1\", [None], indirect=[\"fixture_1\"])\n            def test_finalize_fixture_1(self, fixture_1):\n                ...\n\n        def test_result():\n            assert execution_order == [\"setup 2\", \"setup 3\", \"teardown 3\", \"teardown 2\"]\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n\n\ndef test_parametrized_fixture_scope_allowed(pytester: Pytester) -> None:\n    \"\"\"\n    Make sure scope from parametrize does not affect fixture's ability to be\n    depended upon.\n\n    Regression test for #13248\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture(scope=\"session\")\n        def my_fixture(request):\n            return getattr(request, \"param\", None)\n\n        @pytest.fixture(scope=\"session\")\n        def another_fixture(my_fixture):\n            return my_fixture\n\n        @pytest.mark.parametrize(\"my_fixture\", [\"a value\"], indirect=True, scope=\"function\")\n        def test_foo(another_fixture):\n            assert another_fixture == \"a value\"\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=1)\n\n\ndef test_collect_positional_only(pytester: Pytester) -> None:\n    \"\"\"Support the collection of tests with positional-only arguments (#13376).\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        class Test:\n            @pytest.fixture\n            def fix(self):\n                return 1\n\n            def test_method(self, /, fix):\n                assert fix == 1\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=1)\n\n\ndef test_parametrization_dependency_pruning(pytester: Pytester) -> None:\n    \"\"\"Test that when a fixture is dynamically shadowed by parameterization, it\n    is properly pruned and not executed.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n\n        # This fixture should never run because shadowed_fixture is parametrized.\n        @pytest.fixture\n        def boom():\n            raise RuntimeError(\"BOOM!\")\n\n\n        # This fixture is shadowed by metafunc.parametrize in pytest_generate_tests.\n        @pytest.fixture\n        def shadowed_fixture(boom):\n            return \"fixture_value\"\n\n\n        # Dynamically parametrize shadowed_fixture, replacing the fixture with direct values.\n        def pytest_generate_tests(metafunc):\n            if \"shadowed_fixture\" in metafunc.fixturenames:\n                metafunc.parametrize(\"shadowed_fixture\", [\"param1\", \"param2\"])\n\n\n        # This test should receive shadowed_fixture as a parametrized value, and\n        # boom should not explode.\n        def test_shadowed(shadowed_fixture):\n            assert shadowed_fixture in [\"param1\", \"param2\"]\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=2)\n\n\ndef test_fixture_closure_with_overrides(pytester: Pytester) -> None:\n    \"\"\"Test that an item's static fixture closure properly includes transitive\n    dependencies through overridden fixtures (#13773).\"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def db(): pass\n\n        @pytest.fixture\n        def app(db): pass\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        # Overrides conftest-level `app` and requests it.\n        @pytest.fixture\n        def app(app): pass\n\n        class TestClass:\n            # Overrides module-level `app` and requests it.\n            @pytest.fixture\n            def app(self, app): pass\n\n            def test_something(self, request, app):\n                # Both dynamic and static fixture closures should include 'db'.\n                assert 'db' in request.fixturenames\n                assert 'db' in request.node.fixturenames\n                # No dynamic dependencies, should be equal.\n                assert set(request.fixturenames) == set(request.node.fixturenames)\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.assert_outcomes(passed=1)\n\n\ndef test_fixture_closure_with_overrides_and_intermediary(pytester: Pytester) -> None:\n    \"\"\"Test that an item's static fixture closure properly includes transitive\n    dependencies through overridden fixtures (#13773).\n\n    A more complicated case than test_fixture_closure_with_overrides, adds an\n    intermediary so the override chain is not direct.\n    \"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def db(): pass\n\n        @pytest.fixture\n        def app(db): pass\n\n        @pytest.fixture\n        def intermediate(app): pass\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        # Overrides conftest-level `app` and requests it.\n        @pytest.fixture\n        def app(intermediate): pass\n\n        class TestClass:\n            # Overrides module-level `app` and requests it.\n            @pytest.fixture\n            def app(self, app): pass\n\n            def test_something(self, request, app):\n                # Both dynamic and static fixture closures should include 'db'.\n                assert 'db' in request.fixturenames\n                assert 'db' in request.node.fixturenames\n                # No dynamic dependencies, should be equal.\n                assert set(request.fixturenames) == set(request.node.fixturenames)\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.assert_outcomes(passed=1)\n\n\ndef test_fixture_closure_with_broken_override_chain(pytester: Pytester) -> None:\n    \"\"\"Test that an item's static fixture closure properly includes transitive\n    dependencies through overridden fixtures (#13773).\n\n    A more complicated case than test_fixture_closure_with_overrides, one of the\n    fixtures in the chain doesn't call its super, so it shouldn't be included.\n    \"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def db(): pass\n\n        @pytest.fixture\n        def app(db): pass\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        # Overrides conftest-level `app` and *doesn't* request it.\n        @pytest.fixture\n        def app(): pass\n\n        class TestClass:\n            # Overrides module-level `app` and requests it.\n            @pytest.fixture\n            def app(self, app): pass\n\n            def test_something(self, request, app):\n                # Both dynamic and static fixture closures should include 'db'.\n                assert 'db' not in request.fixturenames\n                assert 'db' not in request.node.fixturenames\n                # No dynamic dependencies, should be equal.\n                assert set(request.fixturenames) == set(request.node.fixturenames)\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.assert_outcomes(passed=1)\n\n\ndef test_fixture_closure_handles_circular_dependencies(pytester: Pytester) -> None:\n    \"\"\"Test that getfixtureclosure properly handles circular dependencies.\n\n    The test will error in the runtest phase due to the fixture loop,\n    but the closure computation still completes.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        # Direct circular dependency.\n        @pytest.fixture\n        def fix_a(fix_b): pass\n\n        @pytest.fixture\n        def fix_b(fix_a): pass\n\n        # Indirect circular dependency through multiple fixtures.\n        @pytest.fixture\n        def fix_x(fix_y): pass\n\n        @pytest.fixture\n        def fix_y(fix_z): pass\n\n        @pytest.fixture\n        def fix_z(fix_x): pass\n\n        def test_circular_deps(fix_a, fix_x):\n            pass\n        \"\"\"\n    )\n    items, _hookrec = pytester.inline_genitems()\n    assert isinstance(items[0], Function)\n    assert items[0].fixturenames == [\"fix_a\", \"fix_x\", \"fix_b\", \"fix_y\", \"fix_z\"]\n\n\ndef test_fixture_closure_handles_diamond_dependencies(pytester: Pytester) -> None:\n    \"\"\"Test that getfixtureclosure properly handles diamond dependencies.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def db(): pass\n\n        @pytest.fixture\n        def user(db): pass\n\n        @pytest.fixture\n        def session(db): pass\n\n        @pytest.fixture\n        def app(user, session): pass\n\n        def test_diamond_deps(request, app):\n            assert request.node.fixturenames == [\"request\", \"app\", \"user\", \"db\", \"session\"]\n            assert request.fixturenames == [\"request\", \"app\", \"user\", \"db\", \"session\"]\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.assert_outcomes(passed=1)\n\n\ndef test_fixture_closure_with_complex_override_and_shared_deps(\n    pytester: Pytester,\n) -> None:\n    \"\"\"Test that shared dependencies in override chains are processed only once.\"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def db(): pass\n\n        @pytest.fixture\n        def cache(): pass\n\n        @pytest.fixture\n        def settings(): pass\n\n        @pytest.fixture\n        def app(db, cache, settings): pass\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        # Override app, but also directly use cache and settings.\n        # This creates multiple paths to the same fixtures.\n        @pytest.fixture\n        def app(app, cache, settings): pass\n\n        class TestClass:\n            # Another override that uses both app and cache.\n            @pytest.fixture\n            def app(self, app, cache): pass\n\n            def test_shared_deps(self, request, app):\n                assert request.node.fixturenames == [\"request\", \"app\", \"db\", \"cache\", \"settings\"]\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.assert_outcomes(passed=1)\n\n\ndef test_fixture_closure_with_parametrize_ignore(pytester: Pytester) -> None:\n    \"\"\"Test that getfixtureclosure properly handles parametrization argnames\n    which override a fixture.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def fix1(fix2): pass\n\n        @pytest.fixture\n        def fix2(fix3): pass\n\n        @pytest.fixture\n        def fix3(): pass\n\n        @pytest.mark.parametrize('fix2', ['2'])\n        def test_it(request, fix1):\n            assert request.node.fixturenames == [\"request\", \"fix1\", \"fix2\"]\n            assert request.fixturenames == [\"request\", \"fix1\", \"fix2\"]\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.assert_outcomes(passed=1)\n\n\ndef test_overridden_fixture_depends_on_parametrized(pytester: Pytester) -> None:\n    \"\"\"#11075\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture(params=[\"foo\"])\n        def fixture_foo(request):\n            yield request.param\n\n        @pytest.fixture\n        def fixture_bar(fixture_foo):\n            yield fixture_foo\n\n        class TestFoobar:\n            @pytest.fixture\n            def fixture_bar(self, fixture_bar):\n                yield fixture_bar\n\n            def test_foobar(self, fixture_bar):\n                assert fixture_bar == \"foo\"\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.assert_outcomes(passed=1)\n"
  },
  {
    "path": "testing/python/integration.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom _pytest._code import getfslineno\nfrom _pytest.fixtures import getfixturemarker\nfrom _pytest.pytester import Pytester\nfrom _pytest.python import Function\nimport pytest\n\n\ndef test_wrapped_getfslineno() -> None:\n    def func():\n        pass\n\n    def wrap(f):\n        func.__wrapped__ = f  # type: ignore\n        func.patchings = [\"qwe\"]  # type: ignore\n        return func\n\n    @wrap\n    def wrapped_func(x, y, z):\n        pass\n\n    _fs, lineno = getfslineno(wrapped_func)\n    _fs2, lineno2 = getfslineno(wrap)\n    assert lineno > lineno2, \"getfslineno does not unwrap correctly\"\n\n\nclass TestMockDecoration:\n    def test_wrapped_getfuncargnames(self) -> None:\n        from _pytest.compat import getfuncargnames\n\n        def wrap(f):\n            def func():\n                pass\n\n            func.__wrapped__ = f  # type: ignore\n            return func\n\n        @wrap\n        def f(x):\n            pass\n\n        values = getfuncargnames(f)\n        assert values == (\"x\",)\n\n    def test_getfuncargnames_patching(self):\n        from unittest.mock import patch\n\n        from _pytest.compat import getfuncargnames\n\n        class T:\n            def original(self, x, y, z):\n                pass\n\n        @patch.object(T, \"original\")\n        def f(x, y, z):\n            pass\n\n        values = getfuncargnames(f)\n        assert values == (\"y\", \"z\")\n\n    def test_unittest_mock(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import unittest.mock\n            class T(unittest.TestCase):\n                @unittest.mock.patch(\"os.path.abspath\")\n                def test_hello(self, abspath):\n                    import os\n                    os.path.abspath(\"hello\")\n                    abspath.assert_any_call(\"hello\")\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_unittest_mock_and_fixture(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import os.path\n            import unittest.mock\n            import pytest\n\n            @pytest.fixture\n            def inject_me():\n                pass\n\n            @unittest.mock.patch.object(os.path, \"abspath\",\n                                        new=unittest.mock.MagicMock)\n            def test_hello(inject_me):\n                import os\n                os.path.abspath(\"hello\")\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_unittest_mock_and_pypi_mock(self, pytester: Pytester) -> None:\n        pytest.importorskip(\"mock\", \"1.0.1\")\n        pytester.makepyfile(\n            \"\"\"\n            import mock\n            import unittest.mock\n            class TestBoth(object):\n                @unittest.mock.patch(\"os.path.abspath\")\n                def test_hello(self, abspath):\n                    import os\n                    os.path.abspath(\"hello\")\n                    abspath.assert_any_call(\"hello\")\n\n                @mock.patch(\"os.path.abspath\")\n                def test_hello_mock(self, abspath):\n                    import os\n                    os.path.abspath(\"hello\")\n                    abspath.assert_any_call(\"hello\")\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_mock_sentinel_check_against_numpy_like(self, pytester: Pytester) -> None:\n        \"\"\"Ensure our function that detects mock arguments compares against sentinels using\n        identity to circumvent objects which can't be compared with equality against others\n        in a truth context, like with numpy arrays (#5606).\n        \"\"\"\n        pytester.makepyfile(\n            dummy=\"\"\"\n            class NumpyLike:\n                def __init__(self, value):\n                    self.value = value\n                def __eq__(self, other):\n                    raise ValueError(\"like numpy, cannot compare against others for truth\")\n            FOO = NumpyLike(10)\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            from unittest.mock import patch\n            import dummy\n            class Test(object):\n                @patch(\"dummy.FOO\", new=dummy.NumpyLike(50))\n                def test_hello(self):\n                    assert dummy.FOO.value == 50\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_mock(self, pytester: Pytester) -> None:\n        pytest.importorskip(\"mock\", \"1.0.1\")\n        pytester.makepyfile(\n            \"\"\"\n            import os\n            import unittest\n            import mock\n\n            class T(unittest.TestCase):\n                @mock.patch(\"os.path.abspath\")\n                def test_hello(self, abspath):\n                    os.path.abspath(\"hello\")\n                    abspath.assert_any_call(\"hello\")\n            def mock_basename(path):\n                return \"mock_basename\"\n            @mock.patch(\"os.path.abspath\")\n            @mock.patch(\"os.path.normpath\")\n            @mock.patch(\"os.path.basename\", new=mock_basename)\n            def test_something(normpath, abspath, tmp_path):\n                abspath.return_value = \"this\"\n                os.path.normpath(os.path.abspath(\"hello\"))\n                normpath.assert_any_call(\"this\")\n                assert os.path.basename(\"123\") == \"mock_basename\"\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n        calls = reprec.getcalls(\"pytest_runtest_logreport\")\n        funcnames = [\n            call.report.location[2] for call in calls if call.report.when == \"call\"\n        ]\n        assert funcnames == [\"T.test_hello\", \"test_something\"]\n\n    def test_mock_sorting(self, pytester: Pytester) -> None:\n        pytest.importorskip(\"mock\", \"1.0.1\")\n        pytester.makepyfile(\n            \"\"\"\n            import os\n            import mock\n\n            @mock.patch(\"os.path.abspath\")\n            def test_one(abspath):\n                pass\n            @mock.patch(\"os.path.abspath\")\n            def test_two(abspath):\n                pass\n            @mock.patch(\"os.path.abspath\")\n            def test_three(abspath):\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        calls = reprec.getreports(\"pytest_runtest_logreport\")\n        calls = [x for x in calls if x.when == \"call\"]\n        names = [x.nodeid.split(\"::\")[-1] for x in calls]\n        assert names == [\"test_one\", \"test_two\", \"test_three\"]\n\n    def test_mock_double_patch_issue473(self, pytester: Pytester) -> None:\n        pytest.importorskip(\"mock\", \"1.0.1\")\n        pytester.makepyfile(\n            \"\"\"\n            from mock import patch\n            from pytest import mark\n\n            @patch('os.getcwd')\n            @patch('os.path')\n            @mark.slow\n            class TestSimple(object):\n                def test_simple_thing(self, mock_path, mock_getcwd):\n                    pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n\nclass TestReRunTests:\n    def test_rerun(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            from _pytest.runner import runtestprotocol\n            def pytest_runtest_protocol(item, nextitem):\n                runtestprotocol(item, log=False, nextitem=nextitem)\n                runtestprotocol(item, log=True, nextitem=nextitem)\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            count = 0\n            req = None\n            @pytest.fixture\n            def fix(request):\n                global count, req\n                assert request != req\n                req = request\n                print(\"fix count %s\" % count)\n                count += 1\n            def test_fix(fix):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *fix count 0*\n            *fix count 1*\n        \"\"\"\n        )\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *2 passed*\n        \"\"\"\n        )\n\n\ndef test_pytestconfig_is_session_scoped() -> None:\n    from _pytest.fixtures import pytestconfig\n\n    marker = getfixturemarker(pytestconfig)\n    assert marker is not None\n    assert marker.scope == \"session\"\n\n\nclass TestNoselikeTestAttribute:\n    def test_module_with_global_test(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            __test__ = False\n            def test_hello():\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        assert not reprec.getfailedcollections()\n        calls = reprec.getreports(\"pytest_runtest_logreport\")\n        assert not calls\n\n    def test_class_and_method(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            __test__ = True\n            def test_func():\n                pass\n            test_func.__test__ = False\n\n            class TestSome(object):\n                __test__ = False\n                def test_method(self):\n                    pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        assert not reprec.getfailedcollections()\n        calls = reprec.getreports(\"pytest_runtest_logreport\")\n        assert not calls\n\n    def test_unittest_class(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import unittest\n            class TC(unittest.TestCase):\n                def test_1(self):\n                    pass\n            class TC2(unittest.TestCase):\n                __test__ = False\n                def test_2(self):\n                    pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        assert not reprec.getfailedcollections()\n        call = reprec.getcalls(\"pytest_collection_modifyitems\")[0]\n        assert len(call.items) == 1\n        assert call.items[0].cls.__name__ == \"TC\"\n\n    def test_class_with_nasty_getattr(self, pytester: Pytester) -> None:\n        \"\"\"Make sure we handle classes with a custom nasty __getattr__ right.\n\n        With a custom __getattr__ which e.g. returns a function (like with a\n        RPC wrapper), we shouldn't assume this meant \"__test__ = True\".\n        \"\"\"\n        # https://github.com/pytest-dev/pytest/issues/1204\n        pytester.makepyfile(\n            \"\"\"\n            class MetaModel(type):\n\n                def __getattr__(cls, key):\n                    return lambda: None\n\n\n            BaseModel = MetaModel('Model', (), {})\n\n\n            class Model(BaseModel):\n\n                __metaclass__ = MetaModel\n\n                def test_blah(self):\n                    pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        assert not reprec.getfailedcollections()\n        call = reprec.getcalls(\"pytest_collection_modifyitems\")[0]\n        assert not call.items\n\n\nclass TestParameterize:\n    \"\"\"#351\"\"\"\n\n    def test_idfn_marker(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def idfn(param):\n                if param == 0:\n                    return 'spam'\n                elif param == 1:\n                    return 'ham'\n                else:\n                    return None\n\n            @pytest.mark.parametrize('a,b', [(0, 2), (1, 2)], ids=idfn)\n            def test_params(a, b):\n                pass\n        \"\"\"\n        )\n        res = pytester.runpytest(\"--collect-only\")\n        res.stdout.fnmatch_lines([\"*spam-2*\", \"*ham-2*\"])\n\n    def test_idfn_fixture(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def idfn(param):\n                if param == 0:\n                    return 'spam'\n                elif param == 1:\n                    return 'ham'\n                else:\n                    return None\n\n            @pytest.fixture(params=[0, 1], ids=idfn)\n            def a(request):\n                return request.param\n\n            @pytest.fixture(params=[1, 2], ids=idfn)\n            def b(request):\n                return request.param\n\n            def test_params(a, b):\n                pass\n        \"\"\"\n        )\n        res = pytester.runpytest(\"--collect-only\")\n        res.stdout.fnmatch_lines([\"*spam-2*\", \"*ham-2*\"])\n\n    def test_param_rejects_usefixtures(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"x\", [\n                pytest.param(1, marks=[pytest.mark.usefixtures(\"foo\")]),\n            ])\n            def test_foo(x):\n                pass\n        \"\"\"\n        )\n        res = pytester.runpytest(\"--collect-only\")\n        res.stdout.fnmatch_lines(\n            [\"*test_param_rejects_usefixtures.py:4*\", \"*pytest.param(*\"]\n        )\n\n\ndef test_function_instance(pytester: Pytester) -> None:\n    items = pytester.getitems(\n        \"\"\"\n        def test_func(): pass\n\n        class TestIt:\n            def test_method(self): pass\n\n            @classmethod\n            def test_class(cls): pass\n\n            @staticmethod\n            def test_static(): pass\n        \"\"\"\n    )\n    assert len(items) == 4\n\n    assert isinstance(items[0], Function)\n    assert items[0].name == \"test_func\"\n    assert items[0].instance is None\n\n    assert isinstance(items[1], Function)\n    assert items[1].name == \"test_method\"\n    assert items[1].instance is not None\n    assert items[1].instance.__class__.__name__ == \"TestIt\"\n\n    # Even class and static methods get an instance!\n    # This is the instance used for bound fixture methods, which\n    # class/staticmethod tests are perfectly able to request.\n    assert isinstance(items[2], Function)\n    assert items[2].name == \"test_class\"\n    assert items[2].instance is not None\n\n    assert isinstance(items[3], Function)\n    assert items[3].name == \"test_static\"\n    assert items[3].instance is not None\n\n    assert items[1].instance is not items[2].instance is not items[3].instance\n"
  },
  {
    "path": "testing/python/metafunc.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom collections.abc import Sequence\nimport dataclasses\nimport itertools\nimport re\nimport sys\nimport textwrap\nfrom typing import Any\nfrom typing import cast\n\nimport hypothesis\nfrom hypothesis import strategies\n\nfrom _pytest import fixtures\nfrom _pytest import python\nfrom _pytest.compat import getfuncargnames\nfrom _pytest.compat import NOTSET\nfrom _pytest.outcomes import fail\nfrom _pytest.outcomes import Failed\nfrom _pytest.pytester import Pytester\nfrom _pytest.python import Function\nfrom _pytest.python import IdMaker\nfrom _pytest.scope import Scope\nimport pytest\n\n\nclass TestMetafunc:\n    def Metafunc(self, func, config=None) -> python.Metafunc:\n        # The unit tests of this class check if things work correctly\n        # on the funcarg level, so we don't need a full blown\n        # initialization.\n        class FuncFixtureInfoMock:\n            name2fixturedefs: dict[str, list[fixtures.FixtureDef[object]]] = {}\n\n            def __init__(self, names):\n                self.names_closure = names\n\n        @dataclasses.dataclass\n        class FixtureManagerMock:\n            config: Any\n\n        @dataclasses.dataclass\n        class SessionMock:\n            _fixturemanager: FixtureManagerMock\n\n        @dataclasses.dataclass\n        class DefinitionMock(python.FunctionDefinition):\n            _nodeid: str\n            obj: object\n\n        names = getfuncargnames(func)\n        fixtureinfo: Any = FuncFixtureInfoMock(names)\n        definition: Any = DefinitionMock._create(obj=func, _nodeid=\"mock::nodeid\")\n        definition._fixtureinfo = fixtureinfo\n        definition.session = SessionMock(FixtureManagerMock({}))\n        return python.Metafunc(definition, fixtureinfo, config, _ispytest=True)\n\n    def test_no_funcargs(self) -> None:\n        def function():\n            pass\n\n        metafunc = self.Metafunc(function)\n        assert not metafunc.fixturenames\n        repr(metafunc._calls)\n\n    def test_function_basic(self) -> None:\n        def func(arg1, arg2=\"qwe\"):\n            pass\n\n        metafunc = self.Metafunc(func)\n        assert len(metafunc.fixturenames) == 1\n        assert \"arg1\" in metafunc.fixturenames\n        assert metafunc.function is func\n        assert metafunc.cls is None\n\n    def test_parametrize_single_arg_trailing_comma(self) -> None:\n        \"\"\"Test that trailing comma in string argnames behaves like tuple argnames.\n\n        Regression test for https://github.com/pytest-dev/pytest/issues/719\n\n        When using a single argument with:\n        - \"arg\" (string, no comma): argvalues is a list of values\n        - \"arg,\" (string, trailing comma): argvalues is a list of tuples (like tuple form)\n        - (\"arg\",) (tuple): argvalues is a list of tuples\n        \"\"\"\n\n        def func(arg):\n            pass  # pragma: no cover\n\n        scenarios = [(\"a\",), (\"b\",)]\n\n        # Tuple form: argvalues are tuples, unpacked to get the value\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize((\"arg\",), scenarios)\n        assert metafunc._calls[0].params == {\"arg\": \"a\"}\n        assert metafunc._calls[1].params == {\"arg\": \"b\"}\n\n        # String with trailing comma: should behave like tuple form\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"arg,\", scenarios)\n        assert metafunc._calls[0].params == {\"arg\": \"a\"}\n        assert metafunc._calls[1].params == {\"arg\": \"b\"}\n\n        # String without comma: argvalues are values directly (tuples are passed as-is)\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"arg\", scenarios)\n        assert metafunc._calls[0].params == {\"arg\": (\"a\",)}\n        assert metafunc._calls[1].params == {\"arg\": (\"b\",)}\n\n        # String without comma with plain values: values are used directly\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"arg\", [\"a\", \"b\"])\n        assert metafunc._calls[0].params == {\"arg\": \"a\"}\n        assert metafunc._calls[1].params == {\"arg\": \"b\"}\n\n    def test_parametrize_error(self) -> None:\n        def func(x, y):\n            pass\n\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"x\", [1, 2])\n        with pytest.raises(pytest.Collector.CollectError):\n            metafunc.parametrize(\"x\", [5, 6])\n        with pytest.raises(pytest.Collector.CollectError):\n            metafunc.parametrize(\"x\", [5, 6])\n        metafunc.parametrize(\"y\", [1, 2])\n        with pytest.raises(pytest.Collector.CollectError):\n            metafunc.parametrize(\"y\", [5, 6])\n        with pytest.raises(pytest.Collector.CollectError):\n            metafunc.parametrize(\"y\", [5, 6])\n\n        with pytest.raises(TypeError, match=r\"^ids must be a callable or an iterable$\"):\n            metafunc.parametrize(\"y\", [5, 6], ids=42)  # type: ignore[arg-type]\n\n    def test_parametrize_error_iterator(self) -> None:\n        def func(x):\n            raise NotImplementedError()\n\n        class Exc(Exception):\n            def __repr__(self):\n                return \"Exc(from_gen)\"\n\n        def gen() -> Iterator[int | None | Exc]:\n            yield 0\n            yield None\n            yield Exc()\n\n        metafunc = self.Metafunc(func)\n        # When the input is an iterator, only len(args) are taken,\n        # so the bad Exc isn't reached.\n        metafunc.parametrize(\"x\", [1, 2], ids=gen())\n        assert [(x.params, x.id) for x in metafunc._calls] == [\n            ({\"x\": 1}, \"0\"),\n            ({\"x\": 2}, \"2\"),\n        ]\n        with pytest.raises(\n            fail.Exception,\n            match=(\n                r\"In mock::nodeid: ids contains unsupported value Exc\\(from_gen\\) \\(type: <class .*Exc'>\\) at index 2. \"\n                r\"Supported types are: .*\"\n            ),\n        ):\n            metafunc.parametrize(\"x\", [1, 2, 3], ids=gen())\n\n    def test_parametrize_bad_scope(self) -> None:\n        def func(x):\n            pass\n\n        metafunc = self.Metafunc(func)\n        with pytest.raises(\n            fail.Exception,\n            match=r\"parametrize\\(\\) call in func got an unexpected scope value 'doggy'\",\n        ):\n            metafunc.parametrize(\"x\", [1], scope=\"doggy\")  # type: ignore[arg-type]\n\n    def test_parametrize_request_name(self, pytester: Pytester) -> None:\n        \"\"\"Show proper error  when 'request' is used as a parameter name in parametrize (#6183)\"\"\"\n\n        def func(request):\n            raise NotImplementedError()\n\n        metafunc = self.Metafunc(func)\n        with pytest.raises(\n            fail.Exception,\n            match=r\"'request' is a reserved name and cannot be used in @pytest.mark.parametrize\",\n        ):\n            metafunc.parametrize(\"request\", [1])\n\n    def test_find_parametrized_scope(self) -> None:\n        \"\"\"Unit test for _find_parametrized_scope (#3941).\"\"\"\n        from _pytest.python import _find_parametrized_scope\n\n        @dataclasses.dataclass\n        class DummyFixtureDef:\n            _scope: Scope\n\n        fixtures_defs = cast(\n            dict[str, Sequence[fixtures.FixtureDef[object]]],\n            dict(\n                session_fix=[DummyFixtureDef(Scope.Session)],\n                package_fix=[DummyFixtureDef(Scope.Package)],\n                module_fix=[DummyFixtureDef(Scope.Module)],\n                class_fix=[DummyFixtureDef(Scope.Class)],\n                func_fix=[DummyFixtureDef(Scope.Function)],\n                mixed_fix=[DummyFixtureDef(Scope.Module), DummyFixtureDef(Scope.Class)],\n            ),\n        )\n\n        # use arguments to determine narrow scope; the cause of the bug is that it would look on all\n        # fixture defs given to the method\n        def find_scope(argnames, indirect):\n            return _find_parametrized_scope(argnames, fixtures_defs, indirect=indirect)\n\n        assert find_scope([\"func_fix\"], indirect=True) == Scope.Function\n        assert find_scope([\"class_fix\"], indirect=True) == Scope.Class\n        assert find_scope([\"module_fix\"], indirect=True) == Scope.Module\n        assert find_scope([\"package_fix\"], indirect=True) == Scope.Package\n        assert find_scope([\"session_fix\"], indirect=True) == Scope.Session\n\n        assert find_scope([\"class_fix\", \"func_fix\"], indirect=True) == Scope.Function\n        assert find_scope([\"func_fix\", \"session_fix\"], indirect=True) == Scope.Function\n        assert find_scope([\"session_fix\", \"class_fix\"], indirect=True) == Scope.Class\n        assert (\n            find_scope([\"package_fix\", \"session_fix\"], indirect=True) == Scope.Package\n        )\n        assert find_scope([\"module_fix\", \"session_fix\"], indirect=True) == Scope.Module\n\n        # when indirect is False or is not for all scopes, always use function\n        assert (\n            find_scope([\"session_fix\", \"module_fix\"], indirect=False) == Scope.Function\n        )\n        assert (\n            find_scope([\"session_fix\", \"module_fix\"], indirect=[\"module_fix\"])\n            == Scope.Function\n        )\n        assert (\n            find_scope(\n                [\"session_fix\", \"module_fix\"], indirect=[\"session_fix\", \"module_fix\"]\n            )\n            == Scope.Module\n        )\n        assert find_scope([\"mixed_fix\"], indirect=True) == Scope.Class\n\n    def test_parametrize_and_id(self) -> None:\n        def func(x, y):\n            pass\n\n        metafunc = self.Metafunc(func)\n\n        metafunc.parametrize(\"x\", [1, 2], ids=[\"basic\", \"advanced\"])\n        metafunc.parametrize(\"y\", [\"abc\", \"def\"])\n        ids = [x.id for x in metafunc._calls]\n        assert ids == [\"basic-abc\", \"basic-def\", \"advanced-abc\", \"advanced-def\"]\n\n    def test_parametrize_and_id_unicode(self) -> None:\n        \"\"\"Allow unicode strings for \"ids\" parameter in Python 2 (##1905)\"\"\"\n\n        def func(x):\n            pass\n\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"x\", [1, 2], ids=[\"basic\", \"advanced\"])\n        ids = [x.id for x in metafunc._calls]\n        assert ids == [\"basic\", \"advanced\"]\n\n    def test_parametrize_with_wrong_number_of_ids(self) -> None:\n        def func(x, y):\n            pass\n\n        metafunc = self.Metafunc(func)\n\n        with pytest.raises(fail.Exception):\n            metafunc.parametrize(\"x\", [1, 2], ids=[\"basic\"])\n\n        with pytest.raises(fail.Exception):\n            metafunc.parametrize(\n                (\"x\", \"y\"), [(\"abc\", \"def\"), (\"ghi\", \"jkl\")], ids=[\"one\"]\n            )\n\n    def test_parametrize_ids_iterator_without_mark(self) -> None:\n        def func(x, y):\n            pass\n\n        it = itertools.count()\n\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"x\", [1, 2], ids=it)\n        metafunc.parametrize(\"y\", [3, 4], ids=it)\n        ids = [x.id for x in metafunc._calls]\n        assert ids == [\"0-2\", \"0-3\", \"1-2\", \"1-3\"]\n\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"x\", [1, 2], ids=it)\n        metafunc.parametrize(\"y\", [3, 4], ids=it)\n        ids = [x.id for x in metafunc._calls]\n        assert ids == [\"4-6\", \"4-7\", \"5-6\", \"5-7\"]\n\n    def test_parametrize_empty_list(self) -> None:\n        \"\"\"#510\"\"\"\n\n        def func(y):\n            pass\n\n        class MockConfig:\n            def getini(self, name):\n                return \"\"\n\n            @property\n            def hook(self):\n                return self\n\n            def pytest_make_parametrize_id(self, **kw):\n                pass\n\n        metafunc = self.Metafunc(func, MockConfig())\n        metafunc.parametrize(\"y\", [])\n        assert \"skip\" == metafunc._calls[0].marks[0].name\n\n    def test_parametrize_with_userobjects(self) -> None:\n        def func(x, y):\n            pass\n\n        metafunc = self.Metafunc(func)\n\n        class A:\n            pass\n\n        metafunc.parametrize(\"x\", [A(), A()])\n        metafunc.parametrize(\"y\", list(\"ab\"))\n        assert metafunc._calls[0].id == \"x0-a\"\n        assert metafunc._calls[1].id == \"x0-b\"\n        assert metafunc._calls[2].id == \"x1-a\"\n        assert metafunc._calls[3].id == \"x1-b\"\n\n    @hypothesis.given(strategies.text() | strategies.binary())\n    @hypothesis.settings(\n        deadline=400.0\n    )  # very close to std deadline and CI boxes are not reliable in CPU power\n    def test_idval_hypothesis(self, value) -> None:\n        escaped = IdMaker([], [], None, None, None, None)._idval(value, \"a\", 6)\n        assert isinstance(escaped, str)\n        escaped.encode(\"ascii\")\n\n    def test_unicode_idval(self) -> None:\n        \"\"\"Test that Unicode strings outside the ASCII character set get\n        escaped, using byte escapes if they're in that range or unicode\n        escapes if they're not.\n\n        \"\"\"\n        values = [\n            (\"\", r\"\"),\n            (\"ascii\", r\"ascii\"),\n            (\"ação\", r\"a\\xe7\\xe3o\"),\n            (\"josé@blah.com\", r\"jos\\xe9@blah.com\"),\n            (\n                r\"δοκ.ιμή@παράδειγμα.δοκιμή\",\n                r\"\\u03b4\\u03bf\\u03ba.\\u03b9\\u03bc\\u03ae@\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\"\n                r\"\\u03bc\\u03b1.\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae\",\n            ),\n        ]\n        for val, expected in values:\n            assert (\n                IdMaker([], [], None, None, None, None)._idval(val, \"a\", 6) == expected\n            )\n\n    def test_unicode_idval_with_config(self) -> None:\n        \"\"\"Unit test for expected behavior to obtain ids with\n        disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n        option (#5294).\"\"\"\n\n        class MockConfig:\n            def __init__(self, config):\n                self.config = config\n\n            @property\n            def hook(self):\n                return self\n\n            def pytest_make_parametrize_id(self, **kw):\n                pass\n\n            def getini(self, name):\n                return self.config[name]\n\n        option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n        values: list[tuple[str, Any, str]] = [\n            (\"ação\", MockConfig({option: True}), \"ação\"),\n            (\"ação\", MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n        ]\n        for val, config, expected in values:\n            actual = IdMaker([], [], None, None, config, None)._idval(val, \"a\", 6)\n            assert actual == expected\n\n    def test_bytes_idval(self) -> None:\n        \"\"\"Unit test for the expected behavior to obtain ids for parametrized\n        bytes values: bytes objects are always escaped using \"binary escape\".\"\"\"\n        values = [\n            (b\"\", r\"\"),\n            (b\"\\xc3\\xb4\\xff\\xe4\", r\"\\xc3\\xb4\\xff\\xe4\"),\n            (b\"ascii\", r\"ascii\"),\n            (\"αρά\".encode(), r\"\\xce\\xb1\\xcf\\x81\\xce\\xac\"),\n        ]\n        for val, expected in values:\n            assert (\n                IdMaker([], [], None, None, None, None)._idval(val, \"a\", 6) == expected\n            )\n\n    def test_class_or_function_idval(self) -> None:\n        \"\"\"Unit test for the expected behavior to obtain ids for parametrized\n        values that are classes or functions: their __name__.\"\"\"\n\n        class TestClass:\n            pass\n\n        def test_function():\n            pass\n\n        values = [(TestClass, \"TestClass\"), (test_function, \"test_function\")]\n        for val, expected in values:\n            assert (\n                IdMaker([], [], None, None, None, None)._idval(val, \"a\", 6) == expected\n            )\n\n    def test_notset_idval(self) -> None:\n        \"\"\"Test that a NOTSET value (used by an empty parameterset) generates\n        a proper ID.\n\n        Regression test for #7686.\n        \"\"\"\n        assert IdMaker([], [], None, None, None, None)._idval(NOTSET, \"a\", 0) == \"a0\"\n\n    def test_idmaker_autoname(self) -> None:\n        \"\"\"#250\"\"\"\n        result = IdMaker(\n            (\"a\", \"b\"),\n            [pytest.param(\"string\", 1.0), pytest.param(\"st-ring\", 2.0)],\n            None,\n            None,\n            None,\n            None,\n        ).make_unique_parameterset_ids()\n        assert result == [\"string-1.0\", \"st-ring-2.0\"]\n\n        result = IdMaker(\n            (\"a\", \"b\"),\n            [pytest.param(object(), 1.0), pytest.param(object(), object())],\n            None,\n            None,\n            None,\n            None,\n        ).make_unique_parameterset_ids()\n        assert result == [\"a0-1.0\", \"a1-b1\"]\n        # unicode mixing, issue250\n        result = IdMaker(\n            (\"a\", \"b\"), [pytest.param({}, b\"\\xc3\\xb4\")], None, None, None, None\n        ).make_unique_parameterset_ids()\n        assert result == [\"a0-\\\\xc3\\\\xb4\"]\n\n    def test_idmaker_with_bytes_regex(self) -> None:\n        result = IdMaker(\n            (\"a\"), [pytest.param(re.compile(b\"foo\"))], None, None, None, None\n        ).make_unique_parameterset_ids()\n        assert result == [\"foo\"]\n\n    def test_idmaker_native_strings(self) -> None:\n        result = IdMaker(\n            (\"a\", \"b\"),\n            [\n                pytest.param(1.0, -1.1),\n                pytest.param(2, -202),\n                pytest.param(\"three\", \"three hundred\"),\n                pytest.param(True, False),\n                pytest.param(None, None),\n                pytest.param(re.compile(\"foo\"), re.compile(\"bar\")),\n                pytest.param(str, int),\n                pytest.param(list(\"six\"), [66, 66]),\n                pytest.param({7}, set(\"seven\")),\n                pytest.param(tuple(\"eight\"), (8, -8, 8)),\n                pytest.param(b\"\\xc3\\xb4\", b\"name\"),\n                pytest.param(b\"\\xc3\\xb4\", \"other\"),\n                pytest.param(1.0j, -2.0j),\n            ],\n            None,\n            None,\n            None,\n            None,\n        ).make_unique_parameterset_ids()\n        assert result == [\n            \"1.0--1.1\",\n            \"2--202\",\n            \"three-three hundred\",\n            \"True-False\",\n            \"None-None\",\n            \"foo-bar\",\n            \"str-int\",\n            \"a7-b7\",\n            \"a8-b8\",\n            \"a9-b9\",\n            \"\\\\xc3\\\\xb4-name\",\n            \"\\\\xc3\\\\xb4-other\",\n            \"1j-(-0-2j)\",\n        ]\n\n    def test_idmaker_non_printable_characters(self) -> None:\n        result = IdMaker(\n            (\"s\", \"n\"),\n            [\n                pytest.param(\"\\x00\", 1),\n                pytest.param(\"\\x05\", 2),\n                pytest.param(b\"\\x00\", 3),\n                pytest.param(b\"\\x05\", 4),\n                pytest.param(\"\\t\", 5),\n                pytest.param(b\"\\t\", 6),\n            ],\n            None,\n            None,\n            None,\n            None,\n        ).make_unique_parameterset_ids()\n        assert result == [\"\\\\x00-1\", \"\\\\x05-2\", \"\\\\x00-3\", \"\\\\x05-4\", \"\\\\t-5\", \"\\\\t-6\"]\n\n    def test_idmaker_manual_ids_must_be_printable(self) -> None:\n        result = IdMaker(\n            (\"s\",),\n            [\n                pytest.param(\"x00\", id=\"hello \\x00\"),\n                pytest.param(\"x05\", id=\"hello \\x05\"),\n            ],\n            None,\n            None,\n            None,\n            None,\n        ).make_unique_parameterset_ids()\n        assert result == [\"hello \\\\x00\", \"hello \\\\x05\"]\n\n    def test_idmaker_enum(self) -> None:\n        enum = pytest.importorskip(\"enum\")\n        e = enum.Enum(\"Foo\", \"one, two\")\n        result = IdMaker(\n            (\"a\", \"b\"), [pytest.param(e.one, e.two)], None, None, None, None\n        ).make_unique_parameterset_ids()\n        assert result == [\"Foo.one-Foo.two\"]\n\n    def test_idmaker_idfn(self) -> None:\n        \"\"\"#351\"\"\"\n\n        def ids(val: object) -> str | None:\n            if isinstance(val, Exception):\n                return repr(val)\n            return None\n\n        result = IdMaker(\n            (\"a\", \"b\"),\n            [\n                pytest.param(10.0, IndexError()),\n                pytest.param(20, KeyError()),\n                pytest.param(\"three\", [1, 2, 3]),\n            ],\n            ids,\n            None,\n            None,\n            None,\n        ).make_unique_parameterset_ids()\n        assert result == [\"10.0-IndexError()\", \"20-KeyError()\", \"three-b2\"]\n\n    def test_idmaker_idfn_unique_names(self) -> None:\n        \"\"\"#351\"\"\"\n\n        def ids(val: object) -> str:\n            return \"a\"\n\n        result = IdMaker(\n            (\"a\", \"b\"),\n            [\n                pytest.param(10.0, IndexError()),\n                pytest.param(20, KeyError()),\n                pytest.param(\"three\", [1, 2, 3]),\n            ],\n            ids,\n            None,\n            None,\n            None,\n        ).make_unique_parameterset_ids()\n        assert result == [\"a-a0\", \"a-a1\", \"a-a2\"]\n\n    def test_idmaker_with_idfn_and_config(self) -> None:\n        \"\"\"Unit test for expected behavior to create ids with idfn and\n        disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n        option (#5294).\n        \"\"\"\n\n        class MockConfig:\n            def __init__(self, config):\n                self.config = config\n\n            @property\n            def hook(self):\n                return self\n\n            def pytest_make_parametrize_id(self, **kw):\n                pass\n\n            def getini(self, name):\n                return self.config[name]\n\n        option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n        values: list[tuple[Any, str]] = [\n            (MockConfig({option: True}), \"ação\"),\n            (MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n        ]\n        for config, expected in values:\n            result = IdMaker(\n                (\"a\",),\n                [pytest.param(\"string\")],\n                lambda _: \"ação\",\n                None,\n                config,\n                None,\n            ).make_unique_parameterset_ids()\n            assert result == [expected]\n\n    def test_idmaker_with_ids_and_config(self) -> None:\n        \"\"\"Unit test for expected behavior to create ids with ids and\n        disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n        option (#5294).\n        \"\"\"\n\n        class MockConfig:\n            def __init__(self, config):\n                self.config = config\n\n            @property\n            def hook(self):\n                return self\n\n            def pytest_make_parametrize_id(self, **kw):\n                pass\n\n            def getini(self, name):\n                return self.config[name]\n\n        option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n        values: list[tuple[Any, str]] = [\n            (MockConfig({option: True}), \"ação\"),\n            (MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n        ]\n        for config, expected in values:\n            result = IdMaker(\n                (\"a\",), [pytest.param(\"string\")], None, [\"ação\"], config, None\n            ).make_unique_parameterset_ids()\n            assert result == [expected]\n\n    def test_idmaker_with_param_id_and_config(self) -> None:\n        \"\"\"Unit test for expected behavior to create ids with pytest.param(id=...) and\n        disable_test_id_escaping_and_forfeit_all_rights_to_community_support\n        option (#9037).\n        \"\"\"\n\n        class MockConfig:\n            def __init__(self, config):\n                self.config = config\n\n            def getini(self, name):\n                return self.config[name]\n\n        option = \"disable_test_id_escaping_and_forfeit_all_rights_to_community_support\"\n\n        values: list[tuple[Any, str]] = [\n            (MockConfig({option: True}), \"ação\"),\n            (MockConfig({option: False}), \"a\\\\xe7\\\\xe3o\"),\n        ]\n        for config, expected in values:\n            result = IdMaker(\n                (\"a\",),\n                [pytest.param(\"string\", id=\"ação\")],\n                None,\n                None,\n                config,\n                None,\n            ).make_unique_parameterset_ids()\n            assert result == [expected]\n\n    def test_idmaker_duplicated_empty_str(self) -> None:\n        \"\"\"Regression test for empty strings parametrized more than once (#11563).\"\"\"\n        result = IdMaker(\n            (\"a\",), [pytest.param(\"\"), pytest.param(\"\")], None, None, None, None\n        ).make_unique_parameterset_ids()\n        assert result == [\"0\", \"1\"]\n\n    def test_parametrize_ids_exception(self, pytester: Pytester) -> None:\n        \"\"\"\n        :param pytester: the instance of Pytester class, a temporary\n        test directory.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n                import pytest\n\n                def ids(arg):\n                    raise Exception(\"bad ids\")\n\n                @pytest.mark.parametrize(\"arg\", [\"a\", \"b\"], ids=ids)\n                def test_foo(arg):\n                    pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*Exception: bad ids\",\n                \"*test_foo: error raised while trying to determine id of parameter 'arg' at position 0\",\n            ]\n        )\n\n    def test_parametrize_ids_returns_non_string(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n            import pytest\n\n            def ids(d):\n                return d\n\n            @pytest.mark.parametrize(\"arg\", ({1: 2}, {3, 4}), ids=ids)\n            def test(arg):\n                assert arg\n\n            @pytest.mark.parametrize(\"arg\", (1, 2.0, True), ids=ids)\n            def test_int(arg):\n                assert arg\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-vv\", \"-s\")\n        result.stdout.fnmatch_lines(\n            [\n                \"test_parametrize_ids_returns_non_string.py::test[arg0] PASSED\",\n                \"test_parametrize_ids_returns_non_string.py::test[arg1] PASSED\",\n                \"test_parametrize_ids_returns_non_string.py::test_int[1] PASSED\",\n                \"test_parametrize_ids_returns_non_string.py::test_int[2.0] PASSED\",\n                \"test_parametrize_ids_returns_non_string.py::test_int[True] PASSED\",\n            ]\n        )\n\n    def test_idmaker_with_ids(self) -> None:\n        result = IdMaker(\n            (\"a\", \"b\"),\n            [pytest.param(1, 2), pytest.param(3, 4)],\n            None,\n            [\"a\", None],\n            None,\n            None,\n        ).make_unique_parameterset_ids()\n        assert result == [\"a\", \"3-4\"]\n\n    def test_idmaker_with_paramset_id(self) -> None:\n        result = IdMaker(\n            (\"a\", \"b\"),\n            [pytest.param(1, 2, id=\"me\"), pytest.param(3, 4, id=\"you\")],\n            None,\n            [\"a\", None],\n            None,\n            None,\n        ).make_unique_parameterset_ids()\n        assert result == [\"me\", \"you\"]\n\n    def test_idmaker_with_ids_unique_names(self) -> None:\n        result = IdMaker(\n            (\"a\"),\n            list(map(pytest.param, [1, 2, 3, 4, 5])),\n            None,\n            [\"a\", \"a\", \"b\", \"c\", \"b\"],\n            None,\n            None,\n        ).make_unique_parameterset_ids()\n        assert result == [\"a0\", \"a1\", \"b0\", \"c\", \"b1\"]\n\n    def test_parametrize_indirect(self) -> None:\n        \"\"\"#714\"\"\"\n\n        def func(x, y):\n            pass\n\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"x\", [1], indirect=True)\n        metafunc.parametrize(\"y\", [2, 3], indirect=True)\n        assert len(metafunc._calls) == 2\n        assert metafunc._calls[0].params == dict(x=1, y=2)\n        assert metafunc._calls[1].params == dict(x=1, y=3)\n\n    def test_parametrize_indirect_list(self) -> None:\n        \"\"\"#714\"\"\"\n\n        def func(x, y):\n            pass\n\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\"])\n        assert metafunc._calls[0].params == dict(x=\"a\", y=\"b\")\n        # Since `y` is a direct parameter, its pseudo-fixture would\n        # be registered.\n        assert list(metafunc._arg2fixturedefs.keys()) == [\"y\"]\n\n    def test_parametrize_indirect_list_all(self) -> None:\n        \"\"\"#714\"\"\"\n\n        def func(x, y):\n            pass\n\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\", \"y\"])\n        assert metafunc._calls[0].params == dict(x=\"a\", y=\"b\")\n        assert list(metafunc._arg2fixturedefs.keys()) == []\n\n    def test_parametrize_indirect_list_empty(self) -> None:\n        \"\"\"#714\"\"\"\n\n        def func(x, y):\n            pass\n\n        metafunc = self.Metafunc(func)\n        metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[])\n        assert metafunc._calls[0].params == dict(x=\"a\", y=\"b\")\n        assert list(metafunc._arg2fixturedefs.keys()) == [\"x\", \"y\"]\n\n    def test_parametrize_indirect_wrong_type(self) -> None:\n        def func(x, y):\n            pass\n\n        metafunc = self.Metafunc(func)\n        with pytest.raises(\n            fail.Exception,\n            match=\"In mock::nodeid: expected Sequence or boolean for indirect, got dict\",\n        ):\n            metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect={})  # type: ignore[arg-type]\n\n    def test_parametrize_indirect_list_functional(self, pytester: Pytester) -> None:\n        \"\"\"\n        #714\n        Test parametrization with 'indirect' parameter applied on\n        particular arguments. As y is direct, its value should\n        be used directly rather than being passed to the fixture y.\n\n        :param pytester: the instance of Pytester class, a temporary\n        test directory.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope='function')\n            def x(request):\n                return request.param * 3\n            @pytest.fixture(scope='function')\n            def y(request):\n                return request.param * 2\n            @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])\n            def test_simple(x,y):\n                assert len(x) == 3\n                assert len(y) == 1\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines([\"*test_simple*a-b*\", \"*1 passed*\"])\n\n    def test_parametrize_indirect_list_error(self) -> None:\n        \"\"\"#714\"\"\"\n\n        def func(x, y):\n            pass\n\n        metafunc = self.Metafunc(func)\n        with pytest.raises(fail.Exception):\n            metafunc.parametrize(\"x, y\", [(\"a\", \"b\")], indirect=[\"x\", \"z\"])\n\n    def test_parametrize_uses_no_fixture_error_indirect_false(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"The 'uses no fixture' error tells the user at collection time\n        that the parametrize data they've set up doesn't correspond to the\n        fixtures in their test function, rather than silently ignoring this\n        and letting the test potentially pass.\n\n        #714\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=False)\n            def test_simple(x):\n                assert len(x) == 3\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines([\"*uses no argument 'y'*\"])\n\n    def test_parametrize_uses_no_fixture_error_indirect_true(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"#714\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope='function')\n            def x(request):\n                return request.param * 3\n            @pytest.fixture(scope='function')\n            def y(request):\n                return request.param * 2\n\n            @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=True)\n            def test_simple(x):\n                assert len(x) == 3\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])\n\n    def test_parametrize_indirect_uses_no_fixture_error_indirect_string(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"#714\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope='function')\n            def x(request):\n                return request.param * 3\n\n            @pytest.mark.parametrize('x, y', [('a', 'b')], indirect='y')\n            def test_simple(x):\n                assert len(x) == 3\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])\n\n    def test_parametrize_indirect_uses_no_fixture_error_indirect_list(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"#714\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope='function')\n            def x(request):\n                return request.param * 3\n\n            @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['y'])\n            def test_simple(x):\n                assert len(x) == 3\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines([\"*uses no fixture 'y'*\"])\n\n    def test_parametrize_argument_not_in_indirect_list(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"#714\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope='function')\n            def x(request):\n                return request.param * 3\n\n            @pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])\n            def test_simple(x):\n                assert len(x) == 3\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines([\"*uses no argument 'y'*\"])\n\n    def test_parametrize_gives_indicative_error_on_function_with_default_argument(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize('x, y', [('a', 'b')])\n            def test_simple(x, y=1):\n                assert len(x) == 1\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines(\n            [\"*already takes an argument 'y' with a default value\"]\n        )\n\n    def test_parametrize_functional(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize('x', [1,2], indirect=True)\n                metafunc.parametrize('y', [2])\n            @pytest.fixture\n            def x(request):\n                return request.param * 10\n\n            def test_simple(x,y):\n                assert x in (10,20)\n                assert y == 2\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines(\n            [\"*test_simple*1-2*\", \"*test_simple*2-2*\", \"*2 passed*\"]\n        )\n\n    def test_parametrize_onearg(self) -> None:\n        metafunc = self.Metafunc(lambda x: None)\n        metafunc.parametrize(\"x\", [1, 2])\n        assert len(metafunc._calls) == 2\n        assert metafunc._calls[0].params == dict(x=1)\n        assert metafunc._calls[0].id == \"1\"\n        assert metafunc._calls[1].params == dict(x=2)\n        assert metafunc._calls[1].id == \"2\"\n\n    def test_parametrize_onearg_indirect(self) -> None:\n        metafunc = self.Metafunc(lambda x: None)\n        metafunc.parametrize(\"x\", [1, 2], indirect=True)\n        assert metafunc._calls[0].params == dict(x=1)\n        assert metafunc._calls[0].id == \"1\"\n        assert metafunc._calls[1].params == dict(x=2)\n        assert metafunc._calls[1].id == \"2\"\n\n    def test_parametrize_twoargs(self) -> None:\n        metafunc = self.Metafunc(lambda x, y: None)\n        metafunc.parametrize((\"x\", \"y\"), [(1, 2), (3, 4)])\n        assert len(metafunc._calls) == 2\n        assert metafunc._calls[0].params == dict(x=1, y=2)\n        assert metafunc._calls[0].id == \"1-2\"\n        assert metafunc._calls[1].params == dict(x=3, y=4)\n        assert metafunc._calls[1].id == \"3-4\"\n\n    def test_high_scoped_parametrize_reordering(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"arg2\", [3, 4])\n            @pytest.mark.parametrize(\"arg1\", [0, 1, 2], scope='module')\n            def test1(arg1, arg2):\n                pass\n\n            def test2():\n                pass\n\n            @pytest.mark.parametrize(\"arg1\", [0, 1, 2], scope='module')\n            def test3(arg1):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.re_match_lines(\n            [\n                r\"    <Function test1\\[0-3\\]>\",\n                r\"    <Function test3\\[0\\]>\",\n                r\"    <Function test1\\[0-4\\]>\",\n                r\"    <Function test3\\[1\\]>\",\n                r\"    <Function test1\\[1-3\\]>\",\n                r\"    <Function test3\\[2\\]>\",\n                r\"    <Function test1\\[1-4\\]>\",\n                r\"    <Function test1\\[2-3\\]>\",\n                r\"    <Function test1\\[2-4\\]>\",\n                r\"    <Function test2>\",\n            ]\n        )\n\n    def test_parametrize_multiple_times(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            pytestmark = pytest.mark.parametrize(\"x\", [1,2])\n            def test_func(x):\n                assert 0, x\n            class TestClass(object):\n                pytestmark = pytest.mark.parametrize(\"y\", [3,4])\n                def test_meth(self, x, y):\n                    assert 0, x\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.assert_outcomes(failed=6)\n\n    def test_parametrize_CSV(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.parametrize(\"x, y,\", [(1,2), (2,3)])\n            def test_func(x, y):\n                assert x+1 == y\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    def test_parametrize_class_scenarios(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n        # same as doc/en/example/parametrize scenario example\n        def pytest_generate_tests(metafunc):\n            idlist = []\n            argvalues = []\n            for scenario in metafunc.cls.scenarios:\n                idlist.append(scenario[0])\n                items = scenario[1].items()\n                argnames = [x[0] for x in items]\n                argvalues.append(([x[1] for x in items]))\n            metafunc.parametrize(argnames, argvalues, ids=idlist, scope=\"class\")\n\n        class Test(object):\n               scenarios = [['1', {'arg': {1: 2}, \"arg2\": \"value2\"}],\n                            ['2', {'arg':'value2', \"arg2\": \"value2\"}]]\n\n               def test_1(self, arg, arg2):\n                  pass\n\n               def test_2(self, arg2, arg):\n                  pass\n\n               def test_3(self, arg, arg2):\n                  pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *test_1*1*\n            *test_2*1*\n            *test_3*1*\n            *test_1*2*\n            *test_2*2*\n            *test_3*2*\n            *6 passed*\n        \"\"\"\n        )\n\n    def test_parametrize_iterator_deprecation(self) -> None:\n        \"\"\"Test that using iterators for argvalues raises a deprecation warning.\"\"\"\n\n        def func(x: int) -> None:\n            raise NotImplementedError()\n\n        def data_generator() -> Iterator[int]:\n            yield 1\n            yield 2\n\n        metafunc = self.Metafunc(func)\n\n        with pytest.warns(\n            pytest.PytestRemovedIn10Warning,\n            match=r\"Passing a non-Collection iterable to parametrize is deprecated\",\n        ):\n            metafunc.parametrize(\"x\", data_generator())\n\n\nclass TestMetafuncFunctional:\n    def test_attributes(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            # assumes that generate/provide runs in the same process\n            import sys, pytest\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize('metafunc', [metafunc])\n\n            @pytest.fixture\n            def metafunc(request):\n                return request.param\n\n            def test_function(metafunc, pytestconfig):\n                assert metafunc.config == pytestconfig\n                assert metafunc.module.__name__ == __name__\n                assert metafunc.function == test_function\n                assert metafunc.cls is None\n\n            class TestClass(object):\n                def test_method(self, metafunc, pytestconfig):\n                    assert metafunc.config == pytestconfig\n                    assert metafunc.module.__name__ == __name__\n                    unbound = TestClass.test_method\n                    assert metafunc.function == unbound\n                    assert metafunc.cls == TestClass\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-v\")\n        result.assert_outcomes(passed=2)\n\n    def test_two_functions(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize('arg1', [10, 20], ids=['0', '1'])\n\n            def test_func1(arg1):\n                assert arg1 == 10\n\n            def test_func2(arg1):\n                assert arg1 in (10, 20)\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\", p)\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_func1*0*PASS*\",\n                \"*test_func1*1*FAIL*\",\n                \"*test_func2*PASS*\",\n                \"*test_func2*PASS*\",\n                \"*1 failed, 3 passed*\",\n            ]\n        )\n\n    def test_noself_in_method(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def pytest_generate_tests(metafunc):\n                assert 'xyz' not in metafunc.fixturenames\n\n            class TestHello(object):\n                def test_hello(xyz):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.assert_outcomes(passed=1)\n\n    def test_generate_tests_in_class(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            class TestClass(object):\n                def pytest_generate_tests(self, metafunc):\n                    metafunc.parametrize('hello', ['world'], ids=['hellow'])\n\n                def test_myfunc(self, hello):\n                    assert hello == \"world\"\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\", p)\n        result.stdout.fnmatch_lines([\"*test_myfunc*hello*PASS*\", \"*1 passed*\"])\n\n    def test_two_functions_not_same_instance(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize('arg1', [10, 20], ids=[\"0\", \"1\"])\n\n            class TestClass(object):\n                def test_func(self, arg1):\n                    assert not hasattr(self, 'x')\n                    self.x = 1\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\", p)\n        result.stdout.fnmatch_lines(\n            [\"*test_func*0*PASS*\", \"*test_func*1*PASS*\", \"*2 pass*\"]\n        )\n\n    def test_issue28_setup_method_in_generate_tests(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize('arg1', [1])\n\n            class TestClass(object):\n                def test_method(self, arg1):\n                    assert arg1 == self.val\n                def setup_method(self, func):\n                    self.val = 1\n            \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.assert_outcomes(passed=1)\n\n    def test_parametrize_functional2(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize(\"arg1\", [1,2])\n                metafunc.parametrize(\"arg2\", [4,5])\n            def test_hello(arg1, arg2):\n                assert 0, (arg1, arg2)\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\"*(1, 4)*\", \"*(1, 5)*\", \"*(2, 4)*\", \"*(2, 5)*\", \"*4 failed*\"]\n        )\n\n    def test_parametrize_single_arg_trailing_comma_functional(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test that trailing comma in string argnames behaves like tuple argnames.\n\n        Regression test for https://github.com/pytest-dev/pytest/issues/719\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            scenarios = [('a',), ('b',)]\n\n            @pytest.mark.parametrize((\"arg\",), scenarios)\n            def test_tuple_form(arg):\n                # Tuple argnames: values are unpacked from tuples\n                assert arg in ('a', 'b')\n                assert isinstance(arg, str)\n\n            @pytest.mark.parametrize(\"arg,\", scenarios)\n            def test_string_trailing_comma(arg):\n                # String with trailing comma: should behave like tuple form\n                assert arg in ('a', 'b')\n                assert isinstance(arg, str)\n\n            @pytest.mark.parametrize(\"arg\", scenarios)\n            def test_string_no_comma(arg):\n                # String without comma: tuples are passed as-is\n                assert arg in (('a',), ('b',))\n                assert isinstance(arg, tuple)\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        result.assert_outcomes(passed=6)\n\n    def test_parametrize_and_inner_getfixturevalue(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize(\"arg1\", [1], indirect=True)\n                metafunc.parametrize(\"arg2\", [10], indirect=True)\n\n            import pytest\n            @pytest.fixture\n            def arg1(request):\n                x = request.getfixturevalue(\"arg2\")\n                return x + request.param\n\n            @pytest.fixture\n            def arg2(request):\n                return request.param\n\n            def test_func1(arg1, arg2):\n                assert arg1 == 11\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\", p)\n        result.stdout.fnmatch_lines([\"*test_func1*1*PASS*\", \"*1 passed*\"])\n\n    def test_parametrize_on_setup_arg(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def pytest_generate_tests(metafunc):\n                assert \"arg1\" in metafunc.fixturenames\n                metafunc.parametrize(\"arg1\", [1], indirect=True)\n\n            import pytest\n            @pytest.fixture\n            def arg1(request):\n                return request.param\n\n            @pytest.fixture\n            def arg2(request, arg1):\n                return 10 * arg1\n\n            def test_func(arg2):\n                assert arg2 == 10\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\", p)\n        result.stdout.fnmatch_lines([\"*test_func*1*PASS*\", \"*1 passed*\"])\n\n    def test_parametrize_with_ids(self, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style=classic\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,2)],\n                                     ids=[\"basic\", \"advanced\"])\n\n            def test_function(a, b):\n                assert a == b\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        assert result.ret == 1\n        result.stdout.fnmatch_lines_random(\n            [\"*test_function*basic*PASSED\", \"*test_function*advanced*FAILED\"]\n        )\n\n    def test_parametrize_without_ids(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize((\"a\", \"b\"),\n                                     [(1,object()), (1.3,object())])\n\n            def test_function(a, b):\n                assert 1\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *test_function*1-b0*\n            *test_function*1.3-b1*\n        \"\"\"\n        )\n\n    def test_parametrize_with_None_in_ids(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,1), (1,2)],\n                                     ids=[\"basic\", None, \"advanced\"])\n\n            def test_function(a, b):\n                assert a == b\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        assert result.ret == 1\n        result.stdout.fnmatch_lines_random(\n            [\n                \"*test_function*basic*PASSED*\",\n                \"*test_function*1-1*PASSED*\",\n                \"*test_function*advanced*FAILED*\",\n            ]\n        )\n\n    def test_fixture_parametrized_empty_ids(self, pytester: Pytester) -> None:\n        \"\"\"Fixtures parametrized with empty ids cause an internal error (#1849).\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"module\", ids=[], params=[])\n            def temp(request):\n               return request.param\n\n            def test_temp(temp):\n                 pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 1 skipped *\"])\n\n    def test_parametrized_empty_ids(self, pytester: Pytester) -> None:\n        \"\"\"Tests parametrized with empty ids cause an internal error (#1849).\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize('temp', [], ids=list())\n            def test_temp(temp):\n                 pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 1 skipped *\"])\n\n    def test_parametrized_ids_invalid_type(self, pytester: Pytester) -> None:\n        \"\"\"Test error with non-strings/non-ints, without generator (#1857).\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"x, expected\", [(1, 2), (3, 4), (5, 6)], ids=(None, 2, OSError()))\n            def test_ids_numbers(x,expected):\n                assert x * 2 == expected\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"In test_parametrized_ids_invalid_type.py::test_ids_numbers: ids contains unsupported value \"\n                \"OSError() (type: <class 'OSError'>) at index 2. \"\n                \"Supported types are: str, bytes, int, float, complex, bool, enum, regex or anything with a __name__.\"\n            ]\n        )\n\n    def test_parametrize_with_identical_ids_get_unique_names(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def pytest_generate_tests(metafunc):\n                metafunc.parametrize((\"a\", \"b\"), [(1,1), (1,2)],\n                                     ids=[\"a\", \"a\"])\n\n            def test_function(a, b):\n                assert a == b\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        assert result.ret == 1\n        result.stdout.fnmatch_lines_random(\n            [\"*test_function*a0*PASSED*\", \"*test_function*a1*FAILED*\"]\n        )\n\n    @pytest.mark.parametrize((\"scope\", \"length\"), [(\"module\", 2), (\"function\", 4)])\n    def test_parametrize_scope_overrides(\n        self, pytester: Pytester, scope: str, length: int\n    ) -> None:\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest\n            values = []\n            def pytest_generate_tests(metafunc):\n                if \"arg\" in metafunc.fixturenames:\n                    metafunc.parametrize(\"arg\", [1,2], indirect=True,\n                                         scope={scope!r})\n            @pytest.fixture\n            def arg(request):\n                values.append(request.param)\n                return request.param\n            def test_hello(arg):\n                assert arg in (1,2)\n            def test_world(arg):\n                assert arg in (1,2)\n            def test_checklength():\n                assert len(values) == {length}\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=5)\n\n    def test_parametrize_issue323(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='module', params=range(966))\n            def foo(request):\n                return request.param\n\n            def test_it(foo):\n                pass\n            def test_it2(foo):\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"--collect-only\")\n        assert not reprec.getcalls(\"pytest_internalerror\")\n\n    def test_usefixtures_seen_in_generate_tests(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def pytest_generate_tests(metafunc):\n                assert \"abc\" in metafunc.fixturenames\n                metafunc.parametrize(\"abc\", [1])\n\n            @pytest.mark.usefixtures(\"abc\")\n            def test_function():\n                pass\n        \"\"\"\n        )\n        reprec = pytester.runpytest()\n        reprec.assert_outcomes(passed=1)\n\n    def test_generate_tests_only_done_in_subdir(self, pytester: Pytester) -> None:\n        sub1 = pytester.mkpydir(\"sub1\")\n        sub2 = pytester.mkpydir(\"sub2\")\n        sub1.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                def pytest_generate_tests(metafunc):\n                    assert metafunc.function.__name__ == \"test_1\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        sub2.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                def pytest_generate_tests(metafunc):\n                    assert metafunc.function.__name__ == \"test_2\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        sub1.joinpath(\"test_in_sub1.py\").write_text(\n            \"def test_1(): pass\", encoding=\"utf-8\"\n        )\n        sub2.joinpath(\"test_in_sub2.py\").write_text(\n            \"def test_2(): pass\", encoding=\"utf-8\"\n        )\n        result = pytester.runpytest(\"--keep-duplicates\", \"-v\", \"-s\", sub1, sub2, sub1)\n        result.assert_outcomes(passed=3)\n\n    def test_generate_same_function_names_issue403(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def make_tests():\n                @pytest.mark.parametrize(\"x\", range(2))\n                def test_foo(x):\n                    pass\n                return test_foo\n\n            test_x = make_tests()\n            test_y = make_tests()\n        \"\"\"\n        )\n        reprec = pytester.runpytest()\n        reprec.assert_outcomes(passed=4)\n\n    def test_parametrize_misspelling(self, pytester: Pytester) -> None:\n        \"\"\"#463\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrise(\"x\", range(2))\n            def test_foo(x):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 0 items / 1 error\",\n                \"\",\n                \"*= ERRORS =*\",\n                \"*_ ERROR collecting test_parametrize_misspelling.py _*\",\n                \"test_parametrize_misspelling.py:3: in <module>\",\n                '    @pytest.mark.parametrise(\"x\", range(2))',\n                \"E   Failed: Unknown 'parametrise' mark, did you mean 'parametrize'?\",\n                \"*! Interrupted: 1 error during collection !*\",\n                \"*= no tests collected, 1 error in *\",\n            ]\n        )\n\n    @pytest.mark.parametrize(\"scope\", [\"class\", \"package\"])\n    def test_parametrize_missing_scope_doesnt_crash(\n        self, pytester: Pytester, scope: str\n    ) -> None:\n        \"\"\"Doesn't crash when parametrize(scope=<scope>) is used without a\n        corresponding <scope> node.\"\"\"\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"x\", [0], scope=\"{scope}\")\n            def test_it(x): pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_parametrize_module_level_test_with_class_scope(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"\n        Test that a class-scoped parametrization without a corresponding `Class`\n        gets module scope, i.e. we only create a single FixtureDef for it per module.\n        \"\"\"\n        module = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"x\", [0, 1], scope=\"class\")\n            def test_1(x):\n                pass\n\n            @pytest.mark.parametrize(\"x\", [1, 2], scope=\"module\")\n            def test_2(x):\n                pass\n        \"\"\"\n        )\n        test_1_0, _, test_2_0, _ = pytester.genitems((pytester.getmodulecol(module),))\n\n        assert isinstance(test_1_0, Function)\n        assert test_1_0.name == \"test_1[0]\"\n        test_1_fixture_x = test_1_0._fixtureinfo.name2fixturedefs[\"x\"][-1]\n\n        assert isinstance(test_2_0, Function)\n        assert test_2_0.name == \"test_2[1]\"\n        test_2_fixture_x = test_2_0._fixtureinfo.name2fixturedefs[\"x\"][-1]\n\n        assert test_1_fixture_x is test_2_fixture_x\n\n    def test_reordering_with_scopeless_and_just_indirect_parametrization(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"package\")\n            def fixture1():\n                pass\n            \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope=\"module\")\n            def fixture0():\n                pass\n\n            @pytest.fixture(scope=\"module\")\n            def fixture1(fixture0):\n                pass\n\n            @pytest.mark.parametrize(\"fixture1\", [0], indirect=True)\n            def test_0(fixture1):\n                pass\n\n            @pytest.fixture(scope=\"module\")\n            def fixture():\n                pass\n\n            @pytest.mark.parametrize(\"fixture\", [0], indirect=True)\n            def test_1(fixture):\n                pass\n\n            def test_2():\n                pass\n\n            class Test:\n                @pytest.fixture(scope=\"class\")\n                def fixture(self, fixture):\n                    pass\n\n                @pytest.mark.parametrize(\"fixture\", [0], indirect=True)\n                def test_3(self, fixture):\n                    pass\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_0*\",\n                \"*test_1*\",\n                \"*test_2*\",\n                \"*test_3*\",\n            ]\n        )\n\n    def test_parametrize_generator_multiple_runs(self, pytester: Pytester) -> None:\n        \"\"\"Test that generators in parametrize work with multiple pytest.main() (deprecated).\"\"\"\n        testfile = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def data_generator():\n                yield 1\n                yield 2\n\n            @pytest.mark.parametrize(\"bar\", data_generator())\n            def test_foo(bar):\n                pass\n\n            if __name__ == '__main__':\n                args = [\"-q\", \"--collect-only\"]\n                pytest.main(args)  # First run - should work with warning\n                pytest.main(args)  # Second run - should also work with warning\n            \"\"\"\n        )\n        result = pytester.run(sys.executable, \"-Wdefault\", testfile)\n        # Should see the deprecation warnings.\n        result.stdout.fnmatch_lines(\n            [\n                \"*PytestRemovedIn10Warning: Passing a non-Collection iterable*\",\n                \"*PytestRemovedIn10Warning: Passing a non-Collection iterable*\",\n            ]\n        )\n\n    def test_parametrize_iterator_class_multiple_tests(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test that iterators in parametrize on a class get exhausted (deprecated).\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"n\", iter(range(2)))\n            class Test:\n                def test_1(self, n):\n                    pass\n\n                def test_2(self, n):\n                    pass\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-v\", \"-Wdefault\")\n        # Iterator gets exhausted after first test, second test gets no parameters.\n        # This is deprecated.\n        result.assert_outcomes(passed=2, skipped=1)\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_parametrize_iterator_class_multiple_tests.py::Test::test_1[[]0] PASSED*\",\n                \"*test_parametrize_iterator_class_multiple_tests.py::Test::test_1[[]1] PASSED*\",\n                \"*test_parametrize_iterator_class_multiple_tests.py::Test::test_2[[]NOTSET] SKIPPED*\",\n                \"*PytestRemovedIn10Warning: Passing a non-Collection iterable*\",\n            ]\n        )\n\n\nclass TestMetafuncFunctionalAuto:\n    \"\"\"Tests related to automatically find out the correct scope for\n    parametrized tests (#1832).\"\"\"\n\n    def test_parametrize_auto_scope(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='session', autouse=True)\n            def fixture():\n                return 1\n\n            @pytest.mark.parametrize('animal', [\"dog\", \"cat\"])\n            def test_1(animal):\n                assert animal in ('dog', 'cat')\n\n            @pytest.mark.parametrize('animal', ['fish'])\n            def test_2(animal):\n                assert animal == 'fish'\n\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 3 passed *\"])\n\n    def test_parametrize_auto_scope_indirect(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='session')\n            def echo(request):\n                return request.param\n\n            @pytest.mark.parametrize('animal, echo', [(\"dog\", 1), (\"cat\", 2)], indirect=['echo'])\n            def test_1(animal, echo):\n                assert animal in ('dog', 'cat')\n                assert echo in (1, 2, 3)\n\n            @pytest.mark.parametrize('animal, echo', [('fish', 3)], indirect=['echo'])\n            def test_2(animal, echo):\n                assert animal == 'fish'\n                assert echo in (1, 2, 3)\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 3 passed *\"])\n\n    def test_parametrize_auto_scope_override_fixture(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='session', autouse=True)\n            def animal():\n                return 'fox'\n\n            @pytest.mark.parametrize('animal', [\"dog\", \"cat\"])\n            def test_1(animal):\n                assert animal in ('dog', 'cat')\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 2 passed *\"])\n\n    def test_parametrize_all_indirects(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture()\n            def animal(request):\n                return request.param\n\n            @pytest.fixture(scope='session')\n            def echo(request):\n                return request.param\n\n            @pytest.mark.parametrize('animal, echo', [(\"dog\", 1), (\"cat\", 2)], indirect=True)\n            def test_1(animal, echo):\n                assert animal in ('dog', 'cat')\n                assert echo in (1, 2, 3)\n\n            @pytest.mark.parametrize('animal, echo', [(\"fish\", 3)], indirect=True)\n            def test_2(animal, echo):\n                assert animal == 'fish'\n                assert echo in (1, 2, 3)\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 3 passed *\"])\n\n    def test_parametrize_some_arguments_auto_scope(\n        self, pytester: Pytester, monkeypatch\n    ) -> None:\n        \"\"\"Integration test for (#3941)\"\"\"\n        class_fix_setup: list[object] = []\n        monkeypatch.setattr(sys, \"class_fix_setup\", class_fix_setup, raising=False)\n        func_fix_setup: list[object] = []\n        monkeypatch.setattr(sys, \"func_fix_setup\", func_fix_setup, raising=False)\n\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            import sys\n\n            @pytest.fixture(scope='class', autouse=True)\n            def class_fix(request):\n                sys.class_fix_setup.append(request.param)\n\n            @pytest.fixture(autouse=True)\n            def func_fix():\n                sys.func_fix_setup.append(True)\n\n            @pytest.mark.parametrize('class_fix', [10, 20], indirect=True)\n            class Test:\n                def test_foo(self):\n                    pass\n                def test_bar(self):\n                    pass\n            \"\"\"\n        )\n        result = pytester.runpytest_inprocess()\n        result.stdout.fnmatch_lines([\"* 4 passed in *\"])\n        assert func_fix_setup == [True] * 4\n        assert class_fix_setup == [10, 20]\n\n    def test_parametrize_issue634(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture(scope='module')\n            def foo(request):\n                print('preparing foo-%d' % request.param)\n                return 'foo-%d' % request.param\n\n            def test_one(foo):\n                pass\n\n            def test_two(foo):\n                pass\n\n            test_two.test_with = (2, 3)\n\n            def pytest_generate_tests(metafunc):\n                params = (1, 2, 3, 4)\n                if not 'foo' in metafunc.fixturenames:\n                    return\n\n                test_with = getattr(metafunc.function, 'test_with', None)\n                if test_with:\n                    params = test_with\n                metafunc.parametrize('foo', params, indirect=True)\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\")\n        output = result.stdout.str()\n        assert output.count(\"preparing foo-2\") == 1\n        assert output.count(\"preparing foo-3\") == 1\n\n\nclass TestMarkersWithParametrization:\n    \"\"\"#308\"\"\"\n\n    def test_simple_mark(self, pytester: Pytester) -> None:\n        s = \"\"\"\n            import pytest\n\n            @pytest.mark.foo\n            @pytest.mark.parametrize((\"n\", \"expected\"), [\n                (1, 2),\n                pytest.param(1, 3, marks=pytest.mark.bar),\n                (2, 3),\n            ])\n            def test_increment(n, expected):\n                assert n + 1 == expected\n        \"\"\"\n        items = pytester.getitems(s)\n        assert len(items) == 3\n        for item in items:\n            assert \"foo\" in item.keywords\n        assert \"bar\" not in items[0].keywords\n        assert \"bar\" in items[1].keywords\n        assert \"bar\" not in items[2].keywords\n\n    def test_select_based_on_mark(self, pytester: Pytester) -> None:\n        s = \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize((\"n\", \"expected\"), [\n                (1, 2),\n                pytest.param(2, 3, marks=pytest.mark.foo),\n                (3, 4),\n            ])\n            def test_increment(n, expected):\n                assert n + 1 == expected\n        \"\"\"\n        pytester.makepyfile(s)\n        rec = pytester.inline_run(\"-m\", \"foo\")\n        passed, skipped, fail = rec.listoutcomes()\n        assert len(passed) == 1\n        assert len(skipped) == 0\n        assert len(fail) == 0\n\n    def test_simple_xfail(self, pytester: Pytester) -> None:\n        s = \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize((\"n\", \"expected\"), [\n                (1, 2),\n                pytest.param(1, 3, marks=pytest.mark.xfail),\n                (2, 3),\n            ])\n            def test_increment(n, expected):\n                assert n + 1 == expected\n        \"\"\"\n        pytester.makepyfile(s)\n        reprec = pytester.inline_run()\n        # xfail is skip??\n        reprec.assertoutcome(passed=2, skipped=1)\n\n    def test_simple_xfail_single_argname(self, pytester: Pytester) -> None:\n        s = \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"n\", [\n                2,\n                pytest.param(3, marks=pytest.mark.xfail),\n                4,\n            ])\n            def test_isEven(n):\n                assert n % 2 == 0\n        \"\"\"\n        pytester.makepyfile(s)\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2, skipped=1)\n\n    def test_xfail_with_arg(self, pytester: Pytester) -> None:\n        s = \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize((\"n\", \"expected\"), [\n                (1, 2),\n                pytest.param(1, 3, marks=pytest.mark.xfail(\"True\")),\n                (2, 3),\n            ])\n            def test_increment(n, expected):\n                assert n + 1 == expected\n        \"\"\"\n        pytester.makepyfile(s)\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2, skipped=1)\n\n    def test_xfail_with_kwarg(self, pytester: Pytester) -> None:\n        s = \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize((\"n\", \"expected\"), [\n                (1, 2),\n                pytest.param(1, 3, marks=pytest.mark.xfail(reason=\"some bug\")),\n                (2, 3),\n            ])\n            def test_increment(n, expected):\n                assert n + 1 == expected\n        \"\"\"\n        pytester.makepyfile(s)\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2, skipped=1)\n\n    def test_xfail_with_arg_and_kwarg(self, pytester: Pytester) -> None:\n        s = \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize((\"n\", \"expected\"), [\n                (1, 2),\n                pytest.param(1, 3, marks=pytest.mark.xfail(\"True\", reason=\"some bug\")),\n                (2, 3),\n            ])\n            def test_increment(n, expected):\n                assert n + 1 == expected\n        \"\"\"\n        pytester.makepyfile(s)\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2, skipped=1)\n\n    @pytest.mark.parametrize(\"strict\", [True, False])\n    def test_xfail_passing_is_xpass(self, pytester: Pytester, strict: bool) -> None:\n        s = f\"\"\"\n            import pytest\n\n            m = pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict})\n\n            @pytest.mark.parametrize((\"n\", \"expected\"), [\n                (1, 2),\n                pytest.param(2, 3, marks=m),\n                (3, 4),\n            ])\n            def test_increment(n, expected):\n                assert n + 1 == expected\n        \"\"\"\n        pytester.makepyfile(s)\n        reprec = pytester.inline_run()\n        passed, failed = (2, 1) if strict else (3, 0)\n        reprec.assertoutcome(passed=passed, failed=failed)\n\n    def test_parametrize_called_in_generate_tests(self, pytester: Pytester) -> None:\n        s = \"\"\"\n            import pytest\n\n\n            def pytest_generate_tests(metafunc):\n                passingTestData = [(1, 2),\n                                   (2, 3)]\n                failingTestData = [(1, 3),\n                                   (2, 2)]\n\n                testData = passingTestData + [pytest.param(*d, marks=pytest.mark.xfail)\n                                  for d in failingTestData]\n                metafunc.parametrize((\"n\", \"expected\"), testData)\n\n\n            def test_increment(n, expected):\n                assert n + 1 == expected\n        \"\"\"\n        pytester.makepyfile(s)\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2, skipped=2)\n\n    def test_parametrize_ID_generation_string_int_works(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"#290\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def myfixture():\n                return 'example'\n            @pytest.mark.parametrize(\n                'limit', (0, '0'))\n            def test_limit(limit, myfixture):\n                return\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=2)\n\n    @pytest.mark.parametrize(\"strict\", [True, False])\n    def test_parametrize_marked_value(self, pytester: Pytester, strict: bool) -> None:\n        s = f\"\"\"\n            import pytest\n\n            @pytest.mark.parametrize((\"n\", \"expected\"), [\n                pytest.param(\n                    2,3,\n                    marks=pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict}),\n                ),\n                pytest.param(\n                    2,3,\n                    marks=[pytest.mark.xfail(\"sys.version_info > (0, 0, 0)\", reason=\"some bug\", strict={strict})],\n                ),\n            ])\n            def test_increment(n, expected):\n                assert n + 1 == expected\n        \"\"\"\n        pytester.makepyfile(s)\n        reprec = pytester.inline_run()\n        passed, failed = (0, 2) if strict else (2, 0)\n        reprec.assertoutcome(passed=passed, failed=failed)\n\n    def test_pytest_make_parametrize_id(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_make_parametrize_id(config, val):\n                return str(val * 2)\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n                import pytest\n\n                @pytest.mark.parametrize(\"x\", range(2))\n                def test_func(x):\n                    pass\n                \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines([\"*test_func*0*PASS*\", \"*test_func*2*PASS*\"])\n\n    def test_pytest_make_parametrize_id_with_argname(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_make_parametrize_id(config, val, argname):\n                return str(val * 2 if argname == 'x' else val * 10)\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n                import pytest\n\n                @pytest.mark.parametrize(\"x\", range(2))\n                def test_func_a(x):\n                    pass\n\n                @pytest.mark.parametrize(\"y\", [1])\n                def test_func_b(y):\n                    pass\n                \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines(\n            [\"*test_func_a*0*PASS*\", \"*test_func_a*2*PASS*\", \"*test_func_b*10*PASS*\"]\n        )\n\n    def test_parametrize_positional_args(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"a\", [1], False)\n            def test_foo(a):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(passed=1)\n\n    def test_parametrize_iterator(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import itertools\n            import pytest\n\n            id_parametrize = pytest.mark.parametrize(\n                ids=(\"param%d\" % i for i in itertools.count())\n            )\n\n            @id_parametrize('y', ['a', 'b'])\n            def test1(y):\n                pass\n\n            @id_parametrize('y', ['a', 'b'])\n            def test2(y):\n                pass\n\n            @pytest.mark.parametrize(\"a, b\", [(1, 2), (3, 4)], ids=itertools.count())\n            def test_converted_to_str(a, b):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-vv\", \"-s\")\n        result.stdout.fnmatch_lines(\n            [\n                \"test_parametrize_iterator.py::test1[param0] PASSED\",\n                \"test_parametrize_iterator.py::test1[param1] PASSED\",\n                \"test_parametrize_iterator.py::test2[param0] PASSED\",\n                \"test_parametrize_iterator.py::test2[param1] PASSED\",\n                \"test_parametrize_iterator.py::test_converted_to_str[0] PASSED\",\n                \"test_parametrize_iterator.py::test_converted_to_str[1] PASSED\",\n                \"*= 6 passed in *\",\n            ]\n        )\n\n\nclass TestHiddenParam:\n    \"\"\"Test that pytest.HIDDEN_PARAM works\"\"\"\n\n    def test_parametrize_ids(self, pytester: Pytester) -> None:\n        items = pytester.getitems(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\n                (\"foo\", \"bar\"),\n                [\n                    (\"a\", \"x\"),\n                    (\"b\", \"y\"),\n                    (\"c\", \"z\"),\n                ],\n                ids=[\"paramset1\", pytest.HIDDEN_PARAM, \"paramset3\"],\n            )\n            def test_func(foo, bar):\n                pass\n        \"\"\"\n        )\n        names = [item.name for item in items]\n        assert names == [\n            \"test_func[paramset1]\",\n            \"test_func\",\n            \"test_func[paramset3]\",\n        ]\n\n    def test_param_id(self, pytester: Pytester) -> None:\n        items = pytester.getitems(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\n                (\"foo\", \"bar\"),\n                [\n                    pytest.param(\"a\", \"x\", id=\"paramset1\"),\n                    pytest.param(\"b\", \"y\", id=pytest.HIDDEN_PARAM),\n                    (\"c\", \"z\"),\n                ],\n            )\n            def test_func(foo, bar):\n                pass\n        \"\"\"\n        )\n        names = [item.name for item in items]\n        assert names == [\n            \"test_func[paramset1]\",\n            \"test_func\",\n            \"test_func[c-z]\",\n        ]\n\n    def test_multiple_hidden_param_is_forbidden(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\n                (\"foo\", \"bar\"),\n                [\n                    (\"a\", \"x\"),\n                    (\"b\", \"y\"),\n                ],\n                ids=[pytest.HIDDEN_PARAM, pytest.HIDDEN_PARAM],\n            )\n            def test_func(foo, bar):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 0 items / 1 error\",\n                \"\",\n                \"*= ERRORS =*\",\n                \"*_ ERROR collecting test_multiple_hidden_param_is_forbidden.py _*\",\n                \"E   Failed: In test_multiple_hidden_param_is_forbidden.py::test_func: multiple instances of \"\n                \"HIDDEN_PARAM cannot be used in the same parametrize call, because the tests names need to be unique.\",\n                \"*! Interrupted: 1 error during collection !*\",\n                \"*= no tests collected, 1 error in *\",\n            ]\n        )\n\n    def test_multiple_hidden_param_is_forbidden_idmaker(self) -> None:\n        id_maker = IdMaker(\n            (\"foo\", \"bar\"),\n            [pytest.param(\"a\", \"x\"), pytest.param(\"b\", \"y\")],\n            None,\n            [pytest.HIDDEN_PARAM, pytest.HIDDEN_PARAM],\n            None,\n            \"some_node_id\",\n        )\n        expected = \"In some_node_id: multiple instances of HIDDEN_PARAM\"\n        with pytest.raises(Failed, match=expected):\n            id_maker.make_unique_parameterset_ids()\n\n    def test_idmaker_error_without_nodeid(self) -> None:\n        id_maker = IdMaker([\"a\"], [pytest.param(\"a\")], None, [object()], None, None)\n        with pytest.raises(Failed, match=\"ids contains unsupported value\"):\n            id_maker.make_unique_parameterset_ids()\n\n    def test_multiple_parametrize(self, pytester: Pytester) -> None:\n        items = pytester.getitems(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\n                \"bar\",\n                [\"x\", \"y\"],\n            )\n            @pytest.mark.parametrize(\n                \"foo\",\n                [\"a\", \"b\"],\n                ids=[\"a\", pytest.HIDDEN_PARAM],\n            )\n            def test_func(foo, bar):\n                pass\n        \"\"\"\n        )\n        names = [item.name for item in items]\n        assert names == [\n            \"test_func[a-x]\",\n            \"test_func[a-y]\",\n            \"test_func[x]\",\n            \"test_func[y]\",\n        ]\n"
  },
  {
    "path": "testing/python/raises.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport io\nimport re\nimport sys\n\nfrom _pytest.outcomes import Failed\nfrom _pytest.pytester import Pytester\nfrom _pytest.warning_types import PytestWarning\nimport pytest\n\n\ndef wrap_escape(s: str) -> str:\n    return \"^\" + re.escape(s) + \"$\"\n\n\nclass TestRaises:\n    def test_check_callable(self) -> None:\n        with pytest.raises(TypeError, match=r\".* must be callable\"):\n            pytest.raises(RuntimeError, \"int('qwe')\")  # type: ignore[call-overload]\n\n    def test_raises(self):\n        excinfo = pytest.raises(ValueError, int, \"qwe\")\n        assert \"invalid literal\" in str(excinfo.value)\n\n    def test_raises_function(self):\n        excinfo = pytest.raises(ValueError, int, \"hello\")\n        assert \"invalid literal\" in str(excinfo.value)\n\n    def test_raises_does_not_allow_none(self):\n        with pytest.raises(\n            ValueError,\n            match=wrap_escape(\"You must specify at least one parameter to match on.\"),\n        ):\n            # We're testing that this invalid usage gives a helpful error,\n            # so we can ignore Mypy telling us that None is invalid.\n            pytest.raises(expected_exception=None)  # type: ignore\n\n    # it's unclear if this message is helpful, and if it is, should it trigger more\n    # liberally? Usually you'd get a TypeError here\n    def test_raises_false_and_arg(self):\n        with pytest.raises(\n            ValueError,\n            match=wrap_escape(\n                \"Expected an exception type or a tuple of exception types, but got `False`. \"\n                \"Raising exceptions is already understood as failing the test, so you don't need \"\n                \"any special code to say 'this should never raise an exception'.\"\n            ),\n        ):\n            pytest.raises(False, int)  # type: ignore[call-overload]\n\n    def test_raises_does_not_allow_empty_tuple(self):\n        with pytest.raises(\n            ValueError,\n            match=wrap_escape(\"You must specify at least one parameter to match on.\"),\n        ):\n            pytest.raises(expected_exception=())\n\n    def test_raises_callable_no_exception(self) -> None:\n        class A:\n            def __call__(self):\n                pass\n\n        try:\n            pytest.raises(ValueError, A())\n        except pytest.fail.Exception:\n            pass\n\n    def test_raises_falsey_type_error(self) -> None:\n        with pytest.raises(TypeError):\n            with pytest.raises(AssertionError, match=0):  # type: ignore[call-overload]\n                raise AssertionError(\"ohai\")\n\n    def test_raises_repr_inflight(self):\n        \"\"\"Ensure repr() on an exception info inside a pytest.raises with block works (#4386)\"\"\"\n\n        class E(Exception):\n            pass\n\n        with pytest.raises(E) as excinfo:\n            # this test prints the inflight uninitialized object\n            # using repr and str as well as pprint to demonstrate\n            # it works\n            print(str(excinfo))\n            print(repr(excinfo))\n            import pprint\n\n            pprint.pprint(excinfo)\n            raise E()\n\n    def test_raises_as_contextmanager(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            import _pytest._code\n\n            def test_simple():\n                with pytest.raises(ZeroDivisionError) as excinfo:\n                    assert isinstance(excinfo, _pytest._code.ExceptionInfo)\n                    1/0\n                print(excinfo)\n                assert excinfo.type == ZeroDivisionError\n                assert isinstance(excinfo.value, ZeroDivisionError)\n\n            def test_noraise():\n                with pytest.raises(pytest.raises.Exception):\n                    with pytest.raises(ValueError):\n                           int()\n\n            def test_raise_wrong_exception_passes_by():\n                with pytest.raises(ZeroDivisionError):\n                    with pytest.raises(ValueError):\n                           1/0\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n    def test_does_not_raise(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            from contextlib import nullcontext as does_not_raise\n            import pytest\n\n            @pytest.mark.parametrize('example_input,expectation', [\n                (3, does_not_raise()),\n                (2, does_not_raise()),\n                (1, does_not_raise()),\n                (0, pytest.raises(ZeroDivisionError)),\n            ])\n            def test_division(example_input, expectation):\n                '''Test how much I know division.'''\n                with expectation:\n                    assert (6 / example_input) is not None\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*4 passed*\"])\n\n    def test_does_not_raise_does_raise(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            from contextlib import nullcontext as does_not_raise\n            import pytest\n\n            @pytest.mark.parametrize('example_input,expectation', [\n                (0, does_not_raise()),\n                (1, pytest.raises(ZeroDivisionError)),\n            ])\n            def test_division(example_input, expectation):\n                '''Test how much I know division.'''\n                with expectation:\n                    assert (6 / example_input) is not None\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*2 failed*\"])\n\n    def test_raises_with_invalid_regex(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def test_invalid_regex():\n                with pytest.raises(ValueError, match=\"invalid regex character [\"):\n                    raise ValueError()\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*Invalid regex pattern provided to 'match': unterminated character set at position 24*\",\n            ]\n        )\n        result.stdout.no_fnmatch_line(\"*Traceback*\")\n        result.stdout.no_fnmatch_line(\"*File*\")\n        result.stdout.no_fnmatch_line(\"*line*\")\n\n    def test_noclass(self) -> None:\n        with pytest.raises(TypeError):\n            pytest.raises(\"wrong\", lambda: None)  # type: ignore[call-overload]\n\n    def test_invalid_arguments_to_raises(self) -> None:\n        with pytest.raises(TypeError, match=\"unknown\"):\n            with pytest.raises(TypeError, unknown=\"bogus\"):  # type: ignore[call-overload]\n                raise ValueError()\n\n    def test_tuple(self):\n        with pytest.raises((KeyError, ValueError)):\n            raise KeyError(\"oops\")\n\n    def test_no_raise_message(self) -> None:\n        try:\n            pytest.raises(ValueError, int, \"0\")\n        except pytest.fail.Exception as e:\n            assert e.msg == f\"DID NOT RAISE {ValueError!r}\"\n        else:\n            assert False, \"Expected pytest.raises.Exception\"\n\n        try:\n            with pytest.raises(ValueError):\n                pass\n        except pytest.fail.Exception as e:\n            assert e.msg == f\"DID NOT RAISE {ValueError!r}\"\n        else:\n            assert False, \"Expected pytest.raises.Exception\"\n\n    @pytest.mark.parametrize(\n        \"method\", [\"function\", \"function_match\", \"with\", \"with_raisesexc\", \"with_group\"]\n    )\n    def test_raises_cyclic_reference(self, method):\n        \"\"\"Ensure pytest.raises does not leave a reference cycle (#1965).\"\"\"\n        import gc\n\n        class T:\n            def __call__(self):\n                raise ValueError\n\n        t = T()\n        refcount = len(gc.get_referrers(t))\n\n        if method == \"function\":\n            pytest.raises(ValueError, t)\n        elif method == \"function_match\":\n            pytest.raises(ValueError, t).match(\"^$\")\n        elif method == \"with\":\n            with pytest.raises(ValueError):\n                t()\n        elif method == \"with_raisesexc\":\n            with pytest.RaisesExc(ValueError):\n                t()\n        elif method == \"with_group\":\n            with pytest.RaisesGroup(ValueError, allow_unwrapped=True):\n                t()\n        else:  # pragma: no cover\n            raise AssertionError(\"bad parametrization\")\n\n        # ensure both forms of pytest.raises don't leave exceptions in sys.exc_info()\n        assert sys.exc_info() == (None, None, None)\n\n        assert refcount == len(gc.get_referrers(t))\n\n    def test_raises_match(self) -> None:\n        msg = r\"with base \\d+\"\n        with pytest.raises(ValueError, match=msg):\n            int(\"asdf\")\n\n        msg = \"with base 10\"\n        with pytest.raises(ValueError, match=msg):\n            int(\"asdf\")\n\n        msg = \"with base 16\"\n        expr = (\n            \"Regex pattern did not match.\\n\"\n            f\"  Expected regex: {msg!r}\\n\"\n            f\"  Actual message: \\\"invalid literal for int() with base 10: 'asdf'\\\"\"\n        )\n        with pytest.raises(AssertionError, match=\"^\" + re.escape(expr) + \"$\"):\n            with pytest.raises(ValueError, match=msg):\n                int(\"asdf\", base=10)\n\n        # \"match\" without context manager.\n        pytest.raises(ValueError, int, \"asdf\").match(\"invalid literal\")\n        with pytest.raises(AssertionError) as excinfo:\n            pytest.raises(ValueError, int, \"asdf\").match(msg)\n        assert str(excinfo.value) == expr\n\n        pytest.raises(TypeError, int, match=\"invalid\")\n\n        def tfunc(match):\n            raise ValueError(f\"match={match}\")\n\n        pytest.raises(ValueError, tfunc, match=\"asdf\").match(\"match=asdf\")\n        pytest.raises(ValueError, tfunc, match=\"\").match(\"match=\")\n\n        # empty string matches everything, which is probably not what the user wants\n        with pytest.warns(\n            PytestWarning,\n            match=wrap_escape(\n                \"matching against an empty string will *always* pass. If you want to check for an empty message you \"\n                \"need to pass '^$'. If you don't want to match you should pass `None` or leave out the parameter.\"\n            ),\n        ):\n            pytest.raises(match=\"\")\n\n    def test_match_failure_string_quoting(self):\n        with pytest.raises(AssertionError) as excinfo:\n            with pytest.raises(AssertionError, match=\"'foo\"):\n                raise AssertionError(\"'bar\")\n        (msg,) = excinfo.value.args\n        assert (\n            msg\n            == '''Regex pattern did not match.\\n  Expected regex: \"'foo\"\\n  Actual message: \"'bar\"'''\n        )\n\n    def test_match_failure_exact_string_message(self):\n        message = \"Oh here is a message with (42) numbers in parameters\"\n        with pytest.raises(AssertionError) as excinfo:\n            with pytest.raises(AssertionError, match=message):\n                raise AssertionError(message)\n        (msg,) = excinfo.value.args\n        assert msg == (\n            \"Regex pattern did not match.\\n\"\n            \"  Expected regex: 'Oh here is a message with (42) numbers in parameters'\\n\"\n            \"  Actual message: 'Oh here is a message with (42) numbers in parameters'\\n\"\n            \" Did you mean to `re.escape()` the regex?\"\n        )\n\n    def test_raises_match_wrong_type(self):\n        \"\"\"Raising an exception with the wrong type and match= given.\n\n        pytest should throw the unexpected exception - the pattern match is not\n        really relevant if we got a different exception.\n        \"\"\"\n        with pytest.raises(\n            ValueError,\n            match=wrap_escape(\"invalid literal for int() with base 10: 'asdf'\"),\n        ):\n            with pytest.raises(IndexError, match=\"nomatch\"):\n                int(\"asdf\")\n\n    def test_raises_exception_looks_iterable(self):\n        class Meta(type):\n            def __getitem__(self, item):\n                return 1 / 0\n\n            def __len__(self):\n                return 1\n\n        class ClassLooksIterableException(Exception, metaclass=Meta):\n            pass\n\n        with pytest.raises(\n            Failed,\n            match=r\"DID NOT RAISE <class 'raises(\\..*)*ClassLooksIterableException'>\",\n        ):\n            pytest.raises(ClassLooksIterableException, lambda: None)\n\n    def test_raises_with_raising_dunder_class(self) -> None:\n        \"\"\"Test current behavior with regard to exceptions via __class__ (#4284).\"\"\"\n\n        class CrappyClass(Exception):\n            # Type ignored because it's bypassed intentionally.\n            @property  # type: ignore\n            def __class__(self):\n                assert False, \"via __class__\"\n\n        with pytest.raises(AssertionError) as excinfo:\n            with pytest.raises(CrappyClass()):  # type: ignore[call-overload]\n                pass\n        assert \"via __class__\" in excinfo.value.args[0]\n\n    def test_raises_context_manager_with_kwargs(self):\n        with pytest.raises(expected_exception=ValueError):\n            raise ValueError\n        with pytest.raises(\n            TypeError,\n            match=wrap_escape(\n                \"Unexpected keyword arguments passed to pytest.raises: foo\\n\"\n                \"Use context-manager form instead?\"\n            ),\n        ):\n            with pytest.raises(OSError, foo=\"bar\"):  # type: ignore[call-overload]\n                pass\n\n    def test_expected_exception_is_not_a_baseexception(self) -> None:\n        with pytest.raises(\n            TypeError,\n            match=wrap_escape(\"Expected a BaseException type, but got 'str'\"),\n        ):\n            with pytest.raises(\"hello\"):  # type: ignore[call-overload]\n                pass  # pragma: no cover\n\n        class NotAnException:\n            pass\n\n        with pytest.raises(\n            ValueError,\n            match=wrap_escape(\n                \"Expected a BaseException type, but got 'NotAnException'\"\n            ),\n        ):\n            with pytest.raises(NotAnException):  # type: ignore[type-var]\n                pass  # pragma: no cover\n\n        with pytest.raises(\n            TypeError,\n            match=wrap_escape(\"Expected a BaseException type, but got 'str'\"),\n        ):\n            with pytest.raises((\"hello\", NotAnException)):  # type: ignore[arg-type]\n                pass  # pragma: no cover\n\n    def test_issue_11872(self) -> None:\n        \"\"\"Regression test for #11872.\n\n        urllib.error.HTTPError on some Python 3.10/11 minor releases raises\n        KeyError instead of AttributeError on invalid attribute access.\n\n        https://github.com/python/cpython/issues/98778\n        \"\"\"\n        from email.message import Message\n        from urllib.error import HTTPError\n\n        with pytest.raises(HTTPError, match=\"Not Found\") as exc_info:\n            raise HTTPError(\n                code=404, msg=\"Not Found\", fp=io.BytesIO(), hdrs=Message(), url=\"\"\n            )\n        exc_info.value.close()  # avoid a resource warning\n\n    def test_raises_match_compiled_regex(self) -> None:\n        \"\"\"Test that compiled regex patterns work with pytest.raises.\"\"\"\n        # Test with a compiled pattern that matches\n        pattern = re.compile(r\"with base \\d+\")\n        with pytest.raises(ValueError, match=pattern):\n            int(\"asdf\")\n\n        # Test with a compiled pattern that doesn't match\n        pattern_nomatch = re.compile(r\"with base 16\")\n        expr = (\n            \"Regex pattern did not match.\\n\"\n            f\"  Expected regex: {pattern_nomatch.pattern!r}\\n\"\n            f\"  Actual message: \\\"invalid literal for int() with base 10: 'asdf'\\\"\"\n        )\n        with pytest.raises(AssertionError, match=\"^\" + re.escape(expr) + \"$\"):\n            with pytest.raises(ValueError, match=pattern_nomatch):\n                int(\"asdf\", base=10)\n\n        # Test compiled pattern with flags\n        pattern_with_flags = re.compile(r\"INVALID LITERAL\", re.IGNORECASE)\n        with pytest.raises(ValueError, match=pattern_with_flags):\n            int(\"asdf\")\n\n    def test_pipe_is_treated_as_regex_metacharacter(self) -> None:\n        \"\"\"| (pipe) must be recognized as a regex metacharacter.\"\"\"\n        from _pytest.raises import is_fully_escaped\n        from _pytest.raises import unescape\n\n        assert not is_fully_escaped(\"foo|bar\")\n        assert is_fully_escaped(r\"foo\\|bar\")\n        assert unescape(r\"foo\\|bar\") == \"foo|bar\"\n"
  },
  {
    "path": "testing/python/raises_group.py",
    "content": "from __future__ import annotations\n\n# several expected multi-line strings contain long lines. We don't wanna break them up\n# as that makes it confusing to see where the line breaks are.\n# ruff: noqa: E501\nfrom contextlib import AbstractContextManager\nimport re\nimport sys\n\nfrom _pytest._code import ExceptionInfo\nfrom _pytest.outcomes import Failed\nfrom _pytest.pytester import Pytester\nfrom _pytest.raises import RaisesExc\nfrom _pytest.raises import RaisesGroup\nfrom _pytest.raises import repr_callable\nimport pytest\n\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import BaseExceptionGroup\n    from exceptiongroup import ExceptionGroup\n\n\ndef wrap_escape(s: str) -> str:\n    return \"^\" + re.escape(s) + \"$\"\n\n\ndef fails_raises_group(msg: str, add_prefix: bool = True) -> RaisesExc[Failed]:\n    assert msg[-1] != \"\\n\", (\n        \"developer error, expected string should not end with newline\"\n    )\n    prefix = \"Raised exception group did not match: \" if add_prefix else \"\"\n    return pytest.raises(Failed, match=wrap_escape(prefix + msg))\n\n\ndef test_raises_group() -> None:\n    with pytest.raises(\n        TypeError,\n        match=wrap_escape(\"Expected a BaseException type, but got 'int'\"),\n    ):\n        RaisesExc(5)  # type: ignore[call-overload]\n    with pytest.raises(\n        ValueError,\n        match=wrap_escape(\"Expected a BaseException type, but got 'int'\"),\n    ):\n        RaisesExc(int)  # type: ignore[type-var]\n    with pytest.raises(\n        TypeError,\n        match=wrap_escape(\n            \"Expected a BaseException type, RaisesExc, or RaisesGroup, but got an exception instance: ValueError\",\n        ),\n    ):\n        RaisesGroup(ValueError())  # type: ignore[call-overload]\n    with RaisesGroup(ValueError):\n        raise ExceptionGroup(\"foo\", (ValueError(),))\n\n    with (\n        fails_raises_group(\"`SyntaxError()` is not an instance of `ValueError`\"),\n        RaisesGroup(ValueError),\n    ):\n        raise ExceptionGroup(\"foo\", (SyntaxError(),))\n\n    # multiple exceptions\n    with RaisesGroup(ValueError, SyntaxError):\n        raise ExceptionGroup(\"foo\", (ValueError(), SyntaxError()))\n\n    # order doesn't matter\n    with RaisesGroup(SyntaxError, ValueError):\n        raise ExceptionGroup(\"foo\", (ValueError(), SyntaxError()))\n\n    # nested exceptions\n    with RaisesGroup(RaisesGroup(ValueError)):\n        raise ExceptionGroup(\"foo\", (ExceptionGroup(\"bar\", (ValueError(),)),))\n\n    with RaisesGroup(\n        SyntaxError,\n        RaisesGroup(ValueError),\n        RaisesGroup(RuntimeError),\n    ):\n        raise ExceptionGroup(\n            \"foo\",\n            (\n                SyntaxError(),\n                ExceptionGroup(\"bar\", (ValueError(),)),\n                ExceptionGroup(\"\", (RuntimeError(),)),\n            ),\n        )\n\n\ndef test_incorrect_number_exceptions() -> None:\n    # We previously gave an error saying the number of exceptions was wrong,\n    # but we now instead indicate excess/missing exceptions\n    with (\n        fails_raises_group(\n            \"1 matched exception. Unexpected exception(s): [RuntimeError()]\"\n        ),\n        RaisesGroup(ValueError),\n    ):\n        raise ExceptionGroup(\"\", (RuntimeError(), ValueError()))\n\n    # will error if there's missing exceptions\n    with (\n        fails_raises_group(\n            \"1 matched exception. Too few exceptions raised, found no match for: [SyntaxError]\"\n        ),\n        RaisesGroup(ValueError, SyntaxError),\n    ):\n        raise ExceptionGroup(\"\", (ValueError(),))\n\n    with (\n        fails_raises_group(\n            \"\\n\"\n            \"1 matched exception. \\n\"\n            \"Too few exceptions raised!\\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  ValueError\\n\"\n            \"    It matches `ValueError()` which was paired with `ValueError`\"\n        ),\n        RaisesGroup(ValueError, ValueError),\n    ):\n        raise ExceptionGroup(\"\", (ValueError(),))\n\n    with (\n        fails_raises_group(\n            \"\\n\"\n            \"1 matched exception. \\n\"\n            \"Unexpected exception(s)!\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ValueError('b'):\\n\"\n            \"    It matches `ValueError` which was paired with `ValueError('a')`\"\n        ),\n        RaisesGroup(ValueError),\n    ):\n        raise ExceptionGroup(\"\", (ValueError(\"a\"), ValueError(\"b\")))\n\n    with (\n        fails_raises_group(\n            \"\\n\"\n            \"1 matched exception. \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  ValueError\\n\"\n            \"    It matches `ValueError()` which was paired with `ValueError`\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  SyntaxError():\\n\"\n            \"    `SyntaxError()` is not an instance of `ValueError`\"\n        ),\n        RaisesGroup(ValueError, ValueError),\n    ):\n        raise ExceptionGroup(\"\", [ValueError(), SyntaxError()])\n\n\ndef test_flatten_subgroups() -> None:\n    # loose semantics, as with expect*\n    with RaisesGroup(ValueError, flatten_subgroups=True):\n        raise ExceptionGroup(\"\", (ExceptionGroup(\"\", (ValueError(),)),))\n\n    with RaisesGroup(ValueError, TypeError, flatten_subgroups=True):\n        raise ExceptionGroup(\"\", (ExceptionGroup(\"\", (ValueError(), TypeError())),))\n    with RaisesGroup(ValueError, TypeError, flatten_subgroups=True):\n        raise ExceptionGroup(\"\", [ExceptionGroup(\"\", [ValueError()]), TypeError()])\n\n    # mixed loose is possible if you want it to be at least N deep\n    with RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)):\n        raise ExceptionGroup(\"\", (ExceptionGroup(\"\", (ValueError(),)),))\n    with RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)):\n        raise ExceptionGroup(\n            \"\",\n            (ExceptionGroup(\"\", (ExceptionGroup(\"\", (ValueError(),)),)),),\n        )\n\n    # but not the other way around\n    with pytest.raises(\n        ValueError,\n        match=r\"^You cannot specify a nested structure inside a RaisesGroup with\",\n    ):\n        RaisesGroup(RaisesGroup(ValueError), flatten_subgroups=True)  # type: ignore[call-overload]\n\n    # flatten_subgroups is not sufficient to catch fully unwrapped\n    with (\n        fails_raises_group(\n            \"`ValueError()` is not an exception group, but would match with `allow_unwrapped=True`\"\n        ),\n        RaisesGroup(ValueError, flatten_subgroups=True),\n    ):\n        raise ValueError\n    with (\n        fails_raises_group(\n            \"RaisesGroup(ValueError, flatten_subgroups=True): `ValueError()` is not an exception group, but would match with `allow_unwrapped=True`\"\n        ),\n        RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True)),\n    ):\n        raise ExceptionGroup(\"\", (ValueError(),))\n\n    # helpful suggestion if flatten_subgroups would make it pass\n    with (\n        fails_raises_group(\n            \"Raised exception group did not match: \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  ValueError\\n\"\n            \"  TypeError\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ExceptionGroup('', [ValueError(), TypeError()]):\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `TypeError`\\n\"\n            \"Did you mean to use `flatten_subgroups=True`?\",\n            add_prefix=False,\n        ),\n        RaisesGroup(ValueError, TypeError),\n    ):\n        raise ExceptionGroup(\"\", [ExceptionGroup(\"\", [ValueError(), TypeError()])])\n    # but doesn't consider check (otherwise we'd break typing guarantees)\n    with (\n        fails_raises_group(\n            \"Raised exception group did not match: \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  ValueError\\n\"\n            \"  TypeError\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ExceptionGroup('', [ValueError(), TypeError()]):\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `TypeError`\\n\"\n            \"Did you mean to use `flatten_subgroups=True`?\",\n            add_prefix=False,\n        ),\n        RaisesGroup(\n            ValueError,\n            TypeError,\n            check=lambda eg: len(eg.exceptions) == 1,\n        ),\n    ):\n        raise ExceptionGroup(\"\", [ExceptionGroup(\"\", [ValueError(), TypeError()])])\n    # correct number of exceptions, and flatten_subgroups would make it pass\n    # This now doesn't print a repr of the caught exception at all, but that can be found in the traceback\n    with (\n        fails_raises_group(\n            \"Raised exception group did not match: Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"  Did you mean to use `flatten_subgroups=True`?\",\n            add_prefix=False,\n        ),\n        RaisesGroup(ValueError),\n    ):\n        raise ExceptionGroup(\"\", [ExceptionGroup(\"\", [ValueError()])])\n    # correct number of exceptions, but flatten_subgroups wouldn't help, so we don't suggest it\n    with (\n        fails_raises_group(\n            \"Unexpected nested `ExceptionGroup()`, expected `ValueError`\"\n        ),\n        RaisesGroup(ValueError),\n    ):\n        raise ExceptionGroup(\"\", [ExceptionGroup(\"\", [TypeError()])])\n\n    # flatten_subgroups can be suggested if nested. This will implicitly ask the user to\n    # do `RaisesGroup(RaisesGroup(ValueError, flatten_subgroups=True))` which is unlikely\n    # to be what they actually want - but I don't think it's worth trying to special-case\n    with (\n        fails_raises_group(\n            \"RaisesGroup(ValueError): Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"  Did you mean to use `flatten_subgroups=True`?\",\n        ),\n        RaisesGroup(RaisesGroup(ValueError)),\n    ):\n        raise ExceptionGroup(\n            \"\",\n            [ExceptionGroup(\"\", [ExceptionGroup(\"\", [ValueError()])])],\n        )\n\n    # Don't mention \"unexpected nested\" if expecting an ExceptionGroup.\n    # Although it should perhaps be an error to specify `RaisesGroup(ExceptionGroup)` in\n    # favor of doing `RaisesGroup(RaisesGroup(...))`.\n    with (\n        fails_raises_group(\n            \"`BaseExceptionGroup()` is not an instance of `ExceptionGroup`\"\n        ),\n        RaisesGroup(ExceptionGroup),\n    ):\n        raise BaseExceptionGroup(\"\", [BaseExceptionGroup(\"\", [KeyboardInterrupt()])])\n\n\ndef test_catch_unwrapped_exceptions() -> None:\n    # Catches lone exceptions with strict=False\n    # just as except* would\n    with RaisesGroup(ValueError, allow_unwrapped=True):\n        raise ValueError\n\n    # expecting multiple unwrapped exceptions is not possible\n    with pytest.raises(\n        ValueError,\n        match=r\"^You cannot specify multiple exceptions with\",\n    ):\n        RaisesGroup(SyntaxError, ValueError, allow_unwrapped=True)  # type: ignore[call-overload]\n    # if users want one of several exception types they need to use a RaisesExc\n    # (which the error message suggests)\n    with RaisesGroup(\n        RaisesExc(check=lambda e: isinstance(e, SyntaxError | ValueError)),\n        allow_unwrapped=True,\n    ):\n        raise ValueError\n\n    # Unwrapped nested `RaisesGroup` is likely a user error, so we raise an error.\n    with pytest.raises(ValueError, match=\"has no effect when expecting\"):\n        RaisesGroup(RaisesGroup(ValueError), allow_unwrapped=True)  # type: ignore[call-overload]\n\n    # But it *can* be used to check for nesting level +- 1 if they move it to\n    # the nested RaisesGroup. Users should probably use `RaisesExc`s instead though.\n    with RaisesGroup(RaisesGroup(ValueError, allow_unwrapped=True)):\n        raise ExceptionGroup(\"\", [ExceptionGroup(\"\", [ValueError()])])\n    with RaisesGroup(RaisesGroup(ValueError, allow_unwrapped=True)):\n        raise ExceptionGroup(\"\", [ValueError()])\n\n    # with allow_unwrapped=False (default) it will not be caught\n    with (\n        fails_raises_group(\n            \"`ValueError()` is not an exception group, but would match with `allow_unwrapped=True`\"\n        ),\n        RaisesGroup(ValueError),\n    ):\n        raise ValueError(\"value error text\")\n\n    # allow_unwrapped on its own won't match against nested groups\n    with (\n        fails_raises_group(\n            \"Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"  Did you mean to use `flatten_subgroups=True`?\",\n        ),\n        RaisesGroup(ValueError, allow_unwrapped=True),\n    ):\n        raise ExceptionGroup(\"foo\", [ExceptionGroup(\"bar\", [ValueError()])])\n\n    # you need both allow_unwrapped and flatten_subgroups to fully emulate except*\n    with RaisesGroup(ValueError, allow_unwrapped=True, flatten_subgroups=True):\n        raise ExceptionGroup(\"\", [ExceptionGroup(\"\", [ValueError()])])\n\n    # code coverage\n    with (\n        fails_raises_group(\n            \"Raised exception (group) did not match: `TypeError()` is not an instance of `ValueError`\",\n            add_prefix=False,\n        ),\n        RaisesGroup(ValueError, allow_unwrapped=True),\n    ):\n        raise TypeError(\"this text doesn't show up in the error message\")\n    with (\n        fails_raises_group(\n            \"Raised exception (group) did not match: RaisesExc(ValueError): `TypeError()` is not an instance of `ValueError`\",\n            add_prefix=False,\n        ),\n        RaisesGroup(RaisesExc(ValueError), allow_unwrapped=True),\n    ):\n        raise TypeError\n\n    # check we don't suggest unwrapping with nested RaisesGroup\n    with (\n        fails_raises_group(\"`ValueError()` is not an exception group\"),\n        RaisesGroup(RaisesGroup(ValueError)),\n    ):\n        raise ValueError\n\n\ndef test_match() -> None:\n    # supports match string\n    with RaisesGroup(ValueError, match=\"bar\"):\n        raise ExceptionGroup(\"bar\", (ValueError(),))\n\n    # now also works with ^$\n    with RaisesGroup(ValueError, match=\"^bar$\"):\n        raise ExceptionGroup(\"bar\", (ValueError(),))\n\n    # it also includes notes\n    with RaisesGroup(ValueError, match=\"my note\"):\n        e = ExceptionGroup(\"bar\", (ValueError(),))\n        e.add_note(\"my note\")\n        raise e\n\n    # and technically you can match it all with ^$\n    # but you're probably better off using a RaisesExc at that point\n    with RaisesGroup(ValueError, match=\"^bar\\nmy note$\"):\n        e = ExceptionGroup(\"bar\", (ValueError(),))\n        e.add_note(\"my note\")\n        raise e\n\n    with (\n        fails_raises_group(\n            \"Regex pattern did not match the `ExceptionGroup()`.\\n\"\n            \"  Expected regex: 'foo'\\n\"\n            \"  Actual message: 'bar'\"\n        ),\n        RaisesGroup(ValueError, match=\"foo\"),\n    ):\n        raise ExceptionGroup(\"bar\", (ValueError(),))\n\n    # Suggest a fix for easy pitfall of adding match to the RaisesGroup instead of\n    # using a RaisesExc.\n    # This requires a single expected & raised exception, the expected is a type,\n    # and `isinstance(raised, expected_type)`.\n    with (\n        fails_raises_group(\n            \"Regex pattern did not match the `ExceptionGroup()`.\\n\"\n            \"  Expected regex: 'foo'\\n\"\n            \"  Actual message: 'bar'\\n\"\n            \" but matched the expected `ValueError`.\\n\"\n            \" You might want `RaisesGroup(RaisesExc(ValueError, match='foo'))`\"\n        ),\n        RaisesGroup(ValueError, match=\"foo\"),\n    ):\n        raise ExceptionGroup(\"bar\", [ValueError(\"foo\")])\n\n\ndef test_check() -> None:\n    exc = ExceptionGroup(\"\", (ValueError(),))\n\n    def is_exc(e: ExceptionGroup[ValueError]) -> bool:\n        return e is exc\n\n    is_exc_repr = repr_callable(is_exc)\n    with RaisesGroup(ValueError, check=is_exc):\n        raise exc\n\n    with (\n        fails_raises_group(\n            f\"check {is_exc_repr} did not return True on the ExceptionGroup\"\n        ),\n        RaisesGroup(ValueError, check=is_exc),\n    ):\n        raise ExceptionGroup(\"\", (ValueError(),))\n\n    def is_value_error(e: BaseException) -> bool:\n        return isinstance(e, ValueError)\n\n    # helpful suggestion if the user thinks the check is for the sub-exception\n    with (\n        fails_raises_group(\n            f\"check {is_value_error} did not return True on the ExceptionGroup, but did return True for the expected ValueError. You might want RaisesGroup(RaisesExc(ValueError, check=<...>))\"\n        ),\n        RaisesGroup(ValueError, check=is_value_error),\n    ):\n        raise ExceptionGroup(\"\", (ValueError(),))\n\n\ndef test_unwrapped_match_check() -> None:\n    def my_check(e: object) -> bool:  # pragma: no cover\n        return True\n\n    msg = (\n        \"`allow_unwrapped=True` bypasses the `match` and `check` parameters\"\n        \" if the exception is unwrapped. If you intended to match/check the\"\n        \" exception you should use a `RaisesExc` object. If you want to match/check\"\n        \" the exceptiongroup when the exception *is* wrapped you need to\"\n        \" do e.g. `if isinstance(exc.value, ExceptionGroup):\"\n        \" assert RaisesGroup(...).matches(exc.value)` afterwards.\"\n    )\n    with pytest.raises(ValueError, match=re.escape(msg)):\n        RaisesGroup(ValueError, allow_unwrapped=True, match=\"foo\")  # type: ignore[call-overload]\n    with pytest.raises(ValueError, match=re.escape(msg)):\n        RaisesGroup(ValueError, allow_unwrapped=True, check=my_check)  # type: ignore[call-overload]\n\n    # Users should instead use a RaisesExc\n    rg = RaisesGroup(RaisesExc(ValueError, match=\"^foo$\"), allow_unwrapped=True)\n    with rg:\n        raise ValueError(\"foo\")\n    with rg:\n        raise ExceptionGroup(\"\", [ValueError(\"foo\")])\n\n    # or if they wanted to match/check the group, do a conditional `.matches()`\n    with RaisesGroup(ValueError, allow_unwrapped=True) as exc:\n        raise ExceptionGroup(\"bar\", [ValueError(\"foo\")])\n    if isinstance(exc.value, ExceptionGroup):  # pragma: no branch\n        assert RaisesGroup(ValueError, match=\"bar\").matches(exc.value)\n\n\ndef test_matches() -> None:\n    rg = RaisesGroup(ValueError)\n    assert not rg.matches(None)\n    assert not rg.matches(ValueError())\n    assert rg.matches(ExceptionGroup(\"\", (ValueError(),)))\n\n    re = RaisesExc(ValueError)\n    assert not re.matches(None)\n    assert re.matches(ValueError())\n\n\ndef test_message() -> None:\n    def check_message(\n        message: str,\n        body: RaisesGroup[BaseException],\n    ) -> None:\n        with (\n            pytest.raises(\n                Failed,\n                match=f\"^DID NOT RAISE any exception, expected `{re.escape(message)}`$\",\n            ),\n            body,\n        ):\n            ...\n\n    # basic\n    check_message(\"ExceptionGroup(ValueError)\", RaisesGroup(ValueError))\n    # multiple exceptions\n    check_message(\n        \"ExceptionGroup(ValueError, ValueError)\",\n        RaisesGroup(ValueError, ValueError),\n    )\n    # nested\n    check_message(\n        \"ExceptionGroup(ExceptionGroup(ValueError))\",\n        RaisesGroup(RaisesGroup(ValueError)),\n    )\n\n    # RaisesExc\n    check_message(\n        \"ExceptionGroup(RaisesExc(ValueError, match='my_str'))\",\n        RaisesGroup(RaisesExc(ValueError, match=\"my_str\")),\n    )\n    check_message(\n        \"ExceptionGroup(RaisesExc(match='my_str'))\",\n        RaisesGroup(RaisesExc(match=\"my_str\")),\n    )\n    # one-size tuple is printed as not being a tuple\n    check_message(\n        \"ExceptionGroup(RaisesExc(ValueError))\",\n        RaisesGroup(RaisesExc((ValueError,))),\n    )\n    check_message(\n        \"ExceptionGroup(RaisesExc((ValueError, IndexError)))\",\n        RaisesGroup(RaisesExc((ValueError, IndexError))),\n    )\n\n    # BaseExceptionGroup\n    check_message(\n        \"BaseExceptionGroup(KeyboardInterrupt)\",\n        RaisesGroup(KeyboardInterrupt),\n    )\n    # BaseExceptionGroup with type inside RaisesExc\n    check_message(\n        \"BaseExceptionGroup(RaisesExc(KeyboardInterrupt))\",\n        RaisesGroup(RaisesExc(KeyboardInterrupt)),\n    )\n    check_message(\n        \"BaseExceptionGroup(RaisesExc((ValueError, KeyboardInterrupt)))\",\n        RaisesGroup(RaisesExc((ValueError, KeyboardInterrupt))),\n    )\n    # Base-ness transfers to parent containers\n    check_message(\n        \"BaseExceptionGroup(BaseExceptionGroup(KeyboardInterrupt))\",\n        RaisesGroup(RaisesGroup(KeyboardInterrupt)),\n    )\n    # but not to child containers\n    check_message(\n        \"BaseExceptionGroup(BaseExceptionGroup(KeyboardInterrupt), ExceptionGroup(ValueError))\",\n        RaisesGroup(RaisesGroup(KeyboardInterrupt), RaisesGroup(ValueError)),\n    )\n\n\ndef test_assert_message() -> None:\n    # the message does not need to list all parameters to RaisesGroup, nor all exceptions\n    # in the exception group, as those are both visible in the traceback.\n    # first fails to match\n    with (\n        fails_raises_group(\"`TypeError()` is not an instance of `ValueError`\"),\n        RaisesGroup(ValueError),\n    ):\n        raise ExceptionGroup(\"a\", [TypeError()])\n    with (\n        fails_raises_group(\n            \"Raised exception group did not match: \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  RaisesGroup(ValueError)\\n\"\n            \"  RaisesGroup(ValueError, match='a')\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ExceptionGroup('', [RuntimeError()]):\\n\"\n            \"    RaisesGroup(ValueError): `RuntimeError()` is not an instance of `ValueError`\\n\"\n            \"    RaisesGroup(ValueError, match='a'): Regex pattern did not match the `ExceptionGroup()`.\\n\"\n            \"      Expected regex: 'a'\\n\"\n            \"      Actual message: ''\\n\"\n            \"  RuntimeError():\\n\"\n            \"    RaisesGroup(ValueError): `RuntimeError()` is not an exception group\\n\"\n            \"    RaisesGroup(ValueError, match='a'): `RuntimeError()` is not an exception group\",\n            add_prefix=False,  # to see the full structure\n        ),\n        RaisesGroup(RaisesGroup(ValueError), RaisesGroup(ValueError, match=\"a\")),\n    ):\n        raise ExceptionGroup(\n            \"\",\n            [ExceptionGroup(\"\", [RuntimeError()]), RuntimeError()],\n        )\n\n    with (\n        fails_raises_group(\n            \"Raised exception group did not match: \\n\"\n            \"2 matched exceptions. \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  RaisesGroup(RuntimeError)\\n\"\n            \"  RaisesGroup(ValueError)\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  RuntimeError():\\n\"\n            \"    RaisesGroup(RuntimeError): `RuntimeError()` is not an exception group, but would match with `allow_unwrapped=True`\\n\"\n            \"    RaisesGroup(ValueError): `RuntimeError()` is not an exception group\\n\"\n            \"  ValueError('bar'):\\n\"\n            \"    It matches `ValueError` which was paired with `ValueError('foo')`\\n\"\n            \"    RaisesGroup(RuntimeError): `ValueError()` is not an exception group\\n\"\n            \"    RaisesGroup(ValueError): `ValueError()` is not an exception group, but would match with `allow_unwrapped=True`\",\n            add_prefix=False,  # to see the full structure\n        ),\n        RaisesGroup(\n            ValueError,\n            RaisesExc(TypeError),\n            RaisesGroup(RuntimeError),\n            RaisesGroup(ValueError),\n        ),\n    ):\n        raise ExceptionGroup(\n            \"a\",\n            [RuntimeError(), TypeError(), ValueError(\"foo\"), ValueError(\"bar\")],\n        )\n\n    with (\n        fails_raises_group(\n            \"1 matched exception. `AssertionError()` is not an instance of `TypeError`\"\n        ),\n        RaisesGroup(ValueError, TypeError),\n    ):\n        raise ExceptionGroup(\"a\", [ValueError(), AssertionError()])\n\n    with (\n        fails_raises_group(\n            \"RaisesExc(ValueError): `TypeError()` is not an instance of `ValueError`\"\n        ),\n        RaisesGroup(RaisesExc(ValueError)),\n    ):\n        raise ExceptionGroup(\"a\", [TypeError()])\n\n    # suggest escaping\n    with (\n        fails_raises_group(\n            # TODO: did not match Exceptiongroup('h(ell)o', ...) ?\n            \"Raised exception group did not match: Regex pattern did not match the `ExceptionGroup()`.\\n\"\n            \"  Expected regex: 'h(ell)o'\\n\"\n            \"  Actual message: 'h(ell)o'\\n\"\n            \" Did you mean to `re.escape()` the regex?\",\n            add_prefix=False,  # to see the full structure\n        ),\n        RaisesGroup(ValueError, match=\"h(ell)o\"),\n    ):\n        raise ExceptionGroup(\"h(ell)o\", [ValueError()])\n    with (\n        fails_raises_group(\n            \"RaisesExc(match='h(ell)o'): Regex pattern did not match.\\n\"\n            \"  Expected regex: 'h(ell)o'\\n\"\n            \"  Actual message: 'h(ell)o'\\n\"\n            \" Did you mean to `re.escape()` the regex?\",\n        ),\n        RaisesGroup(RaisesExc(match=\"h(ell)o\")),\n    ):\n        raise ExceptionGroup(\"\", [ValueError(\"h(ell)o\")])\n\n    with (\n        fails_raises_group(\n            \"Raised exception group did not match: \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  ValueError\\n\"\n            \"  ValueError\\n\"\n            \"  ValueError\\n\"\n            \"  ValueError\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ExceptionGroup('', [ValueError(), TypeError()]):\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `ValueError`\",\n            add_prefix=False,  # to see the full structure\n        ),\n        RaisesGroup(ValueError, ValueError, ValueError, ValueError),\n    ):\n        raise ExceptionGroup(\"\", [ExceptionGroup(\"\", [ValueError(), TypeError()])])\n\n\ndef test_message_indent() -> None:\n    with (\n        fails_raises_group(\n            \"Raised exception group did not match: \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  RaisesGroup(ValueError, ValueError)\\n\"\n            \"  ValueError\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ExceptionGroup('', [TypeError(), RuntimeError()]):\\n\"\n            \"    RaisesGroup(ValueError, ValueError): \\n\"\n            \"      The following expected exceptions did not find a match:\\n\"\n            \"        ValueError\\n\"\n            \"        ValueError\\n\"\n            \"      The following raised exceptions did not find a match\\n\"\n            \"        TypeError():\\n\"\n            \"          `TypeError()` is not an instance of `ValueError`\\n\"\n            \"          `TypeError()` is not an instance of `ValueError`\\n\"\n            \"        RuntimeError():\\n\"\n            \"          `RuntimeError()` is not an instance of `ValueError`\\n\"\n            \"          `RuntimeError()` is not an instance of `ValueError`\\n\"\n            # TODO: this line is not great, should maybe follow the same format as the other and say\n            # ValueError: Unexpected nested `ExceptionGroup()` (?)\n            \"    Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"  TypeError():\\n\"\n            \"    RaisesGroup(ValueError, ValueError): `TypeError()` is not an exception group\\n\"\n            \"    `TypeError()` is not an instance of `ValueError`\",\n            add_prefix=False,\n        ),\n        RaisesGroup(\n            RaisesGroup(ValueError, ValueError),\n            ValueError,\n        ),\n    ):\n        raise ExceptionGroup(\n            \"\",\n            [\n                ExceptionGroup(\"\", [TypeError(), RuntimeError()]),\n                TypeError(),\n            ],\n        )\n    with (\n        fails_raises_group(\n            \"Raised exception group did not match: \\n\"\n            \"RaisesGroup(ValueError, ValueError): \\n\"\n            \"  The following expected exceptions did not find a match:\\n\"\n            \"    ValueError\\n\"\n            \"    ValueError\\n\"\n            \"  The following raised exceptions did not find a match\\n\"\n            \"    TypeError():\\n\"\n            \"      `TypeError()` is not an instance of `ValueError`\\n\"\n            \"      `TypeError()` is not an instance of `ValueError`\\n\"\n            \"    RuntimeError():\\n\"\n            \"      `RuntimeError()` is not an instance of `ValueError`\\n\"\n            \"      `RuntimeError()` is not an instance of `ValueError`\",\n            add_prefix=False,\n        ),\n        RaisesGroup(\n            RaisesGroup(ValueError, ValueError),\n        ),\n    ):\n        raise ExceptionGroup(\n            \"\",\n            [\n                ExceptionGroup(\"\", [TypeError(), RuntimeError()]),\n            ],\n        )\n\n\ndef test_suggestion_on_nested_and_brief_error() -> None:\n    # Make sure \"Did you mean\" suggestion gets indented iff it follows a single-line error\n    with (\n        fails_raises_group(\n            \"\\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  RaisesGroup(ValueError)\\n\"\n            \"  ValueError\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ExceptionGroup('', [ExceptionGroup('', [ValueError()])]):\\n\"\n            \"    RaisesGroup(ValueError): Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"      Did you mean to use `flatten_subgroups=True`?\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `ValueError`\",\n        ),\n        RaisesGroup(RaisesGroup(ValueError), ValueError),\n    ):\n        raise ExceptionGroup(\n            \"\",\n            [ExceptionGroup(\"\", [ExceptionGroup(\"\", [ValueError()])])],\n        )\n    # if indented here it would look like another raised exception\n    with (\n        fails_raises_group(\n            \"\\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  RaisesGroup(ValueError, ValueError)\\n\"\n            \"  ValueError\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ExceptionGroup('', [ValueError(), ExceptionGroup('', [ValueError()])]):\\n\"\n            \"    RaisesGroup(ValueError, ValueError): \\n\"\n            \"      1 matched exception. \\n\"\n            \"      The following expected exceptions did not find a match:\\n\"\n            \"        ValueError\\n\"\n            \"          It matches `ValueError()` which was paired with `ValueError`\\n\"\n            \"      The following raised exceptions did not find a match\\n\"\n            \"        ExceptionGroup('', [ValueError()]):\\n\"\n            \"          Unexpected nested `ExceptionGroup()`, expected `ValueError`\\n\"\n            \"      Did you mean to use `flatten_subgroups=True`?\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `ValueError`\"\n        ),\n        RaisesGroup(RaisesGroup(ValueError, ValueError), ValueError),\n    ):\n        raise ExceptionGroup(\n            \"\",\n            [ExceptionGroup(\"\", [ValueError(), ExceptionGroup(\"\", [ValueError()])])],\n        )\n\n    # re.escape always comes after single-line errors\n    with (\n        fails_raises_group(\n            \"\\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  RaisesGroup(Exception, match='^hello')\\n\"\n            \"  ValueError\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ExceptionGroup('^hello', [Exception()]):\\n\"\n            \"    RaisesGroup(Exception, match='^hello'): Regex pattern did not match the `ExceptionGroup()`.\\n\"\n            \"      Expected regex: '^hello'\\n\"\n            \"      Actual message: '^hello'\\n\"\n            \"     Did you mean to `re.escape()` the regex?\\n\"\n            \"    Unexpected nested `ExceptionGroup()`, expected `ValueError`\"\n        ),\n        RaisesGroup(RaisesGroup(Exception, match=\"^hello\"), ValueError),\n    ):\n        raise ExceptionGroup(\"\", [ExceptionGroup(\"^hello\", [Exception()])])\n\n\ndef test_assert_message_nested() -> None:\n    # we only get one instance of aaaaaaaaaa... and bbbbbb..., but we do get multiple instances of ccccc... and dddddd..\n    # but I think this now only prints the full repr when that is necessary to disambiguate exceptions\n    with (\n        fails_raises_group(\n            \"Raised exception group did not match: \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  RaisesGroup(ValueError)\\n\"\n            \"  RaisesGroup(RaisesGroup(ValueError))\\n\"\n            \"  RaisesGroup(RaisesExc(TypeError, match='foo'))\\n\"\n            \"  RaisesGroup(TypeError, ValueError)\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  TypeError('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'):\\n\"\n            \"    RaisesGroup(ValueError): `TypeError()` is not an exception group\\n\"\n            \"    RaisesGroup(RaisesGroup(ValueError)): `TypeError()` is not an exception group\\n\"\n            \"    RaisesGroup(RaisesExc(TypeError, match='foo')): `TypeError()` is not an exception group\\n\"\n            \"    RaisesGroup(TypeError, ValueError): `TypeError()` is not an exception group\\n\"\n            \"  ExceptionGroup('Exceptions from Trio nursery', [TypeError('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')]):\\n\"\n            \"    RaisesGroup(ValueError): `TypeError()` is not an instance of `ValueError`\\n\"\n            \"    RaisesGroup(RaisesGroup(ValueError)): RaisesGroup(ValueError): `TypeError()` is not an exception group\\n\"\n            \"    RaisesGroup(RaisesExc(TypeError, match='foo')): RaisesExc(TypeError, match='foo'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'foo'\\n\"\n            \"      Actual message: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'\\n\"\n            \"    RaisesGroup(TypeError, ValueError): 1 matched exception. Too few exceptions raised, found no match for: [ValueError]\\n\"\n            \"  ExceptionGroup('Exceptions from Trio nursery', [TypeError('cccccccccccccccccccccccccccccc'), TypeError('dddddddddddddddddddddddddddddd')]):\\n\"\n            \"    RaisesGroup(ValueError): \\n\"\n            \"      The following expected exceptions did not find a match:\\n\"\n            \"        ValueError\\n\"\n            \"      The following raised exceptions did not find a match\\n\"\n            \"        TypeError('cccccccccccccccccccccccccccccc'):\\n\"\n            \"          `TypeError()` is not an instance of `ValueError`\\n\"\n            \"        TypeError('dddddddddddddddddddddddddddddd'):\\n\"\n            \"          `TypeError()` is not an instance of `ValueError`\\n\"\n            \"    RaisesGroup(RaisesGroup(ValueError)): \\n\"\n            \"      The following expected exceptions did not find a match:\\n\"\n            \"        RaisesGroup(ValueError)\\n\"\n            \"      The following raised exceptions did not find a match\\n\"\n            \"        TypeError('cccccccccccccccccccccccccccccc'):\\n\"\n            \"          RaisesGroup(ValueError): `TypeError()` is not an exception group\\n\"\n            \"        TypeError('dddddddddddddddddddddddddddddd'):\\n\"\n            \"          RaisesGroup(ValueError): `TypeError()` is not an exception group\\n\"\n            \"    RaisesGroup(RaisesExc(TypeError, match='foo')): \\n\"\n            \"      The following expected exceptions did not find a match:\\n\"\n            \"        RaisesExc(TypeError, match='foo')\\n\"\n            \"      The following raised exceptions did not find a match\\n\"\n            \"        TypeError('cccccccccccccccccccccccccccccc'):\\n\"\n            \"          RaisesExc(TypeError, match='foo'): Regex pattern did not match.\\n\"\n            \"            Expected regex: 'foo'\\n\"\n            \"            Actual message: 'cccccccccccccccccccccccccccccc'\\n\"\n            \"        TypeError('dddddddddddddddddddddddddddddd'):\\n\"\n            \"          RaisesExc(TypeError, match='foo'): Regex pattern did not match.\\n\"\n            \"            Expected regex: 'foo'\\n\"\n            \"            Actual message: 'dddddddddddddddddddddddddddddd'\\n\"\n            \"    RaisesGroup(TypeError, ValueError): \\n\"\n            \"      1 matched exception. \\n\"\n            \"      The following expected exceptions did not find a match:\\n\"\n            \"        ValueError\\n\"\n            \"      The following raised exceptions did not find a match\\n\"\n            \"        TypeError('dddddddddddddddddddddddddddddd'):\\n\"\n            \"          It matches `TypeError` which was paired with `TypeError('cccccccccccccccccccccccccccccc')`\\n\"\n            \"          `TypeError()` is not an instance of `ValueError`\",\n            add_prefix=False,  # to see the full structure\n        ),\n        RaisesGroup(\n            RaisesGroup(ValueError),\n            RaisesGroup(RaisesGroup(ValueError)),\n            RaisesGroup(RaisesExc(TypeError, match=\"foo\")),\n            RaisesGroup(TypeError, ValueError),\n        ),\n    ):\n        raise ExceptionGroup(\n            \"\",\n            [\n                TypeError(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"),\n                ExceptionGroup(\n                    \"Exceptions from Trio nursery\",\n                    [TypeError(\"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\")],\n                ),\n                ExceptionGroup(\n                    \"Exceptions from Trio nursery\",\n                    [\n                        TypeError(\"cccccccccccccccccccccccccccccc\"),\n                        TypeError(\"dddddddddddddddddddddddddddddd\"),\n                    ],\n                ),\n            ],\n        )\n\n\n# CI always runs with hypothesis, but this is not a critical test - it overlaps\n# with several others\n@pytest.mark.skipif(\n    \"hypothesis\" in sys.modules,\n    reason=\"hypothesis may have monkeypatched _check_repr\",\n)\ndef test_check_no_patched_repr() -> None:  # pragma: no cover\n    # We make `_check_repr` monkeypatchable to avoid this very ugly and verbose\n    # repr. The other tests that use `check` make use of `_check_repr` so they'll\n    # continue passing in case it is patched - but we have this one test that\n    # demonstrates just how nasty it gets otherwise.\n    match_str = (\n        r\"^Raised exception group did not match: \\n\"\n        r\"The following expected exceptions did not find a match:\\n\"\n        r\"  RaisesExc\\(check=<function test_check_no_patched_repr.<locals>.<lambda> at .*>\\)\\n\"\n        r\"  TypeError\\n\"\n        r\"The following raised exceptions did not find a match\\n\"\n        r\"  ValueError\\('foo'\\):\\n\"\n        r\"    RaisesExc\\(check=<function test_check_no_patched_repr.<locals>.<lambda> at .*>\\): check did not return True\\n\"\n        r\"    `ValueError\\(\\)` is not an instance of `TypeError`\\n\"\n        r\"  ValueError\\('bar'\\):\\n\"\n        r\"    RaisesExc\\(check=<function test_check_no_patched_repr.<locals>.<lambda> at .*>\\): check did not return True\\n\"\n        r\"    `ValueError\\(\\)` is not an instance of `TypeError`$\"\n    )\n    with (\n        pytest.raises(Failed, match=match_str),\n        RaisesGroup(RaisesExc(check=lambda x: False), TypeError),\n    ):\n        raise ExceptionGroup(\"\", [ValueError(\"foo\"), ValueError(\"bar\")])\n\n\ndef test_misordering_example() -> None:\n    with (\n        fails_raises_group(\n            \"\\n\"\n            \"3 matched exceptions. \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  RaisesExc(ValueError, match='foo')\\n\"\n            \"    It matches `ValueError('foo')` which was paired with `ValueError`\\n\"\n            \"    It matches `ValueError('foo')` which was paired with `ValueError`\\n\"\n            \"    It matches `ValueError('foo')` which was paired with `ValueError`\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ValueError('bar'):\\n\"\n            \"    It matches `ValueError` which was paired with `ValueError('foo')`\\n\"\n            \"    It matches `ValueError` which was paired with `ValueError('foo')`\\n\"\n            \"    It matches `ValueError` which was paired with `ValueError('foo')`\\n\"\n            \"    RaisesExc(ValueError, match='foo'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'foo'\\n\"\n            \"      Actual message: 'bar'\\n\"\n            \"There exist a possible match when attempting an exhaustive check, but RaisesGroup uses a greedy algorithm. Please make your expected exceptions more stringent with `RaisesExc` etc so the greedy algorithm can function.\"\n        ),\n        RaisesGroup(\n            ValueError, ValueError, ValueError, RaisesExc(ValueError, match=\"foo\")\n        ),\n    ):\n        raise ExceptionGroup(\n            \"\",\n            [\n                ValueError(\"foo\"),\n                ValueError(\"foo\"),\n                ValueError(\"foo\"),\n                ValueError(\"bar\"),\n            ],\n        )\n\n\ndef test_brief_error_on_one_fail() -> None:\n    \"\"\"If only one raised and one expected fail to match up, we print a full table iff\n    the raised exception would match one of the expected that previously got matched\"\"\"\n    # no also-matched\n    with (\n        fails_raises_group(\n            \"1 matched exception. `TypeError()` is not an instance of `RuntimeError`\"\n        ),\n        RaisesGroup(ValueError, RuntimeError),\n    ):\n        raise ExceptionGroup(\"\", [ValueError(), TypeError()])\n\n    # raised would match an expected\n    with (\n        fails_raises_group(\n            \"\\n\"\n            \"1 matched exception. \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  RuntimeError\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  TypeError():\\n\"\n            \"    It matches `Exception` which was paired with `ValueError()`\\n\"\n            \"    `TypeError()` is not an instance of `RuntimeError`\"\n        ),\n        RaisesGroup(Exception, RuntimeError),\n    ):\n        raise ExceptionGroup(\"\", [ValueError(), TypeError()])\n\n    # expected would match a raised\n    with (\n        fails_raises_group(\n            \"\\n\"\n            \"1 matched exception. \\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  ValueError\\n\"\n            \"    It matches `ValueError()` which was paired with `ValueError`\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  TypeError():\\n\"\n            \"    `TypeError()` is not an instance of `ValueError`\"\n        ),\n        RaisesGroup(ValueError, ValueError),\n    ):\n        raise ExceptionGroup(\"\", [ValueError(), TypeError()])\n\n\ndef test_identity_oopsies() -> None:\n    # it's both possible to have several instances of the same exception in the same group\n    # and to expect multiple of the same type\n    # this previously messed up the logic\n\n    with (\n        fails_raises_group(\n            \"3 matched exceptions. `RuntimeError()` is not an instance of `TypeError`\"\n        ),\n        RaisesGroup(ValueError, ValueError, ValueError, TypeError),\n    ):\n        raise ExceptionGroup(\n            \"\", [ValueError(), ValueError(), ValueError(), RuntimeError()]\n        )\n\n    e = ValueError(\"foo\")\n    m = RaisesExc(match=\"bar\")\n    with (\n        fails_raises_group(\n            \"\\n\"\n            \"The following expected exceptions did not find a match:\\n\"\n            \"  RaisesExc(match='bar')\\n\"\n            \"  RaisesExc(match='bar')\\n\"\n            \"  RaisesExc(match='bar')\\n\"\n            \"The following raised exceptions did not find a match\\n\"\n            \"  ValueError('foo'):\\n\"\n            \"    RaisesExc(match='bar'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'bar'\\n\"\n            \"      Actual message: 'foo'\\n\"\n            \"    RaisesExc(match='bar'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'bar'\\n\"\n            \"      Actual message: 'foo'\\n\"\n            \"    RaisesExc(match='bar'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'bar'\\n\"\n            \"      Actual message: 'foo'\\n\"\n            \"  ValueError('foo'):\\n\"\n            \"    RaisesExc(match='bar'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'bar'\\n\"\n            \"      Actual message: 'foo'\\n\"\n            \"    RaisesExc(match='bar'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'bar'\\n\"\n            \"      Actual message: 'foo'\\n\"\n            \"    RaisesExc(match='bar'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'bar'\\n\"\n            \"      Actual message: 'foo'\\n\"\n            \"  ValueError('foo'):\\n\"\n            \"    RaisesExc(match='bar'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'bar'\\n\"\n            \"      Actual message: 'foo'\\n\"\n            \"    RaisesExc(match='bar'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'bar'\\n\"\n            \"      Actual message: 'foo'\\n\"\n            \"    RaisesExc(match='bar'): Regex pattern did not match.\\n\"\n            \"      Expected regex: 'bar'\\n\"\n            \"      Actual message: 'foo'\"\n        ),\n        RaisesGroup(m, m, m),\n    ):\n        raise ExceptionGroup(\"\", [e, e, e])\n\n\ndef test_raisesexc() -> None:\n    with pytest.raises(\n        ValueError,\n        match=r\"^You must specify at least one parameter to match on.$\",\n    ):\n        RaisesExc()  # type: ignore[call-overload]\n    with pytest.raises(\n        ValueError,\n        match=wrap_escape(\"Expected a BaseException type, but got 'object'\"),\n    ):\n        RaisesExc(object)  # type: ignore[type-var]\n\n    with RaisesGroup(RaisesExc(ValueError)):\n        raise ExceptionGroup(\"\", (ValueError(),))\n    with (\n        fails_raises_group(\n            \"RaisesExc(TypeError): `ValueError()` is not an instance of `TypeError`\"\n        ),\n        RaisesGroup(RaisesExc(TypeError)),\n    ):\n        raise ExceptionGroup(\"\", (ValueError(),))\n\n    with RaisesExc(ValueError):\n        raise ValueError\n\n    # FIXME: leaving this one formatted differently for now to not change\n    # tests in python/raises.py\n    with pytest.raises(Failed, match=wrap_escape(\"DID NOT RAISE <class 'ValueError'>\")):\n        with RaisesExc(ValueError):\n            ...\n\n    with pytest.raises(Failed, match=wrap_escape(\"DID NOT RAISE any exception\")):\n        with RaisesExc(match=\"foo\"):\n            ...\n\n    with pytest.raises(\n        # FIXME: do we want repr(type) or type.__name__ ?\n        Failed,\n        match=wrap_escape(\n            \"DID NOT RAISE any of (<class 'ValueError'>, <class 'TypeError'>)\"\n        ),\n    ):\n        with RaisesExc((ValueError, TypeError)):\n            ...\n\n    # currently RaisesGroup says \"Raised exception did not match\" but RaisesExc doesn't...\n    with pytest.raises(\n        AssertionError,\n        match=wrap_escape(\n            \"Regex pattern did not match.\\n  Expected regex: 'foo'\\n  Actual message: 'bar'\"\n        ),\n    ):\n        with RaisesExc(TypeError, match=\"foo\"):\n            raise TypeError(\"bar\")\n\n\ndef test_raisesexc_match() -> None:\n    with RaisesGroup(RaisesExc(ValueError, match=\"foo\")):\n        raise ExceptionGroup(\"\", (ValueError(\"foo\"),))\n    with (\n        fails_raises_group(\n            \"RaisesExc(ValueError, match='foo'): Regex pattern did not match.\\n\"\n            \"  Expected regex: 'foo'\\n\"\n            \"  Actual message: 'bar'\"\n        ),\n        RaisesGroup(RaisesExc(ValueError, match=\"foo\")),\n    ):\n        raise ExceptionGroup(\"\", (ValueError(\"bar\"),))\n\n    # Can be used without specifying the type\n    with RaisesGroup(RaisesExc(match=\"foo\")):\n        raise ExceptionGroup(\"\", (ValueError(\"foo\"),))\n    with (\n        fails_raises_group(\n            \"RaisesExc(match='foo'): Regex pattern did not match.\\n\"\n            \"  Expected regex: 'foo'\\n\"\n            \"  Actual message: 'bar'\"\n        ),\n        RaisesGroup(RaisesExc(match=\"foo\")),\n    ):\n        raise ExceptionGroup(\"\", (ValueError(\"bar\"),))\n\n    # check ^$\n    with RaisesGroup(RaisesExc(ValueError, match=\"^bar$\")):\n        raise ExceptionGroup(\"\", [ValueError(\"bar\")])\n    with (\n        fails_raises_group(\n            \"\\nRaisesExc(ValueError, match='^bar$'): \\n  - barr\\n  ?    -\\n  + bar\"\n        ),\n        RaisesGroup(RaisesExc(ValueError, match=\"^bar$\")),\n    ):\n        raise ExceptionGroup(\"\", [ValueError(\"barr\")])\n\n\ndef test_RaisesExc_check() -> None:\n    def check_oserror_and_errno_is_5(e: BaseException) -> bool:\n        return isinstance(e, OSError) and e.errno == 5\n\n    with RaisesGroup(RaisesExc(check=check_oserror_and_errno_is_5)):\n        raise ExceptionGroup(\"\", (OSError(5, \"\"),))\n\n    # specifying exception_type narrows the parameter type to the callable\n    def check_errno_is_5(e: OSError) -> bool:\n        return e.errno == 5\n\n    with RaisesGroup(RaisesExc(OSError, check=check_errno_is_5)):\n        raise ExceptionGroup(\"\", (OSError(5, \"\"),))\n\n    # avoid printing overly verbose repr multiple times\n    with (\n        fails_raises_group(\n            f\"RaisesExc(OSError, check={check_errno_is_5!r}): check did not return True\"\n        ),\n        RaisesGroup(RaisesExc(OSError, check=check_errno_is_5)),\n    ):\n        raise ExceptionGroup(\"\", (OSError(6, \"\"),))\n\n    # in nested cases you still get it multiple times though\n    # to address this you'd need logic in RaisesExc.__repr__ and RaisesGroup.__repr__\n    with (\n        fails_raises_group(\n            f\"RaisesGroup(RaisesExc(OSError, check={check_errno_is_5!r})): RaisesExc(OSError, check={check_errno_is_5!r}): check did not return True\"\n        ),\n        RaisesGroup(RaisesGroup(RaisesExc(OSError, check=check_errno_is_5))),\n    ):\n        raise ExceptionGroup(\"\", [ExceptionGroup(\"\", [OSError(6, \"\")])])\n\n\ndef test_raisesexc_tostring() -> None:\n    assert str(RaisesExc(ValueError)) == \"RaisesExc(ValueError)\"\n    assert str(RaisesExc(match=\"[a-z]\")) == \"RaisesExc(match='[a-z]')\"\n    pattern_no_flags = re.compile(r\"noflag\", 0)\n    assert str(RaisesExc(match=pattern_no_flags)) == \"RaisesExc(match='noflag')\"\n    pattern_flags = re.compile(r\"noflag\", re.IGNORECASE)\n    assert str(RaisesExc(match=pattern_flags)) == f\"RaisesExc(match={pattern_flags!r})\"\n    assert (\n        str(RaisesExc(ValueError, match=\"re\", check=bool))\n        == f\"RaisesExc(ValueError, match='re', check={bool!r})\"\n    )\n\n\ndef test_raisesgroup_tostring() -> None:\n    def check_str_and_repr(s: str) -> None:\n        evaled = eval(s)\n        assert s == str(evaled) == repr(evaled)\n\n    check_str_and_repr(\"RaisesGroup(ValueError)\")\n    check_str_and_repr(\"RaisesGroup(RaisesGroup(ValueError))\")\n    check_str_and_repr(\"RaisesGroup(RaisesExc(ValueError))\")\n    check_str_and_repr(\"RaisesGroup(ValueError, allow_unwrapped=True)\")\n    check_str_and_repr(\"RaisesGroup(ValueError, match='aoeu')\")\n\n    assert (\n        str(RaisesGroup(ValueError, match=\"[a-z]\", check=bool))\n        == f\"RaisesGroup(ValueError, match='[a-z]', check={bool!r})\"\n    )\n\n\ndef test_assert_matches() -> None:\n    e = ValueError()\n\n    # it's easy to do this\n    assert RaisesExc(ValueError).matches(e)\n\n    # but you don't get a helpful error\n    with pytest.raises(AssertionError, match=r\"assert False\\n \\+  where False = .*\"):\n        assert RaisesExc(TypeError).matches(e)\n\n    with pytest.raises(\n        AssertionError,\n        match=wrap_escape(\n            \"`ValueError()` is not an instance of `TypeError`\\n\"\n            \"assert False\\n\"\n            \" +  where False = matches(ValueError())\\n\"\n            \" +    where matches = RaisesExc(TypeError).matches\"\n        ),\n    ):\n        # you'd need to do this arcane incantation\n        assert (m := RaisesExc(TypeError)).matches(e), m.fail_reason\n\n    # but even if we add assert_matches, will people remember to use it?\n    # other than writing a linter rule, I don't think we can catch `assert RaisesExc(...).matches`\n    # ... no wait pytest catches other asserts ... so we probably can??\n\n\n# https://github.com/pytest-dev/pytest/issues/12504\ndef test_xfail_raisesgroup(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import sys\n        import pytest\n        if sys.version_info < (3, 11):\n            from exceptiongroup import ExceptionGroup\n        @pytest.mark.xfail(raises=pytest.RaisesGroup(ValueError))\n        def test_foo() -> None:\n            raise ExceptionGroup(\"foo\", [ValueError()])\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(xfailed=1)\n\n\ndef test_xfail_RaisesExc(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.xfail(raises=pytest.RaisesExc(ValueError))\n        def test_foo() -> None:\n            raise ValueError\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(xfailed=1)\n\n\n@pytest.mark.parametrize(\n    \"wrap_in_group,handler\",\n    [\n        (False, pytest.raises(ValueError)),\n        (True, RaisesGroup(ValueError)),\n    ],\n)\ndef test_parametrizing_conditional_raisesgroup(\n    wrap_in_group: bool, handler: AbstractContextManager[ExceptionInfo[BaseException]]\n) -> None:\n    with handler:\n        if wrap_in_group:\n            raise ExceptionGroup(\"\", [ValueError()])\n        raise ValueError()\n\n\ndef test_annotated_group() -> None:\n    # repr depends on if exceptiongroup backport is being used or not\n    t = repr(ExceptionGroup[ValueError])\n    msg = \"Only `ExceptionGroup[Exception]` or `BaseExceptionGroup[BaseException]` are accepted as generic types but got `{}`. As `raises` will catch all instances of the specified group regardless of the generic argument specific nested exceptions has to be checked with `RaisesGroup`.\"\n\n    fail_msg = wrap_escape(msg.format(t))\n    with pytest.raises(ValueError, match=fail_msg):\n        RaisesGroup(ExceptionGroup[ValueError])\n    with pytest.raises(ValueError, match=fail_msg):\n        RaisesExc(ExceptionGroup[ValueError])\n    with pytest.raises(\n        ValueError,\n        match=wrap_escape(msg.format(repr(BaseExceptionGroup[KeyboardInterrupt]))),\n    ):\n        with RaisesExc(BaseExceptionGroup[KeyboardInterrupt]):\n            raise BaseExceptionGroup(\"\", [KeyboardInterrupt()])\n\n    with RaisesGroup(ExceptionGroup[Exception]):\n        raise ExceptionGroup(\n            \"\", [ExceptionGroup(\"\", [ValueError(), ValueError(), ValueError()])]\n        )\n    with RaisesExc(BaseExceptionGroup[BaseException]):\n        raise BaseExceptionGroup(\"\", [KeyboardInterrupt()])\n\n    # assure AbstractRaises.is_baseexception is set properly\n    assert (\n        RaisesGroup(ExceptionGroup[Exception]).expected_type()\n        == \"ExceptionGroup(ExceptionGroup)\"\n    )\n    assert (\n        RaisesGroup(BaseExceptionGroup[BaseException]).expected_type()\n        == \"BaseExceptionGroup(BaseExceptionGroup)\"\n    )\n\n\ndef test_tuples() -> None:\n    # raises has historically supported one of several exceptions being raised\n    with pytest.raises((ValueError, IndexError)):\n        raise ValueError\n    # so now RaisesExc also does\n    with RaisesExc((ValueError, IndexError)):\n        raise IndexError\n    # but RaisesGroup currently doesn't. There's an argument it shouldn't because\n    # it can be confusing - RaisesGroup((ValueError, TypeError)) looks a lot like\n    # RaisesGroup(ValueError, TypeError), and the former might be interpreted as the latter.\n    with pytest.raises(\n        TypeError,\n        match=wrap_escape(\n            \"Expected a BaseException type, RaisesExc, or RaisesGroup, but got 'tuple'.\\n\"\n            \"RaisesGroup does not support tuples of exception types when expecting one of \"\n            \"several possible exception types like RaisesExc.\\n\"\n            \"If you meant to expect a group with multiple exceptions, list them as separate arguments.\"\n        ),\n    ):\n        RaisesGroup((ValueError, IndexError))  # type: ignore[call-overload]\n"
  },
  {
    "path": "testing/python/show_fixtures_per_test.py",
    "content": "from __future__ import annotations\n\nfrom _pytest.pytester import Pytester\n\n\ndef test_no_items_should_not_show_output(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--fixtures-per-test\")\n    result.stdout.no_fnmatch_line(\"*fixtures used by*\")\n    assert result.ret == 0\n\n\ndef test_fixtures_in_module(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture\n        def _arg0():\n            \"\"\"hidden arg0 fixture\"\"\"\n        @pytest.fixture\n        def arg1():\n            \"\"\"arg1 docstring\"\"\"\n        def test_arg1(arg1):\n            pass\n    '''\n    )\n\n    result = pytester.runpytest(\"--fixtures-per-test\", p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"*fixtures used by test_arg1*\",\n            \"*(test_fixtures_in_module.py:9)*\",\n            \"arg1 -- test_fixtures_in_module.py:6\",\n            \"    arg1 docstring\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*_arg0*\")\n\n\ndef test_fixtures_in_conftest(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        '''\n        import pytest\n        @pytest.fixture\n        def arg1():\n            \"\"\"arg1 docstring\"\"\"\n        @pytest.fixture\n        def arg2():\n            \"\"\"arg2 docstring\"\"\"\n        @pytest.fixture\n        def arg3(arg1, arg2):\n            \"\"\"arg3\n            docstring\n            \"\"\"\n    '''\n    )\n    p = pytester.makepyfile(\n        \"\"\"\n        def test_arg2(arg2):\n            pass\n        def test_arg3(arg3):\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--fixtures-per-test\", p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"*fixtures used by test_arg2*\",\n            \"*(test_fixtures_in_conftest.py:2)*\",\n            \"arg2 -- conftest.py:6\",\n            \"    arg2 docstring\",\n            \"*fixtures used by test_arg3*\",\n            \"*(test_fixtures_in_conftest.py:4)*\",\n            \"arg1 -- conftest.py:3\",\n            \"    arg1 docstring\",\n            \"arg2 -- conftest.py:6\",\n            \"    arg2 docstring\",\n            \"arg3 -- conftest.py:9\",\n            \"    arg3\",\n        ]\n    )\n\n\ndef test_should_show_fixtures_used_by_test(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        '''\n        import pytest\n        @pytest.fixture\n        def arg1():\n            \"\"\"arg1 from conftest\"\"\"\n        @pytest.fixture\n        def arg2():\n            \"\"\"arg2 from conftest\"\"\"\n    '''\n    )\n    p = pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture\n        def arg1():\n            \"\"\"arg1 from testmodule\"\"\"\n        def test_args(arg1, arg2):\n            pass\n    '''\n    )\n    result = pytester.runpytest(\"--fixtures-per-test\", p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"*fixtures used by test_args*\",\n            \"*(test_should_show_fixtures_used_by_test.py:6)*\",\n            \"arg1 -- test_should_show_fixtures_used_by_test.py:3\",\n            \"    arg1 from testmodule\",\n            \"arg2 -- conftest.py:6\",\n            \"    arg2 from conftest\",\n        ]\n    )\n\n\ndef test_verbose_include_private_fixtures_and_loc(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        '''\n        import pytest\n        @pytest.fixture\n        def _arg1():\n            \"\"\"_arg1 from conftest\"\"\"\n        @pytest.fixture\n        def arg2(_arg1):\n            \"\"\"arg2 from conftest\"\"\"\n    '''\n    )\n    p = pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture\n        def arg3():\n            \"\"\"arg3 from testmodule\"\"\"\n        def test_args(arg2, arg3):\n            pass\n    '''\n    )\n    result = pytester.runpytest(\"--fixtures-per-test\", \"-v\", p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"*fixtures used by test_args*\",\n            \"*(test_verbose_include_private_fixtures_and_loc.py:6)*\",\n            \"_arg1 -- conftest.py:3\",\n            \"    _arg1 from conftest\",\n            \"arg2 -- conftest.py:6\",\n            \"    arg2 from conftest\",\n            \"arg3 -- test_verbose_include_private_fixtures_and_loc.py:3\",\n            \"    arg3 from testmodule\",\n        ]\n    )\n\n\ndef test_doctest_items(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        '''\n        def foo():\n            \"\"\"\n            >>> 1 + 1\n            2\n            \"\"\"\n    '''\n    )\n    pytester.maketxtfile(\n        \"\"\"\n        >>> 1 + 1\n        2\n    \"\"\"\n    )\n    result = pytester.runpytest(\n        \"--fixtures-per-test\", \"--doctest-modules\", \"--doctest-glob=*.txt\", \"-v\"\n    )\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines([\"*collected 2 items*\"])\n\n\ndef test_multiline_docstring_in_module(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture\n        def arg1():\n            \"\"\"Docstring content that spans across multiple lines,\n            through second line,\n            and through third line.\n\n            Docstring content that extends into a second paragraph.\n\n            Docstring content that extends into a third paragraph.\n            \"\"\"\n        def test_arg1(arg1):\n            pass\n    '''\n    )\n\n    result = pytester.runpytest(\"--fixtures-per-test\", p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"*fixtures used by test_arg1*\",\n            \"*(test_multiline_docstring_in_module.py:13)*\",\n            \"arg1 -- test_multiline_docstring_in_module.py:3\",\n            \"    Docstring content that spans across multiple lines,\",\n            \"    through second line,\",\n            \"    and through third line.\",\n        ]\n    )\n\n\ndef test_verbose_include_multiline_docstring(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture\n        def arg1():\n            \"\"\"Docstring content that spans across multiple lines,\n            through second line,\n            and through third line.\n\n            Docstring content that extends into a second paragraph.\n\n            Docstring content that extends into a third paragraph.\n            \"\"\"\n        def test_arg1(arg1):\n            pass\n    '''\n    )\n\n    result = pytester.runpytest(\"--fixtures-per-test\", \"-v\", p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"*fixtures used by test_arg1*\",\n            \"*(test_verbose_include_multiline_docstring.py:13)*\",\n            \"arg1 -- test_verbose_include_multiline_docstring.py:3\",\n            \"    Docstring content that spans across multiple lines,\",\n            \"    through second line,\",\n            \"    and through third line.\",\n            \"    \",\n            \"    Docstring content that extends into a second paragraph.\",\n            \"    \",\n            \"    Docstring content that extends into a third paragraph.\",\n        ]\n    )\n"
  },
  {
    "path": "testing/test_argcomplete.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom pathlib import Path\nimport subprocess\nimport sys\n\nfrom _pytest.monkeypatch import MonkeyPatch\nimport pytest\n\n\n# Test for _argcomplete but not specific for any application.\n\n\ndef equal_with_bash(prefix, ffc, fc, out=None):\n    res = ffc(prefix)\n    res_bash = set(fc(prefix))\n    retval = set(res) == res_bash\n    if out:\n        out.write(f\"equal_with_bash({prefix}) {retval} {res}\\n\")\n        if not retval:\n            out.write(\" python - bash: %s\\n\" % (set(res) - res_bash))\n            out.write(\" bash - python: %s\\n\" % (res_bash - set(res)))\n    return retval\n\n\n# Copied from argcomplete.completers as import from there.\n# Also pulls in argcomplete.__init__ which opens filedescriptor 9.\n# This gives an OSError at the end of testrun.\n\n\ndef _wrapcall(*args, **kargs):\n    try:\n        return subprocess.check_output(*args, **kargs).decode().splitlines()\n    except subprocess.CalledProcessError:\n        return []\n\n\nclass FilesCompleter:\n    \"\"\"File completer class, optionally takes a list of allowed extensions.\"\"\"\n\n    def __init__(self, allowednames=(), directories=True):\n        # Fix if someone passes in a string instead of a list\n        if type(allowednames) is str:\n            allowednames = [allowednames]\n\n        self.allowednames = [x.lstrip(\"*\").lstrip(\".\") for x in allowednames]\n        self.directories = directories\n\n    def __call__(self, prefix, **kwargs):\n        completion = []\n        if self.allowednames:\n            if self.directories:\n                files = _wrapcall([\"bash\", \"-c\", f\"compgen -A directory -- '{prefix}'\"])\n                completion += [f + \"/\" for f in files]\n            for x in self.allowednames:\n                completion += _wrapcall(\n                    [\"bash\", \"-c\", f\"compgen -A file -X '!*.{x}' -- '{prefix}'\"]\n                )\n        else:\n            completion += _wrapcall([\"bash\", \"-c\", f\"compgen -A file -- '{prefix}'\"])\n\n            anticomp = _wrapcall([\"bash\", \"-c\", f\"compgen -A directory -- '{prefix}'\"])\n\n            completion = list(set(completion) - set(anticomp))\n\n            if self.directories:\n                completion += [f + \"/\" for f in anticomp]\n        return completion\n\n\nclass TestArgComplete:\n    @pytest.mark.skipif(\"sys.platform in ('win32', 'darwin')\")\n    def test_compare_with_compgen(\n        self, tmp_path: Path, monkeypatch: MonkeyPatch\n    ) -> None:\n        from _pytest._argcomplete import FastFilesCompleter\n\n        ffc = FastFilesCompleter()\n        fc = FilesCompleter()\n\n        monkeypatch.chdir(tmp_path)\n\n        assert equal_with_bash(\"\", ffc, fc, out=sys.stdout)\n\n        tmp_path.cwd().joinpath(\"data\").touch()\n\n        for x in [\"d\", \"data\", \"doesnotexist\", \"\"]:\n            assert equal_with_bash(x, ffc, fc, out=sys.stdout)\n\n    @pytest.mark.skipif(\"sys.platform in ('win32', 'darwin')\")\n    def test_remove_dir_prefix(self):\n        \"\"\"This is not compatible with compgen but it is with bash itself: ls /usr/<TAB>.\"\"\"\n        from _pytest._argcomplete import FastFilesCompleter\n\n        ffc = FastFilesCompleter()\n        fc = FilesCompleter()\n        for x in \"/usr/\".split():\n            assert not equal_with_bash(x, ffc, fc, out=sys.stdout)\n"
  },
  {
    "path": "testing/test_assertion.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import MutableSequence\nimport sys\nimport textwrap\nfrom typing import Any\nfrom typing import NamedTuple\n\nimport attr\n\nfrom _pytest import outcomes\nimport _pytest.assertion as plugin\nfrom _pytest.assertion import truncate\nfrom _pytest.assertion import util\nfrom _pytest.config import Config as _Config\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\ndef mock_config(verbose: int = 0, assertion_override: int | None = None):\n    class TerminalWriter:\n        def _highlight(self, source, lexer=\"python\"):\n            return source\n\n    class Config:\n        def get_terminal_writer(self):\n            return TerminalWriter()\n\n        def get_verbosity(self, verbosity_type: str | None = None) -> int:\n            if verbosity_type is None:\n                return verbose\n            if verbosity_type == _Config.VERBOSITY_ASSERTIONS:\n                if assertion_override is not None:\n                    return assertion_override\n                return verbose\n\n            raise KeyError(f\"Not mocked out: {verbosity_type}\")\n\n    return Config()\n\n\nclass TestMockConfig:\n    SOME_VERBOSITY_LEVEL = 3\n    SOME_OTHER_VERBOSITY_LEVEL = 10\n\n    def test_verbose_exposes_value(self):\n        config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL)\n\n        assert config.get_verbosity() == TestMockConfig.SOME_VERBOSITY_LEVEL\n\n    def test_get_assertion_override_not_set_verbose_value(self):\n        config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL)\n\n        assert (\n            config.get_verbosity(_Config.VERBOSITY_ASSERTIONS)\n            == TestMockConfig.SOME_VERBOSITY_LEVEL\n        )\n\n    def test_get_assertion_override_set_custom_value(self):\n        config = mock_config(\n            verbose=TestMockConfig.SOME_VERBOSITY_LEVEL,\n            assertion_override=TestMockConfig.SOME_OTHER_VERBOSITY_LEVEL,\n        )\n\n        assert (\n            config.get_verbosity(_Config.VERBOSITY_ASSERTIONS)\n            == TestMockConfig.SOME_OTHER_VERBOSITY_LEVEL\n        )\n\n    def test_get_unsupported_type_error(self):\n        config = mock_config(verbose=TestMockConfig.SOME_VERBOSITY_LEVEL)\n\n        with pytest.raises(KeyError):\n            config.get_verbosity(\"--- NOT A VERBOSITY LEVEL ---\")\n\n\nclass TestImportHookInstallation:\n    @pytest.mark.parametrize(\"initial_conftest\", [True, False])\n    @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n    def test_conftest_assertion_rewrite(\n        self, pytester: Pytester, initial_conftest, mode\n    ) -> None:\n        \"\"\"Test that conftest files are using assertion rewrite on import (#1619).\"\"\"\n        pytester.mkdir(\"foo\")\n        pytester.mkdir(\"foo/tests\")\n        conftest_path = \"conftest.py\" if initial_conftest else \"foo/conftest.py\"\n        contents = {\n            conftest_path: \"\"\"\n                import pytest\n                @pytest.fixture\n                def check_first():\n                    def check(values, value):\n                        assert values.pop(0) == value\n                    return check\n            \"\"\",\n            \"foo/tests/test_foo.py\": \"\"\"\n                def test(check_first):\n                    check_first([10, 30], 30)\n            \"\"\",\n        }\n        pytester.makepyfile(**contents)\n        result = pytester.runpytest_subprocess(f\"--assert={mode}\")\n        if mode == \"plain\":\n            expected = \"E       AssertionError\"\n        elif mode == \"rewrite\":\n            expected = \"*assert 10 == 30*\"\n        else:\n            assert 0\n        result.stdout.fnmatch_lines([expected])\n\n    def test_rewrite_assertions_pytester_plugin(self, pytester: Pytester) -> None:\n        \"\"\"\n        Assertions in the pytester plugin must also benefit from assertion\n        rewriting (#1920).\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            pytest_plugins = ['pytester']\n            def test_dummy_failure(pytester):  # how meta!\n                pytester.makepyfile('def test(): assert 0')\n                r = pytester.inline_run()\n                r.assertoutcome(passed=1)\n        \"\"\"\n        )\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines(\n            [\n                \">       r.assertoutcome(passed=1)\",\n                \"E       AssertionError: ([[][]], [[][]], [[]<TestReport *>[]])*\",\n                \"E       assert {'failed': 1,... 'skipped': 0} == {'failed': 0,... 'skipped': 0}\",\n                \"E         Omitting 1 identical items, use -vv to show\",\n                \"E         Differing items:\",\n                \"E         Use -v to get more diff\",\n            ]\n        )\n        # XXX: unstable output.\n        result.stdout.fnmatch_lines_random(\n            [\n                \"E         {'failed': 1} != {'failed': 0}\",\n                \"E         {'passed': 0} != {'passed': 1}\",\n            ]\n        )\n\n    @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n    def test_pytest_plugins_rewrite(self, pytester: Pytester, mode) -> None:\n        contents = {\n            \"conftest.py\": \"\"\"\n                pytest_plugins = ['ham']\n            \"\"\",\n            \"ham.py\": \"\"\"\n                import pytest\n                @pytest.fixture\n                def check_first():\n                    def check(values, value):\n                        assert values.pop(0) == value\n                    return check\n            \"\"\",\n            \"test_foo.py\": \"\"\"\n                def test_foo(check_first):\n                    check_first([10, 30], 30)\n            \"\"\",\n        }\n        pytester.makepyfile(**contents)\n        result = pytester.runpytest_subprocess(f\"--assert={mode}\")\n        if mode == \"plain\":\n            expected = \"E       AssertionError\"\n        elif mode == \"rewrite\":\n            expected = \"*assert 10 == 30*\"\n        else:\n            assert 0\n        result.stdout.fnmatch_lines([expected])\n\n    @pytest.mark.parametrize(\"mode\", [\"str\", \"list\"])\n    def test_pytest_plugins_rewrite_module_names(\n        self, pytester: Pytester, mode\n    ) -> None:\n        \"\"\"Test that pluginmanager correct marks pytest_plugins variables\n        for assertion rewriting if they are defined as plain strings or\n        list of strings (#1888).\n        \"\"\"\n        plugins = '\"ham\"' if mode == \"str\" else '[\"ham\"]'\n        contents = {\n            \"conftest.py\": f\"\"\"\n                pytest_plugins = {plugins}\n            \"\"\",\n            \"ham.py\": \"\"\"\n                import pytest\n            \"\"\",\n            \"test_foo.py\": \"\"\"\n                def test_foo(pytestconfig):\n                    assert 'ham' in pytestconfig.pluginmanager.rewrite_hook._must_rewrite\n            \"\"\",\n        }\n        pytester.makepyfile(**contents)\n        result = pytester.runpytest_subprocess(\"--assert=rewrite\")\n        assert result.ret == 0\n\n    def test_pytest_plugins_rewrite_module_names_correctly(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test that we match files correctly when they are marked for rewriting (#2939).\"\"\"\n        contents = {\n            \"conftest.py\": \"\"\"\\\n                pytest_plugins = \"ham\"\n            \"\"\",\n            \"ham.py\": \"\",\n            \"hamster.py\": \"\",\n            \"test_foo.py\": \"\"\"\\\n                def test_foo(pytestconfig):\n                    assert pytestconfig.pluginmanager.rewrite_hook.find_spec('ham') is not None\n                    assert pytestconfig.pluginmanager.rewrite_hook.find_spec('hamster') is None\n            \"\"\",\n        }\n        pytester.makepyfile(**contents)\n        result = pytester.runpytest_subprocess(\"--assert=rewrite\")\n        assert result.ret == 0\n\n    @pytest.mark.parametrize(\"mode\", [\"plain\", \"rewrite\"])\n    @pytest.mark.parametrize(\"disable_plugin_autoload\", [\"env_var\", \"cli\", \"\"])\n    @pytest.mark.parametrize(\"explicit_specify\", [\"env_var\", \"cli\", \"\"])\n    def test_installed_plugin_rewrite(\n        self,\n        pytester: Pytester,\n        mode: str,\n        monkeypatch: pytest.MonkeyPatch,\n        disable_plugin_autoload: str,\n        explicit_specify: str,\n    ) -> None:\n        args = [\"mainwrapper.py\", \"-s\", f\"--assert={mode}\"]\n        if disable_plugin_autoload == \"env_var\":\n            monkeypatch.setenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", \"1\")\n        elif disable_plugin_autoload == \"cli\":\n            monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n            args.append(\"--disable-plugin-autoload\")\n        else:\n            assert disable_plugin_autoload == \"\"\n            monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n        name = \"spamplugin\"\n\n        if explicit_specify == \"env_var\":\n            monkeypatch.setenv(\"PYTEST_PLUGINS\", name)\n        elif explicit_specify == \"cli\":\n            args.append(\"-p\")\n            args.append(name)\n        else:\n            assert explicit_specify == \"\"\n\n        # Make sure the hook is installed early enough so that plugins\n        # installed via distribution package are rewritten.\n        pytester.mkdir(\"hampkg\")\n        contents = {\n            \"hampkg/__init__.py\": \"\"\"\\\n                import pytest\n\n                @pytest.fixture\n                def check_first2():\n                    def check(values, value):\n                        assert values.pop(0) == value\n                    return check\n            \"\"\",\n            \"spamplugin.py\": \"\"\"\\\n            import pytest\n            from hampkg import check_first2\n\n            @pytest.fixture\n            def check_first():\n                def check(values, value):\n                    assert values.pop(0) == value\n                return check\n            \"\"\",\n            \"mainwrapper.py\": \"\"\"\\\n            import importlib.metadata\n            import pytest\n\n            class DummyEntryPoint(object):\n                name = 'spamplugin'\n                module_name = 'spam.py'\n                group = 'pytest11'\n\n                def load(self):\n                    import spamplugin\n                    return spamplugin\n\n            class DummyDistInfo(object):\n                version = '1.0'\n                files = ('spamplugin.py', 'hampkg/__init__.py')\n                entry_points = (DummyEntryPoint(),)\n                metadata = {'name': 'foo'}\n\n            def distributions():\n                return (DummyDistInfo(),)\n\n            importlib.metadata.distributions = distributions\n            pytest.main()\n            \"\"\",\n            \"test_foo.py\": \"\"\"\\\n            def test(check_first):\n                check_first([10, 30], 30)\n\n            def test2(check_first2):\n                check_first2([10, 30], 30)\n            \"\"\",\n        }\n        pytester.makepyfile(**contents)\n        result = pytester.run(sys.executable, *args)\n        if mode == \"plain\":\n            expected = \"E       AssertionError\"\n        elif mode == \"rewrite\":\n            expected = \"*assert 10 == 30*\"\n        else:\n            assert 0\n\n        if not disable_plugin_autoload or explicit_specify:\n            result.assert_outcomes(failed=2)\n            result.stdout.fnmatch_lines([expected, expected])\n        else:\n            result.assert_outcomes(errors=2)\n            result.stdout.fnmatch_lines(\n                [\n                    \"E       fixture 'check_first' not found\",\n                    \"E       fixture 'check_first2' not found\",\n                ]\n            )\n\n    def test_rewrite_ast(self, pytester: Pytester) -> None:\n        pytester.mkdir(\"pkg\")\n        contents = {\n            \"pkg/__init__.py\": \"\"\"\n                import pytest\n                pytest.register_assert_rewrite('pkg.helper')\n            \"\"\",\n            \"pkg/helper.py\": \"\"\"\n                def tool():\n                    a, b = 2, 3\n                    assert a == b\n            \"\"\",\n            \"pkg/plugin.py\": \"\"\"\n                import pytest, pkg.helper\n                @pytest.fixture\n                def tool():\n                    return pkg.helper.tool\n            \"\"\",\n            \"pkg/other.py\": \"\"\"\n                values = [3, 2]\n                def tool():\n                    assert values.pop() == 3\n            \"\"\",\n            \"conftest.py\": \"\"\"\n                pytest_plugins = ['pkg.plugin']\n            \"\"\",\n            \"test_pkg.py\": \"\"\"\n                import pkg.other\n                def test_tool(tool):\n                    tool()\n                def test_other():\n                    pkg.other.tool()\n            \"\"\",\n        }\n        pytester.makepyfile(**contents)\n        result = pytester.runpytest_subprocess(\"--assert=rewrite\")\n        result.stdout.fnmatch_lines(\n            [\n                \">*assert a == b*\",\n                \"E*assert 2 == 3*\",\n                \">*assert values.pop() == 3*\",\n                \"E*AssertionError\",\n            ]\n        )\n\n    def test_register_assert_rewrite_checks_types(self) -> None:\n        with pytest.raises(TypeError):\n            pytest.register_assert_rewrite([\"pytest_tests_internal_non_existing\"])  # type: ignore\n        pytest.register_assert_rewrite(\n            \"pytest_tests_internal_non_existing\", \"pytest_tests_internal_non_existing2\"\n        )\n\n\nclass TestBinReprIntegration:\n    def test_pytest_assertrepr_compare_called(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            values = []\n            def pytest_assertrepr_compare(op, left, right):\n                values.append((op, left, right))\n\n            @pytest.fixture\n            def list(request):\n                return values\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_hello():\n                assert 0 == 1\n            def test_check(list):\n                assert list == [(\"==\", 0, 1)]\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines([\"*test_hello*FAIL*\", \"*test_check*PASS*\"])\n\n\ndef callop(op: str, left: Any, right: Any, verbose: int = 0) -> list[str] | None:\n    config = mock_config(verbose=verbose)\n    return plugin.pytest_assertrepr_compare(config, op, left, right)\n\n\ndef callequal(left: Any, right: Any, verbose: int = 0) -> list[str] | None:\n    return callop(\"==\", left, right, verbose)\n\n\nclass TestAssert_reprcompare:\n    def test_different_types(self) -> None:\n        assert callequal([0, 1], \"foo\") is None\n\n    def test_summary(self) -> None:\n        lines = callequal([0, 1], [0, 2])\n        assert lines is not None\n        summary = lines[0]\n        assert len(summary) < 65\n\n    def test_text_diff(self) -> None:\n        assert callequal(\"spam\", \"eggs\") == [\n            \"'spam' == 'eggs'\",\n            \"\",\n            \"- eggs\",\n            \"+ spam\",\n        ]\n\n    def test_text_skipping(self) -> None:\n        lines = callequal(\"a\" * 50 + \"spam\", \"a\" * 50 + \"eggs\")\n        assert lines is not None\n        assert \"Skipping\" in lines[2]\n        for line in lines:\n            assert \"a\" * 50 not in line\n\n    def test_text_skipping_verbose(self) -> None:\n        lines = callequal(\"a\" * 50 + \"spam\", \"a\" * 50 + \"eggs\", verbose=1)\n        assert lines is not None\n        assert \"- \" + \"a\" * 50 + \"eggs\" in lines\n        assert \"+ \" + \"a\" * 50 + \"spam\" in lines\n\n    def test_multiline_text_diff(self) -> None:\n        left = \"foo\\nspam\\nbar\"\n        right = \"foo\\neggs\\nbar\"\n        diff = callequal(left, right)\n        assert diff is not None\n        assert \"- eggs\" in diff\n        assert \"+ spam\" in diff\n\n    def test_bytes_diff_normal(self) -> None:\n        \"\"\"Check special handling for bytes diff (#5260)\"\"\"\n        diff = callequal(b\"spam\", b\"eggs\")\n\n        assert diff == [\n            \"b'spam' == b'eggs'\",\n            \"\",\n            \"At index 0 diff: b's' != b'e'\",\n            \"Use -v to get more diff\",\n        ]\n\n    def test_bytes_diff_verbose(self) -> None:\n        \"\"\"Check special handling for bytes diff (#5260)\"\"\"\n        diff = callequal(b\"spam\", b\"eggs\", verbose=1)\n        assert diff == [\n            \"b'spam' == b'eggs'\",\n            \"\",\n            \"At index 0 diff: b's' != b'e'\",\n            \"\",\n            \"Full diff:\",\n            \"- b'eggs'\",\n            \"+ b'spam'\",\n        ]\n\n    def test_list(self) -> None:\n        expl = callequal([0, 1], [0, 2])\n        assert expl is not None\n        assert len(expl) > 1\n\n    @pytest.mark.parametrize(\n        [\"left\", \"right\", \"expected\"],\n        [\n            pytest.param(\n                [0, 1],\n                [0, 2],\n                \"\"\"\n                Full diff:\n                  [\n                      0,\n                -     2,\n                ?     ^\n                +     1,\n                ?     ^\n                  ]\n                \"\"\",\n                id=\"lists\",\n            ),\n            pytest.param(\n                {0: 1},\n                {0: 2},\n                \"\"\"\n                Full diff:\n                  {\n                -     0: 2,\n                ?        ^\n                +     0: 1,\n                ?        ^\n                  }\n            \"\"\",\n                id=\"dicts\",\n            ),\n            pytest.param(\n                {0, 1},\n                {0, 2},\n                \"\"\"\n                Full diff:\n                  {\n                      0,\n                -     2,\n                ?     ^\n                +     1,\n                ?     ^\n                  }\n            \"\"\",\n                id=\"sets\",\n            ),\n        ],\n    )\n    def test_iterable_full_diff(self, left, right, expected) -> None:\n        \"\"\"Test the full diff assertion failure explanation.\n\n        When verbose is False, then just a -v notice to get the diff is rendered,\n        when verbose is True, then ndiff of the pprint is returned.\n        \"\"\"\n        expl = callequal(left, right, verbose=0)\n        assert expl is not None\n        assert expl[-1] == \"Use -v to get more diff\"\n        verbose_expl = callequal(left, right, verbose=1)\n        assert verbose_expl is not None\n        assert \"\\n\".join(verbose_expl).endswith(textwrap.dedent(expected).strip())\n\n    def test_iterable_quiet(self) -> None:\n        expl = callequal([1, 2], [10, 2], verbose=-1)\n        assert expl == [\n            \"[1, 2] == [10, 2]\",\n            \"\",\n            \"At index 0 diff: 1 != 10\",\n            \"Use -v to get more diff\",\n        ]\n\n    def test_iterable_full_diff_ci(\n        self, monkeypatch: MonkeyPatch, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            r\"\"\"\n            def test_full_diff():\n                left = [0, 1]\n                right = [0, 2]\n                assert left == right\n        \"\"\"\n        )\n        monkeypatch.setenv(\"CI\", \"true\")\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"E         Full diff:\"])\n\n        # Setting CI to empty string is same as having it undefined\n        monkeypatch.setenv(\"CI\", \"\")\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"E         Use -v to get more diff\"])\n\n        monkeypatch.delenv(\"CI\", raising=False)\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"E         Use -v to get more diff\"])\n\n    def test_list_different_lengths(self) -> None:\n        expl = callequal([0, 1], [0, 1, 2])\n        assert expl is not None\n        assert len(expl) > 1\n        expl = callequal([0, 1, 2], [0, 1])\n        assert expl is not None\n        assert len(expl) > 1\n\n    def test_list_wrap_for_multiple_lines(self) -> None:\n        long_d = \"d\" * 80\n        l1 = [\"a\", \"b\", \"c\"]\n        l2 = [\"a\", \"b\", \"c\", long_d]\n        diff = callequal(l1, l2, verbose=True)\n        assert diff == [\n            \"['a', 'b', 'c'] == ['a', 'b', 'c...dddddddddddd']\",\n            \"\",\n            \"Right contains one more item: '\" + long_d + \"'\",\n            \"\",\n            \"Full diff:\",\n            \"  [\",\n            \"      'a',\",\n            \"      'b',\",\n            \"      'c',\",\n            \"-     '\" + long_d + \"',\",\n            \"  ]\",\n        ]\n\n        diff = callequal(l2, l1, verbose=True)\n        assert diff == [\n            \"['a', 'b', 'c...dddddddddddd'] == ['a', 'b', 'c']\",\n            \"\",\n            \"Left contains one more item: '\" + long_d + \"'\",\n            \"\",\n            \"Full diff:\",\n            \"  [\",\n            \"      'a',\",\n            \"      'b',\",\n            \"      'c',\",\n            \"+     '\" + long_d + \"',\",\n            \"  ]\",\n        ]\n\n    def test_list_wrap_for_width_rewrap_same_length(self) -> None:\n        long_a = \"a\" * 30\n        long_b = \"b\" * 30\n        long_c = \"c\" * 30\n        l1 = [long_a, long_b, long_c]\n        l2 = [long_b, long_c, long_a]\n        diff = callequal(l1, l2, verbose=True)\n        assert diff == [\n            \"['aaaaaaaaaaa...cccccccccccc'] == ['bbbbbbbbbbb...aaaaaaaaaaaa']\",\n            \"\",\n            \"At index 0 diff: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' != 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'\",\n            \"\",\n            \"Full diff:\",\n            \"  [\",\n            \"+     'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',\",\n            \"      'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',\",\n            \"      'cccccccccccccccccccccccccccccc',\",\n            \"-     'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',\",\n            \"  ]\",\n        ]\n\n    def test_list_dont_wrap_strings(self) -> None:\n        long_a = \"a\" * 10\n        l1 = [\"a\"] + [long_a for _ in range(7)]\n        l2 = [\"should not get wrapped\"]\n        diff = callequal(l1, l2, verbose=True)\n        assert diff == [\n            \"['a', 'aaaaaa...aaaaaaa', ...] == ['should not get wrapped']\",\n            \"\",\n            \"At index 0 diff: 'a' != 'should not get wrapped'\",\n            \"Left contains 7 more items, first extra item: 'aaaaaaaaaa'\",\n            \"\",\n            \"Full diff:\",\n            \"  [\",\n            \"-     'should not get wrapped',\",\n            \"+     'a',\",\n            \"+     'aaaaaaaaaa',\",\n            \"+     'aaaaaaaaaa',\",\n            \"+     'aaaaaaaaaa',\",\n            \"+     'aaaaaaaaaa',\",\n            \"+     'aaaaaaaaaa',\",\n            \"+     'aaaaaaaaaa',\",\n            \"+     'aaaaaaaaaa',\",\n            \"  ]\",\n        ]\n\n    def test_dict_wrap(self) -> None:\n        d1 = {\"common\": 1, \"env\": {\"env1\": 1, \"env2\": 2}}\n        d2 = {\"common\": 1, \"env\": {\"env1\": 1}}\n\n        diff = callequal(d1, d2, verbose=True)\n        assert diff == [\n            \"{'common': 1,...1, 'env2': 2}} == {'common': 1,...: {'env1': 1}}\",\n            \"\",\n            \"Omitting 1 identical items, use -vv to show\",\n            \"Differing items:\",\n            \"{'env': {'env1': 1, 'env2': 2}} != {'env': {'env1': 1}}\",\n            \"\",\n            \"Full diff:\",\n            \"  {\",\n            \"      'common': 1,\",\n            \"      'env': {\",\n            \"          'env1': 1,\",\n            \"+         'env2': 2,\",\n            \"      },\",\n            \"  }\",\n        ]\n\n        long_a = \"a\" * 80\n        sub = {\"long_a\": long_a, \"sub1\": {\"long_a\": \"substring that gets wrapped \" * 3}}\n        d1 = {\"env\": {\"sub\": sub}}\n        d2 = {\"env\": {\"sub\": sub}, \"new\": 1}\n        diff = callequal(d1, d2, verbose=True)\n        assert diff == [\n            \"{'env': {'sub... wrapped '}}}} == {'env': {'sub...}}}, 'new': 1}\",\n            \"\",\n            \"Omitting 1 identical items, use -vv to show\",\n            \"Right contains 1 more item:\",\n            \"{'new': 1}\",\n            \"\",\n            \"Full diff:\",\n            \"  {\",\n            \"      'env': {\",\n            \"          'sub': {\",\n            f\"              'long_a': '{long_a}',\",\n            \"              'sub1': {\",\n            \"                  'long_a': 'substring that gets wrapped substring that gets wrapped '\",\n            \"                  'substring that gets wrapped ',\",\n            \"              },\",\n            \"          },\",\n            \"      },\",\n            \"-     'new': 1,\",\n            \"  }\",\n        ]\n\n    def test_dict(self) -> None:\n        expl = callequal({\"a\": 0}, {\"a\": 1})\n        assert expl is not None\n        assert len(expl) > 1\n\n    def test_dict_omitting(self) -> None:\n        lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1})\n        assert lines is not None\n        assert lines[2].startswith(\"Omitting 1 identical item\")\n        assert \"Common items\" not in lines\n        for line in lines[1:]:\n            assert \"b\" not in line\n\n    def test_dict_omitting_with_verbosity_1(self) -> None:\n        \"\"\"Ensure differing items are visible for verbosity=1 (#1512).\"\"\"\n        lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1}, verbose=1)\n        assert lines is not None\n        assert lines[1] == \"\"\n        assert lines[2].startswith(\"Omitting 1 identical item\")\n        assert lines[3].startswith(\"Differing items\")\n        assert lines[4] == \"{'a': 0} != {'a': 1}\"\n        assert \"Common items\" not in lines\n\n    def test_dict_omitting_with_verbosity_2(self) -> None:\n        lines = callequal({\"a\": 0, \"b\": 1}, {\"a\": 1, \"b\": 1}, verbose=2)\n        assert lines is not None\n        assert lines[2].startswith(\"Common items:\")\n        assert \"Omitting\" not in lines[2]\n        assert lines[3] == \"{'b': 1}\"\n\n    def test_dict_different_items(self) -> None:\n        lines = callequal({\"a\": 0}, {\"b\": 1, \"c\": 2}, verbose=2)\n        assert lines == [\n            \"{'a': 0} == {'b': 1, 'c': 2}\",\n            \"\",\n            \"Left contains 1 more item:\",\n            \"{'a': 0}\",\n            \"Right contains 2 more items:\",\n            \"{'b': 1, 'c': 2}\",\n            \"\",\n            \"Full diff:\",\n            \"  {\",\n            \"-     'b': 1,\",\n            \"?      ^   ^\",\n            \"+     'a': 0,\",\n            \"?      ^   ^\",\n            \"-     'c': 2,\",\n            \"  }\",\n        ]\n        lines = callequal({\"b\": 1, \"c\": 2}, {\"a\": 0}, verbose=2)\n        assert lines == [\n            \"{'b': 1, 'c': 2} == {'a': 0}\",\n            \"\",\n            \"Left contains 2 more items:\",\n            \"{'b': 1, 'c': 2}\",\n            \"Right contains 1 more item:\",\n            \"{'a': 0}\",\n            \"\",\n            \"Full diff:\",\n            \"  {\",\n            \"-     'a': 0,\",\n            \"?      ^   ^\",\n            \"+     'b': 1,\",\n            \"?      ^   ^\",\n            \"+     'c': 2,\",\n            \"  }\",\n        ]\n\n    def test_sequence_different_items(self) -> None:\n        lines = callequal((1, 2), (3, 4, 5), verbose=2)\n        assert lines == [\n            \"(1, 2) == (3, 4, 5)\",\n            \"\",\n            \"At index 0 diff: 1 != 3\",\n            \"Right contains one more item: 5\",\n            \"\",\n            \"Full diff:\",\n            \"  (\",\n            \"-     3,\",\n            \"?     ^\",\n            \"+     1,\",\n            \"?     ^\",\n            \"-     4,\",\n            \"?     ^\",\n            \"+     2,\",\n            \"?     ^\",\n            \"-     5,\",\n            \"  )\",\n        ]\n        lines = callequal((1, 2, 3), (4,), verbose=2)\n        assert lines == [\n            \"(1, 2, 3) == (4,)\",\n            \"\",\n            \"At index 0 diff: 1 != 4\",\n            \"Left contains 2 more items, first extra item: 2\",\n            \"\",\n            \"Full diff:\",\n            \"  (\",\n            \"-     4,\",\n            \"?     ^\",\n            \"+     1,\",\n            \"?     ^\",\n            \"+     2,\",\n            \"+     3,\",\n            \"  )\",\n        ]\n        lines = callequal((1, 2, 3), (1, 20, 3), verbose=2)\n        assert lines == [\n            \"(1, 2, 3) == (1, 20, 3)\",\n            \"\",\n            \"At index 1 diff: 2 != 20\",\n            \"\",\n            \"Full diff:\",\n            \"  (\",\n            \"      1,\",\n            \"-     20,\",\n            \"?      -\",\n            \"+     2,\",\n            \"      3,\",\n            \"  )\",\n        ]\n\n    def test_set(self) -> None:\n        expl = callequal({0, 1}, {0, 2})\n        assert expl is not None\n        assert len(expl) > 1\n\n    def test_frozenzet(self) -> None:\n        expl = callequal(frozenset([0, 1]), {0, 2})\n        assert expl is not None\n        assert len(expl) > 1\n\n    def test_Sequence(self) -> None:\n        # Test comparing with a Sequence subclass.\n        class TestSequence(MutableSequence[int]):\n            def __init__(self, iterable):\n                self.elements = list(iterable)\n\n            def __getitem__(self, item):\n                return self.elements[item]\n\n            def __len__(self):\n                return len(self.elements)\n\n            def __setitem__(self, item, value):\n                pass\n\n            def __delitem__(self, item):\n                pass\n\n            def insert(self, index, value):\n                pass\n\n        expl = callequal(TestSequence([0, 1]), list([0, 2]))\n        assert expl is not None\n        assert len(expl) > 1\n\n    def test_list_tuples(self) -> None:\n        expl = callequal([], [(1, 2)])\n        assert expl is not None\n        assert len(expl) > 1\n        expl = callequal([(1, 2)], [])\n        assert expl is not None\n        assert len(expl) > 1\n\n    def test_list_bad_repr(self) -> None:\n        class A:\n            def __repr__(self):\n                raise ValueError(42)\n\n        expl = callequal([], [A()])\n        assert expl is not None\n        assert \"ValueError\" in \"\".join(expl)\n        expl = callequal({}, {\"1\": A()}, verbose=2)\n        assert expl is not None\n        assert expl[0].startswith(\"{} == <[ValueError\")\n        assert \"raised in repr\" in expl[0]\n        assert expl[2:] == [\n            \"(pytest_assertion plugin: representation of details failed:\"\n            f\" {__file__}:{A.__repr__.__code__.co_firstlineno + 1}: ValueError: 42.\",\n            \" Probably an object has a faulty __repr__.)\",\n        ]\n\n    def test_one_repr_empty(self) -> None:\n        \"\"\"The faulty empty string repr did trigger an unbound local error in _diff_text.\"\"\"\n\n        class A(str):\n            def __repr__(self):\n                return \"\"\n\n        expl = callequal(A(), \"\")\n        assert not expl\n\n    def test_repr_no_exc(self) -> None:\n        expl = callequal(\"foo\", \"bar\")\n        assert expl is not None\n        assert \"raised in repr()\" not in \" \".join(expl)\n\n    def test_unicode(self) -> None:\n        assert callequal(\"£€\", \"£\") == [\n            \"'£€' == '£'\",\n            \"\",\n            \"- £\",\n            \"+ £€\",\n        ]\n\n    def test_nonascii_text(self) -> None:\n        \"\"\"\n        :issue: 877\n        non ascii python2 str caused a UnicodeDecodeError\n        \"\"\"\n\n        class A(str):\n            def __repr__(self):\n                return \"\\xff\"\n\n        expl = callequal(A(), \"1\")\n        assert expl == [\"ÿ == '1'\", \"\", \"- 1\"]\n\n    def test_format_nonascii_explanation(self) -> None:\n        assert util.format_explanation(\"λ\")\n\n    def test_mojibake(self) -> None:\n        # issue 429\n        left = b\"e\"\n        right = b\"\\xc3\\xa9\"\n        expl = callequal(left, right)\n        assert expl is not None\n        for line in expl:\n            assert isinstance(line, str)\n        msg = \"\\n\".join(expl)\n        assert msg\n\n    def test_nfc_nfd_same_string(self) -> None:\n        # issue 3426\n        left = \"hyv\\xe4\"\n        right = \"hyva\\u0308\"\n        expl = callequal(left, right)\n        assert expl == [\n            r\"'hyv\\xe4' == 'hyva\\u0308'\",\n            \"\",\n            f\"- {right!s}\",\n            f\"+ {left!s}\",\n        ]\n\n        expl = callequal(left, right, verbose=2)\n        assert expl == [\n            r\"'hyv\\xe4' == 'hyva\\u0308'\",\n            \"\",\n            f\"- {right!s}\",\n            f\"+ {left!s}\",\n        ]\n\n\nclass TestAssert_reprcompare_dataclass:\n    def test_dataclasses(self, pytester: Pytester) -> None:\n        p = pytester.copy_example(\"dataclasses/test_compare_dataclasses.py\")\n        result = pytester.runpytest(p)\n        result.assert_outcomes(failed=1, passed=0)\n        result.stdout.fnmatch_lines(\n            [\n                \"E         Omitting 1 identical items, use -vv to show\",\n                \"E         Differing attributes:\",\n                \"E         ['field_b']\",\n                \"E         \",\n                \"E         Drill down into differing attribute field_b:\",\n                \"E           field_b: 'b' != 'c'\",\n                \"E           - c\",\n                \"E           + b\",\n            ],\n            consecutive=True,\n        )\n\n    def test_recursive_dataclasses(self, pytester: Pytester) -> None:\n        p = pytester.copy_example(\"dataclasses/test_compare_recursive_dataclasses.py\")\n        result = pytester.runpytest(p)\n        result.assert_outcomes(failed=1, passed=0)\n        result.stdout.fnmatch_lines(\n            [\n                \"E         Omitting 1 identical items, use -vv to show\",\n                \"E         Differing attributes:\",\n                \"E         ['g', 'h', 'j']\",\n                \"E         \",\n                \"E         Drill down into differing attribute g:\",\n                \"E           g: S(a=10, b='ten') != S(a=20, b='xxx')...\",\n                \"E         \",\n                \"E         ...Full output truncated (51 lines hidden), use '-vv' to show\",\n            ],\n            consecutive=True,\n        )\n\n    def test_recursive_dataclasses_verbose(self, pytester: Pytester) -> None:\n        p = pytester.copy_example(\"dataclasses/test_compare_recursive_dataclasses.py\")\n        result = pytester.runpytest(p, \"-vv\")\n        result.assert_outcomes(failed=1, passed=0)\n        result.stdout.fnmatch_lines(\n            [\n                \"E         Matching attributes:\",\n                \"E         ['i']\",\n                \"E         Differing attributes:\",\n                \"E         ['g', 'h', 'j']\",\n                \"E         \",\n                \"E         Drill down into differing attribute g:\",\n                \"E           g: S(a=10, b='ten') != S(a=20, b='xxx')\",\n                \"E           \",\n                \"E           Differing attributes:\",\n                \"E           ['a', 'b']\",\n                \"E           \",\n                \"E           Drill down into differing attribute a:\",\n                \"E             a: 10 != 20\",\n                \"E           \",\n                \"E           Drill down into differing attribute b:\",\n                \"E             b: 'ten' != 'xxx'\",\n                \"E             - xxx\",\n                \"E             + ten\",\n                \"E         \",\n                \"E         Drill down into differing attribute h:\",\n            ],\n            consecutive=True,\n        )\n\n    def test_dataclasses_verbose(self, pytester: Pytester) -> None:\n        p = pytester.copy_example(\"dataclasses/test_compare_dataclasses_verbose.py\")\n        result = pytester.runpytest(p, \"-vv\")\n        result.assert_outcomes(failed=1, passed=0)\n        result.stdout.fnmatch_lines(\n            [\n                \"*Matching attributes:*\",\n                \"*['field_a']*\",\n                \"*Differing attributes:*\",\n                \"*field_b: 'b' != 'c'*\",\n            ]\n        )\n\n    def test_dataclasses_with_attribute_comparison_off(\n        self, pytester: Pytester\n    ) -> None:\n        p = pytester.copy_example(\n            \"dataclasses/test_compare_dataclasses_field_comparison_off.py\"\n        )\n        result = pytester.runpytest(p, \"-vv\")\n        result.assert_outcomes(failed=0, passed=1)\n\n    def test_comparing_two_different_data_classes(self, pytester: Pytester) -> None:\n        p = pytester.copy_example(\n            \"dataclasses/test_compare_two_different_dataclasses.py\"\n        )\n        result = pytester.runpytest(p, \"-vv\")\n        result.assert_outcomes(failed=0, passed=1)\n\n    def test_data_classes_with_custom_eq(self, pytester: Pytester) -> None:\n        p = pytester.copy_example(\n            \"dataclasses/test_compare_dataclasses_with_custom_eq.py\"\n        )\n        # issue 9362\n        result = pytester.runpytest(p, \"-vv\")\n        result.assert_outcomes(failed=1, passed=0)\n        result.stdout.no_re_match_line(\".*Differing attributes.*\")\n\n    def test_data_classes_with_initvar(self, pytester: Pytester) -> None:\n        p = pytester.copy_example(\"dataclasses/test_compare_initvar.py\")\n        # issue 9820\n        result = pytester.runpytest(p, \"-vv\")\n        result.assert_outcomes(failed=1, passed=0)\n        result.stdout.no_re_match_line(\".*AttributeError.*\")\n\n\nclass TestAssert_reprcompare_attrsclass:\n    def test_attrs(self) -> None:\n        @attr.s\n        class SimpleDataObject:\n            field_a = attr.ib()\n            field_b = attr.ib()\n\n        left = SimpleDataObject(1, \"b\")\n        right = SimpleDataObject(1, \"c\")\n\n        lines = callequal(left, right)\n        assert lines is not None\n        assert lines[2].startswith(\"Omitting 1 identical item\")\n        assert \"Matching attributes\" not in lines\n        for line in lines[2:]:\n            assert \"field_a\" not in line\n\n    def test_attrs_recursive(self) -> None:\n        @attr.s\n        class OtherDataObject:\n            field_c = attr.ib()\n            field_d = attr.ib()\n\n        @attr.s\n        class SimpleDataObject:\n            field_a = attr.ib()\n            field_b = attr.ib()\n\n        left = SimpleDataObject(OtherDataObject(1, \"a\"), \"b\")\n        right = SimpleDataObject(OtherDataObject(1, \"b\"), \"b\")\n\n        lines = callequal(left, right)\n        assert lines is not None\n        assert \"Matching attributes\" not in lines\n        for line in lines[1:]:\n            assert \"field_b:\" not in line\n            assert \"field_c:\" not in line\n\n    def test_attrs_recursive_verbose(self) -> None:\n        @attr.s\n        class OtherDataObject:\n            field_c = attr.ib()\n            field_d = attr.ib()\n\n        @attr.s\n        class SimpleDataObject:\n            field_a = attr.ib()\n            field_b = attr.ib()\n\n        left = SimpleDataObject(OtherDataObject(1, \"a\"), \"b\")\n        right = SimpleDataObject(OtherDataObject(1, \"b\"), \"b\")\n\n        lines = callequal(left, right)\n        assert lines is not None\n        # indentation in output because of nested object structure\n        assert \"    field_d: 'a' != 'b'\" in lines\n\n    def test_attrs_verbose(self) -> None:\n        @attr.s\n        class SimpleDataObject:\n            field_a = attr.ib()\n            field_b = attr.ib()\n\n        left = SimpleDataObject(1, \"b\")\n        right = SimpleDataObject(1, \"c\")\n\n        lines = callequal(left, right, verbose=2)\n        assert lines is not None\n        assert lines[2].startswith(\"Matching attributes:\")\n        assert \"Omitting\" not in lines[2]\n        assert lines[3] == \"['field_a']\"\n\n    def test_attrs_with_attribute_comparison_off(self) -> None:\n        @attr.s\n        class SimpleDataObject:\n            field_a = attr.ib()\n            field_b = attr.ib(eq=False)\n\n        left = SimpleDataObject(1, \"b\")\n        right = SimpleDataObject(1, \"b\")\n\n        lines = callequal(left, right, verbose=2)\n        assert lines is not None\n        assert lines[2].startswith(\"Matching attributes:\")\n        assert \"Omitting\" not in lines[1]\n        assert lines[3] == \"['field_a']\"\n        for line in lines[3:]:\n            assert \"field_b\" not in line\n\n    def test_comparing_two_different_attrs_classes(self) -> None:\n        @attr.s\n        class SimpleDataObjectOne:\n            field_a = attr.ib()\n            field_b = attr.ib()\n\n        @attr.s\n        class SimpleDataObjectTwo:\n            field_a = attr.ib()\n            field_b = attr.ib()\n\n        left = SimpleDataObjectOne(1, \"b\")\n        right = SimpleDataObjectTwo(1, \"c\")\n\n        lines = callequal(left, right)\n        assert lines is None\n\n    def test_attrs_with_auto_detect_and_custom_eq(self) -> None:\n        @attr.s(\n            auto_detect=True\n        )  # attr.s doesn't ignore a custom eq if auto_detect=True\n        class SimpleDataObject:\n            field_a = attr.ib()\n\n            def __eq__(self, other):  # pragma: no cover\n                return super().__eq__(other)\n\n        left = SimpleDataObject(1)\n        right = SimpleDataObject(2)\n        # issue 9362\n        lines = callequal(left, right, verbose=2)\n        assert lines is None\n\n    def test_attrs_with_custom_eq(self) -> None:\n        @attr.define(slots=False)\n        class SimpleDataObject:\n            field_a = attr.ib()\n\n            def __eq__(self, other):  # pragma: no cover\n                return super().__eq__(other)\n\n        left = SimpleDataObject(1)\n        right = SimpleDataObject(2)\n        # issue 9362\n        lines = callequal(left, right, verbose=2)\n        assert lines is None\n\n\nclass TestAssert_reprcompare_namedtuple:\n    def test_namedtuple(self) -> None:\n        class NT(NamedTuple):\n            a: Any\n            b: Any\n\n        left = NT(1, \"b\")\n        right = NT(1, \"c\")\n\n        lines = callequal(left, right)\n        assert lines == [\n            \"NT(a=1, b='b') == NT(a=1, b='c')\",\n            \"\",\n            \"Omitting 1 identical items, use -vv to show\",\n            \"Differing attributes:\",\n            \"['b']\",\n            \"\",\n            \"Drill down into differing attribute b:\",\n            \"  b: 'b' != 'c'\",\n            \"  - c\",\n            \"  + b\",\n            \"Use -v to get more diff\",\n        ]\n\n    def test_comparing_two_different_namedtuple(self) -> None:\n        class NT1(NamedTuple):\n            a: Any\n            b: Any\n\n        class NT2(NamedTuple):\n            a: Any\n            b: Any\n\n        left = NT1(1, \"b\")\n        right = NT2(2, \"b\")\n\n        lines = callequal(left, right)\n        # Because the types are different, uses the generic sequence matcher.\n        assert lines == [\n            \"NT1(a=1, b='b') == NT2(a=2, b='b')\",\n            \"\",\n            \"At index 0 diff: 1 != 2\",\n            \"Use -v to get more diff\",\n        ]\n\n\nclass TestFormatExplanation:\n    def test_special_chars_full(self, pytester: Pytester) -> None:\n        # Issue 453, for the bug this would raise IndexError\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert '\\\\n}' == ''\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines([\"*AssertionError*\"])\n\n    def test_fmt_simple(self) -> None:\n        expl = \"assert foo\"\n        assert util.format_explanation(expl) == \"assert foo\"\n\n    def test_fmt_where(self) -> None:\n        expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"} == 2\"])\n        res = \"\\n\".join([\"assert 1 == 2\", \" +  where 1 = foo\"])\n        assert util.format_explanation(expl) == res\n\n    def test_fmt_and(self) -> None:\n        expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"} == 2\", \"{2 = bar\", \"}\"])\n        res = \"\\n\".join([\"assert 1 == 2\", \" +  where 1 = foo\", \" +  and   2 = bar\"])\n        assert util.format_explanation(expl) == res\n\n    def test_fmt_where_nested(self) -> None:\n        expl = \"\\n\".join([\"assert 1\", \"{1 = foo\", \"{foo = bar\", \"}\", \"} == 2\"])\n        res = \"\\n\".join([\"assert 1 == 2\", \" +  where 1 = foo\", \" +    where foo = bar\"])\n        assert util.format_explanation(expl) == res\n\n    def test_fmt_newline(self) -> None:\n        expl = \"\\n\".join(['assert \"foo\" == \"bar\"', \"~- foo\", \"~+ bar\"])\n        res = \"\\n\".join(['assert \"foo\" == \"bar\"', \"  - foo\", \"  + bar\"])\n        assert util.format_explanation(expl) == res\n\n    def test_fmt_newline_escaped(self) -> None:\n        expl = \"\\n\".join([\"assert foo == bar\", \"baz\"])\n        res = \"assert foo == bar\\\\nbaz\"\n        assert util.format_explanation(expl) == res\n\n    def test_fmt_newline_before_where(self) -> None:\n        expl = \"\\n\".join(\n            [\n                \"the assertion message here\",\n                \">assert 1\",\n                \"{1 = foo\",\n                \"} == 2\",\n                \"{2 = bar\",\n                \"}\",\n            ]\n        )\n        res = \"\\n\".join(\n            [\n                \"the assertion message here\",\n                \"assert 1 == 2\",\n                \" +  where 1 = foo\",\n                \" +  and   2 = bar\",\n            ]\n        )\n        assert util.format_explanation(expl) == res\n\n    def test_fmt_multi_newline_before_where(self) -> None:\n        expl = \"\\n\".join(\n            [\n                \"the assertion\",\n                \"~message here\",\n                \">assert 1\",\n                \"{1 = foo\",\n                \"} == 2\",\n                \"{2 = bar\",\n                \"}\",\n            ]\n        )\n        res = \"\\n\".join(\n            [\n                \"the assertion\",\n                \"  message here\",\n                \"assert 1 == 2\",\n                \" +  where 1 = foo\",\n                \" +  and   2 = bar\",\n            ]\n        )\n        assert util.format_explanation(expl) == res\n\n\nclass TestTruncateExplanation:\n    # The number of lines in the truncation explanation message. Used\n    # to calculate that results have the expected length.\n    LINES_IN_TRUNCATION_MSG = 2\n\n    def test_doesnt_truncate_when_input_is_empty_list(self) -> None:\n        expl: list[str] = []\n        result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n        assert result == expl\n\n    def test_doesnt_truncate_at_when_input_is_5_lines_and_LT_max_chars(self) -> None:\n        expl = [\"a\" * 100 for x in range(5)]\n        result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n        assert result == expl\n\n    def test_truncates_at_8_lines_when_given_list_of_empty_strings(self) -> None:\n        expl = [\"\" for x in range(50)]\n        result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n        assert len(result) != len(expl)\n        assert result != expl\n        assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n        assert \"Full output truncated\" in result[-1]\n        assert \"42 lines hidden\" in result[-1]\n        last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n        assert last_line_before_trunc_msg.endswith(\"...\")\n\n    def test_truncates_at_8_lines_when_first_8_lines_are_LT_max_chars(self) -> None:\n        total_lines = 100\n        expl = [\"a\" for x in range(total_lines)]\n        result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n        assert result != expl\n        assert len(result) == 8 + self.LINES_IN_TRUNCATION_MSG\n        assert \"Full output truncated\" in result[-1]\n        assert f\"{total_lines - 8} lines hidden\" in result[-1]\n        last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n        assert last_line_before_trunc_msg.endswith(\"...\")\n\n    def test_truncates_at_8_lines_when_there_is_one_line_to_remove(self) -> None:\n        \"\"\"The number of line in the result is 9, the same number as if we truncated.\"\"\"\n        expl = [\"a\" for x in range(9)]\n        result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n        assert result == expl\n        assert \"truncated\" not in result[-1]\n\n    def test_truncates_full_line_because_of_max_chars(self) -> None:\n        \"\"\"A line is fully truncated because of the max_chars value.\"\"\"\n        expl = [\"a\" * 10, \"b\" * 71]\n        result = truncate._truncate_explanation(expl, max_lines=10, max_chars=10)\n        assert result == [\n            \"a\" * 10,\n            \"...\",\n            \"\",\n            \"...Full output truncated (1 line hidden), use '-vv' to show\",\n        ]\n\n    def test_truncates_edgecase_when_truncation_message_makes_the_result_longer_for_chars(\n        self,\n    ) -> None:\n        line = \"a\" * 10\n        expl = [line, line]\n        result = truncate._truncate_explanation(expl, max_lines=10, max_chars=10)\n        assert result == [line, line]\n\n    def test_truncates_edgecase_when_truncation_message_makes_the_result_longer_for_lines(\n        self,\n    ) -> None:\n        line = \"a\" * 10\n        expl = [line, line]\n        result = truncate._truncate_explanation(expl, max_lines=1, max_chars=100)\n        assert result == [line, line]\n\n    def test_truncates_at_8_lines_when_first_8_lines_are_EQ_max_chars(self) -> None:\n        expl = [chr(97 + x) * 80 for x in range(16)]\n        result = truncate._truncate_explanation(expl, max_lines=8, max_chars=8 * 80)\n        assert result != expl\n        assert len(result) == 16 - 8 + self.LINES_IN_TRUNCATION_MSG\n        assert \"Full output truncated\" in result[-1]\n        assert \"8 lines hidden\" in result[-1]\n        last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n        assert last_line_before_trunc_msg.endswith(\"...\")\n\n    def test_truncates_at_4_lines_when_first_4_lines_are_GT_max_chars(self) -> None:\n        expl = [\"a\" * 250 for x in range(10)]\n        result = truncate._truncate_explanation(expl, max_lines=8, max_chars=999)\n        assert result != expl\n        assert len(result) == 4 + self.LINES_IN_TRUNCATION_MSG\n        assert \"Full output truncated\" in result[-1]\n        assert \"7 lines hidden\" in result[-1]\n        last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n        assert last_line_before_trunc_msg.endswith(\"...\")\n\n    def test_truncates_at_1_line_when_first_line_is_GT_max_chars(self) -> None:\n        expl = [\"a\" * 250 for x in range(1000)]\n        result = truncate._truncate_explanation(expl, max_lines=8, max_chars=100)\n        assert result != expl\n        assert len(result) == 1 + self.LINES_IN_TRUNCATION_MSG\n        assert \"Full output truncated\" in result[-1]\n        assert \"1000 lines hidden\" in result[-1]\n        last_line_before_trunc_msg = result[-self.LINES_IN_TRUNCATION_MSG - 1]\n        assert last_line_before_trunc_msg.endswith(\"...\")\n\n    def test_full_output_truncated(self, monkeypatch, pytester: Pytester) -> None:\n        \"\"\"Test against full runpytest() output.\"\"\"\n        line_count = 7\n        line_len = 100\n        expected_truncated_lines = 2\n        pytester.makepyfile(\n            rf\"\"\"\n            def test_many_lines():\n                a = list([str(i)[0] * {line_len} for i in range({line_count})])\n                b = a[::2]\n                a = '\\n'.join(map(str, a))\n                b = '\\n'.join(map(str, b))\n                assert a == b\n        \"\"\"\n        )\n        monkeypatch.delenv(\"CI\", raising=False)\n\n        result = pytester.runpytest()\n        # without -vv, truncate the message showing a few diff lines only\n        result.stdout.fnmatch_lines(\n            [\n                \"*+ 1*\",\n                \"*+ 3*\",\n                f\"*truncated ({expected_truncated_lines} lines hidden)*use*-vv*\",\n            ]\n        )\n\n        result = pytester.runpytest(\"-vv\")\n        result.stdout.fnmatch_lines([\"* 6*\"])\n\n        # Setting CI to empty string is same as having it undefined\n        monkeypatch.setenv(\"CI\", \"\")\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*+ 1*\",\n                \"*+ 3*\",\n                f\"*truncated ({expected_truncated_lines} lines hidden)*use*-vv*\",\n            ]\n        )\n\n        monkeypatch.setenv(\"CI\", \"1\")\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 6*\"])\n\n    @pytest.mark.parametrize(\n        [\"truncation_lines\", \"truncation_chars\", \"expected_lines_hidden\"],\n        (\n            (3, None, 3),\n            (4, None, 0),\n            (0, None, 0),\n            (None, 8, 6),\n            (None, 9, 0),\n            (None, 0, 0),\n            (0, 0, 0),\n            (0, 1000, 0),\n            (1000, 0, 0),\n        ),\n    )\n    def test_truncation_with_ini(\n        self,\n        monkeypatch,\n        pytester: Pytester,\n        truncation_lines: int | None,\n        truncation_chars: int | None,\n        expected_lines_hidden: int,\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n            string_a = \"123456789\\\\n23456789\\\\n3\"\n            string_b = \"123456789\\\\n23456789\\\\n4\"\n\n            def test():\n                assert string_a == string_b\n            \"\"\"\n        )\n\n        # This test produces 6 lines of diff output or 79 characters\n        # So the effect should be when threshold is < 4 lines (considering 2 additional lines for explanation)\n        # Or < 9 characters (considering 70 additional characters for explanation)\n\n        monkeypatch.delenv(\"CI\", raising=False)\n\n        ini = \"[pytest]\\n\"\n        if truncation_lines is not None:\n            ini += f\"truncation_limit_lines = {truncation_lines}\\n\"\n        if truncation_chars is not None:\n            ini += f\"truncation_limit_chars = {truncation_chars}\\n\"\n        pytester.makeini(ini)\n\n        result = pytester.runpytest()\n\n        if expected_lines_hidden != 0:\n            result.stdout.fnmatch_lines(\n                [f\"*truncated ({expected_lines_hidden} lines hidden)*\"]\n            )\n        else:\n            result.stdout.no_fnmatch_line(\"*truncated*\")\n            result.stdout.fnmatch_lines(\n                [\n                    \"*- 4*\",\n                    \"*+ 3*\",\n                ]\n            )\n\n\ndef test_python25_compile_issue257(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_rewritten():\n            assert 1 == 2\n        # some comment\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 1\n    result.stdout.fnmatch_lines(\n        \"\"\"\n            *E*assert 1 == 2*\n            *1 failed*\n    \"\"\"\n    )\n\n\ndef test_rewritten(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_rewritten():\n            assert \"@py_builtins\" in globals()\n    \"\"\"\n    )\n    assert pytester.runpytest().ret == 0\n\n\ndef test_reprcompare_notin() -> None:\n    assert callop(\"not in\", \"foo\", \"aaafoobbb\") == [\n        \"'foo' not in 'aaafoobbb'\",\n        \"\",\n        \"'foo' is contained here:\",\n        \"  aaafoobbb\",\n        \"?    +++\",\n    ]\n\n\ndef test_reprcompare_whitespaces() -> None:\n    assert callequal(\"\\r\\n\", \"\\n\") == [\n        r\"'\\r\\n' == '\\n'\",\n        \"\",\n        r\"Strings contain only whitespace, escaping them using repr()\",\n        r\"- '\\n'\",\n        r\"+ '\\r\\n'\",\n        r\"?  ++\",\n    ]\n\n\nclass TestSetAssertions:\n    @pytest.mark.parametrize(\"op\", [\">=\", \">\", \"<=\", \"<\", \"==\"])\n    def test_set_extra_item(self, op, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            f\"\"\"\n            def test_hello():\n                x = set(\"hello x\")\n                y = set(\"hello y\")\n                assert x {op} y\n        \"\"\"\n        )\n\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*def test_hello():*\",\n                f\"*assert x {op} y*\",\n            ]\n        )\n        if op in [\">=\", \">\", \"==\"]:\n            result.stdout.fnmatch_lines(\n                [\n                    \"*E*Extra items in the right set:*\",\n                    \"*E*'y'\",\n                ]\n            )\n        if op in [\"<=\", \"<\", \"==\"]:\n            result.stdout.fnmatch_lines(\n                [\n                    \"*E*Extra items in the left set:*\",\n                    \"*E*'x'\",\n                ]\n            )\n\n    @pytest.mark.parametrize(\"op\", [\">\", \"<\", \"!=\"])\n    def test_set_proper_superset_equal(self, pytester: Pytester, op) -> None:\n        pytester.makepyfile(\n            f\"\"\"\n            def test_hello():\n                x = set([1, 2, 3])\n                y = x.copy()\n                assert x {op} y\n        \"\"\"\n        )\n\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*def test_hello():*\",\n                f\"*assert x {op} y*\",\n                \"*E*Both sets are equal*\",\n            ]\n        )\n\n    def test_pytest_assertrepr_compare_integration(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_hello():\n                x = set(range(100))\n                y = x.copy()\n                y.remove(50)\n                assert x == y\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*def test_hello():*\",\n                \"*assert x == y*\",\n                \"*E*Extra items*left*\",\n                \"*E*50*\",\n                \"*= 1 failed in*\",\n            ]\n        )\n\n\ndef test_assertrepr_loaded_per_dir(pytester: Pytester) -> None:\n    pytester.makepyfile(test_base=[\"def test_base(): assert 1 == 2\"])\n    a = pytester.mkdir(\"a\")\n    a.joinpath(\"test_a.py\").write_text(\"def test_a(): assert 1 == 2\", encoding=\"utf-8\")\n    a.joinpath(\"conftest.py\").write_text(\n        'def pytest_assertrepr_compare(): return [\"summary a\"]', encoding=\"utf-8\"\n    )\n    b = pytester.mkdir(\"b\")\n    b.joinpath(\"test_b.py\").write_text(\"def test_b(): assert 1 == 2\", encoding=\"utf-8\")\n    b.joinpath(\"conftest.py\").write_text(\n        'def pytest_assertrepr_compare(): return [\"summary b\"]', encoding=\"utf-8\"\n    )\n\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"*def test_a():*\",\n            \"*E*assert summary a*\",\n            \"*def test_b():*\",\n            \"*E*assert summary b*\",\n            \"*def test_base():*\",\n            \"*E*assert 1 == 2*\",\n        ]\n    )\n\n\ndef test_assertion_options(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_hello():\n            x = 3\n            assert x == 4\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert \"3 == 4\" in result.stdout.str()\n    result = pytester.runpytest_subprocess(\"--assert=plain\")\n    result.stdout.no_fnmatch_line(\"*3 == 4*\")\n\n\ndef test_triple_quoted_string_issue113(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_hello():\n            assert \"\" == '''\n    '''\"\"\"\n    )\n    result = pytester.runpytest(\"--fulltrace\")\n    result.stdout.fnmatch_lines([\"*1 failed*\"])\n    result.stdout.no_fnmatch_line(\"*SyntaxError*\")\n\n\ndef test_traceback_failure(pytester: Pytester) -> None:\n    p1 = pytester.makepyfile(\n        \"\"\"\n        def g():\n            return 2\n        def f(x):\n            assert x == g()\n        def test_onefails():\n            f(3)\n    \"\"\"\n    )\n    result = pytester.runpytest(p1, \"--tb=long\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*test_traceback_failure.py F*\",\n            \"====* FAILURES *====\",\n            \"____*____\",\n            \"\",\n            \"    def test_onefails():\",\n            \">       f(3)\",\n            \"\",\n            \"*test_*.py:6: \",\n            \"_ _ _ *\",\n            # \"\",\n            \"    def f(x):\",\n            \">       assert x == g()\",\n            \"E       assert 3 == 2\",\n            \"E        +  where 2 = g()\",\n            \"\",\n            \"*test_traceback_failure.py:4: AssertionError\",\n        ]\n    )\n\n    result = pytester.runpytest(p1)  # \"auto\"\n    result.stdout.fnmatch_lines(\n        [\n            \"*test_traceback_failure.py F*\",\n            \"====* FAILURES *====\",\n            \"____*____\",\n            \"\",\n            \"    def test_onefails():\",\n            \">       f(3)\",\n            \"\",\n            \"*test_*.py:6: \",\n            \"\",\n            \"    def f(x):\",\n            \">       assert x == g()\",\n            \"E       assert 3 == 2\",\n            \"E        +  where 2 = g()\",\n            \"\",\n            \"*test_traceback_failure.py:4: AssertionError\",\n        ]\n    )\n\n\ndef test_exception_handling_no_traceback(pytester: Pytester) -> None:\n    \"\"\"Handle chain exceptions in tasks submitted by the multiprocess module (#1984).\"\"\"\n    p1 = pytester.makepyfile(\n        \"\"\"\n        from multiprocessing import Pool\n\n        def process_task(n):\n            assert n == 10\n\n        def multitask_job():\n            tasks = [1]\n            with Pool(processes=1) as pool:\n                pool.map(process_task, tasks)\n\n        def test_multitask_job():\n            multitask_job()\n    \"\"\"\n    )\n    pytester.syspathinsert()\n    result = pytester.runpytest(p1, \"--tb=long\")\n    result.stdout.fnmatch_lines(\n        [\n            \"====* FAILURES *====\",\n            \"*multiprocessing.pool.RemoteTraceback:*\",\n            \"Traceback (most recent call last):\",\n            \"*assert n == 10\",\n            \"The above exception was the direct cause of the following exception:\",\n            \"> * multitask_job()\",\n        ]\n    )\n\n\n@pytest.mark.skipif(\"'__pypy__' in sys.builtin_module_names\")\n@pytest.mark.parametrize(\n    \"cmdline_args, warning_output\",\n    [\n        (\n            [\"-OO\", \"-m\", \"pytest\", \"-h\"],\n            [\"warning :*PytestConfigWarning:*assert statements are not executed*\"],\n        ),\n        (\n            [\"-OO\", \"-m\", \"pytest\"],\n            [\n                \"=*= warnings summary =*=\",\n                \"*PytestConfigWarning:*assert statements are not executed*\",\n            ],\n        ),\n        (\n            [\"-OO\", \"-m\", \"pytest\", \"--assert=plain\"],\n            [\n                \"=*= warnings summary =*=\",\n                \"*PytestConfigWarning: ASSERTIONS ARE NOT EXECUTED and FAILING TESTS WILL PASS.  \"\n                \"Are you using python -O?\",\n            ],\n        ),\n    ],\n)\ndef test_warn_missing(pytester: Pytester, cmdline_args, warning_output) -> None:\n    pytester.makepyfile(\"\")\n\n    result = pytester.run(sys.executable, *cmdline_args)\n    result.stdout.fnmatch_lines(warning_output)\n\n\ndef test_recursion_source_decode(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_something():\n            pass\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        python_files = *.py\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--collect-only\")\n    result.stdout.fnmatch_lines(\n        [\n            \"  <Module*>\",\n        ]\n    )\n\n\ndef test_AssertionError_message(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_hello():\n            x,y = 1,2\n            assert 0, (x,y)\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        *def test_hello*\n        *assert 0, (x,y)*\n        *AssertionError: (1, 2)*\n    \"\"\"\n    )\n\n\ndef test_diff_newline_at_end(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        r\"\"\"\n        def test_diff():\n            assert 'asdf' == 'asdf\\n'\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        r\"\"\"\n        *assert 'asdf' == 'asdf\\n'\n        *  - asdf\n        *  ?     -\n        *  + asdf\n    \"\"\"\n    )\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_assert_tuple_warning(pytester: Pytester) -> None:\n    msg = \"assertion is always true\"\n    pytester.makepyfile(\n        \"\"\"\n        def test_tuple():\n            assert(False, 'you shall not pass')\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([f\"*test_assert_tuple_warning.py:2:*{msg}*\"])\n\n    # tuples with size != 2 should not trigger the warning\n    pytester.makepyfile(\n        \"\"\"\n        def test_tuple():\n            assert ()\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert msg not in result.stdout.str()\n\n\ndef test_assert_indirect_tuple_no_warning(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_tuple():\n            tpl = ('foo', 'bar')\n            assert tpl\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    output = \"\\n\".join(result.stdout.lines)\n    assert \"WR1\" not in output\n\n\ndef test_assert_with_unicode(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\\\n        def test_unicode():\n            assert '유니코드' == 'Unicode'\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*AssertionError*\"])\n\n\ndef test_raise_unprintable_assertion_error(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        r\"\"\"\n        def test_raise_assertion_error():\n            raise AssertionError('\\xff')\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [r\">       raise AssertionError('\\xff')\", \"E       AssertionError: *\"]\n    )\n\n\ndef test_raise_assertion_error_raising_repr(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        class RaisingRepr(object):\n            def __repr__(self):\n                raise Exception()\n        def test_raising_repr():\n            raise AssertionError(RaisingRepr())\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"E       AssertionError: <exception str() failed>\"])\n\n\ndef test_issue_1944(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def f():\n            return\n\n        assert f() == 10\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*1 error*\"])\n    assert (\n        \"AttributeError: 'Module' object has no attribute '_obj'\"\n        not in result.stdout.str()\n    )\n\n\ndef test_exit_from_assertrepr_compare(monkeypatch) -> None:\n    def raise_exit(obj):\n        outcomes.exit(\"Quitting debugger\")\n\n    monkeypatch.setattr(util, \"istext\", raise_exit)\n\n    with pytest.raises(outcomes.Exit, match=\"Quitting debugger\"):\n        callequal(1, 1)\n\n\ndef test_assertion_location_with_coverage(pytester: Pytester) -> None:\n    \"\"\"This used to report the wrong location when run with coverage (#5754).\"\"\"\n    p = pytester.makepyfile(\n        \"\"\"\n        def test():\n            assert False, 1\n            assert False, 2\n        \"\"\"\n    )\n    result = pytester.runpytest(str(p))\n    result.stdout.fnmatch_lines(\n        [\n            \">       assert False, 1\",\n            \"E       AssertionError: 1\",\n            \"E       assert False\",\n            \"*= 1 failed in*\",\n        ]\n    )\n\n\ndef test_reprcompare_verbose_long() -> None:\n    a = {f\"v{i}\": i for i in range(11)}\n    b = a.copy()\n    b[\"v2\"] += 10\n    lines = callop(\"==\", a, b, verbose=2)\n    assert lines is not None\n    assert lines[0] == (\n        \"{'v0': 0, 'v1': 1, 'v2': 2, 'v3': 3, 'v4': 4, 'v5': 5, \"\n        \"'v6': 6, 'v7': 7, 'v8': 8, 'v9': 9, 'v10': 10}\"\n        \" == \"\n        \"{'v0': 0, 'v1': 1, 'v2': 12, 'v3': 3, 'v4': 4, 'v5': 5, \"\n        \"'v6': 6, 'v7': 7, 'v8': 8, 'v9': 9, 'v10': 10}\"\n    )\n\n\n@pytest.mark.parametrize(\"enable_colors\", [True, False])\n@pytest.mark.parametrize(\n    (\"test_code\", \"expected_lines\"),\n    (\n        (\n            \"\"\"\n            def test():\n                assert [0, 1] == [0, 2]\n            \"\"\",\n            [\n                \"{bold}{red}E         At index 1 diff: {reset}{number}1{hl-reset}{endline} != {reset}{number}2*\",\n                \"{bold}{red}E         {light-red}-     2,{hl-reset}{endline}{reset}\",\n                \"{bold}{red}E         {light-green}+     1,{hl-reset}{endline}{reset}\",\n            ],\n        ),\n        (\n            \"\"\"\n            def test():\n                assert {f\"number-is-{i}\": i for i in range(1, 6)} == {\n                    f\"number-is-{i}\": i for i in range(5)\n                }\n            \"\"\",\n            [\n                \"{bold}{red}E         Common items:{reset}\",\n                \"{bold}{red}E         {reset}{{{str}'{hl-reset}{str}number-is-1{hl-reset}{str}'{hl-reset}: {number}1*\",\n                \"{bold}{red}E         Left contains 1 more item:{reset}\",\n                \"{bold}{red}E         {reset}{{{str}'{hl-reset}{str}number-is-5{hl-reset}{str}'{hl-reset}: {number}5*\",\n                \"{bold}{red}E         Right contains 1 more item:{reset}\",\n                \"{bold}{red}E         {reset}{{{str}'{hl-reset}{str}number-is-0{hl-reset}{str}'{hl-reset}: {number}0*\",\n                \"{bold}{red}E         {reset}{light-gray} {hl-reset} {{{endline}{reset}\",\n                \"{bold}{red}E         {light-gray} {hl-reset}     'number-is-1': 1,{endline}{reset}\",\n                \"{bold}{red}E         {light-green}+     'number-is-5': 5,{hl-reset}{endline}{reset}\",\n            ],\n        ),\n        (\n            \"\"\"\n            def test():\n                assert \"abcd\" == \"abce\"\n            \"\"\",\n            [\n                \"{bold}{red}E         {reset}{light-red}- abce{hl-reset}{endline}{reset}\",\n                \"{bold}{red}E         {light-green}+ abcd{hl-reset}{endline}{reset}\",\n            ],\n        ),\n    ),\n)\ndef test_comparisons_handle_colors(\n    pytester: Pytester, color_mapping, enable_colors, test_code, expected_lines\n) -> None:\n    p = pytester.makepyfile(test_code)\n    result = pytester.runpytest(\n        f\"--color={'yes' if enable_colors else 'no'}\", \"-vv\", str(p)\n    )\n    formatter = (\n        color_mapping.format_for_fnmatch\n        if enable_colors\n        else color_mapping.strip_colors\n    )\n\n    result.stdout.fnmatch_lines(formatter(expected_lines), consecutive=False)\n\n\ndef test_fine_grained_assertion_verbosity(pytester: Pytester):\n    long_text = \"Lorem ipsum dolor sit amet \" * 10\n    p = pytester.makepyfile(\n        f\"\"\"\n        def test_ok():\n            pass\n\n\n        def test_words_fail():\n            fruits1 = [\"banana\", \"apple\", \"grapes\", \"melon\", \"kiwi\"]\n            fruits2 = [\"banana\", \"apple\", \"orange\", \"melon\", \"kiwi\"]\n            assert fruits1 == fruits2\n\n\n        def test_numbers_fail():\n            number_to_text1 = {{str(x): x for x in range(5)}}\n            number_to_text2 = {{str(x * 10): x * 10 for x in range(5)}}\n            assert number_to_text1 == number_to_text2\n\n\n        def test_long_text_fail():\n            long_text = \"{long_text}\"\n            assert \"hello world\" in long_text\n        \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        verbosity_assertions = 2\n        \"\"\"\n    )\n    result = pytester.runpytest(p)\n\n    result.stdout.fnmatch_lines(\n        [\n            f\"{p.name} .FFF                            [100%]\",\n            \"E         At index 2 diff: 'grapes' != 'orange'\",\n            \"E         Full diff:\",\n            \"E           [\",\n            \"E               'banana',\",\n            \"E               'apple',\",\n            \"E         -     'orange',\",\n            \"E         ?      ^  ^^\",\n            \"E         +     'grapes',\",\n            \"E         ?      ^  ^ +\",\n            \"E               'melon',\",\n            \"E               'kiwi',\",\n            \"E           ]\",\n            \"E         Full diff:\",\n            \"E           {\",\n            \"E               '0': 0,\",\n            \"E         -     '10': 10,\",\n            \"E         ?       -    -\",\n            \"E         +     '1': 1,\",\n            \"E         -     '20': 20,\",\n            \"E         ?       -    -\",\n            \"E         +     '2': 2,\",\n            \"E         -     '30': 30,\",\n            \"E         ?       -    -\",\n            \"E         +     '3': 3,\",\n            \"E         -     '40': 40,\",\n            \"E         ?       -    -\",\n            \"E         +     '4': 4,\",\n            \"E           }\",\n            f\"E       AssertionError: assert 'hello world' in '{long_text}'\",\n        ]\n    )\n\n\ndef test_full_output_vvv(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        r\"\"\"\n        def crash_helper(m):\n            assert 1 == 2\n        def test_vvv():\n            crash_helper(500 * \"a\")\n    \"\"\"\n    )\n    result = pytester.runpytest(\"\")\n    # without -vvv, the passed args are truncated\n    expected_non_vvv_arg_line = \"m = 'aaaaaaaaaaaaaaa*..aaaaaaaaaaaa*\"\n    result.stdout.fnmatch_lines(\n        [\n            expected_non_vvv_arg_line,\n            \"test_full_output_vvv.py:2: AssertionError\",\n        ],\n    )\n    # double check that the untruncated part is not in the output\n    expected_vvv_arg_line = \"m = '{}'\".format(500 * \"a\")\n    result.stdout.no_fnmatch_line(expected_vvv_arg_line)\n\n    # but with \"-vvv\" the args are not truncated\n    result = pytester.runpytest(\"-vvv\")\n    result.stdout.fnmatch_lines(\n        [\n            expected_vvv_arg_line,\n            \"test_full_output_vvv.py:2: AssertionError\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(expected_non_vvv_arg_line)\n\n\ndef test_dict_extra_items_preserve_insertion_order(pytester: Pytester) -> None:\n    \"\"\"Assertion output of dict diff shows keys in insertion order (#13503).\"\"\"\n    pytester.makepyfile(\n        test_order=\"\"\"\n        def test_order():\n            a = {\n                \"b\": 2,\n                \"a\": 1,\n                \"d\": 4,\n                \"e\": 5,\n                \"c\": 3,\n            }\n            assert a == {}\n        \"\"\"\n    )\n\n    result = pytester.runpytest(\"-vv\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*Left contains 5 more items:*\",\n            \"*Full diff:\",\n            \"* + *'b': 2,\",\n            \"* + *'a': 1,\",\n            \"* + *'d': 4,\",\n            \"* + *'e': 5,\",\n            \"* + *'c': 3,\",\n            \"test_order.py:*: AssertionError\",\n        ]\n    )\n"
  },
  {
    "path": "testing/test_assertrewrite.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport ast\nfrom collections.abc import Generator\nfrom collections.abc import Mapping\nimport dis\nimport errno\nfrom functools import partial\nimport glob\nimport importlib\nimport inspect\nimport marshal\nimport os\nfrom pathlib import Path\nimport py_compile\nimport re\nimport stat\nimport sys\nimport textwrap\nfrom typing import cast\nfrom unittest import mock\nimport zipfile\n\nimport _pytest._code\nfrom _pytest._io.saferepr import DEFAULT_REPR_MAX_SIZE\nfrom _pytest.assertion import util\nfrom _pytest.assertion.rewrite import _get_assertion_exprs\nfrom _pytest.assertion.rewrite import _get_maxsize_for_saferepr\nfrom _pytest.assertion.rewrite import _saferepr\nfrom _pytest.assertion.rewrite import AssertionRewritingHook\nfrom _pytest.assertion.rewrite import get_cache_dir\nfrom _pytest.assertion.rewrite import PYC_TAIL\nfrom _pytest.assertion.rewrite import PYTEST_TAG\nfrom _pytest.assertion.rewrite import rewrite_asserts\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.pathlib import make_numbered_dir\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\ndef rewrite(src: str) -> ast.Module:\n    tree = ast.parse(src)\n    rewrite_asserts(tree, src.encode())\n    return tree\n\n\ndef getmsg(\n    f, extra_ns: Mapping[str, object] | None = None, *, must_pass: bool = False\n) -> str | None:\n    \"\"\"Rewrite the assertions in f, run it, and get the failure message.\"\"\"\n    src = \"\\n\".join(_pytest._code.Code.from_function(f).source().lines)\n    mod = rewrite(src)\n    code = compile(mod, \"<test>\", \"exec\")\n    ns: dict[str, object] = {}\n    if extra_ns is not None:\n        ns.update(extra_ns)\n    exec(code, ns)\n    func = ns[f.__name__]\n    try:\n        func()  # type: ignore[operator]\n    except AssertionError:\n        if must_pass:\n            pytest.fail(\"shouldn't have raised\")\n        s = str(sys.exc_info()[1])\n        if not s.startswith(\"assert\"):\n            return \"AssertionError: \" + s\n        return s\n    else:\n        if not must_pass:\n            pytest.fail(\"function didn't raise at all\")\n        return None\n\n\nclass TestAssertionRewrite:\n    def test_place_initial_imports(self) -> None:\n        s = \"\"\"'Doc string'\\nother = stuff\"\"\"\n        m = rewrite(s)\n        assert isinstance(m.body[0], ast.Expr)\n        for imp in m.body[1:3]:\n            assert isinstance(imp, ast.Import)\n            assert imp.lineno == 2\n            assert imp.col_offset == 0\n        assert isinstance(m.body[3], ast.Assign)\n        s = \"\"\"from __future__ import division\\nother_stuff\"\"\"\n        m = rewrite(s)\n        assert isinstance(m.body[0], ast.ImportFrom)\n        for imp in m.body[1:3]:\n            assert isinstance(imp, ast.Import)\n            assert imp.lineno == 2\n            assert imp.col_offset == 0\n        assert isinstance(m.body[3], ast.Expr)\n        s = \"\"\"'doc string'\\nfrom __future__ import division\"\"\"\n        m = rewrite(s)\n        assert isinstance(m.body[0], ast.Expr)\n        assert isinstance(m.body[1], ast.ImportFrom)\n        for imp in m.body[2:4]:\n            assert isinstance(imp, ast.Import)\n            assert imp.lineno == 2\n            assert imp.col_offset == 0\n        s = \"\"\"'doc string'\\nfrom __future__ import division\\nother\"\"\"\n        m = rewrite(s)\n        assert isinstance(m.body[0], ast.Expr)\n        assert isinstance(m.body[1], ast.ImportFrom)\n        for imp in m.body[2:4]:\n            assert isinstance(imp, ast.Import)\n            assert imp.lineno == 3\n            assert imp.col_offset == 0\n        assert isinstance(m.body[4], ast.Expr)\n        s = \"\"\"from . import relative\\nother_stuff\"\"\"\n        m = rewrite(s)\n        for imp in m.body[:2]:\n            assert isinstance(imp, ast.Import)\n            assert imp.lineno == 1\n            assert imp.col_offset == 0\n        assert isinstance(m.body[3], ast.Expr)\n\n    def test_location_is_set(self) -> None:\n        s = textwrap.dedent(\n            \"\"\"\n\n        assert False, (\n\n            \"Ouch\"\n          )\n\n        \"\"\"\n        )\n        m = rewrite(s)\n        for node in m.body:\n            if isinstance(node, ast.Import):\n                continue\n            for n in [node, *ast.iter_child_nodes(node)]:\n                assert isinstance(n, ast.stmt | ast.expr)\n                for location in [\n                    (n.lineno, n.col_offset),\n                    (n.end_lineno, n.end_col_offset),\n                ]:\n                    assert (3, 0) <= location <= (6, 3)\n\n    def test_positions_are_preserved(self) -> None:\n        \"\"\"Ensure AST positions are preserved during rewriting (#12818).\"\"\"\n\n        def preserved(code: str) -> None:\n            s = textwrap.dedent(code)\n            locations = []\n\n            def loc(msg: str | None = None) -> None:\n                frame = inspect.currentframe()\n                assert frame\n                frame = frame.f_back\n                assert frame\n                frame = frame.f_back\n                assert frame\n\n                offset = frame.f_lasti\n\n                instructions = {i.offset: i for i in dis.get_instructions(frame.f_code)}\n\n                # skip CACHE instructions\n                while offset not in instructions and offset >= 0:\n                    offset -= 1\n\n                instruction = instructions[offset]\n                if sys.version_info >= (3, 11):\n                    position = instruction.positions\n                else:\n                    position = instruction.starts_line\n\n                locations.append((msg, instruction.opname, position))\n\n            globals = {\"loc\": loc}\n\n            m = rewrite(s)\n            mod = compile(m, \"<string>\", \"exec\")\n            exec(mod, globals, globals)\n            transformed_locations = locations\n            locations = []\n\n            mod = compile(s, \"<string>\", \"exec\")\n            exec(mod, globals, globals)\n            original_locations = locations\n\n            assert len(original_locations) > 0\n            assert original_locations == transformed_locations\n\n        preserved(\"\"\"\n            def f():\n                loc()\n                return 8\n\n            assert f() in [8]\n            assert (f()\n                    in\n                    [8])\n        \"\"\")\n\n        preserved(\"\"\"\n            class T:\n                def __init__(self):\n                    loc(\"init\")\n                def __getitem__(self,index):\n                    loc(\"getitem\")\n                    return index\n\n            assert T()[5] == 5\n            assert (T\n                    ()\n                    [5]\n                    ==\n                    5)\n        \"\"\")\n\n        for name, op in [\n            (\"pos\", \"+\"),\n            (\"neg\", \"-\"),\n            (\"invert\", \"~\"),\n        ]:\n            preserved(f\"\"\"\n                class T:\n                    def __{name}__(self):\n                        loc(\"{name}\")\n                        return \"{name}\"\n\n                assert {op}T() == \"{name}\"\n                assert ({op}\n                        T\n                        ()\n                        ==\n                        \"{name}\")\n            \"\"\")\n\n        for name, op in [\n            (\"add\", \"+\"),\n            (\"sub\", \"-\"),\n            (\"mul\", \"*\"),\n            (\"truediv\", \"/\"),\n            (\"floordiv\", \"//\"),\n            (\"mod\", \"%\"),\n            (\"pow\", \"**\"),\n            (\"lshift\", \"<<\"),\n            (\"rshift\", \">>\"),\n            (\"or\", \"|\"),\n            (\"xor\", \"^\"),\n            (\"and\", \"&\"),\n            (\"matmul\", \"@\"),\n        ]:\n            preserved(f\"\"\"\n                class T:\n                    def __{name}__(self,other):\n                        loc(\"{name}\")\n                        return other\n\n                    def __r{name}__(self,other):\n                        loc(\"r{name}\")\n                        return other\n\n                assert T() {op} 2 == 2\n                assert 2 {op} T() == 2\n\n                assert (T\n                        ()\n                        {op}\n                        2\n                        ==\n                        2)\n\n                assert (2\n                        {op}\n                        T\n                        ()\n                        ==\n                        2)\n        \"\"\")\n\n        for name, op in [\n            (\"eq\", \"==\"),\n            (\"ne\", \"!=\"),\n            (\"lt\", \"<\"),\n            (\"le\", \"<=\"),\n            (\"gt\", \">\"),\n            (\"ge\", \">=\"),\n        ]:\n            preserved(f\"\"\"\n                class T:\n                    def __{name}__(self,other):\n                        loc()\n                        return True\n\n                assert  T() {op} 5\n                assert  (T\n                        ()\n                        {op}\n                        5)\n        \"\"\")\n\n        for name, op in [\n            (\"eq\", \"==\"),\n            (\"ne\", \"!=\"),\n            (\"lt\", \">\"),\n            (\"le\", \">=\"),\n            (\"gt\", \"<\"),\n            (\"ge\", \"<=\"),\n            (\"contains\", \"in\"),\n        ]:\n            preserved(f\"\"\"\n                class T:\n                    def __{name}__(self,other):\n                        loc()\n                        return True\n\n                assert  5 {op} T()\n                assert  (5\n                         {op}\n                         T\n                         ())\n        \"\"\")\n\n        preserved(\"\"\"\n            def func(value):\n                loc(\"func\")\n                return value\n\n            class T:\n                def __iter__(self):\n                    loc(\"iter\")\n                    return iter([5])\n\n            assert  func(*T()) == 5\n        \"\"\")\n\n        preserved(\"\"\"\n            class T:\n                def __getattr__(self,name):\n                    loc()\n                    return name\n\n            assert  T().attr == \"attr\"\n        \"\"\")\n\n    def test_dont_rewrite(self) -> None:\n        s = \"\"\"'PYTEST_DONT_REWRITE'\\nassert 14\"\"\"\n        m = rewrite(s)\n        assert len(m.body) == 2\n        assert isinstance(m.body[1], ast.Assert)\n        assert m.body[1].msg is None\n\n    def test_dont_rewrite_plugin(self, pytester: Pytester) -> None:\n        contents = {\n            \"conftest.py\": \"pytest_plugins = 'plugin'; import plugin\",\n            \"plugin.py\": \"'PYTEST_DONT_REWRITE'\",\n            \"test_foo.py\": \"def test_foo(): pass\",\n        }\n        pytester.makepyfile(**contents)\n        result = pytester.runpytest_subprocess()\n        assert \"warning\" not in \"\".join(result.outlines)\n\n    def test_rewrites_plugin_as_a_package(self, pytester: Pytester) -> None:\n        pkgdir = pytester.mkpydir(\"plugin\")\n        pkgdir.joinpath(\"__init__.py\").write_text(\n            \"import pytest\\n\"\n            \"@pytest.fixture\\n\"\n            \"def special_asserter():\\n\"\n            \"    def special_assert(x, y):\\n\"\n            \"        assert x == y\\n\"\n            \"    return special_assert\\n\",\n            encoding=\"utf-8\",\n        )\n        pytester.makeconftest('pytest_plugins = [\"plugin\"]')\n        pytester.makepyfile(\"def test(special_asserter): special_asserter(1, 2)\\n\")\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*assert 1 == 2*\"])\n\n    def test_honors_pep_235(self, pytester: Pytester, monkeypatch) -> None:\n        # note: couldn't make it fail on macos with a single `sys.path` entry\n        # note: these modules are named `test_*` to trigger rewriting\n        pytester.makepyfile(test_y=\"x = 1\")\n        xdir = pytester.mkdir(\"x\")\n        pytester.mkpydir(str(xdir.joinpath(\"test_Y\")))\n        xdir.joinpath(\"test_Y\").joinpath(\"__init__.py\").write_text(\n            \"x = 2\", encoding=\"utf-8\"\n        )\n        pytester.makepyfile(\n            \"import test_y\\n\"\n            \"import test_Y\\n\"\n            \"def test():\\n\"\n            \"    assert test_y.x == 1\\n\"\n            \"    assert test_Y.x == 2\\n\"\n        )\n        monkeypatch.syspath_prepend(str(xdir))\n        pytester.runpytest().assert_outcomes(passed=1)\n\n    def test_name(self, request) -> None:\n        def f1() -> None:\n            assert False\n\n        assert getmsg(f1) == \"assert False\"\n\n        def f2() -> None:\n            f = False\n            assert f\n\n        assert getmsg(f2) == \"assert False\"\n\n        def f3() -> None:\n            assert a_global  # type: ignore[name-defined] # noqa: F821\n\n        assert getmsg(f3, {\"a_global\": False}) == \"assert False\"\n\n        def f4() -> None:\n            assert sys == 42  # type: ignore[comparison-overlap]\n\n        msg = getmsg(f4, {\"sys\": sys})\n        assert msg == \"assert sys == 42\"\n\n        def f5() -> None:\n            assert cls == 42  # type: ignore[name-defined]  # noqa: F821\n\n        class X:\n            pass\n\n        msg = getmsg(f5, {\"cls\": X})\n        assert msg is not None\n        lines = msg.splitlines()\n        assert lines == [\"assert cls == 42\"]\n\n    def test_assertrepr_compare_same_width(self, request) -> None:\n        \"\"\"Should use same width/truncation with same initial width.\"\"\"\n\n        def f() -> None:\n            assert \"1234567890\" * 5 + \"A\" == \"1234567890\" * 5 + \"B\"\n\n        msg = getmsg(f)\n        assert msg is not None\n        line = msg.splitlines()[0]\n        if request.config.getoption(\"verbose\") > 1:\n            assert line == (\n                \"assert '12345678901234567890123456789012345678901234567890A' \"\n                \"== '12345678901234567890123456789012345678901234567890B'\"\n            )\n        else:\n            assert line == (\n                \"assert '123456789012...901234567890A' \"\n                \"== '123456789012...901234567890B'\"\n            )\n\n    def test_dont_rewrite_if_hasattr_fails(self, request) -> None:\n        class Y:\n            \"\"\"A class whose getattr fails, but not with `AttributeError`.\"\"\"\n\n            def __getattr__(self, attribute_name):\n                raise KeyError()\n\n            def __repr__(self) -> str:\n                return \"Y\"\n\n            def __init__(self) -> None:\n                self.foo = 3\n\n        def f() -> None:\n            assert cls().foo == 2  # type: ignore[name-defined] # noqa: F821\n\n        # XXX: looks like the \"where\" should also be there in verbose mode?!\n        msg = getmsg(f, {\"cls\": Y})\n        assert msg is not None\n        lines = msg.splitlines()\n        assert lines == [\n            \"assert 3 == 2\",\n            \" +  where 3 = Y.foo\",\n            \" +    where Y = cls()\",\n        ]\n\n    def test_assert_already_has_message(self) -> None:\n        def f():\n            assert False, \"something bad!\"\n\n        assert getmsg(f) == \"AssertionError: something bad!\\nassert False\"\n\n    def test_assertion_message(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert 1 == 2, \"The failure message\"\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines(\n            [\"*AssertionError*The failure message*\", \"*assert 1 == 2*\"]\n        )\n\n    def test_assertion_message_multiline(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert 1 == 2, \"A multiline\\\\nfailure message\"\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines(\n            [\"*AssertionError*A multiline*\", \"*failure message*\", \"*assert 1 == 2*\"]\n        )\n\n    def test_assertion_message_tuple(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert 1 == 2, (1, 2)\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines([f\"*AssertionError*{(1, 2)!r}*\", \"*assert 1 == 2*\"])\n\n    def test_assertion_message_expr(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert 1 == 2, 1 + 2\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines([\"*AssertionError*3*\", \"*assert 1 == 2*\"])\n\n    def test_assertion_message_escape(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert 1 == 2, 'To be escaped: %'\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines(\n            [\"*AssertionError: To be escaped: %\", \"*assert 1 == 2\"]\n        )\n\n    def test_assertion_messages_bytes(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\"def test_bytes_assertion():\\n    assert False, b'ohai!'\\n\")\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines([\"*AssertionError: b'ohai!'\", \"*assert False\"])\n\n    def test_assertion_message_verbosity(self, pytester: Pytester) -> None:\n        \"\"\"\n        Obey verbosity levels when printing the \"message\" part of assertions, when they are\n        non-strings (#6682).\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            class LongRepr:\n\n                def __repr__(self):\n                    return \"A\" * 500\n\n            def test_assertion_verbosity():\n                assert False, LongRepr()\n            \"\"\"\n        )\n        # Normal verbosity: assertion message gets abbreviated.\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.re_match_lines(\n            [r\".*AssertionError: A+\\.\\.\\.A+$\", \".*assert False\"]\n        )\n\n        # High-verbosity: do not abbreviate the assertion message.\n        result = pytester.runpytest(\"-vv\")\n        assert result.ret == 1\n        result.stdout.re_match_lines([r\".*AssertionError: A+$\", \".*assert False\"])\n\n    def test_boolop(self) -> None:\n        def f1() -> None:\n            f = g = False\n            assert f and g\n\n        assert getmsg(f1) == \"assert (False)\"\n\n        def f2() -> None:\n            f = True\n            g = False\n            assert f and g\n\n        assert getmsg(f2) == \"assert (True and False)\"\n\n        def f3() -> None:\n            f = False\n            g = True\n            assert f and g\n\n        assert getmsg(f3) == \"assert (False)\"\n\n        def f4() -> None:\n            f = g = False\n            assert f or g\n\n        assert getmsg(f4) == \"assert (False or False)\"\n\n        def f5() -> None:\n            f = g = False\n            assert not f and not g\n\n        getmsg(f5, must_pass=True)\n\n        def x() -> bool:\n            return False\n\n        def f6() -> None:\n            assert x() and x()\n\n        assert (\n            getmsg(f6, {\"x\": x})\n            == \"\"\"assert (False)\n +  where False = x()\"\"\"\n        )\n\n        def f7() -> None:\n            assert False or x()\n\n        assert (\n            getmsg(f7, {\"x\": x})\n            == \"\"\"assert (False or False)\n +  where False = x()\"\"\"\n        )\n\n        def f8() -> None:\n            assert 1 in {} and 2 in {}\n\n        assert getmsg(f8) == \"assert (1 in {})\"\n\n        def f9() -> None:\n            x = 1\n            y = 2\n            assert x in {1: None} and y in {}\n\n        assert getmsg(f9) == \"assert (1 in {1: None} and 2 in {})\"\n\n        def f10() -> None:\n            f = True\n            g = False\n            assert f or g\n\n        getmsg(f10, must_pass=True)\n\n        def f11() -> None:\n            f = g = h = lambda: True\n            assert f() and g() and h()\n\n        getmsg(f11, must_pass=True)\n\n    def test_short_circuit_evaluation(self) -> None:\n        def f1() -> None:\n            assert True or explode  # type: ignore[name-defined,unreachable] # noqa: F821\n\n        getmsg(f1, must_pass=True)\n\n        def f2() -> None:\n            x = 1\n            assert x == 1 or x == 2  # noqa: PLR1714\n\n        getmsg(f2, must_pass=True)\n\n    def test_unary_op(self) -> None:\n        def f1() -> None:\n            x = True\n            assert not x\n\n        assert getmsg(f1) == \"assert not True\"\n\n        def f2() -> None:\n            x = 0\n            assert ~x + 1\n\n        assert getmsg(f2) == \"assert (~0 + 1)\"\n\n        def f3() -> None:\n            x = 3\n            assert -x + x\n\n        assert getmsg(f3) == \"assert (-3 + 3)\"\n\n        def f4() -> None:\n            x = 0\n            assert +x + x\n\n        assert getmsg(f4) == \"assert (+0 + 0)\"\n\n    def test_binary_op(self) -> None:\n        def f1() -> None:\n            x = 1\n            y = -1\n            assert x + y\n\n        assert getmsg(f1) == \"assert (1 + -1)\"\n\n        def f2() -> None:\n            assert not 5 % 4\n\n        assert getmsg(f2) == \"assert not (5 % 4)\"\n\n    def test_boolop_percent(self) -> None:\n        def f1() -> None:\n            assert 3 % 2 and False\n\n        assert getmsg(f1) == \"assert ((3 % 2) and False)\"\n\n        def f2() -> None:\n            assert False or 4 % 2\n\n        assert getmsg(f2) == \"assert (False or (4 % 2))\"\n\n    def test_at_operator_issue1290(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            class Matrix(object):\n                def __init__(self, num):\n                    self.num = num\n                def __matmul__(self, other):\n                    return self.num * other.num\n\n            def test_multmat_operator():\n                assert Matrix(2) @ Matrix(3) == 6\"\"\"\n        )\n        pytester.runpytest().assert_outcomes(passed=1)\n\n    def test_starred_with_side_effect(self, pytester: Pytester) -> None:\n        \"\"\"See #4412\"\"\"\n        pytester.makepyfile(\n            \"\"\"\\\n            def test():\n                f = lambda x: x\n                x = iter([1, 2, 3])\n                assert 2 * next(x) == f(*[next(x)])\n            \"\"\"\n        )\n        pytester.runpytest().assert_outcomes(passed=1)\n\n    def test_call(self) -> None:\n        def g(a=42, *args, **kwargs) -> bool:\n            return False\n\n        ns = {\"g\": g}\n\n        def f1() -> None:\n            assert g()\n\n        assert (\n            getmsg(f1, ns)\n            == \"\"\"assert False\n +  where False = g()\"\"\"\n        )\n\n        def f2() -> None:\n            assert g(1)\n\n        assert (\n            getmsg(f2, ns)\n            == \"\"\"assert False\n +  where False = g(1)\"\"\"\n        )\n\n        def f3() -> None:\n            assert g(1, 2)\n\n        assert (\n            getmsg(f3, ns)\n            == \"\"\"assert False\n +  where False = g(1, 2)\"\"\"\n        )\n\n        def f4() -> None:\n            assert g(1, g=42)\n\n        assert (\n            getmsg(f4, ns)\n            == \"\"\"assert False\n +  where False = g(1, g=42)\"\"\"\n        )\n\n        def f5() -> None:\n            assert g(1, 3, g=23)\n\n        assert (\n            getmsg(f5, ns)\n            == \"\"\"assert False\n +  where False = g(1, 3, g=23)\"\"\"\n        )\n\n        def f6() -> None:\n            seq = [1, 2, 3]\n            assert g(*seq)\n\n        assert (\n            getmsg(f6, ns)\n            == \"\"\"assert False\n +  where False = g(*[1, 2, 3])\"\"\"\n        )\n\n        def f7() -> None:\n            x = \"a\"\n            assert g(**{x: 2})\n\n        assert (\n            getmsg(f7, ns)\n            == \"\"\"assert False\n +  where False = g(**{'a': 2})\"\"\"\n        )\n\n    def test_attribute(self) -> None:\n        class X:\n            g = 3\n\n        ns = {\"x\": X}\n\n        def f1() -> None:\n            assert not x.g  # type: ignore[name-defined] # noqa: F821\n\n        assert (\n            getmsg(f1, ns)\n            == \"\"\"assert not 3\n +  where 3 = x.g\"\"\"\n        )\n\n        def f2() -> None:\n            x.a = False  # type: ignore[name-defined] # noqa: F821\n            assert x.a  # type: ignore[name-defined] # noqa: F821\n\n        assert (\n            getmsg(f2, ns)\n            == \"\"\"assert False\n +  where False = x.a\"\"\"\n        )\n\n    def test_comparisons(self) -> None:\n        def f1() -> None:\n            a, b = range(2)\n            assert b < a\n\n        assert getmsg(f1) == \"\"\"assert 1 < 0\"\"\"\n\n        def f2() -> None:\n            a, b, c = range(3)\n            assert a > b > c\n\n        assert getmsg(f2) == \"\"\"assert 0 > 1\"\"\"\n\n        def f3() -> None:\n            a, b, c = range(3)\n            assert a < b > c\n\n        assert getmsg(f3) == \"\"\"assert 1 > 2\"\"\"\n\n        def f4() -> None:\n            a, b, c = range(3)\n            assert a < b <= c\n\n        getmsg(f4, must_pass=True)\n\n        def f5() -> None:\n            a, b, c = range(3)\n            assert a < b\n            assert b < c\n\n        getmsg(f5, must_pass=True)\n\n    def test_len(self, request) -> None:\n        def f():\n            values = list(range(10))\n            assert len(values) == 11\n\n        msg = getmsg(f)\n        assert msg == \"assert 10 == 11\\n +  where 10 = len([0, 1, 2, 3, 4, 5, ...])\"\n\n    def test_custom_reprcompare(self, monkeypatch) -> None:\n        def my_reprcompare1(op, left, right) -> str:\n            return \"42\"\n\n        monkeypatch.setattr(util, \"_reprcompare\", my_reprcompare1)\n\n        def f1() -> None:\n            assert 42 < 3\n\n        assert getmsg(f1) == \"assert 42\"\n\n        def my_reprcompare2(op, left, right) -> str:\n            return f\"{left} {op} {right}\"\n\n        monkeypatch.setattr(util, \"_reprcompare\", my_reprcompare2)\n\n        def f2() -> None:\n            assert 1 < 3 < 5 <= 4 < 7\n\n        assert getmsg(f2) == \"assert 5 <= 4\"\n\n    def test_assert_raising__bool__in_comparison(self) -> None:\n        def f() -> None:\n            class A:\n                def __bool__(self):\n                    raise ValueError(42)\n\n                def __lt__(self, other):\n                    return A()\n\n                def __repr__(self):\n                    return \"<MY42 object>\"\n\n            def myany(x) -> bool:\n                return False\n\n            assert myany(A() < 0)\n\n        msg = getmsg(f)\n        assert msg is not None\n        assert \"<MY42 object> < 0\" in msg\n\n    def test_assert_handling_raise_in__iter__(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n            class A:\n                def __iter__(self):\n                    raise ValueError()\n\n                def __eq__(self, o: object) -> bool:\n                    return self is o\n\n                def __repr__(self):\n                    return \"<A object>\"\n\n            assert A() == A()\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*E*assert <A object> == <A object>\"])\n\n    def test_formatchar(self) -> None:\n        def f() -> None:\n            assert \"%test\" == \"test\"  # type: ignore[comparison-overlap]\n\n        msg = getmsg(f)\n        assert msg is not None\n        assert msg.startswith(\"assert '%test' == 'test'\")\n\n    def test_custom_repr(self, request) -> None:\n        def f() -> None:\n            class Foo:\n                a = 1\n\n                def __repr__(self):\n                    return \"\\n{ \\n~ \\n}\"\n\n            f = Foo()\n            assert 0 == f.a\n\n        msg = getmsg(f)\n        assert msg is not None\n        lines = util._format_lines([msg])\n        assert lines == [\"assert 0 == 1\\n +  where 1 = \\\\n{ \\\\n~ \\\\n}.a\"]\n\n    def test_custom_repr_non_ascii(self) -> None:\n        def f() -> None:\n            class A:\n                name = \"ä\"\n\n                def __repr__(self):\n                    return self.name.encode(\"UTF-8\")  # only legal in python2\n\n            a = A()\n            assert not a.name\n\n        msg = getmsg(f)\n        assert msg is not None\n        assert \"UnicodeDecodeError\" not in msg\n        assert \"UnicodeEncodeError\" not in msg\n\n    def test_assert_fixture(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n        import pytest\n        @pytest.fixture\n        def fixt():\n            return 42\n\n        def test_something():  # missing \"fixt\" argument\n            assert fixt == 42\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\"*assert <pytest_fixture(<function fixt at *>)> == 42*\"]\n        )\n\n\nclass TestRewriteOnImport:\n    def test_pycache_is_a_file(self, pytester: Pytester) -> None:\n        pytester.path.joinpath(\"__pycache__\").write_text(\"Hello\", encoding=\"utf-8\")\n        pytester.makepyfile(\n            \"\"\"\n            def test_rewritten():\n                assert \"@py_builtins\" in globals()\"\"\"\n        )\n        assert pytester.runpytest().ret == 0\n\n    def test_pycache_is_readonly(self, pytester: Pytester) -> None:\n        cache = pytester.mkdir(\"__pycache__\")\n        old_mode = cache.stat().st_mode\n        cache.chmod(old_mode ^ stat.S_IWRITE)\n        pytester.makepyfile(\n            \"\"\"\n            def test_rewritten():\n                assert \"@py_builtins\" in globals()\"\"\"\n        )\n        try:\n            assert pytester.runpytest().ret == 0\n        finally:\n            cache.chmod(old_mode)\n\n    def test_zipfile(self, pytester: Pytester) -> None:\n        z = pytester.path.joinpath(\"myzip.zip\")\n        z_fn = str(z)\n        f = zipfile.ZipFile(z_fn, \"w\")\n        try:\n            f.writestr(\"test_gum/__init__.py\", \"\")\n            f.writestr(\"test_gum/test_lizard.py\", \"\")\n        finally:\n            f.close()\n        z.chmod(256)\n        pytester.makepyfile(\n            f\"\"\"\n            import sys\n            sys.path.append({z_fn!r})\n            import test_gum.test_lizard\"\"\"\n        )\n        assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED\n\n    def test_load_resource_via_files_with_rewrite(self, pytester: Pytester) -> None:\n        example = pytester.path.joinpath(\"demo\") / \"example\"\n        init = pytester.path.joinpath(\"demo\") / \"__init__.py\"\n        pytester.makepyfile(\n            **{\n                \"demo/__init__.py\": \"\"\"\n                from importlib.resources import files\n\n                def load():\n                    return files(__name__)\n                \"\"\",\n                \"test_load\": f\"\"\"\n                pytest_plugins = [\"demo\"]\n\n                def test_load():\n                    from demo import load\n                    found = {{str(i) for i in load().iterdir() if i.name != \"__pycache__\"}}\n                    assert found == {{{str(example)!r}, {str(init)!r}}}\n                \"\"\",\n            }\n        )\n        example.mkdir()\n\n        assert pytester.runpytest(\"-vv\").ret == ExitCode.OK\n\n    def test_readonly(self, pytester: Pytester) -> None:\n        sub = pytester.mkdir(\"testing\")\n        sub.joinpath(\"test_readonly.py\").write_bytes(\n            b\"\"\"\ndef test_rewritten():\n    assert \"@py_builtins\" in globals()\n            \"\"\",\n        )\n        old_mode = sub.stat().st_mode\n        sub.chmod(320)\n        try:\n            assert pytester.runpytest().ret == 0\n        finally:\n            sub.chmod(old_mode)\n\n    def test_dont_write_bytecode(self, pytester: Pytester, monkeypatch) -> None:\n        monkeypatch.delenv(\"PYTHONPYCACHEPREFIX\", raising=False)\n\n        pytester.makepyfile(\n            \"\"\"\n            import os\n            def test_no_bytecode():\n                assert \"__pycache__\" in __cached__\n                assert not os.path.exists(__cached__)\n                assert not os.path.exists(os.path.dirname(__cached__))\"\"\"\n        )\n        monkeypatch.setenv(\"PYTHONDONTWRITEBYTECODE\", \"1\")\n        assert pytester.runpytest_subprocess().ret == 0\n\n    def test_orphaned_pyc_file(self, pytester: Pytester, monkeypatch) -> None:\n        monkeypatch.delenv(\"PYTHONPYCACHEPREFIX\", raising=False)\n        monkeypatch.setattr(sys, \"pycache_prefix\", None, raising=False)\n\n        pytester.makepyfile(\n            \"\"\"\n            import orphan\n            def test_it():\n                assert orphan.value == 17\n            \"\"\"\n        )\n        pytester.makepyfile(\n            orphan=\"\"\"\n            value = 17\n            \"\"\"\n        )\n        py_compile.compile(\"orphan.py\")\n        os.remove(\"orphan.py\")\n\n        # Python 3 puts the .pyc files in a __pycache__ directory, and will\n        # not import from there without source.  It will import a .pyc from\n        # the source location though.\n        if not os.path.exists(\"orphan.pyc\"):\n            pycs = glob.glob(\"__pycache__/orphan.*.pyc\")\n            assert len(pycs) == 1\n            os.rename(pycs[0], \"orphan.pyc\")\n\n        assert pytester.runpytest().ret == 0\n\n    def test_cached_pyc_includes_pytest_version(\n        self, pytester: Pytester, monkeypatch\n    ) -> None:\n        \"\"\"Avoid stale caches (#1671)\"\"\"\n        monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n        monkeypatch.delenv(\"PYTHONPYCACHEPREFIX\", raising=False)\n        pytester.makepyfile(\n            test_foo=\"\"\"\n            def test_foo():\n                assert True\n            \"\"\"\n        )\n        result = pytester.runpytest_subprocess()\n        assert result.ret == 0\n        found_names = glob.glob(f\"__pycache__/*-pytest-{pytest.__version__}.pyc\")\n        assert found_names, \"pyc with expected tag not found in names: {}\".format(\n            glob.glob(\"__pycache__/*.pyc\")\n        )\n\n    @pytest.mark.skipif('\"__pypy__\" in sys.modules')\n    def test_pyc_vs_pyo(\n        self,\n        pytester: Pytester,\n        monkeypatch: pytest.MonkeyPatch,\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_optimized():\n                \"hello\"\n                assert test_optimized.__doc__ is None\"\"\"\n        )\n        p = make_numbered_dir(root=Path(pytester.path), prefix=\"runpytest-\")\n        tmp = f\"--basetemp={p}\"\n        with monkeypatch.context() as mp:\n            mp.setenv(\"PYTHONOPTIMIZE\", \"2\")\n            mp.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n            mp.delenv(\"PYTHONPYCACHEPREFIX\", raising=False)\n            assert pytester.runpytest_subprocess(tmp).ret == 0\n            tagged = \"test_pyc_vs_pyo.\" + PYTEST_TAG\n            assert tagged + \".pyo\" in os.listdir(\"__pycache__\")\n        monkeypatch.delenv(\"PYTHONDONTWRITEBYTECODE\", raising=False)\n        monkeypatch.delenv(\"PYTHONPYCACHEPREFIX\", raising=False)\n        assert pytester.runpytest_subprocess(tmp).ret == 1\n        assert tagged + \".pyc\" in os.listdir(\"__pycache__\")\n\n    def test_package(self, pytester: Pytester) -> None:\n        pkg = pytester.path.joinpath(\"pkg\")\n        pkg.mkdir()\n        pkg.joinpath(\"__init__.py\")\n        pkg.joinpath(\"test_blah.py\").write_text(\n            \"\"\"\ndef test_rewritten():\n    assert \"@py_builtins\" in globals()\"\"\",\n            encoding=\"utf-8\",\n        )\n        assert pytester.runpytest().ret == 0\n\n    def test_translate_newlines(self, pytester: Pytester) -> None:\n        content = \"def test_rewritten():\\r\\n assert '@py_builtins' in globals()\"\n        b = content.encode(\"utf-8\")\n        pytester.path.joinpath(\"test_newlines.py\").write_bytes(b)\n        assert pytester.runpytest().ret == 0\n\n    def test_package_without__init__py(self, pytester: Pytester) -> None:\n        pkg = pytester.mkdir(\"a_package_without_init_py\")\n        pkg.joinpath(\"module.py\").touch()\n        pytester.makepyfile(\"import a_package_without_init_py.module\")\n        assert pytester.runpytest().ret == ExitCode.NO_TESTS_COLLECTED\n\n    def test_rewrite_warning(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            pytest.register_assert_rewrite(\"_pytest\")\n        \"\"\"\n        )\n        # needs to be a subprocess because pytester explicitly disables this warning\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines([\"*Module already imported*; _pytest\"])\n\n    def test_rewrite_warning_ignore(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            pytest.register_assert_rewrite(\"_pytest\")\n        \"\"\"\n        )\n        # needs to be a subprocess because pytester explicitly disables this warning\n        result = pytester.runpytest_subprocess(\n            \"-W\",\n            \"ignore:Module already imported so cannot be rewritten; _pytest:pytest.PytestAssertRewriteWarning\",\n        )\n        # Previously, when the message pattern used to contain an extra `:`, an error was raised.\n        assert not result.stderr.str().strip()\n        result.stdout.no_fnmatch_line(\"*Module already imported*; _pytest\")\n\n    def test_rewrite_module_imported_from_conftest(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import test_rewrite_module_imported\n        \"\"\"\n        )\n        pytester.makepyfile(\n            test_rewrite_module_imported=\"\"\"\n            def test_rewritten():\n                assert \"@py_builtins\" in globals()\n        \"\"\"\n        )\n        assert pytester.runpytest_subprocess().ret == 0\n\n    def test_remember_rewritten_modules(\n        self, pytestconfig, pytester: Pytester, monkeypatch\n    ) -> None:\n        \"\"\"`AssertionRewriteHook` should remember rewritten modules so it\n        doesn't give false positives (#2005).\"\"\"\n        monkeypatch.syspath_prepend(pytester.path)\n        pytester.makepyfile(test_remember_rewritten_modules=\"\")\n        warnings = []\n        hook = AssertionRewritingHook(pytestconfig)\n        monkeypatch.setattr(\n            hook, \"_warn_already_imported\", lambda code, msg: warnings.append(msg)\n        )\n        spec = hook.find_spec(\"test_remember_rewritten_modules\")\n        assert spec is not None\n        module = importlib.util.module_from_spec(spec)\n        hook.exec_module(module)\n        hook.mark_rewrite(\"test_remember_rewritten_modules\")\n        hook.mark_rewrite(\"test_remember_rewritten_modules\")\n        assert warnings == []\n\n    def test_rewrite_warning_using_pytest_plugins(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            **{\n                \"conftest.py\": \"pytest_plugins = ['core', 'gui', 'sci']\",\n                \"core.py\": \"\",\n                \"gui.py\": \"pytest_plugins = ['core', 'sci']\",\n                \"sci.py\": \"pytest_plugins = ['core']\",\n                \"test_rewrite_warning_pytest_plugins.py\": \"def test(): pass\",\n            }\n        )\n        pytester.chdir()\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines([\"*= 1 passed in *=*\"])\n        result.stdout.no_fnmatch_line(\"*pytest-warning summary*\")\n\n    def test_rewrite_warning_using_pytest_plugins_env_var(\n        self, pytester: Pytester, monkeypatch\n    ) -> None:\n        monkeypatch.setenv(\"PYTEST_PLUGINS\", \"plugin\")\n        pytester.makepyfile(\n            **{\n                \"plugin.py\": \"\",\n                \"test_rewrite_warning_using_pytest_plugins_env_var.py\": \"\"\"\n                import plugin\n                pytest_plugins = ['plugin']\n                def test():\n                    pass\n            \"\"\",\n            }\n        )\n        pytester.chdir()\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines([\"*= 1 passed in *=*\"])\n        result.stdout.no_fnmatch_line(\"*pytest-warning summary*\")\n\n\nclass TestAssertionRewriteHookDetails:\n    def test_sys_meta_path_munged(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_meta_path():\n                import sys; sys.meta_path = []\"\"\"\n        )\n        assert pytester.runpytest().ret == 0\n\n    def test_write_pyc(self, pytester: Pytester, tmp_path) -> None:\n        from _pytest.assertion import AssertionState\n        from _pytest.assertion.rewrite import _write_pyc\n\n        config = pytester.parseconfig()\n        state = AssertionState(config, \"rewrite\")\n        tmp_path.joinpath(\"source.py\").touch()\n        source_path = str(tmp_path)\n        pycpath = tmp_path.joinpath(\"pyc\")\n        co = compile(\"1\", \"f.py\", \"single\")\n        assert _write_pyc(state, co, os.stat(source_path), pycpath)\n\n        with mock.patch.object(os, \"replace\", side_effect=OSError):\n            assert not _write_pyc(state, co, os.stat(source_path), pycpath)\n\n    def test_resources_provider_for_loader(self, pytester: Pytester) -> None:\n        \"\"\"\n        Attempts to load resources from a package should succeed normally,\n        even when the AssertionRewriteHook is used to load the modules.\n\n        See #366 for details.\n        \"\"\"\n        pytest.importorskip(\"pkg_resources\")\n\n        pytester.mkpydir(\"testpkg\")\n        contents = {\n            \"testpkg/test_pkg\": \"\"\"\n                import pkg_resources\n\n                import pytest\n                from _pytest.assertion.rewrite import AssertionRewritingHook\n\n                def test_load_resource():\n                    assert isinstance(__loader__, AssertionRewritingHook)\n                    res = pkg_resources.resource_string(__name__, 'resource.txt')\n                    res = res.decode('ascii')\n                    assert res == 'Load me please.'\n                \"\"\"\n        }\n        pytester.makepyfile(**contents)\n        pytester.maketxtfile(**{\"testpkg/resource\": \"Load me please.\"})\n\n        result = pytester.runpytest_subprocess()\n        result.assert_outcomes(passed=1)\n\n    def test_read_pyc(self, tmp_path: Path) -> None:\n        \"\"\"\n        Ensure that the `_read_pyc` can properly deal with corrupted pyc files.\n        In those circumstances it should just give up instead of generating\n        an exception that is propagated to the caller.\n        \"\"\"\n        import py_compile\n\n        from _pytest.assertion.rewrite import _read_pyc\n\n        source = tmp_path / \"source.py\"\n        pyc = Path(str(source) + \"c\")\n\n        source.write_text(\"def test(): pass\", encoding=\"utf-8\")\n        py_compile.compile(str(source), str(pyc))\n\n        contents = pyc.read_bytes()\n        strip_bytes = 20  # header is around 16 bytes, strip a little more\n        assert len(contents) > strip_bytes\n        pyc.write_bytes(contents[:strip_bytes])\n\n        assert _read_pyc(source, pyc) is None  # no error\n\n    def test_read_pyc_success(self, tmp_path: Path, pytester: Pytester) -> None:\n        \"\"\"\n        Ensure that the _rewrite_test() -> _write_pyc() produces a pyc file\n        that can be properly read with _read_pyc()\n        \"\"\"\n        from _pytest.assertion import AssertionState\n        from _pytest.assertion.rewrite import _read_pyc\n        from _pytest.assertion.rewrite import _rewrite_test\n        from _pytest.assertion.rewrite import _write_pyc\n\n        config = pytester.parseconfig()\n        state = AssertionState(config, \"rewrite\")\n\n        fn = tmp_path / \"source.py\"\n        pyc = Path(str(fn) + \"c\")\n\n        fn.write_text(\"def test(): assert True\", encoding=\"utf-8\")\n\n        source_stat, co = _rewrite_test(fn, config)\n        _write_pyc(state, co, source_stat, pyc)\n        assert _read_pyc(fn, pyc, state.trace) is not None\n\n    def test_read_pyc_more_invalid(self, tmp_path: Path) -> None:\n        from _pytest.assertion.rewrite import _read_pyc\n\n        source = tmp_path / \"source.py\"\n        pyc = tmp_path / \"source.pyc\"\n\n        source_bytes = b\"def test(): pass\\n\"\n        source.write_bytes(source_bytes)\n\n        magic = importlib.util.MAGIC_NUMBER\n\n        flags = b\"\\x00\\x00\\x00\\x00\"\n\n        mtime = b\"\\x58\\x3c\\xb0\\x5f\"\n        mtime_int = int.from_bytes(mtime, \"little\")\n        os.utime(source, (mtime_int, mtime_int))\n\n        size = len(source_bytes).to_bytes(4, \"little\")\n\n        code = marshal.dumps(compile(source_bytes, str(source), \"exec\"))\n\n        # Good header.\n        pyc.write_bytes(magic + flags + mtime + size + code)\n        assert _read_pyc(source, pyc, print) is not None\n\n        # Too short.\n        pyc.write_bytes(magic + flags + mtime)\n        assert _read_pyc(source, pyc, print) is None\n\n        # Bad magic.\n        pyc.write_bytes(b\"\\x12\\x34\\x56\\x78\" + flags + mtime + size + code)\n        assert _read_pyc(source, pyc, print) is None\n\n        # Unsupported flags.\n        pyc.write_bytes(magic + b\"\\x00\\xff\\x00\\x00\" + mtime + size + code)\n        assert _read_pyc(source, pyc, print) is None\n\n        # Bad mtime.\n        pyc.write_bytes(magic + flags + b\"\\x58\\x3d\\xb0\\x5f\" + size + code)\n        assert _read_pyc(source, pyc, print) is None\n\n        # Bad size.\n        pyc.write_bytes(magic + flags + mtime + b\"\\x99\\x00\\x00\\x00\" + code)\n        assert _read_pyc(source, pyc, print) is None\n\n    def test_reload_is_same_and_reloads(self, pytester: Pytester) -> None:\n        \"\"\"Reloading a (collected) module after change picks up the change.\"\"\"\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            python_files = *.py\n            \"\"\"\n        )\n        pytester.makepyfile(\n            file=\"\"\"\n            def reloaded():\n                return False\n\n            def rewrite_self():\n                with open(__file__, 'w', encoding='utf-8') as self:\n                    self.write('def reloaded(): return True')\n            \"\"\",\n            test_fun=\"\"\"\n            import sys\n            from importlib import reload\n\n            def test_loader():\n                import file\n                assert not file.reloaded()\n                file.rewrite_self()\n                assert sys.modules[\"file\"] is reload(file)\n                assert file.reloaded()\n            \"\"\",\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 1 passed*\"])\n\n    def test_get_data_support(self, pytester: Pytester) -> None:\n        \"\"\"Implement optional PEP302 api (#808).\"\"\"\n        path = pytester.mkpydir(\"foo\")\n        path.joinpath(\"test_foo.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                class Test(object):\n                    def test_foo(self):\n                        import pkgutil\n                        data = pkgutil.get_data('foo.test_foo', 'data.txt')\n                        assert data == b'Hey'\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        path.joinpath(\"data.txt\").write_text(\"Hey\", encoding=\"utf-8\")\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_issue731(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n    class LongReprWithBraces(object):\n        def __repr__(self):\n           return 'LongReprWithBraces({' + ('a' * 80) + '}' + ('a' * 120) + ')'\n\n        def some_method(self):\n            return False\n\n    def test_long_repr():\n        obj = LongReprWithBraces()\n        assert obj.some_method()\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.no_fnmatch_line(\"*unbalanced braces*\")\n\n\nclass TestIssue925:\n    def test_simple_case(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n        def test_ternary_display():\n            assert (False == False) == False\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*E*assert (False == False) == False\"])\n\n    def test_long_case(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n        def test_ternary_display():\n             assert False == (False == True) == True\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*E*assert (False == True) == True\"])\n\n    def test_many_brackets(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_ternary_display():\n                 assert True == ((False == True) == True)\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*E*assert True == ((False == True) == True)\"])\n\n\nclass TestIssue2121:\n    def test_rewrite_python_files_contain_subdirs(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            **{\n                \"tests/file.py\": \"\"\"\n                def test_simple_failure():\n                    assert 1 + 1 == 3\n                \"\"\"\n            }\n        )\n        pytester.makeini(\n            \"\"\"\n                [pytest]\n                python_files = tests/**.py\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*E*assert (1 + 1) == 3\"])\n\n\nclass TestAssertionRewriteWalrusOperator:\n    \"\"\"See #10743\"\"\"\n\n    def test_assertion_walrus_operator(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def my_func(before, after):\n                return before == after\n\n            def change_value(value):\n                return value.lower()\n\n            def test_walrus_conversion():\n                a = \"Hello\"\n                assert not my_func(a, a := change_value(a))\n                assert a == \"hello\"\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_walrus_operator_dont_rewrite(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            'PYTEST_DONT_REWRITE'\n            def my_func(before, after):\n                return before == after\n\n            def change_value(value):\n                return value.lower()\n\n            def test_walrus_conversion_dont_rewrite():\n                a = \"Hello\"\n                assert not my_func(a, a := change_value(a))\n                assert a == \"hello\"\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_inline_walrus_operator(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def my_func(before, after):\n                return before == after\n\n            def test_walrus_conversion_inline():\n                a = \"Hello\"\n                assert not my_func(a, a := a.lower())\n                assert a == \"hello\"\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_inline_walrus_operator_reverse(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def my_func(before, after):\n                return before == after\n\n            def test_walrus_conversion_reverse():\n                a = \"Hello\"\n                assert my_func(a := a.lower(), a)\n                assert a == 'hello'\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_walrus_no_variable_name_conflict(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_walrus_conversion_no_conflict():\n                a = \"Hello\"\n                assert a == (b := a.lower())\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines([\"*AssertionError: assert 'Hello' == 'hello'\"])\n\n    def test_assertion_walrus_operator_true_assertion_and_changes_variable_value(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_walrus_conversion_succeed():\n                a = \"Hello\"\n                assert a != (a := a.lower())\n                assert a == 'hello'\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_walrus_operator_fail_assertion(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_walrus_conversion_fails():\n                a = \"Hello\"\n                assert a == (a := a.lower())\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines([\"*AssertionError: assert 'Hello' == 'hello'\"])\n\n    def test_assertion_walrus_operator_boolean_composite(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_walrus_operator_change_boolean_value():\n                a = True\n                assert a and True and ((a := False) is False) and (a is False) and ((a := None) is None)\n                assert a is None\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_walrus_operator_compare_boolean_fails(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_walrus_operator_change_boolean_value():\n                a = True\n                assert not (a and ((a := False) is False))\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines([\"*assert not (True and False is False)\"])\n\n    def test_assertion_walrus_operator_boolean_none_fails(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_walrus_operator_change_boolean_value():\n                a = True\n                assert not (a and ((a := None) is None))\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines([\"*assert not (True and None is None)\"])\n\n    def test_assertion_walrus_operator_value_changes_cleared_after_each_test(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_walrus_operator_change_value():\n                a = True\n                assert (a := None) is None\n\n            def test_walrus_operator_not_override_value():\n                a = True\n                assert a is True\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_namedexpr_compare_left_overwrite(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_namedexpr_compare_left_overwrite():\n                a = \"Hello\"\n                b = \"World\"\n                c = \"Test\"\n                assert (a := b) == c and (a := \"Test\") == \"Test\"\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines([\"*assert ('World' == 'Test'*\"])\n\n\nclass TestIssue11028:\n    def test_assertion_walrus_operator_in_operand(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_in_string():\n              assert (obj := \"foo\") in obj\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_walrus_operator_in_operand_json_dumps(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import json\n\n            def test_json_encoder():\n                assert (obj := \"foo\") in json.dumps(obj)\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_walrus_operator_equals_operand_function(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def f(a):\n                return a\n\n            def test_call_other_function_arg():\n              assert (obj := \"foo\") == f(obj)\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_walrus_operator_equals_operand_function_keyword_arg(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def f(a='test'):\n                return a\n\n            def test_call_other_function_k_arg():\n              assert (obj := \"foo\") == f(a=obj)\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_walrus_operator_equals_operand_function_arg_as_function(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def f(a='test'):\n                return a\n\n            def test_function_of_function():\n              assert (obj := \"foo\") == f(f(obj))\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n    def test_assertion_walrus_operator_gt_operand_function(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def add_one(a):\n                return a + 1\n\n            def test_gt():\n              assert (obj := 4) > add_one(obj)\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 1\n        result.stdout.fnmatch_lines([\"*assert 4 > 5\", \"*where 5 = add_one(4)\"])\n\n\nclass TestIssue11239:\n    def test_assertion_walrus_different_test_cases(self, pytester: Pytester) -> None:\n        \"\"\"Regression for (#11239)\n\n        Walrus operator rewriting would leak to separate test cases if they used the same variables.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                state = {\"x\": 2}.get(\"x\")\n                assert state is not None\n\n            def test_2():\n                db = {\"x\": 2}\n                assert (state := db.get(\"x\")) is not None\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n\n@pytest.mark.skipif(\n    sys.maxsize <= (2**31 - 1), reason=\"Causes OverflowError on 32bit systems\"\n)\n@pytest.mark.parametrize(\"offset\", [-1, +1])\ndef test_source_mtime_long_long(pytester: Pytester, offset) -> None:\n    \"\"\"Support modification dates after 2038 in rewritten files (#4903).\n\n    pytest would crash with:\n\n            fp.write(struct.pack(\"<ll\", mtime, size))\n        E   struct.error: argument out of range\n    \"\"\"\n    p = pytester.makepyfile(\n        \"\"\"\n        def test(): pass\n    \"\"\"\n    )\n    # use unsigned long timestamp which overflows signed long,\n    # which was the cause of the bug\n    # +1 offset also tests masking of 0xFFFFFFFF\n    timestamp = 2**32 + offset\n    os.utime(str(p), (timestamp, timestamp))\n    result = pytester.runpytest()\n    assert result.ret == 0\n\n\ndef test_rewrite_infinite_recursion(\n    pytester: Pytester, pytestconfig, monkeypatch\n) -> None:\n    \"\"\"Fix infinite recursion when writing pyc files: if an import happens to be triggered when writing the pyc\n    file, this would cause another call to the hook, which would trigger another pyc writing, which could\n    trigger another import, and so on. (#3506)\"\"\"\n    from _pytest.assertion import rewrite as rewritemod\n\n    pytester.syspathinsert()\n    pytester.makepyfile(test_foo=\"def test_foo(): pass\")\n    pytester.makepyfile(test_bar=\"def test_bar(): pass\")\n\n    original_write_pyc = rewritemod._write_pyc\n\n    write_pyc_called = []\n\n    def spy_write_pyc(*args, **kwargs):\n        # make a note that we have called _write_pyc\n        write_pyc_called.append(True)\n        # try to import a module at this point: we should not try to rewrite this module\n        assert hook.find_spec(\"test_bar\") is None\n        return original_write_pyc(*args, **kwargs)\n\n    monkeypatch.setattr(rewritemod, \"_write_pyc\", spy_write_pyc)\n    monkeypatch.setattr(sys, \"dont_write_bytecode\", False)\n\n    hook = AssertionRewritingHook(pytestconfig)\n    spec = hook.find_spec(\"test_foo\")\n    assert spec is not None\n    module = importlib.util.module_from_spec(spec)\n    hook.exec_module(module)\n    assert len(write_pyc_called) == 1\n\n\nclass TestEarlyRewriteBailout:\n    @pytest.fixture\n    def hook(\n        self, pytestconfig, monkeypatch, pytester: Pytester\n    ) -> Generator[AssertionRewritingHook]:\n        \"\"\"Returns a patched AssertionRewritingHook instance so we can configure its initial paths and track\n        if PathFinder.find_spec has been called.\n        \"\"\"\n        import importlib.machinery\n\n        self.find_spec_calls: list[str] = []\n        self.initial_paths: set[Path] = set()\n\n        class StubSession:\n            _initialpaths = self.initial_paths\n\n            def isinitpath(self, p):\n                return p in self._initialpaths\n\n        def spy_find_spec(name, path):\n            self.find_spec_calls.append(name)\n            return importlib.machinery.PathFinder.find_spec(name, path)\n\n        hook = AssertionRewritingHook(pytestconfig)\n        # use default patterns, otherwise we inherit pytest's testing config\n        with mock.patch.object(hook, \"fnpats\", [\"test_*.py\", \"*_test.py\"]):\n            monkeypatch.setattr(hook, \"_find_spec\", spy_find_spec)\n            hook.set_session(StubSession())  # type: ignore[arg-type]\n            pytester.syspathinsert()\n            yield hook\n\n    def test_basic(self, pytester: Pytester, hook: AssertionRewritingHook) -> None:\n        \"\"\"\n        Ensure we avoid calling PathFinder.find_spec when we know for sure a certain\n        module will not be rewritten to optimize assertion rewriting (#3918).\n        \"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def fix(): return 1\n        \"\"\"\n        )\n        pytester.makepyfile(test_foo=\"def test_foo(): pass\")\n        pytester.makepyfile(bar=\"def bar(): pass\")\n        foobar_path = pytester.makepyfile(foobar=\"def foobar(): pass\")\n        self.initial_paths.add(foobar_path)\n\n        # conftest files should always be rewritten\n        assert hook.find_spec(\"conftest\") is not None\n        assert self.find_spec_calls == [\"conftest\"]\n\n        # files matching \"python_files\" mask should always be rewritten\n        assert hook.find_spec(\"test_foo\") is not None\n        assert self.find_spec_calls == [\"conftest\", \"test_foo\"]\n\n        # file does not match \"python_files\": early bailout\n        assert hook.find_spec(\"bar\") is None\n        assert self.find_spec_calls == [\"conftest\", \"test_foo\"]\n\n        # file is an initial path (passed on the command-line): should be rewritten\n        assert hook.find_spec(\"foobar\") is not None\n        assert self.find_spec_calls == [\"conftest\", \"test_foo\", \"foobar\"]\n\n    def test_pattern_contains_subdirectories(\n        self, pytester: Pytester, hook: AssertionRewritingHook\n    ) -> None:\n        \"\"\"If one of the python_files patterns contain subdirectories (\"tests/**.py\") we can't bailout early\n        because we need to match with the full path, which can only be found by calling PathFinder.find_spec\n        \"\"\"\n        pytester.makepyfile(\n            **{\n                \"tests/file.py\": \"\"\"\\\n                    def test_simple_failure():\n                        assert 1 + 1 == 3\n                \"\"\"\n            }\n        )\n        pytester.syspathinsert(\"tests\")\n        with mock.patch.object(hook, \"fnpats\", [\"tests/**.py\"]):\n            assert hook.find_spec(\"file\") is not None\n            assert self.find_spec_calls == [\"file\"]\n\n    @pytest.mark.skipif(\n        sys.platform.startswith(\"win32\"), reason=\"cannot remove cwd on Windows\"\n    )\n    @pytest.mark.skipif(\n        sys.platform.startswith(\"sunos5\"), reason=\"cannot remove cwd on Solaris\"\n    )\n    def test_cwd_changed(self, pytester: Pytester, monkeypatch) -> None:\n        # Setup conditions for py's fspath trying to import pathlib on py34\n        # always (previously triggered via xdist only).\n        # Ref: https://github.com/pytest-dev/py/pull/207\n        monkeypatch.syspath_prepend(\"\")\n        monkeypatch.delitem(sys.modules, \"pathlib\", raising=False)\n\n        pytester.makepyfile(\n            **{\n                \"test_setup_nonexisting_cwd.py\": \"\"\"\\\n                    import os\n                    import tempfile\n\n                    with tempfile.TemporaryDirectory() as newpath:\n                        os.chdir(newpath)\n                \"\"\",\n                \"test_test.py\": \"\"\"\\\n                    def test():\n                        pass\n                \"\"\",\n            }\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n\nclass TestAssertionPass:\n    def test_option_default(self, pytester: Pytester) -> None:\n        config = pytester.parseconfig()\n        assert config.getini(\"enable_assertion_pass_hook\") is False\n\n    @pytest.fixture\n    def flag_on(self, pytester: Pytester):\n        pytester.makeini(\"[pytest]\\nenable_assertion_pass_hook = True\\n\")\n\n    @pytest.fixture\n    def hook_on(self, pytester: Pytester):\n        pytester.makeconftest(\n            \"\"\"\\\n            def pytest_assertion_pass(item, lineno, orig, expl):\n                raise Exception(\"Assertion Passed: {} {} at line {}\".format(orig, expl, lineno))\n            \"\"\"\n        )\n\n    def test_hook_call(self, pytester: Pytester, flag_on, hook_on) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n            def test_simple():\n                a=1\n                b=2\n                c=3\n                d=0\n\n                assert a+b == c+d\n\n            # cover failing assertions with a message\n            def test_fails():\n                assert False, \"assert with message\"\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            \"*Assertion Passed: a+b == c+d (1 + 2) == (3 + 0) at line 7*\"\n        )\n\n    def test_hook_call_with_parens(self, pytester: Pytester, flag_on, hook_on) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n            def f(): return 1\n            def test():\n                assert f()\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\"*Assertion Passed: f() 1\")\n\n    def test_hook_not_called_without_hookimpl(\n        self, pytester: Pytester, monkeypatch, flag_on\n    ) -> None:\n        \"\"\"Assertion pass should not be called (and hence formatting should\n        not occur) if there is no hook declared for pytest_assertion_pass\"\"\"\n\n        def raise_on_assertionpass(*_, **__):\n            raise Exception(\"Assertion passed called when it shouldn't!\")\n\n        monkeypatch.setattr(\n            _pytest.assertion.rewrite, \"_call_assertion_pass\", raise_on_assertionpass\n        )\n\n        pytester.makepyfile(\n            \"\"\"\\\n            def test_simple():\n                a=1\n                b=2\n                c=3\n                d=0\n\n                assert a+b == c+d\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(passed=1)\n\n    def test_hook_not_called_without_cmd_option(\n        self, pytester: Pytester, monkeypatch\n    ) -> None:\n        \"\"\"Assertion pass should not be called (and hence formatting should\n        not occur) if there is no hook declared for pytest_assertion_pass\"\"\"\n\n        def raise_on_assertionpass(*_, **__):\n            raise Exception(\"Assertion passed called when it shouldn't!\")\n\n        monkeypatch.setattr(\n            _pytest.assertion.rewrite, \"_call_assertion_pass\", raise_on_assertionpass\n        )\n\n        pytester.makeconftest(\n            \"\"\"\\\n            def pytest_assertion_pass(item, lineno, orig, expl):\n                raise Exception(\"Assertion Passed: {} {} at line {}\".format(orig, expl, lineno))\n            \"\"\"\n        )\n\n        pytester.makepyfile(\n            \"\"\"\\\n            def test_simple():\n                a=1\n                b=2\n                c=3\n                d=0\n\n                assert a+b == c+d\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(passed=1)\n\n\n# fmt: off\n@pytest.mark.parametrize(\n    (\"src\", \"expected\"),\n    (\n        pytest.param(b\"\", {}, id=\"trivial\"),\n        pytest.param(\n            b\"def x(): assert 1\\n\",\n            {1: \"1\"},\n            id=\"assert statement not on own line\",\n        ),\n        pytest.param(\n            b\"def x():\\n\"\n            b\"    assert 1\\n\"\n            b\"    assert 1+2\\n\",\n            {2: \"1\", 3: \"1+2\"},\n            id=\"multiple assertions\",\n        ),\n        pytest.param(\n            # changes in encoding cause the byte offsets to be different\n            \"# -*- coding: latin1\\n\"\n            \"def ÀÀÀÀÀ(): assert 1\\n\".encode(\"latin1\"),\n            {2: \"1\"},\n            id=\"latin1 encoded on first line\\n\",\n        ),\n        pytest.param(\n            # using the default utf-8 encoding\n            \"def ÀÀÀÀÀ(): assert 1\\n\".encode(),\n            {1: \"1\"},\n            id=\"utf-8 encoded on first line\",\n        ),\n        pytest.param(\n            b\"def x():\\n\"\n            b\"    assert (\\n\"\n            b\"        1 + 2  # comment\\n\"\n            b\"    )\\n\",\n            {2: \"(\\n        1 + 2  # comment\\n    )\"},\n            id=\"multi-line assertion\",\n        ),\n        pytest.param(\n            b\"def x():\\n\"\n            b\"    assert y == [\\n\"\n            b\"        1, 2, 3\\n\"\n            b\"    ]\\n\",\n            {2: \"y == [\\n        1, 2, 3\\n    ]\"},\n            id=\"multi line assert with list continuation\",\n        ),\n        pytest.param(\n            b\"def x():\\n\"\n            b\"    assert 1 + \\\\\\n\"\n            b\"        2\\n\",\n            {2: \"1 + \\\\\\n        2\"},\n            id=\"backslash continuation\",\n        ),\n        pytest.param(\n            b\"def x():\\n\"\n            b\"    assert x, y\\n\",\n            {2: \"x\"},\n            id=\"assertion with message\",\n        ),\n        pytest.param(\n            b\"def x():\\n\"\n            b\"    assert (\\n\"\n            b\"        f(1, 2, 3)\\n\"\n            b\"    ),  'f did not work!'\\n\",\n            {2: \"(\\n        f(1, 2, 3)\\n    )\"},\n            id=\"assertion with message, test spanning multiple lines\",\n        ),\n        pytest.param(\n            b\"def x():\\n\"\n            b\"    assert \\\\\\n\"\n            b\"        x\\\\\\n\"\n            b\"        , 'failure message'\\n\",\n            {2: \"x\"},\n            id=\"escaped newlines plus message\",\n        ),\n        pytest.param(\n            b\"def x(): assert 5\",\n            {1: \"5\"},\n            id=\"no newline at end of file\",\n        ),\n    ),\n)\ndef test_get_assertion_exprs(src, expected) -> None:\n    assert _get_assertion_exprs(src) == expected\n# fmt: on\n\n\ndef test_try_makedirs(monkeypatch, tmp_path: Path) -> None:\n    from _pytest.assertion.rewrite import try_makedirs\n\n    p = tmp_path / \"foo\"\n\n    # create\n    assert try_makedirs(p)\n    assert p.is_dir()\n\n    # already exist\n    assert try_makedirs(p)\n\n    # monkeypatch to simulate all error situations\n    def fake_mkdir(p, exist_ok=False, *, exc):\n        assert isinstance(p, Path)\n        raise exc\n\n    monkeypatch.setattr(os, \"makedirs\", partial(fake_mkdir, exc=FileNotFoundError()))\n    assert not try_makedirs(p)\n\n    monkeypatch.setattr(os, \"makedirs\", partial(fake_mkdir, exc=NotADirectoryError()))\n    assert not try_makedirs(p)\n\n    monkeypatch.setattr(os, \"makedirs\", partial(fake_mkdir, exc=PermissionError()))\n    assert not try_makedirs(p)\n\n    err = OSError()\n    err.errno = errno.EROFS\n    monkeypatch.setattr(os, \"makedirs\", partial(fake_mkdir, exc=err))\n    assert not try_makedirs(p)\n\n    err = OSError()\n    err.errno = errno.ENOSYS\n    monkeypatch.setattr(os, \"makedirs\", partial(fake_mkdir, exc=err))\n    assert not try_makedirs(p)\n\n    # unhandled OSError should raise\n    err = OSError()\n    err.errno = errno.ECHILD\n    monkeypatch.setattr(os, \"makedirs\", partial(fake_mkdir, exc=err))\n    with pytest.raises(OSError) as exc_info:\n        try_makedirs(p)\n    assert exc_info.value.errno == errno.ECHILD\n\n\nclass TestPyCacheDir:\n    @pytest.mark.parametrize(\n        \"prefix, source, expected\",\n        [\n            (\"c:/tmp/pycs\", \"d:/projects/src/foo.py\", \"c:/tmp/pycs/projects/src\"),\n            (None, \"d:/projects/src/foo.py\", \"d:/projects/src/__pycache__\"),\n            (\"/tmp/pycs\", \"/home/projects/src/foo.py\", \"/tmp/pycs/home/projects/src\"),\n            (None, \"/home/projects/src/foo.py\", \"/home/projects/src/__pycache__\"),\n        ],\n    )\n    def test_get_cache_dir(self, monkeypatch, prefix, source, expected) -> None:\n        monkeypatch.delenv(\"PYTHONPYCACHEPREFIX\", raising=False)\n        monkeypatch.setattr(sys, \"pycache_prefix\", prefix, raising=False)\n\n        assert get_cache_dir(Path(source)) == Path(expected)\n\n    def test_sys_pycache_prefix_integration(\n        self, tmp_path, monkeypatch, pytester: Pytester\n    ) -> None:\n        \"\"\"Integration test for sys.pycache_prefix (#4730).\"\"\"\n        pycache_prefix = tmp_path / \"my/pycs\"\n        monkeypatch.setattr(sys, \"pycache_prefix\", str(pycache_prefix))\n        monkeypatch.setattr(sys, \"dont_write_bytecode\", False)\n\n        pytester.makepyfile(\n            **{\n                \"src/test_foo.py\": \"\"\"\n                import bar\n                def test_foo():\n                    pass\n            \"\"\",\n                \"src/bar/__init__.py\": \"\",\n            }\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n        test_foo = pytester.path.joinpath(\"src/test_foo.py\")\n        bar_init = pytester.path.joinpath(\"src/bar/__init__.py\")\n        assert test_foo.is_file()\n        assert bar_init.is_file()\n\n        # test file: rewritten, custom pytest cache tag\n        test_foo_pyc = get_cache_dir(test_foo) / (\"test_foo\" + PYC_TAIL)\n        assert test_foo_pyc.is_file()\n\n        # normal file: not touched by pytest, normal cache tag\n        bar_init_pyc = (\n            get_cache_dir(bar_init) / f\"__init__.{sys.implementation.cache_tag}.pyc\"\n        )\n        assert bar_init_pyc.is_file()\n\n\nclass TestReprSizeVerbosity:\n    \"\"\"\n    Check that verbosity also controls the string length threshold to shorten it using\n    ellipsis.\n    \"\"\"\n\n    @pytest.mark.parametrize(\n        \"verbose, expected_size\",\n        [\n            (0, DEFAULT_REPR_MAX_SIZE),\n            (1, DEFAULT_REPR_MAX_SIZE * 10),\n            (2, None),\n            (3, None),\n        ],\n    )\n    def test_get_maxsize_for_saferepr(self, verbose: int, expected_size) -> None:\n        class FakeConfig:\n            def get_verbosity(self, verbosity_type: str | None = None) -> int:\n                return verbose\n\n        config = FakeConfig()\n        assert _get_maxsize_for_saferepr(cast(Config, config)) == expected_size\n\n    def test_get_maxsize_for_saferepr_no_config(self) -> None:\n        assert _get_maxsize_for_saferepr(None) == DEFAULT_REPR_MAX_SIZE\n\n    def create_test_file(self, pytester: Pytester, size: int) -> None:\n        pytester.makepyfile(\n            f\"\"\"\n            def test_very_long_string():\n                text = \"x\" * {size}\n                assert \"hello world\" in text\n            \"\"\"\n        )\n\n    def test_default_verbosity(self, pytester: Pytester) -> None:\n        self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE)\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*xxx...xxx*\"])\n\n    def test_increased_verbosity(self, pytester: Pytester) -> None:\n        self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE)\n        result = pytester.runpytest(\"-v\")\n        result.stdout.no_fnmatch_line(\"*xxx...xxx*\")\n\n    def test_max_increased_verbosity(self, pytester: Pytester) -> None:\n        self.create_test_file(pytester, DEFAULT_REPR_MAX_SIZE * 10)\n        result = pytester.runpytest(\"-vv\")\n        result.stdout.no_fnmatch_line(\"*xxx...xxx*\")\n\n\nclass TestIssue11140:\n    def test_constant_not_picked_as_module_docstring(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n            0\n\n            def test_foo():\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n\n\nclass TestSafereprUnbounded:\n    class Help:\n        def bound_method(self):  # pragma: no cover\n            pass\n\n    def test_saferepr_bound_method(self):\n        \"\"\"saferepr() of a bound method should show only the method name\"\"\"\n        assert _saferepr(self.Help().bound_method) == \"bound_method\"\n\n    def test_saferepr_unbounded(self):\n        \"\"\"saferepr() of an unbound method should still show the full information\"\"\"\n        obj = self.Help()\n        # using id() to fetch memory address fails on different platforms\n        pattern = re.compile(\n            rf\"<{Path(__file__).stem}.{self.__class__.__name__}.Help object at 0x[0-9a-fA-F]*>\",\n        )\n        assert pattern.match(_saferepr(obj))\n        assert (\n            _saferepr(self.Help)\n            == f\"<class '{Path(__file__).stem}.{self.__class__.__name__}.Help'>\"\n        )\n"
  },
  {
    "path": "testing/test_cacheprovider.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Generator\nfrom collections.abc import Sequence\nfrom enum import auto\nfrom enum import Enum\nimport os\nfrom pathlib import Path\nimport shutil\nfrom typing import Any\n\nfrom _pytest.compat import assert_never\nfrom _pytest.config import ExitCode\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nfrom _pytest.tmpdir import TempPathFactory\nimport pytest\n\n\npytest_plugins = (\"pytester\",)\n\n\nclass TestNewAPI:\n    def test_config_cache_mkdir(self, pytester: Pytester) -> None:\n        pytester.makeini(\"[pytest]\")\n        config = pytester.parseconfigure()\n        assert config.cache is not None\n        with pytest.raises(ValueError):\n            config.cache.mkdir(\"key/name\")\n\n        p = config.cache.mkdir(\"name\")\n        assert p.is_dir()\n\n    def test_cache_dir_permissions(self, pytester: Pytester) -> None:\n        \"\"\"The .pytest_cache directory should have world-readable permissions\n        (depending on umask).\n\n        Regression test for #12308.\n        \"\"\"\n        pytester.makeini(\"[pytest]\")\n        config = pytester.parseconfigure()\n        assert config.cache is not None\n        p = config.cache.mkdir(\"name\")\n        assert p.is_dir()\n        # Instead of messing with umask, make sure .pytest_cache has the same\n        # permissions as the default that `mkdir` gives `p`.\n        assert (p.parent.stat().st_mode & 0o777) == (p.stat().st_mode & 0o777)\n\n    def test_config_cache_dataerror(self, pytester: Pytester) -> None:\n        pytester.makeini(\"[pytest]\")\n        config = pytester.parseconfigure()\n        assert config.cache is not None\n        cache = config.cache\n        pytest.raises(TypeError, lambda: cache.set(\"key/name\", cache))\n        config.cache.set(\"key/name\", 0)\n        config.cache._getvaluepath(\"key/name\").write_bytes(b\"123invalid\")\n        val = config.cache.get(\"key/name\", -2)\n        assert val == -2\n\n    @pytest.mark.filterwarnings(\"ignore:could not create cache path\")\n    def test_cache_writefail_cachefile_silent(self, pytester: Pytester) -> None:\n        pytester.makeini(\"[pytest]\")\n        pytester.path.joinpath(\".pytest_cache\").write_text(\n            \"gone wrong\", encoding=\"utf-8\"\n        )\n        config = pytester.parseconfigure()\n        cache = config.cache\n        assert cache is not None\n        cache.set(\"test/broken\", [])\n\n    @pytest.fixture\n    def unwritable_cache_dir(self, pytester: Pytester) -> Generator[Path]:\n        cache_dir = pytester.path.joinpath(\".pytest_cache\")\n        cache_dir.mkdir()\n        mode = cache_dir.stat().st_mode\n        cache_dir.chmod(0)\n        if os.access(cache_dir, os.W_OK):\n            pytest.skip(\"Failed to make cache dir unwritable\")\n\n        yield cache_dir\n        cache_dir.chmod(mode)\n\n    @pytest.mark.filterwarnings(\n        \"ignore:could not create cache path:pytest.PytestWarning\"\n    )\n    def test_cache_writefail_permissions(\n        self, unwritable_cache_dir: Path, pytester: Pytester\n    ) -> None:\n        pytester.makeini(\"[pytest]\")\n        config = pytester.parseconfigure()\n        cache = config.cache\n        assert cache is not None\n        cache.set(\"test/broken\", [])\n\n    @pytest.mark.filterwarnings(\"default\")\n    def test_cache_failure_warns(\n        self,\n        pytester: Pytester,\n        monkeypatch: MonkeyPatch,\n        unwritable_cache_dir: Path,\n    ) -> None:\n        monkeypatch.setenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", \"1\")\n\n        pytester.makepyfile(\"def test_error(): raise Exception\")\n        result = pytester.runpytest()\n        assert result.ret == 1\n        # warnings from nodeids and lastfailed\n        result.stdout.fnmatch_lines(\n            [\n                # Validate location/stacklevel of warning from cacheprovider.\n                \"*= warnings summary =*\",\n                \"*/cacheprovider.py:*\",\n                \"  */cacheprovider.py:*: PytestCacheWarning: could not create cache path \"\n                f\"{unwritable_cache_dir}/v/cache/nodeids: *\",\n                '    config.cache.set(\"cache/nodeids\", sorted(self.cached_nodeids))',\n                \"*1 failed, 2 warnings in*\",\n            ]\n        )\n\n    def test_config_cache(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_configure(config):\n                # see that we get cache information early on\n                assert hasattr(config, \"cache\")\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_session(pytestconfig):\n                assert hasattr(pytestconfig, \"cache\")\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_cachefuncarg(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_cachefuncarg(cache):\n                val = cache.get(\"some/thing\", None)\n                assert val is None\n                cache.set(\"some/thing\", [1])\n                pytest.raises(TypeError, lambda: cache.get(\"some/thing\"))\n                val = cache.get(\"some/thing\", [])\n                assert val == [1]\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_custom_rel_cache_dir(self, pytester: Pytester) -> None:\n        rel_cache_dir = os.path.join(\"custom_cache_dir\", \"subdir\")\n        pytester.makeini(\n            f\"\"\"\n            [pytest]\n            cache_dir = {rel_cache_dir}\n        \"\"\"\n        )\n        pytester.makepyfile(test_errored=\"def test_error():\\n    assert False\")\n        pytester.runpytest()\n        assert pytester.path.joinpath(rel_cache_dir).is_dir()\n\n    def test_custom_abs_cache_dir(\n        self, pytester: Pytester, tmp_path_factory: TempPathFactory\n    ) -> None:\n        tmp = tmp_path_factory.mktemp(\"tmp\")\n        abs_cache_dir = tmp / \"custom_cache_dir\"\n        pytester.makeini(\n            f\"\"\"\n            [pytest]\n            cache_dir = {abs_cache_dir}\n        \"\"\"\n        )\n        pytester.makepyfile(test_errored=\"def test_error():\\n    assert False\")\n        pytester.runpytest()\n        assert abs_cache_dir.is_dir()\n\n    def test_custom_cache_dir_with_env_var(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"env_var\", \"custom_cache_dir\")\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            cache_dir = {cache_dir}\n        \"\"\".format(cache_dir=\"$env_var\")\n        )\n        pytester.makepyfile(test_errored=\"def test_error():\\n    assert False\")\n        pytester.runpytest()\n        assert pytester.path.joinpath(\"custom_cache_dir\").is_dir()\n\n\n@pytest.mark.parametrize(\"env\", ((), (\"TOX_ENV_DIR\", \"mydir/tox-env\")))\ndef test_cache_reportheader(\n    env: Sequence[str], pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    pytester.makepyfile(\"\"\"def test_foo(): pass\"\"\")\n    if env:\n        monkeypatch.setenv(*env)\n        expected = os.path.join(env[1], \".pytest_cache\")\n    else:\n        monkeypatch.delenv(\"TOX_ENV_DIR\", raising=False)\n        expected = \".pytest_cache\"\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines([f\"cachedir: {expected}\"])\n\n\ndef test_cache_reportheader_external_abspath(\n    pytester: Pytester, tmp_path_factory: TempPathFactory\n) -> None:\n    external_cache = tmp_path_factory.mktemp(\n        \"test_cache_reportheader_external_abspath_abs\"\n    )\n\n    pytester.makepyfile(\"def test_hello(): pass\")\n    pytester.makeini(\n        f\"\"\"\n    [pytest]\n    cache_dir = {external_cache}\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines([f\"cachedir: {external_cache}\"])\n\n\ndef test_cache_show(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--cache-show\")\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*cache is empty*\"])\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_configure(config):\n            config.cache.set(\"my/name\", [1,2,3])\n            config.cache.set(\"my/hello\", \"world\")\n            config.cache.set(\"other/some\", {1:2})\n            dp = config.cache.mkdir(\"mydb\")\n            dp.joinpath(\"hello\").touch()\n            dp.joinpath(\"world\").touch()\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 5  # no tests executed\n\n    result = pytester.runpytest(\"--cache-show\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*cachedir:*\",\n            \"*- cache values for '[*]' -*\",\n            \"cache/nodeids contains:\",\n            \"my/name contains:\",\n            \"  [1, 2, 3]\",\n            \"other/some contains:\",\n            \"  {*'1': 2}\",\n            \"*- cache directories for '[*]' -*\",\n            \"*mydb/hello*length 0*\",\n            \"*mydb/world*length 0*\",\n        ]\n    )\n    assert result.ret == 0\n\n    result = pytester.runpytest(\"--cache-show\", \"*/hello\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*cachedir:*\",\n            \"*- cache values for '[*]/hello' -*\",\n            \"my/hello contains:\",\n            \"  *'world'\",\n            \"*- cache directories for '[*]/hello' -*\",\n            \"d/mydb/hello*length 0*\",\n        ]\n    )\n    stdout = result.stdout.str()\n    assert \"other/some\" not in stdout\n    assert \"d/mydb/world\" not in stdout\n    assert result.ret == 0\n\n\nclass TestLastFailed:\n    def test_lastfailed_usecase(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        monkeypatch.setattr(\"sys.dont_write_bytecode\", True)\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_1(): assert 0\n            def test_2(): assert 0\n            def test_3(): assert 1\n            \"\"\"\n        )\n        result = pytester.runpytest(str(p))\n        result.stdout.fnmatch_lines([\"*2 failed*\"])\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_1(): assert 1\n            def test_2(): assert 1\n            def test_3(): assert 0\n            \"\"\"\n        )\n        result = pytester.runpytest(str(p), \"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 3 items / 1 deselected / 2 selected\",\n                \"run-last-failure: rerun previous 2 failures\",\n                \"*= 2 passed, 1 deselected in *\",\n            ]\n        )\n        result = pytester.runpytest(str(p), \"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 3 items\",\n                \"run-last-failure: no previously failed tests, not deselecting items.\",\n                \"*1 failed*2 passed*\",\n            ]\n        )\n        pytester.path.joinpath(\".pytest_cache\", \".git\").mkdir(parents=True)\n        result = pytester.runpytest(str(p), \"--lf\", \"--cache-clear\")\n        result.stdout.fnmatch_lines([\"*1 failed*2 passed*\"])\n        assert pytester.path.joinpath(\".pytest_cache\", \"README.md\").is_file()\n        assert pytester.path.joinpath(\".pytest_cache\", \".git\").is_dir()\n\n        # Run this again to make sure clear-cache is robust\n        if os.path.isdir(\".pytest_cache\"):\n            shutil.rmtree(\".pytest_cache\")\n        result = pytester.runpytest(\"--lf\", \"--cache-clear\")\n        result.stdout.fnmatch_lines([\"*1 failed*2 passed*\"])\n\n    def test_failedfirst_order(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_a=\"def test_always_passes(): pass\",\n            test_b=\"def test_always_fails(): assert 0\",\n        )\n        result = pytester.runpytest()\n        # Test order will be collection order; alphabetical\n        result.stdout.fnmatch_lines([\"test_a.py*\", \"test_b.py*\"])\n        result = pytester.runpytest(\"--ff\")\n        # Test order will be failing tests first\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items\",\n                \"run-last-failure: rerun previous 1 failure first\",\n                \"test_b.py*\",\n                \"test_a.py*\",\n            ]\n        )\n\n    def test_lastfailed_failedfirst_order(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_a=\"def test_always_passes(): assert 1\",\n            test_b=\"def test_always_fails(): assert 0\",\n        )\n        result = pytester.runpytest()\n        # Test order will be collection order; alphabetical\n        result.stdout.fnmatch_lines([\"test_a.py*\", \"test_b.py*\"])\n        result = pytester.runpytest(\"--lf\", \"--ff\")\n        # Test order will be failing tests first\n        result.stdout.fnmatch_lines([\"test_b.py*\"])\n        result.stdout.no_fnmatch_line(\"*test_a.py*\")\n\n    def test_lastfailed_difference_invocations(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        monkeypatch.setattr(\"sys.dont_write_bytecode\", True)\n        pytester.makepyfile(\n            test_a=\"\"\"\n                def test_a1(): assert 0\n                def test_a2(): assert 1\n            \"\"\",\n            test_b=\"def test_b1(): assert 0\",\n        )\n        p = pytester.path.joinpath(\"test_a.py\")\n        p2 = pytester.path.joinpath(\"test_b.py\")\n\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*2 failed*\"])\n        result = pytester.runpytest(\"--lf\", p2)\n        result.stdout.fnmatch_lines([\"*1 failed*\"])\n\n        pytester.makepyfile(test_b=\"def test_b1(): assert 1\")\n        result = pytester.runpytest(\"--lf\", p2)\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n        result = pytester.runpytest(\"--lf\", p)\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items / 1 deselected / 1 selected\",\n                \"run-last-failure: rerun previous 1 failure\",\n                \"*= 1 failed, 1 deselected in *\",\n            ]\n        )\n\n    def test_lastfailed_usecase_splice(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        monkeypatch.setattr(\"sys.dont_write_bytecode\", True)\n        pytester.makepyfile(\n            \"def test_1(): assert 0\", test_something=\"def test_2(): assert 0\"\n        )\n        p2 = pytester.path.joinpath(\"test_something.py\")\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*2 failed*\"])\n        result = pytester.runpytest(\"--lf\", p2)\n        result.stdout.fnmatch_lines([\"*1 failed*\"])\n        result = pytester.runpytest(\"--lf\")\n        result.stdout.fnmatch_lines([\"*2 failed*\"])\n\n    def test_lastfailed_xpass(self, pytester: Pytester) -> None:\n        pytester.inline_runsource(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail\n            def test_hello():\n                assert 1\n        \"\"\"\n        )\n        config = pytester.parseconfigure()\n        assert config.cache is not None\n        lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n        assert lastfailed == -1\n\n    def test_non_serializable_parametrize(self, pytester: Pytester) -> None:\n        \"\"\"Test that failed parametrized tests with unmarshable parameters\n        don't break pytest-cache.\n        \"\"\"\n        pytester.makepyfile(\n            r\"\"\"\n            import pytest\n\n            @pytest.mark.parametrize('val', [\n                b'\\xac\\x10\\x02G',\n            ])\n            def test_fail(val):\n                assert False\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 failed in*\"])\n\n    @pytest.mark.parametrize(\"parent\", (\"directory\", \"package\"))\n    def test_terminal_report_lastfailed(self, pytester: Pytester, parent: str) -> None:\n        if parent == \"package\":\n            pytester.makepyfile(\n                __init__=\"\",\n            )\n\n        test_a = pytester.makepyfile(\n            test_a=\"\"\"\n            def test_a1(): pass\n            def test_a2(): pass\n        \"\"\"\n        )\n        test_b = pytester.makepyfile(\n            test_b=\"\"\"\n            def test_b1(): assert 0\n            def test_b2(): assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 4 items\", \"*2 failed, 2 passed in*\"])\n\n        result = pytester.runpytest(\"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items\",\n                \"run-last-failure: rerun previous 2 failures (skipped 1 file)\",\n                \"*2 failed in*\",\n            ]\n        )\n\n        result = pytester.runpytest(test_a, \"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items\",\n                \"run-last-failure: 2 known failures not in selected tests\",\n                \"*2 passed in*\",\n            ]\n        )\n\n        result = pytester.runpytest(test_b, \"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items\",\n                \"run-last-failure: rerun previous 2 failures\",\n                \"*2 failed in*\",\n            ]\n        )\n\n        result = pytester.runpytest(\"test_b.py::test_b1\", \"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"run-last-failure: rerun previous 1 failure\",\n                \"*1 failed in*\",\n            ]\n        )\n\n    def test_terminal_report_failedfirst(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_a=\"\"\"\n            def test_a1(): assert 0\n            def test_a2(): pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 2 items\", \"*1 failed, 1 passed in*\"])\n\n        result = pytester.runpytest(\"--ff\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items\",\n                \"run-last-failure: rerun previous 1 failure first\",\n                \"*1 failed, 1 passed in*\",\n            ]\n        )\n\n    def test_lastfailed_collectfailure(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        pytester.makepyfile(\n            test_maybe=\"\"\"\n            import os\n            env = os.environ\n            if '1' == env['FAILIMPORT']:\n                raise ImportError('fail')\n            def test_hello():\n                assert '0' == env['FAILTEST']\n        \"\"\"\n        )\n\n        def rlf(fail_import: int, fail_run: int) -> Any:\n            monkeypatch.setenv(\"FAILIMPORT\", str(fail_import))\n            monkeypatch.setenv(\"FAILTEST\", str(fail_run))\n\n            pytester.runpytest(\"-q\")\n            config = pytester.parseconfigure()\n            assert config.cache is not None\n            lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n            return lastfailed\n\n        lastfailed = rlf(fail_import=0, fail_run=0)\n        assert lastfailed == -1\n\n        lastfailed = rlf(fail_import=1, fail_run=0)\n        assert list(lastfailed) == [\"test_maybe.py\"]\n\n        lastfailed = rlf(fail_import=0, fail_run=1)\n        assert list(lastfailed) == [\"test_maybe.py::test_hello\"]\n\n    def test_lastfailed_failure_subset(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        pytester.makepyfile(\n            test_maybe=\"\"\"\n            import os\n            env = os.environ\n            if '1' == env['FAILIMPORT']:\n                raise ImportError('fail')\n            def test_hello():\n                assert '0' == env['FAILTEST']\n        \"\"\"\n        )\n\n        pytester.makepyfile(\n            test_maybe2=\"\"\"\n            import os\n            env = os.environ\n            if '1' == env['FAILIMPORT']:\n                raise ImportError('fail')\n\n            def test_hello():\n                assert '0' == env['FAILTEST']\n\n            def test_pass():\n                pass\n        \"\"\"\n        )\n\n        def rlf(\n            fail_import: int, fail_run: int, args: Sequence[str] = ()\n        ) -> tuple[Any, Any]:\n            monkeypatch.setenv(\"FAILIMPORT\", str(fail_import))\n            monkeypatch.setenv(\"FAILTEST\", str(fail_run))\n\n            result = pytester.runpytest(\"-q\", \"--lf\", *args)\n            config = pytester.parseconfigure()\n            assert config.cache is not None\n            lastfailed = config.cache.get(\"cache/lastfailed\", -1)\n            return result, lastfailed\n\n        result, lastfailed = rlf(fail_import=0, fail_run=0)\n        assert lastfailed == -1\n        result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n        result, lastfailed = rlf(fail_import=1, fail_run=0)\n        assert sorted(list(lastfailed)) == [\"test_maybe.py\", \"test_maybe2.py\"]\n\n        result, lastfailed = rlf(fail_import=0, fail_run=0, args=(\"test_maybe2.py\",))\n        assert list(lastfailed) == [\"test_maybe.py\"]\n\n        # edge case of test selection - even if we remember failures\n        # from other tests we still need to run all tests if no test\n        # matches the failures\n        result, lastfailed = rlf(fail_import=0, fail_run=0, args=(\"test_maybe2.py\",))\n        assert list(lastfailed) == [\"test_maybe.py\"]\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n    def test_lastfailed_creates_cache_when_needed(self, pytester: Pytester) -> None:\n        # Issue #1342\n        pytester.makepyfile(test_empty=\"\")\n        pytester.runpytest(\"-q\", \"--lf\")\n        assert not os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n        pytester.makepyfile(test_successful=\"def test_success():\\n    assert True\")\n        pytester.runpytest(\"-q\", \"--lf\")\n        assert not os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n        pytester.makepyfile(test_errored=\"def test_error():\\n    assert False\")\n        pytester.runpytest(\"-q\", \"--lf\")\n        assert os.path.exists(\".pytest_cache/v/cache/lastfailed\")\n\n    def test_xfail_not_considered_failure(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail\n            def test(): assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n        assert self.get_cached_last_failed(pytester) == []\n\n    def test_xfail_strict_considered_failure(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail(strict=True)\n            def test(): pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 failed*\"])\n        assert self.get_cached_last_failed(pytester) == [\n            \"test_xfail_strict_considered_failure.py::test\"\n        ]\n\n    @pytest.mark.parametrize(\"mark\", [\"mark.xfail\", \"mark.skip\"])\n    def test_failed_changed_to_xfail_or_skip(\n        self, pytester: Pytester, mark: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test(): assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert self.get_cached_last_failed(pytester) == [\n            \"test_failed_changed_to_xfail_or_skip.py::test\"\n        ]\n        assert result.ret == 1\n\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest\n            @pytest.{mark}\n            def test(): assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret == 0\n        assert self.get_cached_last_failed(pytester) == []\n        assert result.ret == 0\n\n    @pytest.mark.parametrize(\"quiet\", [True, False])\n    @pytest.mark.parametrize(\"opt\", [\"--ff\", \"--lf\"])\n    def test_lf_and_ff_prints_no_needless_message(\n        self, quiet: bool, opt: str, pytester: Pytester\n    ) -> None:\n        # Issue 3853\n        pytester.makepyfile(\"def test(): assert 0\")\n        args = [opt]\n        if quiet:\n            args.append(\"-q\")\n        result = pytester.runpytest(*args)\n        result.stdout.no_fnmatch_line(\"*run all*\")\n\n        result = pytester.runpytest(*args)\n        if quiet:\n            result.stdout.no_fnmatch_line(\"*run all*\")\n        else:\n            assert \"rerun previous\" in result.stdout.str()\n\n    def get_cached_last_failed(self, pytester: Pytester) -> list[str]:\n        config = pytester.parseconfigure()\n        assert config.cache is not None\n        return sorted(config.cache.get(\"cache/lastfailed\", {}))\n\n    def test_cache_cumulative(self, pytester: Pytester) -> None:\n        \"\"\"Test workflow where user fixes errors gradually file by file using --lf.\"\"\"\n        # 1. initial run\n        test_bar = pytester.makepyfile(\n            test_bar=\"\"\"\n            def test_bar_1(): pass\n            def test_bar_2(): assert 0\n        \"\"\"\n        )\n        test_foo = pytester.makepyfile(\n            test_foo=\"\"\"\n            def test_foo_3(): pass\n            def test_foo_4(): assert 0\n        \"\"\"\n        )\n        pytester.runpytest()\n        assert self.get_cached_last_failed(pytester) == [\n            \"test_bar.py::test_bar_2\",\n            \"test_foo.py::test_foo_4\",\n        ]\n\n        # 2. fix test_bar_2, run only test_bar.py\n        pytester.makepyfile(\n            test_bar=\"\"\"\n            def test_bar_1(): pass\n            def test_bar_2(): pass\n        \"\"\"\n        )\n        result = pytester.runpytest(test_bar)\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n        # ensure cache does not forget that test_foo_4 failed once before\n        assert self.get_cached_last_failed(pytester) == [\"test_foo.py::test_foo_4\"]\n\n        result = pytester.runpytest(\"--last-failed\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"run-last-failure: rerun previous 1 failure (skipped 1 file)\",\n                \"*= 1 failed in *\",\n            ]\n        )\n        assert self.get_cached_last_failed(pytester) == [\"test_foo.py::test_foo_4\"]\n\n        # 3. fix test_foo_4, run only test_foo.py\n        test_foo = pytester.makepyfile(\n            test_foo=\"\"\"\n            def test_foo_3(): pass\n            def test_foo_4(): pass\n        \"\"\"\n        )\n        result = pytester.runpytest(test_foo, \"--last-failed\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items / 1 deselected / 1 selected\",\n                \"run-last-failure: rerun previous 1 failure\",\n                \"*= 1 passed, 1 deselected in *\",\n            ]\n        )\n        assert self.get_cached_last_failed(pytester) == []\n\n        result = pytester.runpytest(\"--last-failed\")\n        result.stdout.fnmatch_lines([\"*4 passed*\"])\n        assert self.get_cached_last_failed(pytester) == []\n\n    def test_lastfailed_no_failures_behavior_all_passed(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_1(): pass\n            def test_2(): pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n        result = pytester.runpytest(\"--lf\")\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n        result = pytester.runpytest(\"--lf\", \"--lfnf\", \"all\")\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n        # Ensure the list passed to pytest_deselected is a copy,\n        # and not a reference which is cleared right after.\n        pytester.makeconftest(\n            \"\"\"\n            deselected = []\n\n            def pytest_deselected(items):\n                global deselected\n                deselected = items\n\n            def pytest_sessionfinish():\n                print(\"\\\\ndeselected={}\".format(len(deselected)))\n        \"\"\"\n        )\n\n        result = pytester.runpytest(\"--lf\", \"--lfnf\", \"none\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items / 2 deselected / 0 selected\",\n                \"run-last-failure: no previously failed tests, deselecting all items.\",\n                \"deselected=2\",\n                \"* 2 deselected in *\",\n            ]\n        )\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n    def test_lastfailed_no_failures_behavior_empty_cache(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_1(): pass\n            def test_2(): assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--lf\", \"--cache-clear\")\n        result.stdout.fnmatch_lines([\"*1 failed*1 passed*\"])\n        result = pytester.runpytest(\"--lf\", \"--cache-clear\", \"--lfnf\", \"all\")\n        result.stdout.fnmatch_lines([\"*1 failed*1 passed*\"])\n        result = pytester.runpytest(\"--lf\", \"--cache-clear\", \"--lfnf\", \"none\")\n        result.stdout.fnmatch_lines([\"*2 desel*\"])\n\n    def test_lastfailed_skip_collection(self, pytester: Pytester) -> None:\n        \"\"\"\n        Test --lf behavior regarding skipping collection of files that are not marked as\n        failed in the cache (#5172).\n        \"\"\"\n        pytester.makepyfile(\n            **{\n                \"pkg1/test_1.py\": \"\"\"\n                import pytest\n\n                @pytest.mark.parametrize('i', range(3))\n                def test_1(i): pass\n            \"\"\",\n                \"pkg2/test_2.py\": \"\"\"\n                import pytest\n\n                @pytest.mark.parametrize('i', range(5))\n                def test_1(i):\n                    assert i not in (1, 3)\n            \"\"\",\n            }\n        )\n        # first run: collects 8 items (test_1: 3, test_2: 5)\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 8 items\", \"*2 failed*6 passed*\"])\n        # second run: collects only 5 items from test_2, because all tests from test_1 have passed\n        result = pytester.runpytest(\"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items\",\n                \"run-last-failure: rerun previous 2 failures (skipped 1 file)\",\n                \"*= 2 failed in *\",\n            ]\n        )\n\n        # add another file and check if message is correct when skipping more than 1 file\n        pytester.makepyfile(\n            **{\n                \"pkg1/test_3.py\": \"\"\"\n                def test_3(): pass\n            \"\"\"\n            }\n        )\n        result = pytester.runpytest(\"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items\",\n                \"run-last-failure: rerun previous 2 failures (skipped 2 files)\",\n                \"*= 2 failed in *\",\n            ]\n        )\n\n    def test_lastfailed_skip_collection_with_nesting(self, pytester: Pytester) -> None:\n        \"\"\"Check that file skipping works even when the file with failures is\n        nested at a different level of the collection tree.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"test_1.py\": \"\"\"\n                    def test_1(): pass\n                \"\"\",\n                \"pkg/__init__.py\": \"\",\n                \"pkg/test_2.py\": \"\"\"\n                    def test_2(): assert False\n                \"\"\",\n            }\n        )\n        # first run\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 2 items\", \"*1 failed*1 passed*\"])\n        # second run - test_1.py is skipped.\n        result = pytester.runpytest(\"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"run-last-failure: rerun previous 1 failure (skipped 1 file)\",\n                \"*= 1 failed in *\",\n            ]\n        )\n\n    def test_lastfailed_with_known_failures_not_being_selected(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            **{\n                \"pkg1/test_1.py\": \"\"\"def test_1(): assert 0\"\"\",\n                \"pkg1/test_2.py\": \"\"\"def test_2(): pass\"\"\",\n            }\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 2 items\", \"* 1 failed, 1 passed in *\"])\n\n        Path(\"pkg1/test_1.py\").unlink()\n        result = pytester.runpytest(\"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"run-last-failure: 1 known failures not in selected tests\",\n                \"* 1 passed in *\",\n            ]\n        )\n\n        # Recreate file with known failure.\n        pytester.makepyfile(**{\"pkg1/test_1.py\": \"\"\"def test_1(): assert 0\"\"\"})\n        result = pytester.runpytest(\"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"run-last-failure: rerun previous 1 failure (skipped 1 file)\",\n                \"* 1 failed in *\",\n            ]\n        )\n\n        # Remove/rename test: collects the file again.\n        pytester.makepyfile(**{\"pkg1/test_1.py\": \"\"\"def test_renamed(): assert 0\"\"\"})\n        result = pytester.runpytest(\"--lf\", \"-rf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items\",\n                \"run-last-failure: 1 known failures not in selected tests\",\n                \"pkg1/test_1.py F *\",\n                \"pkg1/test_2.py . *\",\n                \"FAILED pkg1/test_1.py::test_renamed - assert 0\",\n                \"* 1 failed, 1 passed in *\",\n            ]\n        )\n\n        result = pytester.runpytest(\"--lf\", \"--co\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"run-last-failure: rerun previous 1 failure (skipped 1 file)\",\n                \"\",\n                \"<Dir *>\",\n                \"  <Dir pkg1>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_renamed>\",\n            ]\n        )\n\n    def test_lastfailed_args_with_deselected(self, pytester: Pytester) -> None:\n        \"\"\"Test regression with --lf running into NoMatch error.\n\n        This was caused by it not collecting (non-failed) nodes given as\n        arguments.\n        \"\"\"\n        pytester.makepyfile(\n            **{\n                \"pkg1/test_1.py\": \"\"\"\n                    def test_pass(): pass\n                    def test_fail(): assert 0\n                \"\"\",\n            }\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 2 items\", \"* 1 failed, 1 passed in *\"])\n        assert result.ret == 1\n\n        result = pytester.runpytest(\"pkg1/test_1.py::test_pass\", \"--lf\", \"--co\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines(\n            [\n                \"*collected 1 item\",\n                \"run-last-failure: 1 known failures not in selected tests\",\n                \"\",\n                \"<Dir *>\",\n                \"  <Dir pkg1>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_pass>\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest(\n            \"pkg1/test_1.py::test_pass\", \"pkg1/test_1.py::test_fail\", \"--lf\", \"--co\"\n        )\n        assert result.ret == 0\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 2 items / 1 deselected / 1 selected\",\n                \"run-last-failure: rerun previous 1 failure\",\n                \"\",\n                \"<Dir *>\",\n                \"  <Dir pkg1>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_fail>\",\n                \"*= 1/2 tests collected (1 deselected) in *\",\n            ],\n        )\n\n    def test_lastfailed_with_class_items(self, pytester: Pytester) -> None:\n        \"\"\"Test regression with --lf deselecting whole classes.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"pkg1/test_1.py\": \"\"\"\n                    class TestFoo:\n                        def test_pass(self): pass\n                        def test_fail(self): assert 0\n\n                    def test_other(): assert 0\n                \"\"\",\n            }\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 3 items\", \"* 2 failed, 1 passed in *\"])\n        assert result.ret == 1\n\n        result = pytester.runpytest(\"--lf\", \"--co\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 3 items / 1 deselected / 2 selected\",\n                \"run-last-failure: rerun previous 2 failures\",\n                \"\",\n                \"<Dir *>\",\n                \"  <Dir pkg1>\",\n                \"    <Module test_1.py>\",\n                \"      <Class TestFoo>\",\n                \"        <Function test_fail>\",\n                \"      <Function test_other>\",\n                \"\",\n                \"*= 2/3 tests collected (1 deselected) in *\",\n            ],\n            consecutive=True,\n        )\n\n    def test_lastfailed_with_all_filtered(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            **{\n                \"pkg1/test_1.py\": \"\"\"\n                    def test_fail(): assert 0\n                    def test_pass(): pass\n                \"\"\",\n            }\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 2 items\", \"* 1 failed, 1 passed in *\"])\n        assert result.ret == 1\n\n        # Remove known failure.\n        pytester.makepyfile(\n            **{\n                \"pkg1/test_1.py\": \"\"\"\n                    def test_pass(): pass\n                \"\"\",\n            }\n        )\n        result = pytester.runpytest(\"--lf\", \"--co\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"run-last-failure: 1 known failures not in selected tests\",\n                \"\",\n                \"<Dir *>\",\n                \"  <Dir pkg1>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_pass>\",\n                \"\",\n                \"*= 1 test collected in*\",\n            ],\n            consecutive=True,\n        )\n        assert result.ret == 0\n\n    def test_packages(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #7758.\n\n        The particular issue here was that Package nodes were included in the\n        filtering, being themselves Modules for the __init__.py, even if they\n        had failed Modules in them.\n\n        The tests includes a test in an __init__.py file just to make sure the\n        fix doesn't somehow regress that, it is not critical for the issue.\n        \"\"\"\n        pytester.makepyfile(\n            **{\n                \"__init__.py\": \"\",\n                \"a/__init__.py\": \"def test_a_init(): assert False\",\n                \"a/test_one.py\": \"def test_1(): assert False\",\n                \"b/__init__.py\": \"\",\n                \"b/test_two.py\": \"def test_2(): assert False\",\n            },\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            python_files = *.py\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.assert_outcomes(failed=3)\n        result = pytester.runpytest(\"--lf\")\n        result.assert_outcomes(failed=3)\n\n    def test_non_python_file_skipped(\n        self,\n        pytester: Pytester,\n        dummy_yaml_custom_test: None,\n    ) -> None:\n        pytester.makepyfile(\n            **{\n                \"test_bad.py\": \"\"\"def test_bad(): assert False\"\"\",\n            },\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 2 items\", \"* 1 failed, 1 passed in *\"])\n\n        result = pytester.runpytest(\"--lf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"run-last-failure: rerun previous 1 failure (skipped 1 file)\",\n                \"* 1 failed in *\",\n            ]\n        )\n\n\nclass TestNewFirst:\n    def test_newfirst_usecase(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            **{\n                \"test_1/test_1.py\": \"\"\"\n                def test_1(): assert 1\n            \"\"\",\n                \"test_2/test_2.py\": \"\"\"\n                def test_1(): assert 1\n            \"\"\",\n            }\n        )\n\n        p1 = pytester.path.joinpath(\"test_1/test_1.py\")\n        os.utime(p1, ns=(p1.stat().st_atime_ns, int(1e9)))\n\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines(\n            [\"*test_1/test_1.py::test_1 PASSED*\", \"*test_2/test_2.py::test_1 PASSED*\"]\n        )\n\n        result = pytester.runpytest(\"-v\", \"--nf\")\n        result.stdout.fnmatch_lines(\n            [\"*test_2/test_2.py::test_1 PASSED*\", \"*test_1/test_1.py::test_1 PASSED*\"]\n        )\n\n        p1.write_text(\n            \"def test_1(): assert 1\\ndef test_2(): assert 1\\n\", encoding=\"utf-8\"\n        )\n        os.utime(p1, ns=(p1.stat().st_atime_ns, int(1e9)))\n\n        result = pytester.runpytest(\"--nf\", \"--collect-only\", \"-q\")\n        result.stdout.fnmatch_lines(\n            [\n                \"test_1/test_1.py::test_2\",\n                \"test_2/test_2.py::test_1\",\n                \"test_1/test_1.py::test_1\",\n            ]\n        )\n\n        # Newest first with (plugin) pytest_collection_modifyitems hook.\n        pytester.makepyfile(\n            myplugin=\"\"\"\n            def pytest_collection_modifyitems(items):\n                items[:] = sorted(items, key=lambda item: item.nodeid)\n                print(\"new_items:\", [x.nodeid for x in items])\n            \"\"\"\n        )\n        pytester.syspathinsert()\n        result = pytester.runpytest(\"--nf\", \"-p\", \"myplugin\", \"--collect-only\", \"-q\")\n        result.stdout.fnmatch_lines(\n            [\n                \"new_items: *test_1.py*test_1.py*test_2.py*\",\n                \"test_1/test_1.py::test_2\",\n                \"test_2/test_2.py::test_1\",\n                \"test_1/test_1.py::test_1\",\n            ]\n        )\n\n    def test_newfirst_parametrize(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            **{\n                \"test_1/test_1.py\": \"\"\"\n                import pytest\n                @pytest.mark.parametrize('num', [1, 2])\n                def test_1(num): assert num\n            \"\"\",\n                \"test_2/test_2.py\": \"\"\"\n                import pytest\n                @pytest.mark.parametrize('num', [1, 2])\n                def test_1(num): assert num\n            \"\"\",\n            }\n        )\n\n        p1 = pytester.path.joinpath(\"test_1/test_1.py\")\n        os.utime(p1, ns=(p1.stat().st_atime_ns, int(1e9)))\n\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_1/test_1.py::test_1[1*\",\n                \"*test_1/test_1.py::test_1[2*\",\n                \"*test_2/test_2.py::test_1[1*\",\n                \"*test_2/test_2.py::test_1[2*\",\n            ]\n        )\n\n        result = pytester.runpytest(\"-v\", \"--nf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_2/test_2.py::test_1[1*\",\n                \"*test_2/test_2.py::test_1[2*\",\n                \"*test_1/test_1.py::test_1[1*\",\n                \"*test_1/test_1.py::test_1[2*\",\n            ]\n        )\n\n        p1.write_text(\n            \"import pytest\\n\"\n            \"@pytest.mark.parametrize('num', [1, 2, 3])\\n\"\n            \"def test_1(num): assert num\\n\",\n            encoding=\"utf-8\",\n        )\n        os.utime(p1, ns=(p1.stat().st_atime_ns, int(1e9)))\n\n        # Running only a subset does not forget about existing ones.\n        result = pytester.runpytest(\"-v\", \"--nf\", \"test_2/test_2.py\")\n        result.stdout.fnmatch_lines(\n            [\"*test_2/test_2.py::test_1[1*\", \"*test_2/test_2.py::test_1[2*\"]\n        )\n\n        result = pytester.runpytest(\"-v\", \"--nf\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_1/test_1.py::test_1[3*\",\n                \"*test_2/test_2.py::test_1[1*\",\n                \"*test_2/test_2.py::test_1[2*\",\n                \"*test_1/test_1.py::test_1[1*\",\n                \"*test_1/test_1.py::test_1[2*\",\n            ]\n        )\n\n\nclass TestReadme:\n    def check_readme(self, pytester: Pytester) -> bool:\n        config = pytester.parseconfigure()\n        assert config.cache is not None\n        readme = config.cache._cachedir.joinpath(\"README.md\")\n        return readme.is_file()\n\n    def test_readme_passed(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\"def test_always_passes(): pass\")\n        pytester.runpytest()\n        assert self.check_readme(pytester) is True\n\n    def test_readme_failed(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\"def test_always_fails(): assert 0\")\n        pytester.runpytest()\n        assert self.check_readme(pytester) is True\n\n\nclass Action(Enum):\n    \"\"\"Action to perform on the cache directory.\"\"\"\n\n    MKDIR = auto()\n    SET = auto()\n\n\n@pytest.mark.parametrize(\"action\", list(Action))\ndef test_gitignore(\n    pytester: Pytester,\n    action: Action,\n) -> None:\n    \"\"\"Ensure we automatically create .gitignore file in the pytest_cache directory (#3286).\"\"\"\n    from _pytest.cacheprovider import Cache\n\n    config = pytester.parseconfig()\n    cache = Cache.for_config(config, _ispytest=True)\n    if action == Action.MKDIR:\n        cache.mkdir(\"foo\")\n    elif action == Action.SET:\n        cache.set(\"foo\", \"bar\")\n    else:\n        assert_never(action)\n    msg = \"# Created by pytest automatically.\\n*\\n\"\n    gitignore_path = cache._cachedir.joinpath(\".gitignore\")\n    assert gitignore_path.read_text(encoding=\"UTF-8\") == msg\n\n    # Does not overwrite existing/custom one.\n    gitignore_path.write_text(\"custom\", encoding=\"utf-8\")\n    if action == Action.MKDIR:\n        cache.mkdir(\"something\")\n    elif action == Action.SET:\n        cache.set(\"something\", \"else\")\n    else:\n        assert_never(action)\n    assert gitignore_path.read_text(encoding=\"UTF-8\") == \"custom\"\n\n\ndef test_preserve_keys_order(pytester: Pytester) -> None:\n    \"\"\"Ensure keys order is preserved when saving dicts (#9205).\"\"\"\n    from _pytest.cacheprovider import Cache\n\n    config = pytester.parseconfig()\n    cache = Cache.for_config(config, _ispytest=True)\n    cache.set(\"foo\", {\"z\": 1, \"b\": 2, \"a\": 3, \"d\": 10})\n    read_back = cache.get(\"foo\", None)\n    assert list(read_back.items()) == [(\"z\", 1), (\"b\", 2), (\"a\", 3), (\"d\", 10)]\n\n\ndef test_does_not_create_boilerplate_in_existing_dirs(pytester: Pytester) -> None:\n    from _pytest.cacheprovider import Cache\n\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        cache_dir = .\n        \"\"\"\n    )\n    config = pytester.parseconfig()\n    cache = Cache.for_config(config, _ispytest=True)\n    cache.set(\"foo\", \"bar\")\n\n    assert os.path.isdir(\"v\")  # cache contents\n    assert not os.path.exists(\".gitignore\")\n    assert not os.path.exists(\"README.md\")\n\n\ndef test_cachedir_tag(pytester: Pytester) -> None:\n    \"\"\"Ensure we automatically create CACHEDIR.TAG file in the pytest_cache directory (#4278).\"\"\"\n    from _pytest.cacheprovider import Cache\n    from _pytest.cacheprovider import CACHEDIR_FILES\n\n    config = pytester.parseconfig()\n    cache = Cache.for_config(config, _ispytest=True)\n    cache.set(\"foo\", \"bar\")\n    cachedir_tag_path = cache._cachedir.joinpath(\"CACHEDIR.TAG\")\n    assert cachedir_tag_path.read_bytes() == CACHEDIR_FILES[\"CACHEDIR.TAG\"]\n\n\ndef test_clioption_with_cacheshow_and_help(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--cache-show\", \"--help\")\n    assert result.ret == 0\n\n\ndef test_make_cachedir_cleans_up_on_base_exception(\n    tmp_path: Path,\n    monkeypatch: MonkeyPatch,\n) -> None:\n    \"\"\"Ensure _make_cachedir cleans up the temp directory on BaseException.\n\n    When a BaseException (like KeyboardInterrupt) is raised during cache\n    directory creation, the temporary directory should be cleaned up before\n    re-raising the exception.\n    \"\"\"\n    from _pytest.cacheprovider import _make_cachedir\n\n    target = tmp_path / \".pytest_cache\"\n\n    def raise_keyboard_interrupt(self: Path, target: Path) -> None:\n        raise KeyboardInterrupt(\"simulated interrupt\")\n\n    # Patch Path.rename only for the duration of the _make_cachedir call\n    with monkeypatch.context() as m:\n        m.setattr(Path, \"rename\", raise_keyboard_interrupt)\n\n        # Verify the exception is re-raised\n        with pytest.raises(KeyboardInterrupt, match=\"simulated interrupt\"):\n            _make_cachedir(target)\n\n    # Verify no temp directories were left behind\n    temp_dirs = list(tmp_path.glob(\"pytest-cache-files-*\"))\n    assert temp_dirs == [], f\"Temp directories not cleaned up: {temp_dirs}\"\n\n    # Verify the target directory was not created\n    assert not target.exists()\n"
  },
  {
    "path": "testing/test_capture.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nimport contextlib\nimport io\nfrom io import UnsupportedOperation\nimport os\nimport re\nimport subprocess\nimport sys\nimport textwrap\nfrom typing import BinaryIO\nfrom typing import cast\nfrom typing import TextIO\n\nfrom _pytest import capture\nfrom _pytest.capture import _get_multicapture\nfrom _pytest.capture import CaptureFixture\nfrom _pytest.capture import CaptureManager\nfrom _pytest.capture import CaptureResult\nfrom _pytest.capture import MultiCapture\nfrom _pytest.config import ExitCode\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\n# note: py.io capture tests where copied from\n# pylib 1.4.20.dev2 (rev 13d9af95547e)\n\n\ndef StdCaptureFD(\n    out: bool = True, err: bool = True, in_: bool = True\n) -> MultiCapture[str]:\n    return capture.MultiCapture(\n        in_=capture.FDCapture(0) if in_ else None,\n        out=capture.FDCapture(1) if out else None,\n        err=capture.FDCapture(2) if err else None,\n    )\n\n\ndef StdCapture(\n    out: bool = True, err: bool = True, in_: bool = True\n) -> MultiCapture[str]:\n    return capture.MultiCapture(\n        in_=capture.SysCapture(0) if in_ else None,\n        out=capture.SysCapture(1) if out else None,\n        err=capture.SysCapture(2) if err else None,\n    )\n\n\ndef TeeStdCapture(\n    out: bool = True, err: bool = True, in_: bool = True\n) -> MultiCapture[str]:\n    return capture.MultiCapture(\n        in_=capture.SysCapture(0, tee=True) if in_ else None,\n        out=capture.SysCapture(1, tee=True) if out else None,\n        err=capture.SysCapture(2, tee=True) if err else None,\n    )\n\n\nclass TestCaptureManager:\n    @pytest.mark.parametrize(\"method\", [\"no\", \"sys\", \"fd\"])\n    def test_capturing_basic_api(self, method) -> None:\n        capouter = StdCaptureFD()\n        old = sys.stdout, sys.stderr, sys.stdin\n        try:\n            capman = CaptureManager(method)\n            capman.start_global_capturing()\n            capman.suspend_global_capture()\n            outerr = capman.read_global_capture()\n            assert outerr == (\"\", \"\")\n            capman.suspend_global_capture()\n            outerr = capman.read_global_capture()\n            assert outerr == (\"\", \"\")\n            print(\"hello\")\n            capman.suspend_global_capture()\n            out, _err = capman.read_global_capture()\n            if method == \"no\":\n                assert old == (sys.stdout, sys.stderr, sys.stdin)\n            else:\n                assert not out\n            capman.resume_global_capture()\n            print(\"hello\")\n            capman.suspend_global_capture()\n            out, _err = capman.read_global_capture()\n            if method != \"no\":\n                assert out == \"hello\\n\"\n            capman.stop_global_capturing()\n        finally:\n            capouter.stop_capturing()\n\n    def test_init_capturing(self):\n        capouter = StdCaptureFD()\n        try:\n            capman = CaptureManager(\"fd\")\n            capman.start_global_capturing()\n            pytest.raises(AssertionError, capman.start_global_capturing)\n            capman.stop_global_capturing()\n        finally:\n            capouter.stop_capturing()\n\n\n@pytest.mark.parametrize(\"method\", [\"fd\", \"sys\"])\ndef test_capturing_unicode(pytester: Pytester, method: str) -> None:\n    obj = \"'b\\u00f6y'\"\n    pytester.makepyfile(\n        f\"\"\"\\\n        # taken from issue 227 from nosetests\n        def test_unicode():\n            import sys\n            print(sys.stdout)\n            print({obj})\n        \"\"\"\n    )\n    result = pytester.runpytest(f\"--capture={method}\")\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\n@pytest.mark.parametrize(\"method\", [\"fd\", \"sys\"])\ndef test_capturing_bytes_in_utf8_encoding(pytester: Pytester, method: str) -> None:\n    pytester.makepyfile(\n        \"\"\"\\\n        def test_unicode():\n            print('b\\\\u00f6y')\n        \"\"\"\n    )\n    result = pytester.runpytest(f\"--capture={method}\")\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_collect_capturing(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import sys\n\n        print(\"collect %s failure\" % 13)\n        sys.stderr.write(\"collect %s_stderr failure\" % 13)\n        import xyz42123\n    \"\"\"\n    )\n    result = pytester.runpytest(p)\n    result.stdout.fnmatch_lines(\n        [\n            \"*Captured stdout*\",\n            \"collect 13 failure\",\n            \"*Captured stderr*\",\n            \"collect 13_stderr failure\",\n        ]\n    )\n\n\nclass TestPerTestCapturing:\n    def test_capture_and_fixtures(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def setup_module(mod):\n                print(\"setup module\")\n            def setup_function(function):\n                print(\"setup \" + function.__name__)\n            def test_func1():\n                print(\"in func1\")\n                assert 0\n            def test_func2():\n                print(\"in func2\")\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines(\n            [\n                \"setup module*\",\n                \"setup test_func1*\",\n                \"in func1*\",\n                \"setup test_func2*\",\n                \"in func2*\",\n            ]\n        )\n\n    @pytest.mark.xfail(reason=\"unimplemented feature\")\n    def test_capture_scope_cache(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import sys\n            def setup_module(func):\n                print(\"module-setup\")\n            def setup_function(func):\n                print(\"function-setup\")\n            def test_func():\n                print(\"in function\")\n                assert 0\n            def teardown_function(func):\n                print(\"in teardown\")\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_func():*\",\n                \"*Captured stdout during setup*\",\n                \"module-setup*\",\n                \"function-setup*\",\n                \"*Captured stdout*\",\n                \"in teardown*\",\n            ]\n        )\n\n    def test_no_carry_over(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_func1():\n                print(\"in func1\")\n            def test_func2():\n                print(\"in func2\")\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        s = result.stdout.str()\n        assert \"in func1\" not in s\n        assert \"in func2\" in s\n\n    def test_teardown_capturing(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def setup_function(function):\n                print(\"setup func1\")\n            def teardown_function(function):\n                print(\"teardown func1\")\n                assert 0\n            def test_func1():\n                print(\"in func1\")\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines(\n            [\n                \"*teardown_function*\",\n                \"*Captured stdout*\",\n                \"setup func1*\",\n                \"in func1*\",\n                \"teardown func1*\",\n                # \"*1 fixture failure*\"\n            ]\n        )\n\n    def test_teardown_capturing_final(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def teardown_module(mod):\n                print(\"teardown module\")\n                assert 0\n            def test_func():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines(\n            [\n                \"*def teardown_module(mod):*\",\n                \"*Captured stdout*\",\n                \"*teardown module*\",\n                \"*1 error*\",\n            ]\n        )\n\n    def test_capturing_outerr(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\\\n            import sys\n            def test_capturing():\n                print(42)\n                sys.stderr.write(str(23))\n            def test_capturing_error():\n                print(1)\n                sys.stderr.write(str(2))\n                raise ValueError\n            \"\"\"\n        )\n        result = pytester.runpytest(p1)\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_capturing_outerr.py .F*\",\n                \"====* FAILURES *====\",\n                \"____*____\",\n                \"*test_capturing_outerr.py:8: ValueError\",\n                \"*--- Captured stdout *call*\",\n                \"1\",\n                \"*--- Captured stderr *call*\",\n                \"2\",\n            ]\n        )\n\n\nclass TestLoggingInteraction:\n    def test_logging_stream_ownership(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\\\n            def test_logging():\n                import logging\n                import pytest\n                stream = capture.CaptureIO()\n                logging.basicConfig(stream=stream)\n                stream.close() # to free memory/release resources\n            \"\"\"\n        )\n        result = pytester.runpytest_subprocess(p)\n        assert result.stderr.str().find(\"atexit\") == -1\n\n    def test_logging_and_immediate_setupteardown(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\\\n            import logging\n            def setup_function(function):\n                logging.warning(\"hello1\")\n\n            def test_logging():\n                logging.warning(\"hello2\")\n                assert 0\n\n            def teardown_function(function):\n                logging.warning(\"hello3\")\n                assert 0\n            \"\"\"\n        )\n        for optargs in ((\"--capture=sys\",), (\"--capture=fd\",)):\n            print(optargs)\n            result = pytester.runpytest_subprocess(p, *optargs)\n            s = result.stdout.str()\n            result.stdout.fnmatch_lines(\n                [\"*WARN*hello3\", \"*WARN*hello1\", \"*WARN*hello2\"]  # errors show first!\n            )\n            # verify proper termination\n            assert \"closed\" not in s\n\n    def test_logging_and_crossscope_fixtures(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\\\n            import logging\n            def setup_module(function):\n                logging.warning(\"hello1\")\n\n            def test_logging():\n                logging.warning(\"hello2\")\n                assert 0\n\n            def teardown_module(function):\n                logging.warning(\"hello3\")\n                assert 0\n            \"\"\"\n        )\n        for optargs in ((\"--capture=sys\",), (\"--capture=fd\",)):\n            print(optargs)\n            result = pytester.runpytest_subprocess(p, *optargs)\n            s = result.stdout.str()\n            result.stdout.fnmatch_lines(\n                [\"*WARN*hello3\", \"*WARN*hello1\", \"*WARN*hello2\"]  # errors come first\n            )\n            # verify proper termination\n            assert \"closed\" not in s\n\n    def test_conftestlogging_is_shown(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\\\n                import logging\n                logging.basicConfig()\n                logging.warning(\"hello435\")\n            \"\"\"\n        )\n        # make sure that logging is still captured in tests\n        result = pytester.runpytest_subprocess(\"-s\", \"-p\", \"no:capturelog\")\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n        result.stderr.fnmatch_lines([\"WARNING*hello435*\"])\n        assert \"operation on closed file\" not in result.stderr.str()\n\n    def test_conftestlogging_and_test_logging(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\\\n                import logging\n                logging.basicConfig()\n            \"\"\"\n        )\n        # make sure that logging is still captured in tests\n        p = pytester.makepyfile(\n            \"\"\"\\\n            def test_hello():\n                import logging\n                logging.warning(\"hello433\")\n                assert 0\n            \"\"\"\n        )\n        result = pytester.runpytest_subprocess(p, \"-p\", \"no:capturelog\")\n        assert result.ret != 0\n        result.stdout.fnmatch_lines([\"WARNING*hello433*\"])\n        assert \"something\" not in result.stderr.str()\n        assert \"operation on closed file\" not in result.stderr.str()\n\n    def test_logging_after_cap_stopped(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\\\n                import pytest\n                import logging\n\n                log = logging.getLogger(__name__)\n\n                @pytest.fixture\n                def log_on_teardown():\n                    yield\n                    log.warning('Logging on teardown')\n            \"\"\"\n        )\n        # make sure that logging is still captured in tests\n        p = pytester.makepyfile(\n            \"\"\"\\\n            def test_hello(log_on_teardown):\n                import logging\n                logging.warning(\"hello433\")\n                assert 1\n                raise KeyboardInterrupt()\n            \"\"\"\n        )\n        result = pytester.runpytest_subprocess(p, \"--log-cli-level\", \"info\")\n        assert result.ret != 0\n        result.stdout.fnmatch_lines(\n            [\"*WARNING*hello433*\", \"*WARNING*Logging on teardown*\"]\n        )\n        assert (\n            \"AttributeError: 'NoneType' object has no attribute 'resume_capturing'\"\n            not in result.stderr.str()\n        )\n\n\nclass TestCaptureFixture:\n    @pytest.mark.parametrize(\"opt\", [[], [\"-s\"]])\n    def test_std_functional(self, pytester: Pytester, opt) -> None:\n        reprec = pytester.inline_runsource(\n            \"\"\"\\\n            def test_hello(capsys):\n                print(42)\n                out, err = capsys.readouterr()\n                assert out.startswith(\"42\")\n            \"\"\",\n            *opt,\n        )\n        reprec.assertoutcome(passed=1)\n\n    def test_capteesys(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\\\n            import sys\n            def test_one(capteesys):\n                print(\"sTdoUt\")\n                print(\"sTdeRr\", file=sys.stderr)\n                out, err = capteesys.readouterr()\n                assert out == \"sTdoUt\\\\n\"\n                assert err == \"sTdeRr\\\\n\"\n            \"\"\"\n        )\n        # -rN and --capture=tee-sys means we'll read them on stdout/stderr,\n        # as opposed to both being reported on stdout\n        result = pytester.runpytest(p, \"--quiet\", \"--quiet\", \"-rN\", \"--capture=tee-sys\")\n        assert result.ret == ExitCode.OK\n        result.stdout.fnmatch_lines([\"sTdoUt\"])  # tee'd out\n        result.stderr.fnmatch_lines([\"sTdeRr\"])  # tee'd out\n\n        result = pytester.runpytest(p, \"--quiet\", \"--quiet\", \"-rA\", \"--capture=tee-sys\")\n        assert result.ret == ExitCode.OK\n        result.stdout.fnmatch_lines(\n            [\"sTdoUt\", \"sTdoUt\", \"sTdeRr\"]\n        )  # tee'd out, the next two reported\n        result.stderr.fnmatch_lines([\"sTdeRr\"])  # tee'd out\n\n        # -rA and --capture=sys means we'll read them on stdout.\n        result = pytester.runpytest(p, \"--quiet\", \"--quiet\", \"-rA\", \"--capture=sys\")\n        assert result.ret == ExitCode.OK\n        result.stdout.fnmatch_lines([\"sTdoUt\", \"sTdeRr\"])  # no tee, just reported\n        assert not result.stderr.lines\n\n    def test_capsyscapfd(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\\\n            def test_one(capsys, capfd):\n                pass\n            def test_two(capfd, capsys):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines(\n            [\n                \"*ERROR*setup*test_one*\",\n                \"E*capfd*capsys*same*time*\",\n                \"*ERROR*setup*test_two*\",\n                \"E*capsys*capfd*same*time*\",\n                \"*2 errors*\",\n            ]\n        )\n\n    def test_capturing_getfixturevalue(self, pytester: Pytester) -> None:\n        \"\"\"Test that asking for \"capfd\" and \"capsys\" using request.getfixturevalue\n        in the same test is an error.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\\\n            def test_one(capsys, request):\n                request.getfixturevalue(\"capfd\")\n            def test_two(capfd, request):\n                request.getfixturevalue(\"capsys\")\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_one*\",\n                \"E * cannot use capfd and capsys at the same time\",\n                \"*test_two*\",\n                \"E * cannot use capsys and capfd at the same time\",\n                \"*2 failed in*\",\n            ]\n        )\n\n    def test_capsyscapfdbinary(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\\\n            def test_one(capsys, capfdbinary):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines(\n            [\"*ERROR*setup*test_one*\", \"E*capfdbinary*capsys*same*time*\", \"*1 error*\"]\n        )\n\n    @pytest.mark.parametrize(\"method\", [\"sys\", \"fd\"])\n    def test_capture_is_represented_on_failure_issue128(\n        self, pytester: Pytester, method\n    ) -> None:\n        p = pytester.makepyfile(\n            f\"\"\"\\\n            def test_hello(cap{method}):\n                print(\"xxx42xxx\")\n                assert 0\n            \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines([\"xxx42xxx\"])\n\n    def test_stdfd_functional(self, pytester: Pytester) -> None:\n        reprec = pytester.inline_runsource(\n            \"\"\"\\\n            def test_hello(capfd):\n                import os\n                os.write(1, b\"42\")\n                out, err = capfd.readouterr()\n                assert out.startswith(\"42\")\n                capfd.close()\n            \"\"\"\n        )\n        reprec.assertoutcome(passed=1)\n\n    @pytest.mark.parametrize(\"nl\", (\"\\n\", \"\\r\\n\", \"\\r\"))\n    def test_cafd_preserves_newlines(self, capfd, nl) -> None:\n        print(\"test\", end=nl)\n        out, _err = capfd.readouterr()\n        assert out.endswith(nl)\n\n    def test_capfdbinary(self, pytester: Pytester) -> None:\n        reprec = pytester.inline_runsource(\n            \"\"\"\\\n            def test_hello(capfdbinary):\n                import os\n                # some likely un-decodable bytes\n                os.write(1, b'\\\\xfe\\\\x98\\\\x20')\n                out, err = capfdbinary.readouterr()\n                assert out == b'\\\\xfe\\\\x98\\\\x20'\n                assert err == b''\n            \"\"\"\n        )\n        reprec.assertoutcome(passed=1)\n\n    def test_capsysbinary(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            r\"\"\"\n            def test_hello(capsysbinary):\n                import sys\n\n                sys.stdout.buffer.write(b'hello')\n\n                # Some likely un-decodable bytes.\n                sys.stdout.buffer.write(b'\\xfe\\x98\\x20')\n\n                sys.stdout.buffer.flush()\n\n                # Ensure writing in text mode still works and is captured.\n                # https://github.com/pytest-dev/pytest/issues/6871\n                print(\"world\", flush=True)\n\n                out, err = capsysbinary.readouterr()\n                assert out == b'hello\\xfe\\x98\\x20world\\n'\n                assert err == b''\n\n                print(\"stdout after\")\n                print(\"stderr after\", file=sys.stderr)\n            \"\"\"\n        )\n        result = pytester.runpytest(str(p1), \"-rA\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*- Captured stdout call -*\",\n                \"stdout after\",\n                \"*- Captured stderr call -*\",\n                \"stderr after\",\n                \"*= 1 passed in *\",\n            ]\n        )\n\n    def test_partial_setup_failure(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\\\n            def test_hello(capsys, missingarg):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines([\"*test_partial_setup_failure*\", \"*1 error*\"])\n\n    def test_keyboardinterrupt_disables_capturing(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\\\n            def test_hello(capfd):\n                import os\n                os.write(1, b'42')\n                raise KeyboardInterrupt()\n            \"\"\"\n        )\n        result = pytester.runpytest_subprocess(p)\n        result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])\n        assert result.ret == 2\n\n    def test_capture_and_logging(self, pytester: Pytester) -> None:\n        \"\"\"#14\"\"\"\n        p = pytester.makepyfile(\n            \"\"\"\\\n            import logging\n            def test_log(capsys):\n                logging.error('x')\n            \"\"\"\n        )\n        result = pytester.runpytest_subprocess(p)\n        assert \"closed\" not in result.stderr.str()\n\n    @pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n    @pytest.mark.parametrize(\"no_capture\", [True, False])\n    def test_disabled_capture_fixture(\n        self, pytester: Pytester, fixture: str, no_capture: bool\n    ) -> None:\n        pytester.makepyfile(\n            f\"\"\"\\\n            def test_disabled({fixture}):\n                print('captured before')\n                with {fixture}.disabled():\n                    print('while capture is disabled')\n                print('captured after')\n                assert {fixture}.readouterr() == ('captured before\\\\ncaptured after\\\\n', '')\n\n            def test_normal():\n                print('test_normal executed')\n        \"\"\"\n        )\n        args = (\"-s\",) if no_capture else ()\n        result = pytester.runpytest_subprocess(*args)\n        result.stdout.fnmatch_lines([\"*while capture is disabled*\", \"*= 2 passed in *\"])\n        result.stdout.no_fnmatch_line(\"*captured before*\")\n        result.stdout.no_fnmatch_line(\"*captured after*\")\n        if no_capture:\n            assert \"test_normal executed\" in result.stdout.str()\n        else:\n            result.stdout.no_fnmatch_line(\"*test_normal executed*\")\n\n    def test_disabled_capture_fixture_twice(self, pytester: Pytester) -> None:\n        \"\"\"Test that an inner disabled() exit doesn't undo an outer disabled().\n\n        Issue #7148.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def test_disabled(capfd):\n                print('captured before')\n                with capfd.disabled():\n                    print('while capture is disabled 1')\n                    with capfd.disabled():\n                        print('while capture is disabled 2')\n                    print('while capture is disabled 1 after')\n                print('captured after')\n                assert capfd.readouterr() == ('captured before\\\\ncaptured after\\\\n', '')\n        \"\"\"\n        )\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines(\n            [\n                \"*while capture is disabled 1\",\n                \"*while capture is disabled 2\",\n                \"*while capture is disabled 1 after\",\n            ],\n            consecutive=True,\n        )\n\n    @pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n    def test_fixture_use_by_other_fixtures(self, pytester: Pytester, fixture) -> None:\n        \"\"\"Ensure that capsys and capfd can be used by other fixtures during\n        setup and teardown.\"\"\"\n        pytester.makepyfile(\n            f\"\"\"\\\n            import sys\n            import pytest\n\n            @pytest.fixture\n            def captured_print({fixture}):\n                print('stdout contents begin')\n                print('stderr contents begin', file=sys.stderr)\n                out, err = {fixture}.readouterr()\n\n                yield out, err\n\n                print('stdout contents end')\n                print('stderr contents end', file=sys.stderr)\n                out, err = {fixture}.readouterr()\n                assert out == 'stdout contents end\\\\n'\n                assert err == 'stderr contents end\\\\n'\n\n            def test_captured_print(captured_print):\n                out, err = captured_print\n                assert out == 'stdout contents begin\\\\n'\n                assert err == 'stderr contents begin\\\\n'\n        \"\"\"\n        )\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n        result.stdout.no_fnmatch_line(\"*stdout contents begin*\")\n        result.stdout.no_fnmatch_line(\"*stderr contents begin*\")\n\n    @pytest.mark.parametrize(\"cap\", [\"capsys\", \"capfd\"])\n    def test_fixture_use_by_other_fixtures_teardown(\n        self, pytester: Pytester, cap\n    ) -> None:\n        \"\"\"Ensure we can access setup and teardown buffers from teardown when using capsys/capfd (##3033)\"\"\"\n        pytester.makepyfile(\n            f\"\"\"\\\n            import sys\n            import pytest\n            import os\n\n            @pytest.fixture()\n            def fix({cap}):\n                print(\"setup out\")\n                sys.stderr.write(\"setup err\\\\n\")\n                yield\n                out, err = {cap}.readouterr()\n                assert out == 'setup out\\\\ncall out\\\\n'\n                assert err == 'setup err\\\\ncall err\\\\n'\n\n            def test_a(fix):\n                print(\"call out\")\n                sys.stderr.write(\"call err\\\\n\")\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n\ndef test_setup_failure_does_not_kill_capturing(pytester: Pytester) -> None:\n    sub1 = pytester.mkpydir(\"sub1\")\n    sub1.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            def pytest_runtest_setup(item):\n                raise ValueError(42)\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    sub1.joinpath(\"test_mod.py\").write_text(\"def test_func1(): pass\", encoding=\"utf-8\")\n    result = pytester.runpytest(pytester.path, \"--traceconfig\")\n    result.stdout.fnmatch_lines([\"*ValueError(42)*\", \"*1 error*\"])\n\n\ndef test_capture_conftest_runtest_setup(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_runtest_setup():\n            print(\"hello19\")\n    \"\"\"\n    )\n    pytester.makepyfile(\"def test_func(): pass\")\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.stdout.no_fnmatch_line(\"*hello19*\")\n\n\ndef test_capture_badoutput_issue412(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import os\n\n        def test_func():\n            omg = bytearray([1,129,1])\n            os.write(1, omg)\n            assert 0\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--capture=fd\")\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        *def test_func*\n        *assert 0*\n        *Captured*\n        *1 failed*\n    \"\"\"\n    )\n\n\ndef test_capture_early_option_parsing(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_runtest_setup():\n            print(\"hello19\")\n    \"\"\"\n    )\n    pytester.makepyfile(\"def test_func(): pass\")\n    result = pytester.runpytest(\"-vs\")\n    assert result.ret == 0\n    assert \"hello19\" in result.stdout.str()\n\n\ndef test_capture_binary_output(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        r\"\"\"\n        import pytest\n\n        def test_a():\n            import sys\n            import subprocess\n            subprocess.call([sys.executable, __file__])\n\n        def test_foo():\n            import os;os.write(1, b'\\xc3')\n\n        if __name__ == '__main__':\n            test_foo()\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--assert=plain\")\n    result.assert_outcomes(passed=2)\n\n\ndef test_error_during_readouterr(pytester: Pytester) -> None:\n    \"\"\"Make sure we suspend capturing if errors occur during readouterr\"\"\"\n    pytester.makepyfile(\n        pytest_xyz=\"\"\"\n        from _pytest.capture import FDCapture\n\n        def bad_snap(self):\n            raise Exception('boom')\n\n        assert FDCapture.snap\n        FDCapture.snap = bad_snap\n    \"\"\"\n    )\n    result = pytester.runpytest_subprocess(\"-p\", \"pytest_xyz\")\n    result.stderr.fnmatch_lines(\n        [\"*in bad_snap\", \"    raise Exception('boom')\", \"Exception: boom\"]\n    )\n\n\nclass TestCaptureIO:\n    def test_text(self) -> None:\n        f = capture.CaptureIO()\n        f.write(\"hello\")\n        s = f.getvalue()\n        assert s == \"hello\"\n        f.close()\n\n    def test_unicode_and_str_mixture(self) -> None:\n        f = capture.CaptureIO()\n        f.write(\"\\u00f6\")\n        pytest.raises(TypeError, f.write, b\"hello\")\n\n    def test_write_bytes_to_buffer(self) -> None:\n        \"\"\"In python3, stdout / stderr are text io wrappers (exposing a buffer\n        property of the underlying bytestream).  See issue #1407\n        \"\"\"\n        f = capture.CaptureIO()\n        f.buffer.write(b\"foo\\r\\n\")\n        assert f.getvalue() == \"foo\\r\\n\"\n\n\nclass TestTeeCaptureIO(TestCaptureIO):\n    def test_text(self) -> None:\n        sio = io.StringIO()\n        f = capture.TeeCaptureIO(sio)\n        f.write(\"hello\")\n        s1 = f.getvalue()\n        assert s1 == \"hello\"\n        s2 = sio.getvalue()\n        assert s2 == s1\n        f.close()\n        sio.close()\n\n    def test_unicode_and_str_mixture(self) -> None:\n        sio = io.StringIO()\n        f = capture.TeeCaptureIO(sio)\n        f.write(\"\\u00f6\")\n        pytest.raises(TypeError, f.write, b\"hello\")\n\n\ndef test_dontreadfrominput() -> None:\n    from _pytest.capture import DontReadFromInput\n\n    f = DontReadFromInput()\n    assert f.buffer is f  # type: ignore[comparison-overlap]\n    assert not f.isatty()\n    pytest.raises(OSError, f.read)\n    pytest.raises(OSError, f.readlines)\n    iter_f = iter(f)\n    pytest.raises(OSError, next, iter_f)\n    pytest.raises(UnsupportedOperation, f.fileno)\n    pytest.raises(UnsupportedOperation, f.flush)\n    assert not f.readable()\n    pytest.raises(UnsupportedOperation, f.seek, 0)\n    assert not f.seekable()\n    pytest.raises(UnsupportedOperation, f.tell)\n    pytest.raises(UnsupportedOperation, f.truncate, 0)\n    pytest.raises(UnsupportedOperation, f.write, b\"\")\n    pytest.raises(UnsupportedOperation, f.writelines, [])\n    assert not f.writable()\n    assert isinstance(f.encoding, str)\n    f.close()  # just for completeness\n    with f:\n        pass\n\n\ndef test_captureresult() -> None:\n    cr = CaptureResult(\"out\", \"err\")\n    assert len(cr) == 2\n    assert cr.out == \"out\"\n    assert cr.err == \"err\"\n    out, err = cr\n    assert out == \"out\"\n    assert err == \"err\"\n    assert cr[0] == \"out\"\n    assert cr[1] == \"err\"\n    assert cr == cr\n    assert cr == CaptureResult(\"out\", \"err\")\n    assert cr != CaptureResult(\"wrong\", \"err\")\n    assert cr == (\"out\", \"err\")\n    assert cr != (\"out\", \"wrong\")\n    assert hash(cr) == hash(CaptureResult(\"out\", \"err\"))\n    assert hash(cr) == hash((\"out\", \"err\"))\n    assert hash(cr) != hash((\"out\", \"wrong\"))\n    assert cr < (\"z\",)\n    assert cr < (\"z\", \"b\")\n    assert cr < (\"z\", \"b\", \"c\")\n    assert cr.count(\"err\") == 1\n    assert cr.count(\"wrong\") == 0\n    assert cr.index(\"err\") == 1\n    with pytest.raises(ValueError):\n        assert cr.index(\"wrong\") == 0\n    assert next(iter(cr)) == \"out\"\n    assert cr._replace(err=\"replaced\") == (\"out\", \"replaced\")\n\n\n@pytest.fixture\ndef tmpfile(pytester: Pytester) -> Generator[BinaryIO]:\n    f = pytester.makepyfile(\"\").open(\"wb+\")\n    yield f\n    if not f.closed:\n        f.close()\n\n\n@contextlib.contextmanager\ndef lsof_check():\n    pid = os.getpid()\n    try:\n        out = subprocess.check_output((\"lsof\", \"-p\", str(pid)), timeout=10).decode()\n    except (\n        OSError,\n        UnicodeDecodeError,\n        subprocess.CalledProcessError,\n        subprocess.TimeoutExpired,\n    ) as exc:\n        # about UnicodeDecodeError, see note on pytester\n        pytest.skip(f\"could not run 'lsof' ({exc!r})\")\n    yield\n    out2 = subprocess.check_output((\"lsof\", \"-p\", str(pid))).decode()\n    len1 = len([x for x in out.split(\"\\n\") if \"REG\" in x])\n    len2 = len([x for x in out2.split(\"\\n\") if \"REG\" in x])\n    assert len2 < len1 + 3, out2\n\n\nclass TestFDCapture:\n    def test_simple(self, tmpfile: BinaryIO) -> None:\n        fd = tmpfile.fileno()\n        cap = capture.FDCapture(fd)\n        data = b\"hello\"\n        os.write(fd, data)\n        pytest.raises(AssertionError, cap.snap)\n        cap.done()\n        cap = capture.FDCapture(fd)\n        cap.start()\n        os.write(fd, data)\n        s = cap.snap()\n        cap.done()\n        assert s == \"hello\"\n\n    def test_simple_many(self, tmpfile: BinaryIO) -> None:\n        for i in range(10):\n            self.test_simple(tmpfile)\n\n    def test_simple_many_check_open_files(self, pytester: Pytester) -> None:\n        with lsof_check():\n            with pytester.makepyfile(\"\").open(\"wb+\") as tmpfile:\n                self.test_simple_many(tmpfile)\n\n    def test_simple_fail_second_start(self, tmpfile: BinaryIO) -> None:\n        fd = tmpfile.fileno()\n        cap = capture.FDCapture(fd)\n        cap.done()\n        pytest.raises(AssertionError, cap.start)\n\n    def test_stderr(self) -> None:\n        cap = capture.FDCapture(2)\n        cap.start()\n        print(\"hello\", file=sys.stderr)\n        s = cap.snap()\n        cap.done()\n        assert s == \"hello\\n\"\n\n    def test_stdin(self) -> None:\n        cap = capture.FDCapture(0)\n        cap.start()\n        x = os.read(0, 100).strip()\n        cap.done()\n        assert x == b\"\"\n\n    def test_writeorg(self, tmpfile: BinaryIO) -> None:\n        data1, data2 = b\"foo\", b\"bar\"\n        cap = capture.FDCapture(tmpfile.fileno())\n        cap.start()\n        tmpfile.write(data1)\n        tmpfile.flush()\n        cap.writeorg(data2.decode(\"ascii\"))\n        scap = cap.snap()\n        cap.done()\n        assert scap == data1.decode(\"ascii\")\n        with open(tmpfile.name, \"rb\") as stmp_file:\n            stmp = stmp_file.read()\n            assert stmp == data2\n\n    def test_simple_resume_suspend(self) -> None:\n        with saved_fd(1):\n            cap = capture.FDCapture(1)\n            cap.start()\n            data = b\"hello\"\n            os.write(1, data)\n            sys.stdout.write(\"whatever\")\n            s = cap.snap()\n            assert s == \"hellowhatever\"\n            cap.suspend()\n            os.write(1, b\"world\")\n            sys.stdout.write(\"qlwkej\")\n            assert not cap.snap()\n            cap.resume()\n            os.write(1, b\"but now\")\n            sys.stdout.write(\" yes\\n\")\n            s = cap.snap()\n            assert s == \"but now yes\\n\"\n            cap.suspend()\n            cap.done()\n            pytest.raises(AssertionError, cap.suspend)\n\n            assert repr(cap) == (\n                f\"<FDCapture 1 oldfd={cap.targetfd_save} _state='done' tmpfile={cap.tmpfile!r}>\"\n            )\n            # Should not crash with missing \"_old\".\n            assert isinstance(cap.syscapture, capture.SysCapture)\n            assert repr(cap.syscapture) == (\n                f\"<SysCapture stdout _old=<UNSET> _state='done' tmpfile={cap.syscapture.tmpfile!r}>\"\n            )\n\n    def test_capfd_sys_stdout_mode(self, capfd) -> None:\n        assert \"b\" not in sys.stdout.mode\n\n\n@contextlib.contextmanager\ndef saved_fd(fd):\n    new_fd = os.dup(fd)\n    try:\n        yield\n    finally:\n        os.dup2(new_fd, fd)\n        os.close(new_fd)\n\n\nclass TestStdCapture:\n    captureclass = staticmethod(StdCapture)\n\n    @contextlib.contextmanager\n    def getcapture(self, **kw):\n        cap = self.__class__.captureclass(**kw)\n        cap.start_capturing()\n        try:\n            yield cap\n        finally:\n            cap.stop_capturing()\n\n    def test_capturing_done_simple(self) -> None:\n        with self.getcapture() as cap:\n            sys.stdout.write(\"hello\")\n            sys.stderr.write(\"world\")\n            out, err = cap.readouterr()\n        assert out == \"hello\"\n        assert err == \"world\"\n\n    def test_capturing_reset_simple(self) -> None:\n        with self.getcapture() as cap:\n            print(\"hello world\")\n            sys.stderr.write(\"hello error\\n\")\n            out, err = cap.readouterr()\n        assert out == \"hello world\\n\"\n        assert err == \"hello error\\n\"\n\n    def test_capturing_readouterr(self) -> None:\n        with self.getcapture() as cap:\n            print(\"hello world\")\n            sys.stderr.write(\"hello error\\n\")\n            out, err = cap.readouterr()\n            assert out == \"hello world\\n\"\n            assert err == \"hello error\\n\"\n            sys.stderr.write(\"error2\")\n            out, err = cap.readouterr()\n        assert err == \"error2\"\n\n    def test_capture_results_accessible_by_attribute(self) -> None:\n        with self.getcapture() as cap:\n            sys.stdout.write(\"hello\")\n            sys.stderr.write(\"world\")\n            capture_result = cap.readouterr()\n        assert capture_result.out == \"hello\"\n        assert capture_result.err == \"world\"\n\n    def test_capturing_readouterr_unicode(self) -> None:\n        with self.getcapture() as cap:\n            print(\"hxąć\")\n            out, _err = cap.readouterr()\n        assert out == \"hxąć\\n\"\n\n    def test_reset_twice_error(self) -> None:\n        with self.getcapture() as cap:\n            print(\"hello\")\n            out, err = cap.readouterr()\n        pytest.raises(ValueError, cap.stop_capturing)\n        assert out == \"hello\\n\"\n        assert not err\n\n    def test_capturing_modify_sysouterr_in_between(self) -> None:\n        oldout = sys.stdout\n        olderr = sys.stderr\n        with self.getcapture() as cap:\n            sys.stdout.write(\"hello\")\n            sys.stderr.write(\"world\")\n            sys.stdout = capture.CaptureIO()\n            sys.stderr = capture.CaptureIO()\n            print(\"not seen\")\n            sys.stderr.write(\"not seen\\n\")\n            out, err = cap.readouterr()\n        assert out == \"hello\"\n        assert err == \"world\"\n        assert sys.stdout == oldout\n        assert sys.stderr == olderr\n\n    def test_capturing_error_recursive(self) -> None:\n        with self.getcapture() as cap1:\n            print(\"cap1\")\n            with self.getcapture() as cap2:\n                print(\"cap2\")\n                out2, _err2 = cap2.readouterr()\n                out1, _err1 = cap1.readouterr()\n        assert out1 == \"cap1\\n\"\n        assert out2 == \"cap2\\n\"\n\n    def test_just_out_capture(self) -> None:\n        with self.getcapture(out=True, err=False) as cap:\n            sys.stdout.write(\"hello\")\n            sys.stderr.write(\"world\")\n            out, err = cap.readouterr()\n        assert out == \"hello\"\n        assert not err\n\n    def test_just_err_capture(self) -> None:\n        with self.getcapture(out=False, err=True) as cap:\n            sys.stdout.write(\"hello\")\n            sys.stderr.write(\"world\")\n            out, err = cap.readouterr()\n        assert err == \"world\"\n        assert not out\n\n    def test_stdin_restored(self) -> None:\n        old = sys.stdin\n        with self.getcapture(in_=True):\n            newstdin = sys.stdin\n        assert newstdin != sys.stdin\n        assert sys.stdin is old\n\n    def test_stdin_nulled_by_default(self) -> None:\n        print(\"XXX this test may well hang instead of crashing\")\n        print(\"XXX which indicates an error in the underlying capturing\")\n        print(\"XXX mechanisms\")\n        with self.getcapture():\n            pytest.raises(OSError, sys.stdin.read)\n\n\nclass TestTeeStdCapture(TestStdCapture):\n    captureclass = staticmethod(TeeStdCapture)\n\n    def test_capturing_error_recursive(self) -> None:\n        r\"\"\"For TeeStdCapture since we passthrough stderr/stdout, cap1\n        should get all output, while cap2 should only get \"cap2\\n\".\"\"\"\n        with self.getcapture() as cap1:\n            print(\"cap1\")\n            with self.getcapture() as cap2:\n                print(\"cap2\")\n                out2, _err2 = cap2.readouterr()\n                out1, _err1 = cap1.readouterr()\n        assert out1 == \"cap1\\ncap2\\n\"\n        assert out2 == \"cap2\\n\"\n\n\nclass TestStdCaptureFD(TestStdCapture):\n    captureclass = staticmethod(StdCaptureFD)\n\n    def test_simple_only_fd(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n            import os\n            def test_x():\n                os.write(1, b\"hello\\\\n\")\n                assert 0\n            \"\"\"\n        )\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *test_x*\n            *assert 0*\n            *Captured stdout*\n        \"\"\"\n        )\n\n    def test_intermingling(self):\n        with self.getcapture() as cap:\n            os.write(1, b\"1\")\n            sys.stdout.write(str(2))\n            sys.stdout.flush()\n            os.write(1, b\"3\")\n            os.write(2, b\"a\")\n            sys.stderr.write(\"b\")\n            sys.stderr.flush()\n            os.write(2, b\"c\")\n            out, err = cap.readouterr()\n        assert out == \"123\"\n        assert err == \"abc\"\n\n    def test_many(self, capfd):\n        with lsof_check():\n            for i in range(10):\n                cap = StdCaptureFD()\n                cap.start_capturing()\n                cap.stop_capturing()\n\n\nclass TestStdCaptureFDinvalidFD:\n    def test_stdcapture_fd_invalid_fd(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import os\n            from fnmatch import fnmatch\n            from _pytest import capture\n\n            def StdCaptureFD(out=True, err=True, in_=True):\n                return capture.MultiCapture(\n                    in_=capture.FDCapture(0) if in_ else None,\n                    out=capture.FDCapture(1) if out else None,\n                    err=capture.FDCapture(2) if err else None,\n                )\n\n            def test_stdout():\n                os.close(1)\n                cap = StdCaptureFD(out=True, err=False, in_=False)\n                assert fnmatch(repr(cap.out), \"<FDCapture 1 oldfd=* _state='initialized' tmpfile=*>\")\n                cap.start_capturing()\n                os.write(1, b\"stdout\")\n                assert cap.readouterr() == (\"stdout\", \"\")\n                cap.stop_capturing()\n\n            def test_stderr():\n                os.close(2)\n                cap = StdCaptureFD(out=False, err=True, in_=False)\n                assert fnmatch(repr(cap.err), \"<FDCapture 2 oldfd=* _state='initialized' tmpfile=*>\")\n                cap.start_capturing()\n                os.write(2, b\"stderr\")\n                assert cap.readouterr() == (\"\", \"stderr\")\n                cap.stop_capturing()\n\n            def test_stdin():\n                os.close(0)\n                cap = StdCaptureFD(out=False, err=False, in_=True)\n                assert fnmatch(repr(cap.in_), \"<FDCapture 0 oldfd=* _state='initialized' tmpfile=*>\")\n                cap.stop_capturing()\n        \"\"\"\n        )\n        result = pytester.runpytest_subprocess(\"--capture=fd\")\n        assert result.ret == 0\n        assert result.parseoutcomes()[\"passed\"] == 3\n\n    def test_fdcapture_invalid_fd_with_fd_reuse(self, pytester: Pytester) -> None:\n        with saved_fd(1):\n            os.close(1)\n            cap = capture.FDCaptureBinary(1)\n            cap.start()\n            os.write(1, b\"started\")\n            cap.suspend()\n            os.write(1, b\" suspended\")\n            cap.resume()\n            os.write(1, b\" resumed\")\n            assert cap.snap() == b\"started resumed\"\n            cap.done()\n            with pytest.raises(OSError):\n                os.write(1, b\"done\")\n\n    def test_fdcapture_invalid_fd_without_fd_reuse(self, pytester: Pytester) -> None:\n        with saved_fd(1), saved_fd(2):\n            os.close(1)\n            os.close(2)\n            cap = capture.FDCaptureBinary(2)\n            cap.start()\n            os.write(2, b\"started\")\n            cap.suspend()\n            os.write(2, b\" suspended\")\n            cap.resume()\n            os.write(2, b\" resumed\")\n            assert cap.snap() == b\"started resumed\"\n            cap.done()\n            with pytest.raises(OSError):\n                os.write(2, b\"done\")\n\n\ndef test_capture_not_started_but_reset() -> None:\n    capsys = StdCapture()\n    capsys.stop_capturing()\n\n\ndef test_using_capsys_fixture_works_with_sys_stdout_encoding(\n    capsys: CaptureFixture[str],\n) -> None:\n    test_text = \"test text\"\n\n    print(test_text.encode(sys.stdout.encoding, \"replace\"))\n    (out, err) = capsys.readouterr()\n    assert out\n    assert err == \"\"\n\n\ndef test_capsys_results_accessible_by_attribute(capsys: CaptureFixture[str]) -> None:\n    sys.stdout.write(\"spam\")\n    sys.stderr.write(\"eggs\")\n    capture_result = capsys.readouterr()\n    assert capture_result.out == \"spam\"\n    assert capture_result.err == \"eggs\"\n\n\ndef test_fdcapture_tmpfile_remains_the_same() -> None:\n    cap = StdCaptureFD(out=False, err=True)\n    assert isinstance(cap.err, capture.FDCapture)\n    try:\n        cap.start_capturing()\n        capfile = cap.err.tmpfile\n        cap.readouterr()\n    finally:\n        cap.stop_capturing()\n    capfile2 = cap.err.tmpfile\n    assert capfile2 == capfile\n\n\ndef test_close_and_capture_again(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import os\n        def test_close():\n            os.close(1)\n        def test_capture_again():\n            os.write(1, b\"hello\\\\n\")\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest_subprocess()\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        *test_capture_again*\n        *assert 0*\n        *stdout*\n        *hello*\n    \"\"\"\n    )\n\n\n@pytest.mark.parametrize(\n    \"method\", [\"SysCapture(2)\", \"SysCapture(2, tee=True)\", \"FDCapture(2)\"]\n)\ndef test_capturing_and_logging_fundamentals(pytester: Pytester, method: str) -> None:\n    # here we check a fundamental feature\n    p = pytester.makepyfile(\n        f\"\"\"\n        import sys, os, logging\n        from _pytest import capture\n        cap = capture.MultiCapture(\n            in_=None,\n            out=None,\n            err=capture.{method},\n        )\n        cap.start_capturing()\n\n        logging.warning(\"hello1\")\n        outerr = cap.readouterr()\n        print(\"suspend, captured %s\" %(outerr,))\n        logging.warning(\"hello2\")\n\n        cap.pop_outerr_to_orig()\n        logging.warning(\"hello3\")\n\n        outerr = cap.readouterr()\n        print(\"suspend2, captured %s\" % (outerr,))\n    \"\"\"\n    )\n    result = pytester.runpython(p)\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        suspend, captured*hello1*\n        suspend2, captured*WARNING:root:hello3*\n    \"\"\"\n    )\n    result.stderr.fnmatch_lines(\n        \"\"\"\n        WARNING:root:hello2\n    \"\"\"\n    )\n    assert \"atexit\" not in result.stderr.str()\n\n\ndef test_error_attribute_issue555(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import sys\n        def test_capattr():\n            assert sys.stdout.errors == \"replace\"\n            assert sys.stderr.errors == \"replace\"\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(passed=1)\n\n\n@pytest.mark.skipif(\n    not sys.platform.startswith(\"win\"),\n    reason=\"only on windows\",\n)\ndef test_windowsconsoleio_workaround_non_standard_streams() -> None:\n    \"\"\"\n    Ensure _windowsconsoleio_workaround function works with objects that\n    do not implement the full ``io``-based stream protocol, for example execnet channels (#2666).\n    \"\"\"\n    from _pytest.capture import _windowsconsoleio_workaround\n\n    class DummyStream:\n        def write(self, s):\n            pass\n\n    stream = cast(TextIO, DummyStream())\n    _windowsconsoleio_workaround(stream)\n\n\ndef test_dontreadfrominput_has_encoding(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import sys\n        def test_capattr():\n            # should not raise AttributeError\n            assert sys.stdout.encoding\n            assert sys.stderr.encoding\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(passed=1)\n\n\ndef test_crash_on_closing_tmpfile_py27(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import threading\n        import sys\n\n        printing = threading.Event()\n\n        def spam():\n            f = sys.stderr\n            print('SPAMBEFORE', end='', file=f)\n            printing.set()\n\n            while True:\n                try:\n                    f.flush()\n                except (OSError, ValueError):\n                    break\n\n        def test_spam_in_thread():\n            t = threading.Thread(target=spam)\n            t.daemon = True\n            t.start()\n\n            printing.wait()\n    \"\"\"\n    )\n    # Do not consider plugins like hypothesis, which might output to stderr.\n    monkeypatch.setenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", \"1\")\n    result = pytester.runpytest_subprocess(str(p))\n    assert result.ret == 0\n    assert result.stderr.str() == \"\"\n    result.stdout.no_fnmatch_line(\"*OSError*\")\n\n\ndef test_global_capture_with_live_logging(pytester: Pytester) -> None:\n    # Issue 3819\n    # capture should work with live cli logging\n\n    # Teardown report seems to have the capture for the whole process (setup, capture, teardown)\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_runtest_logreport(report):\n            if \"test_global\" in report.nodeid:\n                if report.when == \"teardown\":\n                    with open(\"caplog\", \"w\", encoding=\"utf-8\") as f:\n                        f.write(report.caplog)\n                    with open(\"capstdout\", \"w\", encoding=\"utf-8\") as f:\n                        f.write(report.capstdout)\n        \"\"\"\n    )\n\n    pytester.makepyfile(\n        \"\"\"\n        import logging\n        import sys\n        import pytest\n\n        logger = logging.getLogger(__name__)\n\n        @pytest.fixture\n        def fix1():\n            print(\"fix setup\")\n            logging.info(\"fix setup\")\n            yield\n            logging.info(\"fix teardown\")\n            print(\"fix teardown\")\n\n        def test_global(fix1):\n            print(\"begin test\")\n            logging.info(\"something in test\")\n            print(\"end test\")\n        \"\"\"\n    )\n    result = pytester.runpytest_subprocess(\"--log-cli-level=INFO\")\n    assert result.ret == 0\n\n    with open(\"caplog\", encoding=\"utf-8\") as f:\n        caplog = f.read()\n\n    assert \"fix setup\" in caplog\n    assert \"something in test\" in caplog\n    assert \"fix teardown\" in caplog\n\n    with open(\"capstdout\", encoding=\"utf-8\") as f:\n        capstdout = f.read()\n\n    assert \"fix setup\" in capstdout\n    assert \"begin test\" in capstdout\n    assert \"end test\" in capstdout\n    assert \"fix teardown\" in capstdout\n\n\n@pytest.mark.parametrize(\"capture_fixture\", [\"capsys\", \"capfd\"])\ndef test_capture_with_live_logging(\n    pytester: Pytester, capture_fixture: CaptureFixture[str]\n) -> None:\n    # Issue 3819\n    # capture should work with live cli logging\n\n    pytester.makepyfile(\n        f\"\"\"\n        import logging\n        import sys\n\n        logger = logging.getLogger(__name__)\n\n        def test_capture({capture_fixture}):\n            print(\"hello\")\n            sys.stderr.write(\"world\\\\n\")\n            captured = {capture_fixture}.readouterr()\n            assert captured.out == \"hello\\\\n\"\n            assert captured.err == \"world\\\\n\"\n\n            logging.info(\"something\")\n            print(\"next\")\n            logging.info(\"something\")\n\n            captured = {capture_fixture}.readouterr()\n            assert captured.out == \"next\\\\n\"\n        \"\"\"\n    )\n\n    result = pytester.runpytest_subprocess(\"--log-cli-level=INFO\")\n    assert result.ret == 0\n\n\ndef test_typeerror_encodedfile_write(pytester: Pytester) -> None:\n    \"\"\"It should behave the same with and without output capturing (#4861).\"\"\"\n    p = pytester.makepyfile(\n        \"\"\"\n        def test_fails():\n            import sys\n            sys.stdout.write(b\"foo\")\n    \"\"\"\n    )\n    result_without_capture = pytester.runpytest(\"-s\", str(p))\n    result_with_capture = pytester.runpytest(str(p))\n\n    assert result_with_capture.ret == result_without_capture.ret\n    out = result_with_capture.stdout.str()\n    assert (\"TypeError: write() argument must be str, not bytes\" in out) or (\n        \"TypeError: unicode argument expected, got 'bytes'\" in out\n    )\n\n\ndef test_stderr_write_returns_len(capsys: CaptureFixture[str]) -> None:\n    \"\"\"Write on Encoded files, namely captured stderr, should return number of characters written.\"\"\"\n    assert sys.stderr.write(\"Foo\") == 3\n\n\ndef test_encodedfile_writelines(tmpfile: BinaryIO) -> None:\n    ef = capture.EncodedFile(tmpfile, encoding=\"utf-8\")\n    with pytest.raises(TypeError):\n        ef.writelines([b\"line1\", b\"line2\"])  # type: ignore[list-item]\n    assert ef.writelines([\"line3\", \"line4\"]) is None  # type: ignore[func-returns-value]\n    ef.flush()\n    tmpfile.seek(0)\n    assert tmpfile.read() == b\"line3line4\"\n    tmpfile.close()\n    with pytest.raises(ValueError):\n        ef.read()\n\n\ndef test__get_multicapture() -> None:\n    assert isinstance(_get_multicapture(\"no\"), MultiCapture)\n    pytest.raises(ValueError, _get_multicapture, \"unknown\").match(\n        r\"^unknown capturing method: 'unknown'\"\n    )\n\n\ndef test_logging_while_collecting(pytester: Pytester) -> None:\n    \"\"\"Issue #6240: Calls to logging.xxx() during collection causes all logging calls to be duplicated to stderr\"\"\"\n    p = pytester.makepyfile(\n        \"\"\"\\\n        import logging\n\n        logging.warning(\"during collection\")\n\n        def test_logging():\n            logging.warning(\"during call\")\n            assert False\n        \"\"\"\n    )\n    result = pytester.runpytest_subprocess(p)\n    assert result.ret == ExitCode.TESTS_FAILED\n    result.stdout.fnmatch_lines(\n        [\n            \"*test_*.py F*\",\n            \"====* FAILURES *====\",\n            \"____*____\",\n            \"*--- Captured log call*\",\n            \"WARNING * during call\",\n            \"*1 failed*\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*Captured stderr call*\")\n    result.stdout.no_fnmatch_line(\"*during collection*\")\n\n\ndef test_libedit_workaround(pytester: Pytester) -> None:\n    pytester.makeconftest(\"\"\"\n    import pytest\n\n\n    def pytest_terminal_summary(config):\n        capture = config.pluginmanager.getplugin(\"capturemanager\")\n        capture.suspend_global_capture(in_=True)\n\n        print(\"Enter 'hi'\")\n        value = input()\n        print(f\"value: {value!r}\")\n\n        capture.resume_global_capture()\n    \"\"\")\n    readline = pytest.importorskip(\"readline\")\n    backend = getattr(readline, \"backend\", readline.__doc__)  # added in Python 3.13\n    print(f\"Readline backend: {backend}\")\n\n    child = pytester.spawn_pytest(\"\")\n    child.expect(r\"Enter 'hi'\")\n    child.sendline(\"hi\")\n    rest = child.read().decode(\"utf8\")\n    print(rest)\n    match = re.search(r\"^value: '(.*)'\\r?$\", rest, re.MULTILINE)\n    assert match is not None\n    assert match.group(1) == \"hi\"\n"
  },
  {
    "path": "testing/test_collect_imported_tests.py",
    "content": "\"\"\"Tests for the `collect_imported_tests` configuration value.\"\"\"\n\nfrom __future__ import annotations\n\nimport textwrap\n\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\ndef setup_files(pytester: Pytester) -> None:\n    src_dir = pytester.mkdir(\"src\")\n    tests_dir = pytester.mkdir(\"tests\")\n    src_file = src_dir / \"foo.py\"\n\n    src_file.write_text(\n        textwrap.dedent(\"\"\"\\\n            class Testament:\n                def test_collections(self):\n                    pass\n\n            def test_testament(): pass\n        \"\"\"),\n        encoding=\"utf-8\",\n    )\n\n    test_file = tests_dir / \"foo_test.py\"\n    test_file.write_text(\n        textwrap.dedent(\"\"\"\\\n            from foo import Testament, test_testament\n\n            class TestDomain:\n                def test(self):\n                    testament = Testament()\n                    assert testament\n        \"\"\"),\n        encoding=\"utf-8\",\n    )\n\n    pytester.syspathinsert(src_dir)\n\n\ndef test_collect_imports_disabled(pytester: Pytester) -> None:\n    \"\"\"\n    When collect_imported_tests is disabled, only objects in the\n    test modules are collected as tests, so the imported names (`Testament` and `test_testament`)\n    are not collected.\n    \"\"\"\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        collect_imported_tests = false\n        \"\"\"\n    )\n\n    setup_files(pytester)\n    result = pytester.runpytest(\"-v\", \"tests\")\n    result.stdout.fnmatch_lines(\n        [\n            \"tests/foo_test.py::TestDomain::test PASSED*\",\n        ]\n    )\n\n    # Ensure that the hooks were only called for the collected item.\n    reprec = result.reprec  # type:ignore[attr-defined]\n    reports = reprec.getreports(\"pytest_collectreport\")\n    [modified] = reprec.getcalls(\"pytest_collection_modifyitems\")\n    [item_collected] = reprec.getcalls(\"pytest_itemcollected\")\n\n    assert [x.nodeid for x in reports] == [\n        \"\",\n        \"tests/foo_test.py::TestDomain\",\n        \"tests/foo_test.py\",\n        \"tests\",\n    ]\n    assert [x.nodeid for x in modified.items] == [\"tests/foo_test.py::TestDomain::test\"]\n    assert item_collected.item.nodeid == \"tests/foo_test.py::TestDomain::test\"\n\n\n@pytest.mark.parametrize(\"configure_ini\", [False, True])\ndef test_collect_imports_enabled(pytester: Pytester, configure_ini: bool) -> None:\n    \"\"\"\n    When collect_imported_tests is enabled (the default), all names in the\n    test modules are collected as tests.\n    \"\"\"\n    if configure_ini:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            collect_imported_tests = true\n            \"\"\"\n        )\n\n    setup_files(pytester)\n    result = pytester.runpytest(\"-v\", \"tests\")\n    result.stdout.fnmatch_lines(\n        [\n            \"tests/foo_test.py::Testament::test_collections PASSED*\",\n            \"tests/foo_test.py::test_testament PASSED*\",\n            \"tests/foo_test.py::TestDomain::test PASSED*\",\n        ]\n    )\n"
  },
  {
    "path": "testing/test_collection.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nimport os\nfrom pathlib import Path\nfrom pathlib import PurePath\nimport pprint\nimport shutil\nimport sys\nimport tempfile\nimport textwrap\n\nfrom _pytest.compat import running_on_ci\nfrom _pytest.config import ExitCode\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.main import _in_venv\nfrom _pytest.main import Session\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.nodes import Item\nfrom _pytest.pathlib import symlink_or_skip\nfrom _pytest.pytester import HookRecorder\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\ndef ensure_file(file_path: Path) -> Path:\n    \"\"\"Ensure that file exists\"\"\"\n    file_path.parent.mkdir(parents=True, exist_ok=True)\n    file_path.touch(exist_ok=True)\n    return file_path\n\n\nclass TestCollector:\n    def test_collect_versus_item(self) -> None:\n        from pytest import Collector\n        from pytest import Item\n\n        assert not issubclass(Collector, Item)\n        assert not issubclass(Item, Collector)\n\n    def test_check_equality(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            def test_pass(): pass\n            def test_fail(): assert 0\n        \"\"\"\n        )\n        fn1 = pytester.collect_by_name(modcol, \"test_pass\")\n        assert isinstance(fn1, pytest.Function)\n        fn2 = pytester.collect_by_name(modcol, \"test_pass\")\n        assert isinstance(fn2, pytest.Function)\n\n        assert fn1 == fn2\n        assert fn1 != modcol\n        assert hash(fn1) == hash(fn2)\n\n        fn3 = pytester.collect_by_name(modcol, \"test_fail\")\n        assert isinstance(fn3, pytest.Function)\n        assert not (fn1 == fn3)\n        assert fn1 != fn3\n\n        for fn in fn1, fn2, fn3:\n            assert isinstance(fn, pytest.Function)\n            assert fn != 3  # type: ignore[comparison-overlap]\n            assert fn != modcol\n            assert fn != [1, 2, 3]  # type: ignore[comparison-overlap]\n            assert [1, 2, 3] != fn  # type: ignore[comparison-overlap]\n            assert modcol != fn\n\n        assert pytester.collect_by_name(modcol, \"doesnotexist\") is None\n\n    def test_getparent_and_accessors(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            class TestClass:\n                 def test_foo(self):\n                     pass\n        \"\"\"\n        )\n        cls = pytester.collect_by_name(modcol, \"TestClass\")\n        assert isinstance(cls, pytest.Class)\n        fn = pytester.collect_by_name(cls, \"test_foo\")\n        assert isinstance(fn, pytest.Function)\n\n        assert fn.getparent(pytest.Module) is modcol\n        assert modcol.module is not None\n        assert modcol.cls is None\n        assert modcol.instance is None\n\n        assert fn.getparent(pytest.Class) is cls\n        assert cls.module is not None\n        assert cls.cls is not None\n        assert cls.instance is None\n\n        assert fn.getparent(pytest.Function) is fn\n        assert fn.module is not None\n        assert fn.cls is not None\n        assert fn.instance is not None\n        assert fn.function is not None\n\n    def test_getcustomfile_roundtrip(self, pytester: Pytester) -> None:\n        hello = pytester.makefile(\".xxx\", hello=\"world\")\n        pytester.makepyfile(\n            conftest=\"\"\"\n            import pytest\n            class CustomFile(pytest.File):\n                def collect(self):\n                    return []\n            def pytest_collect_file(file_path, parent):\n                if file_path.suffix == \".xxx\":\n                    return CustomFile.from_parent(path=file_path, parent=parent)\n        \"\"\"\n        )\n        node = pytester.getpathnode(hello)\n        assert isinstance(node, pytest.File)\n        assert node.name == \"hello.xxx\"\n        nodes = node.session.perform_collect([node.nodeid], genitems=False)\n        assert len(nodes) == 1\n        assert isinstance(nodes[0], pytest.File)\n\n    def test_can_skip_class_with_test_attr(self, pytester: Pytester) -> None:\n        \"\"\"Assure test class is skipped when using `__test__=False` (See #2007).\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            class TestFoo(object):\n                __test__ = False\n                def __init__(self):\n                    pass\n                def test_foo():\n                    assert True\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 0 items\", \"*no tests ran in*\"])\n\n\nclass TestCollectFS:\n    def test_ignored_certain_directories(self, pytester: Pytester) -> None:\n        tmp_path = pytester.path\n        ensure_file(tmp_path / \"build\" / \"test_notfound.py\")\n        ensure_file(tmp_path / \"dist\" / \"test_notfound.py\")\n        ensure_file(tmp_path / \"_darcs\" / \"test_notfound.py\")\n        ensure_file(tmp_path / \"CVS\" / \"test_notfound.py\")\n        ensure_file(tmp_path / \"{arch}\" / \"test_notfound.py\")\n        ensure_file(tmp_path / \".whatever\" / \"test_notfound.py\")\n        ensure_file(tmp_path / \".bzr\" / \"test_notfound.py\")\n        ensure_file(tmp_path / \"normal\" / \"test_found.py\")\n        for x in tmp_path.rglob(\"test_*.py\"):\n            x.write_text(\"def test_hello(): pass\", encoding=\"utf-8\")\n\n        result = pytester.runpytest(\"--collect-only\")\n        s = result.stdout.str()\n        assert \"test_notfound\" not in s\n        assert \"test_found\" in s\n\n    known_environment_types = pytest.mark.parametrize(\n        \"env_path\",\n        [\n            pytest.param(PurePath(\"pyvenv.cfg\"), id=\"venv\"),\n            pytest.param(PurePath(\"conda-meta\", \"history\"), id=\"conda\"),\n        ],\n    )\n\n    @known_environment_types\n    def test_ignored_virtualenvs(self, pytester: Pytester, env_path: PurePath) -> None:\n        ensure_file(pytester.path / \"virtual\" / env_path)\n        testfile = ensure_file(pytester.path / \"virtual\" / \"test_invenv.py\")\n        testfile.write_text(\"def test_hello(): pass\", encoding=\"utf-8\")\n\n        # by default, ignore tests inside a virtualenv\n        result = pytester.runpytest()\n        result.stdout.no_fnmatch_line(\"*test_invenv*\")\n        # allow test collection if user insists\n        result = pytester.runpytest(\"--collect-in-virtualenv\")\n        assert \"test_invenv\" in result.stdout.str()\n        # allow test collection if user directly passes in the directory\n        result = pytester.runpytest(\"virtual\")\n        assert \"test_invenv\" in result.stdout.str()\n\n    @known_environment_types\n    def test_ignored_virtualenvs_norecursedirs_precedence(\n        self, pytester: Pytester, env_path\n    ) -> None:\n        # norecursedirs takes priority\n        ensure_file(pytester.path / \".virtual\" / env_path)\n        testfile = ensure_file(pytester.path / \".virtual\" / \"test_invenv.py\")\n        testfile.write_text(\"def test_hello(): pass\", encoding=\"utf-8\")\n        result = pytester.runpytest(\"--collect-in-virtualenv\")\n        result.stdout.no_fnmatch_line(\"*test_invenv*\")\n        # ...unless the virtualenv is explicitly given on the CLI\n        result = pytester.runpytest(\"--collect-in-virtualenv\", \".virtual\")\n        assert \"test_invenv\" in result.stdout.str()\n\n    @known_environment_types\n    def test__in_venv(self, pytester: Pytester, env_path: PurePath) -> None:\n        \"\"\"Directly test the virtual env detection function\"\"\"\n        # no env path, not a env\n        base_path = pytester.mkdir(\"venv\")\n        assert _in_venv(base_path) is False\n        # with env path, totally a env\n        ensure_file(base_path.joinpath(env_path))\n        assert _in_venv(base_path) is True\n\n    def test_custom_norecursedirs(self, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            norecursedirs = mydir xyz*\n        \"\"\"\n        )\n        tmp_path = pytester.path\n        ensure_file(tmp_path / \"mydir\" / \"test_hello.py\").write_text(\n            \"def test_1(): pass\", encoding=\"utf-8\"\n        )\n        ensure_file(tmp_path / \"xyz123\" / \"test_2.py\").write_text(\n            \"def test_2(): 0/0\", encoding=\"utf-8\"\n        )\n        ensure_file(tmp_path / \"xy\" / \"test_ok.py\").write_text(\n            \"def test_3(): pass\", encoding=\"utf-8\"\n        )\n        rec = pytester.inline_run()\n        rec.assertoutcome(passed=1)\n        rec = pytester.inline_run(\"xyz123/test_2.py\")\n        rec.assertoutcome(failed=1)\n\n    def test_testpaths_ini(self, pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            testpaths = */tests\n        \"\"\"\n        )\n        tmp_path = pytester.path\n        ensure_file(tmp_path / \"a\" / \"test_1.py\").write_text(\n            \"def test_a(): pass\", encoding=\"utf-8\"\n        )\n        ensure_file(tmp_path / \"b\" / \"tests\" / \"test_2.py\").write_text(\n            \"def test_b(): pass\", encoding=\"utf-8\"\n        )\n        ensure_file(tmp_path / \"c\" / \"tests\" / \"test_3.py\").write_text(\n            \"def test_c(): pass\", encoding=\"utf-8\"\n        )\n\n        # executing from rootdir only tests from `testpaths` directories\n        # are collected\n        items, _reprec = pytester.inline_genitems(\"-v\")\n        assert [x.name for x in items] == [\"test_b\", \"test_c\"]\n\n        # check that explicitly passing directories in the command-line\n        # collects the tests\n        for dirname in (\"a\", \"b\", \"c\"):\n            items, _reprec = pytester.inline_genitems(tmp_path.joinpath(dirname))\n            assert [x.name for x in items] == [f\"test_{dirname}\"]\n\n        # changing cwd to each subdirectory and running pytest without\n        # arguments collects the tests in that directory normally\n        for dirname in (\"a\", \"b\", \"c\"):\n            monkeypatch.chdir(pytester.path.joinpath(dirname))\n            items, _reprec = pytester.inline_genitems()\n            assert [x.name for x in items] == [f\"test_{dirname}\"]\n\n    def test_missing_permissions_on_unselected_directory_doesnt_crash(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Regression test for #12120.\"\"\"\n        test = pytester.makepyfile(test=\"def test(): pass\")\n        bad = pytester.mkdir(\"bad\")\n        try:\n            bad.chmod(0)\n\n            result = pytester.runpytest(test)\n        finally:\n            bad.chmod(750)\n            bad.rmdir()\n\n        assert result.ret == ExitCode.OK\n        result.assert_outcomes(passed=1)\n\n\nclass TestCollectPluginHookRelay:\n    def test_pytest_collect_file(self, pytester: Pytester) -> None:\n        wascalled = []\n\n        class Plugin:\n            def pytest_collect_file(self, file_path: Path) -> None:\n                if not file_path.name.startswith(\".\"):\n                    # Ignore hidden files, e.g. .testmondata.\n                    wascalled.append(file_path)\n\n        pytester.makefile(\".abc\", \"xyz\")\n        pytest.main(pytester.path, plugins=[Plugin()])\n        assert len(wascalled) == 1\n        assert wascalled[0].suffix == \".abc\"\n\n\nclass TestPrunetraceback:\n    def test_custom_repr_failure(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import not_exists\n        \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            def pytest_collect_file(file_path, parent):\n                return MyFile.from_parent(path=file_path, parent=parent)\n            class MyError(Exception):\n                pass\n            class MyFile(pytest.File):\n                def collect(self):\n                    raise MyError()\n                def repr_failure(self, excinfo):\n                    if isinstance(excinfo.value, MyError):\n                        return \"hello world\"\n                    return pytest.File.repr_failure(self, excinfo)\n        \"\"\"\n        )\n\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*hello world*\"])\n\n    @pytest.mark.xfail(reason=\"other mechanism for adding to reporting needed\")\n    def test_collect_report_postprocessing(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import not_exists\n        \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            @pytest.hookimpl(wrapper=True)\n            def pytest_make_collect_report():\n                rep = yield\n                rep.headerlines += [\"header1\"]\n                return rep\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines([\"*ERROR collecting*\", \"*header1*\"])\n\n    def test_collection_error_traceback_is_clean(self, pytester: Pytester) -> None:\n        \"\"\"When a collection error occurs, the report traceback doesn't contain\n        internal pytest stack entries.\n\n        Issue #11710.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            raise Exception(\"LOUSY\")\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*ERROR collecting*\",\n                \"test_*.py:1: in <module>\",\n                '    raise Exception(\"LOUSY\")',\n                \"E   Exception: LOUSY\",\n                \"*= short test summary info =*\",\n            ],\n            consecutive=True,\n        )\n\n\nclass TestCustomConftests:\n    def test_ignore_collect_path(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_ignore_collect(collection_path, config):\n                return collection_path.name.startswith(\"x\") or collection_path.name == \"test_one.py\"\n        \"\"\"\n        )\n        sub = pytester.mkdir(\"xy123\")\n        ensure_file(sub / \"test_hello.py\").write_text(\"syntax error\", encoding=\"utf-8\")\n        sub.joinpath(\"conftest.py\").write_text(\"syntax error\", encoding=\"utf-8\")\n        pytester.makepyfile(\"def test_hello(): pass\")\n        pytester.makepyfile(test_one=\"syntax error\")\n        result = pytester.runpytest(\"--fulltrace\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_ignore_collect_not_called_on_argument(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_ignore_collect(collection_path, config):\n                return True\n        \"\"\"\n        )\n        p = pytester.makepyfile(\"def test_hello(): pass\")\n        result = pytester.runpytest(p)\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n        result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n\n    def test_collectignore_exclude_on_option(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            from pathlib import Path\n\n            class MyPathLike:\n                def __init__(self, path):\n                    self.path = path\n                def __fspath__(self):\n                    return \"path\"\n\n            collect_ignore = [MyPathLike('hello'), 'test_world.py', Path('bye')]\n\n            def pytest_addoption(parser):\n                parser.addoption(\"--XX\", action=\"store_true\", default=False)\n\n            def pytest_configure(config):\n                if config.getvalue(\"XX\"):\n                    collect_ignore[:] = []\n        \"\"\"\n        )\n        pytester.mkdir(\"hello\")\n        pytester.makepyfile(test_world=\"def test_hello(): pass\")\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n        result.stdout.no_fnmatch_line(\"*passed*\")\n        result = pytester.runpytest(\"--XX\")\n        assert result.ret == 0\n        assert \"passed\" in result.stdout.str()\n\n    def test_collectignoreglob_exclude_on_option(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            collect_ignore_glob = ['*w*l[dt]*']\n            def pytest_addoption(parser):\n                parser.addoption(\"--XX\", action=\"store_true\", default=False)\n            def pytest_configure(config):\n                if config.getvalue(\"XX\"):\n                    collect_ignore_glob[:] = []\n        \"\"\"\n        )\n        pytester.makepyfile(test_world=\"def test_hello(): pass\")\n        pytester.makepyfile(test_welt=\"def test_hallo(): pass\")\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n        result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n        result = pytester.runpytest(\"--XX\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n    def test_pytest_fs_collect_hooks_are_seen(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            class MyModule(pytest.Module):\n                pass\n            def pytest_collect_file(file_path, parent):\n                if file_path.suffix == \".py\":\n                    return MyModule.from_parent(path=file_path, parent=parent)\n        \"\"\"\n        )\n        pytester.mkdir(\"sub\")\n        pytester.makepyfile(\"def test_x(): pass\")\n        result = pytester.runpytest(\"--co\")\n        result.stdout.fnmatch_lines([\"*MyModule*\", \"*test_x*\"])\n\n    def test_pytest_collect_file_from_sister_dir(self, pytester: Pytester) -> None:\n        sub1 = pytester.mkpydir(\"sub1\")\n        sub2 = pytester.mkpydir(\"sub2\")\n        conf1 = pytester.makeconftest(\n            \"\"\"\n            import pytest\n            class MyModule1(pytest.Module):\n                pass\n            def pytest_collect_file(file_path, parent):\n                if file_path.suffix == \".py\":\n                    return MyModule1.from_parent(path=file_path, parent=parent)\n        \"\"\"\n        )\n        conf1.replace(sub1.joinpath(conf1.name))\n        conf2 = pytester.makeconftest(\n            \"\"\"\n            import pytest\n            class MyModule2(pytest.Module):\n                pass\n            def pytest_collect_file(file_path, parent):\n                if file_path.suffix == \".py\":\n                    return MyModule2.from_parent(path=file_path, parent=parent)\n        \"\"\"\n        )\n        conf2.replace(sub2.joinpath(conf2.name))\n        p = pytester.makepyfile(\"def test_x(): pass\")\n        shutil.copy(p, sub1.joinpath(p.name))\n        shutil.copy(p, sub2.joinpath(p.name))\n        result = pytester.runpytest(\"--co\")\n        result.stdout.fnmatch_lines([\"*MyModule1*\", \"*MyModule2*\", \"*test_x*\"])\n\n\nclass TestSession:\n    def test_collect_topdir(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\"def test_func(): pass\")\n        id = \"::\".join([p.name, \"test_func\"])\n        # XXX migrate to collectonly? (see below)\n        config = pytester.parseconfig(id)\n        topdir = pytester.path\n        rcol = Session.from_config(config)\n        assert topdir == rcol.path\n        # rootid = rcol.nodeid\n        # root2 = rcol.perform_collect([rcol.nodeid], genitems=False)[0]\n        # assert root2 == rcol, rootid\n        colitems = rcol.perform_collect([rcol.nodeid], genitems=False)\n        assert len(colitems) == 1\n        assert colitems[0].path == topdir\n\n    def get_reported_items(self, hookrec: HookRecorder) -> list[Item]:\n        \"\"\"Return pytest.Item instances reported by the pytest_collectreport hook\"\"\"\n        calls = hookrec.getcalls(\"pytest_collectreport\")\n        return [\n            x\n            for call in calls\n            for x in call.report.result\n            if isinstance(x, pytest.Item)\n        ]\n\n    def test_collect_protocol_single_function(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\"def test_func(): pass\")\n        id = \"::\".join([p.name, \"test_func\"])\n        items, hookrec = pytester.inline_genitems(id)\n        (item,) = items\n        assert item.name == \"test_func\"\n        newid = item.nodeid\n        assert newid == id\n        pprint.pprint(hookrec.calls)\n        topdir = pytester.path  # noqa: F841\n        hookrec.assert_contains(\n            [\n                (\"pytest_collectstart\", \"collector.path == topdir\"),\n                (\"pytest_make_collect_report\", \"collector.path == topdir\"),\n                (\"pytest_collectstart\", \"collector.path == p\"),\n                (\"pytest_make_collect_report\", \"collector.path == p\"),\n                (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n                (\"pytest_collectreport\", \"report.result[0].name == 'test_func'\"),\n            ]\n        )\n        # ensure we are reporting the collection of the single test item (#2464)\n        assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_func\"]\n\n    def test_collect_protocol_method(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            class TestClass(object):\n                def test_method(self):\n                    pass\n        \"\"\"\n        )\n        normid = p.name + \"::TestClass::test_method\"\n        for id in [p.name, p.name + \"::TestClass\", normid]:\n            items, hookrec = pytester.inline_genitems(id)\n            assert len(items) == 1\n            assert items[0].name == \"test_method\"\n            newid = items[0].nodeid\n            assert newid == normid\n            # ensure we are reporting the collection of the single test item (#2464)\n            assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_method\"]\n\n    def test_collect_custom_nodes_multi_id(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\"def test_func(): pass\")\n        pytester.makeconftest(\n            f\"\"\"\n            import pytest\n            class SpecialItem(pytest.Item):\n                def runtest(self):\n                    return # ok\n            class SpecialFile(pytest.File):\n                def collect(self):\n                    return [SpecialItem.from_parent(name=\"check\", parent=self)]\n            def pytest_collect_file(file_path, parent):\n                if file_path.name == {p.name!r}:\n                    return SpecialFile.from_parent(path=file_path, parent=parent)\n        \"\"\"\n        )\n        id = p.name\n\n        items, hookrec = pytester.inline_genitems(id)\n        pprint.pprint(hookrec.calls)\n        assert len(items) == 2\n        hookrec.assert_contains(\n            [\n                (\"pytest_collectstart\", \"collector.path == collector.session.path\"),\n                (\n                    \"pytest_collectstart\",\n                    \"collector.__class__.__name__ == 'SpecialFile'\",\n                ),\n                (\"pytest_collectstart\", \"collector.__class__.__name__ == 'Module'\"),\n                (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n                (\"pytest_collectreport\", \"report.nodeid.startswith(p.name)\"),\n            ]\n        )\n        assert len(self.get_reported_items(hookrec)) == 2\n\n    def test_collect_subdir_event_ordering(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\"def test_func(): pass\")\n        aaa = pytester.mkpydir(\"aaa\")\n        test_aaa = aaa.joinpath(\"test_aaa.py\")\n        p.replace(test_aaa)\n\n        items, hookrec = pytester.inline_genitems()\n        assert len(items) == 1\n        pprint.pprint(hookrec.calls)\n        hookrec.assert_contains(\n            [\n                (\"pytest_collectstart\", \"collector.path == test_aaa\"),\n                (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n                (\"pytest_collectreport\", \"report.nodeid.startswith('aaa/test_aaa.py')\"),\n            ]\n        )\n\n    def test_collect_two_commandline_args(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\"def test_func(): pass\")\n        aaa = pytester.mkpydir(\"aaa\")\n        bbb = pytester.mkpydir(\"bbb\")\n        test_aaa = aaa.joinpath(\"test_aaa.py\")\n        shutil.copy(p, test_aaa)\n        test_bbb = bbb.joinpath(\"test_bbb.py\")\n        p.replace(test_bbb)\n\n        id = \".\"\n\n        items, hookrec = pytester.inline_genitems(id)\n        assert len(items) == 2\n        pprint.pprint(hookrec.calls)\n        hookrec.assert_contains(\n            [\n                (\"pytest_collectstart\", \"collector.path == test_aaa\"),\n                (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n                (\"pytest_collectreport\", \"report.nodeid == 'aaa/test_aaa.py'\"),\n                (\"pytest_collectstart\", \"collector.path == test_bbb\"),\n                (\"pytest_pycollect_makeitem\", \"name == 'test_func'\"),\n                (\"pytest_collectreport\", \"report.nodeid == 'bbb/test_bbb.py'\"),\n            ]\n        )\n\n    def test_serialization_byid(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\"def test_func(): pass\")\n        items, _hookrec = pytester.inline_genitems()\n        assert len(items) == 1\n        (item,) = items\n        items2, _hookrec = pytester.inline_genitems(item.nodeid)\n        (item2,) = items2\n        assert item2.name == item.name\n        assert item2.path == item.path\n\n    def test_find_byid_without_instance_parents(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            class TestClass(object):\n                def test_method(self):\n                    pass\n        \"\"\"\n        )\n        arg = p.name + \"::TestClass::test_method\"\n        items, hookrec = pytester.inline_genitems(arg)\n        assert len(items) == 1\n        (item,) = items\n        assert item.nodeid.endswith(\"TestClass::test_method\")\n        # ensure we are reporting the collection of the single test item (#2464)\n        assert [x.name for x in self.get_reported_items(hookrec)] == [\"test_method\"]\n\n    def test_collect_parametrized_order(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize('i', [0, 1, 2])\n            def test_param(i): ...\n            \"\"\"\n        )\n        items, _hookrec = pytester.inline_genitems(f\"{p}::test_param\")\n        assert len(items) == 3\n        assert [item.nodeid for item in items] == [\n            \"test_collect_parametrized_order.py::test_param[0]\",\n            \"test_collect_parametrized_order.py::test_param[1]\",\n            \"test_collect_parametrized_order.py::test_param[2]\",\n        ]\n\n\nclass Test_getinitialnodes:\n    def test_global_file(self, pytester: Pytester) -> None:\n        tmp_path = pytester.path\n        x = ensure_file(tmp_path / \"x.py\")\n        config = pytester.parseconfigure(x)\n        col = pytester.getnode(config, x)\n        assert isinstance(col, pytest.Module)\n        assert col.name == \"x.py\"\n        assert col.parent is not None\n        assert col.parent.parent is not None\n        assert col.parent.parent.parent is None\n        for parent in col.listchain():\n            assert parent.config is config\n\n    def test_pkgfile(self, pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n        \"\"\"Verify nesting when a module is within a package.\n        The parent chain should match: Module<x.py> -> Package<subdir> -> Session.\n            Session's parent should always be None.\n        \"\"\"\n        tmp_path = pytester.path\n        subdir = tmp_path.joinpath(\"subdir\")\n        x = ensure_file(subdir / \"x.py\")\n        ensure_file(subdir / \"__init__.py\")\n        with monkeypatch.context() as mp:\n            mp.chdir(subdir)\n            config = pytester.parseconfigure(x)\n        col = pytester.getnode(config, x)\n        assert col is not None\n        assert col.name == \"x.py\"\n        assert isinstance(col, pytest.Module)\n        assert isinstance(col.parent, pytest.Package)\n        assert isinstance(col.parent.parent, pytest.Session)\n        # session is batman (has no parents)\n        assert col.parent.parent.parent is None\n        for parent in col.listchain():\n            assert parent.config is config\n\n\nclass Test_genitems:\n    def test_check_collect_hashes(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                pass\n\n            def test_2():\n                pass\n        \"\"\"\n        )\n        shutil.copy(p, p.parent / (p.stem + \"2\" + \".py\"))\n        items, _reprec = pytester.inline_genitems(p.parent)\n        assert len(items) == 4\n        for numi, i in enumerate(items):\n            for numj, j in enumerate(items):\n                if numj != numi:\n                    assert hash(i) != hash(j)\n                    assert i != j\n\n    def test_example_items1(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def testone():\n                pass\n\n            class TestX(object):\n                def testmethod_one(self):\n                    pass\n\n            class TestY(TestX):\n                @pytest.mark.parametrize(\"arg0\", [\".[\"])\n                def testmethod_two(self, arg0):\n                    pass\n        \"\"\"\n        )\n        items, _reprec = pytester.inline_genitems(p)\n        assert len(items) == 4\n        assert items[0].name == \"testone\"\n        assert items[1].name == \"testmethod_one\"\n        assert items[2].name == \"testmethod_one\"\n        assert items[3].name == \"testmethod_two[.[]\"\n\n        # let's also test getmodpath here\n        assert items[0].getmodpath() == \"testone\"  # type: ignore[attr-defined]\n        assert items[1].getmodpath() == \"TestX.testmethod_one\"  # type: ignore[attr-defined]\n        assert items[2].getmodpath() == \"TestY.testmethod_one\"  # type: ignore[attr-defined]\n        # PR #6202: Fix incorrect result of getmodpath method. (Resolves issue #6189)\n        assert items[3].getmodpath() == \"TestY.testmethod_two[.[]\"  # type: ignore[attr-defined]\n\n        s = items[0].getmodpath(stopatmodule=False)  # type: ignore[attr-defined]\n        assert s.endswith(\"test_example_items1.testone\")\n        print(s)\n\n    def test_classmethod_is_discovered(self, pytester: Pytester) -> None:\n        \"\"\"Test that classmethods are discovered\"\"\"\n        p = pytester.makepyfile(\n            \"\"\"\n            class TestCase:\n                @classmethod\n                def test_classmethod(cls) -> None:\n                    pass\n            \"\"\"\n        )\n        items, _reprec = pytester.inline_genitems(p)\n        ids = [x.getmodpath() for x in items]  # type: ignore[attr-defined]\n        assert ids == [\"TestCase.test_classmethod\"]\n\n    def test_class_and_functions_discovery_using_glob(self, pytester: Pytester) -> None:\n        \"\"\"Test that Python_classes and Python_functions config options work\n        as prefixes and glob-like patterns (#600).\"\"\"\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            python_classes = *Suite Test\n            python_functions = *_test test\n        \"\"\"\n        )\n        p = pytester.makepyfile(\n            \"\"\"\n            class MyTestSuite(object):\n                def x_test(self):\n                    pass\n\n            class TestCase(object):\n                def test_y(self):\n                    pass\n        \"\"\"\n        )\n        items, _reprec = pytester.inline_genitems(p)\n        ids = [x.getmodpath() for x in items]  # type: ignore[attr-defined]\n        assert ids == [\"MyTestSuite.x_test\", \"TestCase.test_y\"]\n\n\ndef test_matchnodes_two_collections_same_file(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n        def pytest_configure(config):\n            config.pluginmanager.register(Plugin2())\n\n        class Plugin2(object):\n            def pytest_collect_file(self, file_path, parent):\n                if file_path.suffix == \".abc\":\n                    return MyFile2.from_parent(path=file_path, parent=parent)\n\n        def pytest_collect_file(file_path, parent):\n            if file_path.suffix == \".abc\":\n                return MyFile1.from_parent(path=file_path, parent=parent)\n\n        class MyFile1(pytest.File):\n            def collect(self):\n                yield Item1.from_parent(name=\"item1\", parent=self)\n\n        class MyFile2(pytest.File):\n            def collect(self):\n                yield Item2.from_parent(name=\"item2\", parent=self)\n\n        class Item1(pytest.Item):\n            def runtest(self):\n                pass\n\n        class Item2(pytest.Item):\n            def runtest(self):\n                pass\n    \"\"\"\n    )\n    p = pytester.makefile(\".abc\", \"\")\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*2 passed*\"])\n    res = pytester.runpytest(f\"{p.name}::item2\")\n    res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\nclass TestNodeKeywords:\n    def test_no_under(self, pytester: Pytester) -> None:\n        modcol = pytester.getmodulecol(\n            \"\"\"\n            def test_pass(): pass\n            def test_fail(): assert 0\n        \"\"\"\n        )\n        values = list(modcol.keywords)\n        assert modcol.name in values\n        for x in values:\n            assert not x.startswith(\"_\")\n        assert modcol.name in repr(modcol.keywords)\n\n    def test_issue345(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_should_not_be_selected():\n                assert False, 'I should not have been selected to run'\n\n            def test___repr__():\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-k repr\")\n        reprec.assertoutcome(passed=1, failed=0)\n\n    def test_keyword_matching_is_case_insensitive_by_default(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Check that selection via -k EXPRESSION is case-insensitive.\n\n        Since markers are also added to the node keywords, they too can\n        be matched without having to think about case sensitivity.\n\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def test_sPeCiFiCToPiC_1():\n                assert True\n\n            class TestSpecificTopic_2:\n                def test(self):\n                    assert True\n\n            @pytest.mark.sPeCiFiCToPic_3\n            def test():\n                assert True\n\n            @pytest.mark.sPeCiFiCToPic_4\n            class Test:\n                def test(self):\n                    assert True\n\n            def test_failing_5():\n                assert False, \"This should not match\"\n\n        \"\"\"\n        )\n        num_matching_tests = 4\n        for expression in (\"specifictopic\", \"SPECIFICTOPIC\", \"SpecificTopic\"):\n            reprec = pytester.inline_run(\"-k \" + expression)\n            reprec.assertoutcome(passed=num_matching_tests, failed=0)\n\n    def test_duplicates_handled_correctly(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            pytestmark = pytest.mark.kw\n            class TestClass:\n                pytestmark = pytest.mark.kw\n                def test_method(self): pass\n                test_method.kw = 'method'\n        \"\"\",\n            \"test_method\",\n        )\n        assert item.parent is not None and item.parent.parent is not None\n        item.parent.parent.keywords[\"kw\"] = \"class\"\n\n        assert item.keywords[\"kw\"] == \"method\"\n        assert len(item.keywords) == len(set(item.keywords))\n\n    def test_unpacked_marks_added_to_keywords(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            pytestmark = pytest.mark.foo\n            class TestClass:\n                pytestmark = pytest.mark.bar\n                def test_method(self): pass\n                test_method.pytestmark = pytest.mark.baz\n        \"\"\",\n            \"test_method\",\n        )\n        assert isinstance(item, pytest.Function)\n        cls = item.getparent(pytest.Class)\n        assert cls is not None\n        mod = item.getparent(pytest.Module)\n        assert mod is not None\n\n        assert item.keywords[\"foo\"] == pytest.mark.foo.mark\n        assert item.keywords[\"bar\"] == pytest.mark.bar.mark\n        assert item.keywords[\"baz\"] == pytest.mark.baz.mark\n\n        assert cls.keywords[\"foo\"] == pytest.mark.foo.mark\n        assert cls.keywords[\"bar\"] == pytest.mark.bar.mark\n        assert \"baz\" not in cls.keywords\n\n        assert mod.keywords[\"foo\"] == pytest.mark.foo.mark\n        assert \"bar\" not in mod.keywords\n        assert \"baz\" not in mod.keywords\n\n\nclass TestCollectDirectoryHook:\n    def test_custom_directory_example(self, pytester: Pytester) -> None:\n        \"\"\"Verify the example from the customdirectory.rst doc.\"\"\"\n        pytester.copy_example(\"customdirectory\")\n\n        reprec = pytester.inline_run()\n\n        reprec.assertoutcome(passed=2, failed=0)\n        calls = reprec.getcalls(\"pytest_collect_directory\")\n        assert len(calls) == 2\n        assert calls[0].path == pytester.path\n        assert isinstance(calls[0].parent, pytest.Session)\n        assert calls[1].path == pytester.path / \"tests\"\n        assert isinstance(calls[1].parent, pytest.Dir)\n\n    def test_directory_ignored_if_none(self, pytester: Pytester) -> None:\n        \"\"\"If the (entire) hook returns None, it's OK, the directory is ignored.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.hookimpl(wrapper=True)\n            def pytest_collect_directory():\n                yield\n                return None\n            \"\"\",\n        )\n        pytester.makepyfile(\n            **{\n                \"tests/test_it.py\": \"\"\"\n                    import pytest\n\n                    def test_it(): pass\n                \"\"\",\n            },\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=0, failed=0)\n\n\nCOLLECTION_ERROR_PY_FILES = dict(\n    test_01_failure=\"\"\"\n        def test_1():\n            assert False\n        \"\"\",\n    test_02_import_error=\"\"\"\n        import asdfasdfasdf\n        def test_2():\n            assert True\n        \"\"\",\n    test_03_import_error=\"\"\"\n        import asdfasdfasdf\n        def test_3():\n            assert True\n    \"\"\",\n    test_04_success=\"\"\"\n        def test_4():\n            assert True\n    \"\"\",\n)\n\n\ndef test_exit_on_collection_error(pytester: Pytester) -> None:\n    \"\"\"Verify that all collection errors are collected and no tests executed\"\"\"\n    pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n    res = pytester.runpytest()\n    assert res.ret == 2\n\n    res.stdout.fnmatch_lines(\n        [\n            \"collected 2 items / 2 errors\",\n            \"*ERROR collecting test_02_import_error.py*\",\n            \"*No module named *asdfa*\",\n            \"*ERROR collecting test_03_import_error.py*\",\n            \"*No module named *asdfa*\",\n        ]\n    )\n\n\ndef test_exit_on_collection_with_maxfail_smaller_than_n_errors(\n    pytester: Pytester,\n) -> None:\n    \"\"\"\n    Verify collection is aborted once maxfail errors are encountered ignoring\n    further modules which would cause more collection errors.\n    \"\"\"\n    pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n    res = pytester.runpytest(\"--maxfail=1\")\n    assert res.ret == 1\n    res.stdout.fnmatch_lines(\n        [\n            \"collected 1 item / 1 error\",\n            \"*ERROR collecting test_02_import_error.py*\",\n            \"*No module named *asdfa*\",\n            \"*! stopping after 1 failures !*\",\n            \"*= 1 error in *\",\n        ]\n    )\n    res.stdout.no_fnmatch_line(\"*test_03*\")\n\n\ndef test_exit_on_collection_with_maxfail_bigger_than_n_errors(\n    pytester: Pytester,\n) -> None:\n    \"\"\"\n    Verify the test run aborts due to collection errors even if maxfail count of\n    errors was not reached.\n    \"\"\"\n    pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n    res = pytester.runpytest(\"--maxfail=4\")\n    assert res.ret == 2\n    res.stdout.fnmatch_lines(\n        [\n            \"collected 2 items / 2 errors\",\n            \"*ERROR collecting test_02_import_error.py*\",\n            \"*No module named *asdfa*\",\n            \"*ERROR collecting test_03_import_error.py*\",\n            \"*No module named *asdfa*\",\n            \"*! Interrupted: 2 errors during collection !*\",\n            \"*= 2 errors in *\",\n        ]\n    )\n\n\ndef test_continue_on_collection_errors(pytester: Pytester) -> None:\n    \"\"\"\n    Verify tests are executed even when collection errors occur when the\n    --continue-on-collection-errors flag is set\n    \"\"\"\n    pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n    res = pytester.runpytest(\"--continue-on-collection-errors\")\n    assert res.ret == 1\n\n    res.stdout.fnmatch_lines(\n        [\"collected 2 items / 2 errors\", \"*1 failed, 1 passed, 2 errors*\"]\n    )\n\n\ndef test_continue_on_collection_errors_maxfail(pytester: Pytester) -> None:\n    \"\"\"\n    Verify tests are executed even when collection errors occur and that maxfail\n    is honoured (including the collection error count).\n    4 tests: 2 collection errors + 1 failure + 1 success\n    test_4 is never executed because the test run is with --maxfail=3 which\n    means it is interrupted after the 2 collection errors + 1 failure.\n    \"\"\"\n    pytester.makepyfile(**COLLECTION_ERROR_PY_FILES)\n\n    res = pytester.runpytest(\"--continue-on-collection-errors\", \"--maxfail=3\")\n    assert res.ret == 1\n\n    res.stdout.fnmatch_lines([\"collected 2 items / 2 errors\", \"*1 failed, 2 errors*\"])\n\n\ndef test_fixture_scope_sibling_conftests(pytester: Pytester) -> None:\n    \"\"\"Regression test case for https://github.com/pytest-dev/pytest/issues/2836\"\"\"\n    foo_path = pytester.mkdir(\"foo\")\n    foo_path.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            import pytest\n            @pytest.fixture\n            def fix():\n                return 1\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    foo_path.joinpath(\"test_foo.py\").write_text(\n        \"def test_foo(fix): assert fix == 1\", encoding=\"utf-8\"\n    )\n\n    # Tests in `food/` should not see the conftest fixture from `foo/`\n    food_path = pytester.mkpydir(\"food\")\n    food_path.joinpath(\"test_food.py\").write_text(\n        \"def test_food(fix): assert fix == 1\", encoding=\"utf-8\"\n    )\n\n    res = pytester.runpytest()\n    assert res.ret == 1\n\n    res.stdout.fnmatch_lines(\n        [\n            \"*ERROR at setup of test_food*\",\n            \"E*fixture 'fix' not found\",\n            \"*1 passed, 1 error*\",\n        ]\n    )\n\n\ndef test_collect_init_tests(pytester: Pytester) -> None:\n    \"\"\"Check that we collect files from __init__.py files when they patch the 'python_files' (#3773)\"\"\"\n    p = pytester.copy_example(\"collect/collect_init_tests\")\n    result = pytester.runpytest(p, \"--collect-only\")\n    result.stdout.fnmatch_lines(\n        [\n            \"collected 2 items\",\n            \"<Dir *>\",\n            \"  <Package tests>\",\n            \"    <Module __init__.py>\",\n            \"      <Function test_init>\",\n            \"    <Module test_foo.py>\",\n            \"      <Function test_foo>\",\n        ]\n    )\n    result = pytester.runpytest(\"./tests\", \"--collect-only\")\n    result.stdout.fnmatch_lines(\n        [\n            \"collected 2 items\",\n            \"<Dir *>\",\n            \"  <Package tests>\",\n            \"    <Module __init__.py>\",\n            \"      <Function test_init>\",\n            \"    <Module test_foo.py>\",\n            \"      <Function test_foo>\",\n        ]\n    )\n    # Ignores duplicates with \".\" and pkginit (#4310).\n    result = pytester.runpytest(\"./tests\", \".\", \"--collect-only\")\n    result.stdout.fnmatch_lines(\n        [\n            \"collected 2 items\",\n            \"<Dir *>\",\n            \"  <Package tests>\",\n            \"    <Module __init__.py>\",\n            \"      <Function test_init>\",\n            \"    <Module test_foo.py>\",\n            \"      <Function test_foo>\",\n        ]\n    )\n    # Same as before, but different order.\n    result = pytester.runpytest(\".\", \"tests\", \"--collect-only\")\n    result.stdout.fnmatch_lines(\n        [\n            \"collected 2 items\",\n            \"<Dir *>\",\n            \"  <Package tests>\",\n            \"    <Module __init__.py>\",\n            \"      <Function test_init>\",\n            \"    <Module test_foo.py>\",\n            \"      <Function test_foo>\",\n        ]\n    )\n    result = pytester.runpytest(\"./tests/test_foo.py\", \"--collect-only\")\n    result.stdout.fnmatch_lines(\n        [\n            \"<Dir *>\",\n            \"  <Package tests>\",\n            \"    <Module test_foo.py>\",\n            \"      <Function test_foo>\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*test_init*\")\n    result = pytester.runpytest(\"./tests/__init__.py\", \"--collect-only\")\n    result.stdout.fnmatch_lines(\n        [\n            \"<Dir *>\",\n            \"  <Package tests>\",\n            \"    <Module __init__.py>\",\n            \"      <Function test_init>\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*test_foo*\")\n\n\ndef test_collect_invalid_signature_message(pytester: Pytester) -> None:\n    \"\"\"Check that we issue a proper message when we can't determine the signature of a test\n    function (#4026).\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        class TestCase:\n            @pytest.fixture\n            def fix():\n                pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\"Could not determine arguments of *.fix *: invalid method signature\"]\n    )\n\n\ndef test_collect_handles_raising_on_dunder_class(pytester: Pytester) -> None:\n    \"\"\"Handle proxy classes like Django's LazySettings that might raise on\n    ``isinstance`` (#4266).\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        class ImproperlyConfigured(Exception):\n            pass\n\n        class RaisesOnGetAttr(object):\n            def raises(self):\n                raise ImproperlyConfigured\n\n            __class__ = property(raises)\n\n        raises = RaisesOnGetAttr()\n\n\n        def test_1():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=1)\n    assert result.ret == 0\n\n\ndef test_collect_with_chdir_during_import(pytester: Pytester) -> None:\n    subdir = pytester.mkdir(\"sub\")\n    pytester.path.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            f\"\"\"\n            import os\n            os.chdir({str(subdir)!r})\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    pytester.makepyfile(\n        f\"\"\"\n        def test_1():\n            import os\n            assert os.getcwd() == {str(subdir)!r}\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*1 passed in*\"])\n    assert result.ret == 0\n\n    # Handles relative testpaths.\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        testpaths = .\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--collect-only\")\n    result.stdout.fnmatch_lines([\"collected 1 item\"])\n\n\ndef test_collect_pyargs_with_testpaths(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    testmod = pytester.mkdir(\"testmod\")\n    # NOTE: __init__.py is not collected since it does not match python_files.\n    testmod.joinpath(\"__init__.py\").write_text(\n        \"def test_func(): pass\", encoding=\"utf-8\"\n    )\n    testmod.joinpath(\"test_file.py\").write_text(\n        \"def test_func(): pass\", encoding=\"utf-8\"\n    )\n\n    root = pytester.mkdir(\"root\")\n    root.joinpath(\"pytest.ini\").write_text(\n        textwrap.dedent(\n            \"\"\"\n        [pytest]\n        addopts = --pyargs\n        testpaths = testmod\n    \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    monkeypatch.setenv(\"PYTHONPATH\", str(pytester.path), prepend=os.pathsep)\n    with monkeypatch.context() as mp:\n        mp.chdir(root)\n        result = pytester.runpytest_subprocess()\n    result.assert_outcomes(passed=1)\n\n\ndef test_initial_conftests_with_testpaths(pytester: Pytester) -> None:\n    \"\"\"The testpaths config option should load conftests in those paths as 'initial' (#10987).\"\"\"\n    p = pytester.mkdir(\"some_path\")\n    p.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\n            def pytest_sessionstart(session):\n                raise Exception(\"pytest_sessionstart hook successfully run\")\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        testpaths = some_path\n        \"\"\"\n    )\n\n    # No command line args - falls back to testpaths.\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.INTERNAL_ERROR\n    result.stdout.fnmatch_lines(\n        \"INTERNALERROR* Exception: pytest_sessionstart hook successfully run\"\n    )\n\n    # No fallback.\n    result = pytester.runpytest(\".\")\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_large_option_breaks_initial_conftests(pytester: Pytester) -> None:\n    \"\"\"Long option values do not break initial conftests handling (#10169).\"\"\"\n    option_value = \"x\" * 1024 * 1000\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_addoption(parser):\n            parser.addoption(\"--xx\", default=None)\n        \"\"\"\n    )\n    pytester.makepyfile(\n        f\"\"\"\n        def test_foo(request):\n            assert request.config.getoption(\"xx\") == {option_value!r}\n        \"\"\"\n    )\n    result = pytester.runpytest(f\"--xx={option_value}\")\n    assert result.ret == 0\n\n\ndef test_collect_symlink_file_arg(pytester: Pytester) -> None:\n    \"\"\"Collect a direct symlink works even if it does not match python_files (#4325).\"\"\"\n    real = pytester.makepyfile(\n        real=\"\"\"\n        def test_nodeid(request):\n            assert request.node.nodeid == \"symlink.py::test_nodeid\"\n        \"\"\"\n    )\n    symlink = pytester.path.joinpath(\"symlink.py\")\n    symlink_or_skip(real, symlink)\n    result = pytester.runpytest(\"-v\", symlink)\n    result.stdout.fnmatch_lines([\"symlink.py::test_nodeid PASSED*\", \"*1 passed in*\"])\n    assert result.ret == 0\n\n\ndef test_collect_symlink_out_of_tree(pytester: Pytester) -> None:\n    \"\"\"Test collection of symlink via out-of-tree rootdir.\"\"\"\n    sub = pytester.mkdir(\"sub\")\n    real = sub.joinpath(\"test_real.py\")\n    real.write_text(\n        textwrap.dedent(\n            \"\"\"\n        def test_nodeid(request):\n            # Should not contain sub/ prefix.\n            assert request.node.nodeid == \"test_real.py::test_nodeid\"\n        \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n\n    out_of_tree = pytester.mkdir(\"out_of_tree\")\n    symlink_to_sub = out_of_tree.joinpath(\"symlink_to_sub\")\n    symlink_or_skip(sub, symlink_to_sub)\n    os.chdir(sub)\n    result = pytester.runpytest(\"-vs\", f\"--rootdir={sub}\", symlink_to_sub)\n    result.stdout.fnmatch_lines(\n        [\n            # Should not contain \"sub/\"!\n            \"test_real.py::test_nodeid PASSED\"\n        ]\n    )\n    assert result.ret == 0\n\n\ndef test_collect_symlink_dir(pytester: Pytester) -> None:\n    \"\"\"A symlinked directory is collected.\"\"\"\n    dir = pytester.mkdir(\"dir\")\n    dir.joinpath(\"test_it.py\").write_text(\"def test_it(): pass\", \"utf-8\")\n    symlink_or_skip(pytester.path.joinpath(\"symlink_dir\"), dir)\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=2)\n\n\ndef test_collectignore_via_conftest(pytester: Pytester) -> None:\n    \"\"\"collect_ignore in parent conftest skips importing child (issue #4592).\"\"\"\n    tests = pytester.mkpydir(\"tests\")\n    tests.joinpath(\"conftest.py\").write_text(\n        \"collect_ignore = ['ignore_me']\", encoding=\"utf-8\"\n    )\n\n    ignore_me = tests.joinpath(\"ignore_me\")\n    ignore_me.mkdir()\n    ignore_me.joinpath(\"__init__.py\").touch()\n    ignore_me.joinpath(\"conftest.py\").write_text(\n        \"assert 0, 'should_not_be_called'\", encoding=\"utf-8\"\n    )\n\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_collect_pkg_init_and_file_in_args(pytester: Pytester) -> None:\n    subdir = pytester.mkdir(\"sub\")\n    init = subdir.joinpath(\"__init__.py\")\n    init.write_text(\"def test_init(): pass\", encoding=\"utf-8\")\n    p = subdir.joinpath(\"test_file.py\")\n    p.write_text(\"def test_file(): pass\", encoding=\"utf-8\")\n\n    # Just the package directory, the __init__.py module is filtered out.\n    result = pytester.runpytest(\"-v\", subdir)\n    result.stdout.fnmatch_lines(\n        [\n            \"sub/test_file.py::test_file PASSED*\",\n            \"*1 passed in*\",\n        ]\n    )\n\n    # But it's included if specified directly.\n    result = pytester.runpytest(\"-v\", init, p)\n    result.stdout.fnmatch_lines(\n        [\n            \"sub/__init__.py::test_init PASSED*\",\n            \"sub/test_file.py::test_file PASSED*\",\n            \"*2 passed in*\",\n        ]\n    )\n\n    # Or if the pattern allows it.\n    result = pytester.runpytest(\"-v\", \"-o\", \"python_files=*.py\", subdir)\n    result.stdout.fnmatch_lines(\n        [\n            \"sub/__init__.py::test_init PASSED*\",\n            \"sub/test_file.py::test_file PASSED*\",\n            \"*2 passed in*\",\n        ]\n    )\n\n\ndef test_collect_pkg_init_only(pytester: Pytester) -> None:\n    subdir = pytester.mkdir(\"sub\")\n    init = subdir.joinpath(\"__init__.py\")\n    init.write_text(\"def test_init(): pass\", encoding=\"utf-8\")\n\n    result = pytester.runpytest(subdir)\n    result.stdout.fnmatch_lines([\"*no tests ran in*\"])\n\n    result = pytester.runpytest(\"-v\", init)\n    result.stdout.fnmatch_lines([\"sub/__init__.py::test_init PASSED*\", \"*1 passed in*\"])\n\n    result = pytester.runpytest(\"-v\", \"-o\", \"python_files=*.py\", subdir)\n    result.stdout.fnmatch_lines([\"sub/__init__.py::test_init PASSED*\", \"*1 passed in*\"])\n\n\n@pytest.mark.parametrize(\"use_pkg\", (True, False))\ndef test_collect_sub_with_symlinks(use_pkg: bool, pytester: Pytester) -> None:\n    \"\"\"Collection works with symlinked files and broken symlinks\"\"\"\n    sub = pytester.mkdir(\"sub\")\n    if use_pkg:\n        sub.joinpath(\"__init__.py\").touch()\n    sub.joinpath(\"test_file.py\").write_text(\"def test_file(): pass\", encoding=\"utf-8\")\n\n    # Create a broken symlink.\n    symlink_or_skip(\"test_doesnotexist.py\", sub.joinpath(\"test_broken.py\"))\n\n    # Symlink that gets collected.\n    symlink_or_skip(\"test_file.py\", sub.joinpath(\"test_symlink.py\"))\n\n    result = pytester.runpytest(\"-v\", str(sub))\n    result.stdout.fnmatch_lines(\n        [\n            \"sub/test_file.py::test_file PASSED*\",\n            \"sub/test_symlink.py::test_file PASSED*\",\n            \"*2 passed in*\",\n        ]\n    )\n\n\ndef test_collector_respects_tbstyle(pytester: Pytester) -> None:\n    p1 = pytester.makepyfile(\"assert 0\")\n    result = pytester.runpytest(p1, \"--tb=native\")\n    assert result.ret == ExitCode.INTERRUPTED\n    result.stdout.fnmatch_lines(\n        [\n            \"*_ ERROR collecting test_collector_respects_tbstyle.py _*\",\n            \"Traceback (most recent call last):\",\n            '  File \"*/test_collector_respects_tbstyle.py\", line 1, in <module>',\n            \"    assert 0\",\n            \"AssertionError: assert 0\",\n            \"*! Interrupted: 1 error during collection !*\",\n            \"*= 1 error in *\",\n        ]\n    )\n\n\ndef test_does_not_eagerly_collect_packages(pytester: Pytester) -> None:\n    pytester.makepyfile(\"def test(): pass\")\n    pydir = pytester.mkpydir(\"foopkg\")\n    pydir.joinpath(\"__init__.py\").write_text(\"assert False\", encoding=\"utf-8\")\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.OK\n\n\ndef test_does_not_put_src_on_path(pytester: Pytester) -> None:\n    # `src` is not on sys.path so it should not be importable\n    ensure_file(pytester.path / \"src/nope/__init__.py\")\n    pytester.makepyfile(\n        \"import pytest\\n\"\n        \"def test():\\n\"\n        \"    with pytest.raises(ImportError):\\n\"\n        \"        import nope\\n\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.OK\n\n\ndef test_fscollector_from_parent(pytester: Pytester, request: FixtureRequest) -> None:\n    \"\"\"Ensure File.from_parent can forward custom arguments to the constructor.\n\n    Context: https://github.com/pytest-dev/pytest-cpp/pull/47\n    \"\"\"\n\n    class MyCollector(pytest.File):\n        def __init__(self, *k, x, **kw):\n            super().__init__(*k, **kw)\n            self.x = x\n\n        def collect(self):\n            raise NotImplementedError()\n\n    collector = MyCollector.from_parent(\n        parent=request.session, path=pytester.path / \"foo\", x=10\n    )\n    assert collector.x == 10\n\n\ndef test_class_from_parent(request: FixtureRequest) -> None:\n    \"\"\"Ensure Class.from_parent can forward custom arguments to the constructor.\"\"\"\n\n    class MyCollector(pytest.Class):\n        def __init__(self, name, parent, x):\n            super().__init__(name, parent)\n            self.x = x\n\n        @classmethod\n        def from_parent(cls, parent, *, name, x):  # type: ignore[override]\n            return super().from_parent(parent=parent, name=name, x=x)\n\n    collector = MyCollector.from_parent(parent=request.session, name=\"foo\", x=10)\n    assert collector.x == 10\n\n\nclass TestImportModeImportlib:\n    def test_collect_duplicate_names(self, pytester: Pytester) -> None:\n        \"\"\"--import-mode=importlib can import modules with same names that are not in packages.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"tests_a/test_foo.py\": \"def test_foo1(): pass\",\n                \"tests_b/test_foo.py\": \"def test_foo2(): pass\",\n            }\n        )\n        result = pytester.runpytest(\"-v\", \"--import-mode=importlib\")\n        result.stdout.fnmatch_lines(\n            [\n                \"tests_a/test_foo.py::test_foo1 *\",\n                \"tests_b/test_foo.py::test_foo2 *\",\n                \"* 2 passed in *\",\n            ]\n        )\n\n    def test_conftest(self, pytester: Pytester) -> None:\n        \"\"\"Directory containing conftest modules are not put in sys.path as a side-effect of\n        importing them.\"\"\"\n        tests_dir = pytester.path.joinpath(\"tests\")\n        pytester.makepyfile(\n            **{\n                \"tests/conftest.py\": \"\",\n                \"tests/test_foo.py\": f\"\"\"\n                import sys\n                def test_check():\n                    assert r\"{tests_dir}\" not in sys.path\n                \"\"\",\n            }\n        )\n        result = pytester.runpytest(\"-v\", \"--import-mode=importlib\")\n        result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n    def setup_conftest_and_foo(self, pytester: Pytester) -> None:\n        \"\"\"Setup a tests directory to be used to test if modules in that directory can be imported\n        due to side-effects of --import-mode or not.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"tests/conftest.py\": \"\",\n                \"tests/foo.py\": \"\"\"\n                    def foo(): return 42\n                \"\"\",\n                \"tests/test_foo.py\": \"\"\"\n                    def test_check():\n                        from foo import foo\n                        assert foo() == 42\n                \"\"\",\n            }\n        )\n\n    def test_modules_importable_as_side_effect(self, pytester: Pytester) -> None:\n        \"\"\"In import-modes `prepend` and `append`, we are able to import modules from directories\n        containing conftest.py files due to the side effect of changing sys.path.\"\"\"\n        self.setup_conftest_and_foo(pytester)\n        result = pytester.runpytest(\"-v\", \"--import-mode=prepend\")\n        result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n    def test_modules_not_importable_as_side_effect(self, pytester: Pytester) -> None:\n        \"\"\"In import-mode `importlib`, modules in directories containing conftest.py are not\n        importable, as don't change sys.path or sys.modules as side effect of importing\n        the conftest.py file.\n        \"\"\"\n        self.setup_conftest_and_foo(pytester)\n        result = pytester.runpytest(\"-v\", \"--import-mode=importlib\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*ModuleNotFoundError: No module named 'foo'\",\n                \"tests?test_foo.py:2: ModuleNotFoundError\",\n                \"* 1 failed in *\",\n            ]\n        )\n\n    def test_using_python_path(self, pytester: Pytester) -> None:\n        \"\"\"\n        Dummy modules created by insert_missing_modules should not get in\n        the way of modules that could be imported via python path (#9645).\n        \"\"\"\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            pythonpath = .\n            addopts = --import-mode importlib\n            \"\"\"\n        )\n        pytester.makepyfile(\n            **{\n                \"tests/__init__.py\": \"\",\n                \"tests/conftest.py\": \"\",\n                \"tests/subpath/__init__.py\": \"\",\n                \"tests/subpath/helper.py\": \"\",\n                \"tests/subpath/test_something.py\": \"\"\"\n                import tests.subpath.helper\n\n                def test_something():\n                    assert True\n                \"\"\",\n            }\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\"*1 passed in*\")\n\n\ndef test_does_not_crash_on_error_from_decorated_function(pytester: Pytester) -> None:\n    \"\"\"Regression test for an issue around bad exception formatting due to\n    assertion rewriting mangling lineno's (#4984).\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        @pytest.fixture\n        def a(): return 4\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    # Not INTERNAL_ERROR\n    assert result.ret == ExitCode.INTERRUPTED\n\n\ndef test_does_not_crash_on_recursive_symlink(pytester: Pytester) -> None:\n    \"\"\"Regression test for an issue around recursive symlinks (#7951).\"\"\"\n    symlink_or_skip(\"recursive\", pytester.path.joinpath(\"recursive\"))\n    pytester.makepyfile(\n        \"\"\"\n        def test_foo(): assert True\n        \"\"\"\n    )\n    result = pytester.runpytest()\n\n    assert result.ret == ExitCode.OK\n    assert result.parseoutcomes() == {\"passed\": 1}\n\n\n@pytest.mark.skipif(not sys.platform.startswith(\"win\"), reason=\"Windows only\")\ndef test_collect_short_file_windows(pytester: Pytester) -> None:\n    \"\"\"Reproducer for #11895: short paths not collected on Windows.\"\"\"\n    short_path = tempfile.mkdtemp()\n    if \"~\" not in short_path:  # pragma: no cover\n        if running_on_ci():\n            # On CI, we are expecting that under the current GitHub actions configuration,\n            # tempfile.mkdtemp() is producing short paths, so we want to fail to prevent\n            # this from silently changing without us noticing.\n            pytest.fail(\n                f\"tempfile.mkdtemp() failed to produce a short path on CI: {short_path}\"\n            )\n        else:\n            # We want to skip failing this test locally in this situation because\n            # depending on the local configuration tempfile.mkdtemp() might not produce a short path:\n            # For example, user might have configured %TEMP% exactly to avoid generating short paths.\n            pytest.skip(\n                f\"tempfile.mkdtemp() failed to produce a short path: {short_path}, skipping\"\n            )\n\n    test_file = Path(short_path).joinpath(\"test_collect_short_file_windows.py\")\n    test_file.write_text(\"def test(): pass\", encoding=\"UTF-8\")\n    result = pytester.runpytest(short_path)\n    assert result.parseoutcomes() == {\"passed\": 1}\n\n\ndef test_collect_short_file_windows_multi_level_symlink(\n    pytester: Pytester,\n    request: FixtureRequest,\n) -> None:\n    \"\"\"Regression test for multi-level Windows short-path comparison with\n    symlinks.\n\n    Previously, when matching collection arguments against collected nodes on\n    Windows, the short path fallback resolved symlinks. With a chain a -> b ->\n    target, comparing 'a' against 'b' would incorrectly succeed because both\n    resolved to 'target', which could cause incorrect matching or duplicate\n    collection.\n    \"\"\"\n    # Prepare target directory with a test file.\n    short_path = Path(tempfile.mkdtemp())\n    request.addfinalizer(lambda: shutil.rmtree(short_path, ignore_errors=True))\n    target = short_path / \"target\"\n    target.mkdir()\n    (target / \"test_chain.py\").write_text(\"def test_chain(): pass\", encoding=\"UTF-8\")\n\n    # Create multi-level symlink chain: a -> b -> target.\n    b = short_path / \"b\"\n    a = short_path / \"a\"\n    symlink_or_skip(target, b, target_is_directory=True)\n    symlink_or_skip(b, a, target_is_directory=True)\n\n    # Collect via the first symlink; should find exactly one test.\n    result = pytester.runpytest(a)\n    result.assert_outcomes(passed=1)\n\n    # Collect via the intermediate symlink; also exactly one test.\n    result = pytester.runpytest(b)\n    result.assert_outcomes(passed=1)\n\n\ndef test_pyargs_collection_tree(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n    \"\"\"When using `--pyargs`, the collection tree of a pyargs collection\n    argument should only include parents in the import path, not up to confcutdir.\n\n    Regression test for #11904.\n    \"\"\"\n    site_packages = pytester.path / \"venv/lib/site-packages\"\n    site_packages.mkdir(parents=True)\n    monkeypatch.syspath_prepend(site_packages)\n    pytester.makepyfile(\n        **{\n            \"venv/lib/site-packages/pkg/__init__.py\": \"\",\n            \"venv/lib/site-packages/pkg/sub/__init__.py\": \"\",\n            \"venv/lib/site-packages/pkg/sub/test_it.py\": \"def test(): pass\",\n        }\n    )\n\n    result = pytester.runpytest(\"--pyargs\", \"--collect-only\", \"pkg.sub.test_it\")\n    assert result.ret == ExitCode.OK\n    result.stdout.fnmatch_lines(\n        [\n            \"<Package venv/lib/site-packages/pkg>\",\n            \"  <Package sub>\",\n            \"    <Module test_it.py>\",\n            \"      <Function test>\",\n        ],\n        consecutive=True,\n    )\n\n    # Now with an unrelated rootdir with unrelated files.\n    monkeypatch.chdir(tempfile.gettempdir())\n\n    result = pytester.runpytest(\"--pyargs\", \"--collect-only\", \"pkg.sub.test_it\")\n    assert result.ret == ExitCode.OK\n    result.stdout.fnmatch_lines(\n        [\n            \"<Package *pkg>\",\n            \"  <Package sub>\",\n            \"    <Module test_it.py>\",\n            \"      <Function test>\",\n        ],\n        consecutive=True,\n    )\n\n\ndef test_do_not_collect_symlink_siblings(\n    pytester: Pytester, tmp_path: Path, request: pytest.FixtureRequest\n) -> None:\n    \"\"\"\n    Regression test for #12039: Do not collect from directories that are symlinks to other directories in the same path.\n\n    The check for short paths under Windows via os.path.samefile, introduced in #11936, also finds the symlinked\n    directory created by tmp_path/tmpdir.\n    \"\"\"\n    # Use tmp_path because it creates a symlink with the name \"current\" next to the directory it creates.\n    symlink_path = tmp_path.parent / (tmp_path.name[:-1] + \"current\")\n    if not symlink_path.is_symlink():  # pragma: no cover\n        pytest.skip(\"Symlinks not supported in this environment\")\n\n    # Create test file.\n    tmp_path.joinpath(\"test_foo.py\").write_text(\"def test(): pass\", encoding=\"UTF-8\")\n\n    # Ensure we collect it only once if we pass the tmp_path.\n    result = pytester.runpytest(tmp_path, \"-sv\")\n    result.assert_outcomes(passed=1)\n\n    # Ensure we collect it only once if we pass the symlinked directory.\n    result = pytester.runpytest(symlink_path, \"-sv\")\n    result.assert_outcomes(passed=1)\n\n\n@pytest.mark.parametrize(\n    \"exception_class, msg\",\n    [\n        (KeyboardInterrupt, \"*!!! KeyboardInterrupt !!!*\"),\n        (SystemExit, \"INTERNALERROR> SystemExit\"),\n    ],\n)\ndef test_respect_system_exceptions(\n    pytester: Pytester,\n    exception_class: type[BaseException],\n    msg: str,\n):\n    head = \"Before exception\"\n    tail = \"After exception\"\n    ensure_file(pytester.path / \"test_eggs.py\").write_text(\n        f\"print('{head}')\", encoding=\"UTF-8\"\n    )\n    ensure_file(pytester.path / \"test_ham.py\").write_text(\n        f\"raise {exception_class.__name__}()\", encoding=\"UTF-8\"\n    )\n    ensure_file(pytester.path / \"test_spam.py\").write_text(\n        f\"print('{tail}')\", encoding=\"UTF-8\"\n    )\n\n    result = pytester.runpytest_subprocess(\"-s\")\n    result.stdout.fnmatch_lines([f\"*{head}*\"])\n    result.stdout.fnmatch_lines([msg])\n    result.stdout.no_fnmatch_line(f\"*{tail}*\")\n\n\ndef test_yield_disallowed_in_tests(pytester: Pytester):\n    \"\"\"Ensure generator test functions with 'yield' fail collection (#12960).\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        def test_with_yield():\n            yield 1\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 2\n    result.stdout.fnmatch_lines(\n        [\"*'yield' keyword is allowed in fixtures, but not in tests (test_with_yield)*\"]\n    )\n    # Assert that no tests were collected\n    result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n\n\ndef test_annotations_deferred_future(pytester: Pytester):\n    \"\"\"Ensure stringified annotations don't raise any errors.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        from __future__ import annotations\n        import pytest\n\n        @pytest.fixture\n        def func() -> X: ...  # X is undefined\n\n        def test_func():\n            assert True\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\n@pytest.mark.skipif(\n    sys.version_info < (3, 14), reason=\"Annotations are only skipped on 3.14+\"\n)\ndef test_annotations_deferred_314(pytester: Pytester):\n    \"\"\"Ensure annotation eval is deferred.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def func() -> X: ...  # X is undefined\n\n        def test_func():\n            assert True\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\n@pytest.mark.parametrize(\"import_mode\", [\"prepend\", \"importlib\", \"append\"])\ndef test_namespace_packages(pytester: Pytester, import_mode: str):\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        consider_namespace_packages = true\n        pythonpath = .\n        python_files = *.py\n        addopts = --import-mode {import_mode}\n    \"\"\"\n    )\n    pytester.makepyfile(\n        **{\n            \"pkg/module1.py\": \"def test_module1(): pass\",\n            \"pkg/subpkg_namespace/module2.py\": \"def test_module1(): pass\",\n            \"pkg/subpkg_regular/__init__.py\": \"\",\n            \"pkg/subpkg_regular/module3\": \"def test_module3(): pass\",\n        }\n    )\n\n    # should collect when called with top-level package correctly\n    result = pytester.runpytest(\"--collect-only\", \"--pyargs\", \"pkg\")\n    result.stdout.fnmatch_lines(\n        [\n            \"collected 3 items\",\n            \"<Dir pkg>\",\n            \"  <Module module1.py>\",\n            \"    <Function test_module1>\",\n            \"  <Dir subpkg_namespace>\",\n            \"    <Module module2.py>\",\n            \"      <Function test_module1>\",\n            \"  <Package subpkg_regular>\",\n            \"    <Module module3.py>\",\n            \"      <Function test_module3>\",\n        ]\n    )\n\n    # should also work when called against a more specific subpackage/module\n    result = pytester.runpytest(\"--collect-only\", \"--pyargs\", \"pkg.subpkg_namespace\")\n    result.stdout.fnmatch_lines(\n        [\n            \"collected 1 item\",\n            \"<Dir pkg>\",\n            \"  <Dir subpkg_namespace>\",\n            \"    <Module module2.py>\",\n            \"      <Function test_module1>\",\n        ]\n    )\n\n    result = pytester.runpytest(\"--collect-only\", \"--pyargs\", \"pkg.subpkg_regular\")\n    result.stdout.fnmatch_lines(\n        [\n            \"collected 1 item\",\n            \"<Dir pkg>\",\n            \"  <Package subpkg_regular>\",\n            \"    <Module module3.py>\",\n            \"      <Function test_module3>\",\n        ]\n    )\n\n\nclass TestOverlappingCollectionArguments:\n    \"\"\"Test that overlapping collection arguments (e.g. `pytest a/b a\n    a/c::TestIt) are handled correctly (#12083).\"\"\"\n\n    @pytest.mark.parametrize(\"args\", [(\"a\", \"a/b\"), (\"a/b\", \"a\")])\n    def test_parent_child(self, pytester: Pytester, args: tuple[str, ...]) -> None:\n        \"\"\"Test that 'pytest a a/b' and `pytest a/b a` collects all tests from 'a'.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"a/test_a.py\": \"\"\"\n                    def test_a1(): pass\n                    def test_a2(): pass\n                \"\"\",\n                \"a/b/test_b.py\": \"\"\"\n                    def test_b1(): pass\n                    def test_b2(): pass\n                \"\"\",\n            }\n        )\n\n        result = pytester.runpytest(\"--collect-only\", *args)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Dir a>\",\n                \"    <Dir b>\",\n                \"      <Module test_b.py>\",\n                \"        <Function test_b1>\",\n                \"        <Function test_b2>\",\n                \"    <Module test_a.py>\",\n                \"      <Function test_a1>\",\n                \"      <Function test_a2>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    def test_multiple_nested_paths(self, pytester: Pytester) -> None:\n        \"\"\"Test that 'pytest a/b a a/b/c' collects all tests from 'a'.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"a/test_a.py\": \"\"\"\n                    def test_a(): pass\n                \"\"\",\n                \"a/b/test_b.py\": \"\"\"\n                    def test_b(): pass\n                \"\"\",\n                \"a/b/c/test_c.py\": \"\"\"\n                    def test_c(): pass\n                \"\"\",\n            }\n        )\n\n        result = pytester.runpytest(\"--collect-only\", \"a/b\", \"a\", \"a/b/c\")\n\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Dir a>\",\n                \"    <Dir b>\",\n                \"      <Dir c>\",\n                \"        <Module test_c.py>\",\n                \"          <Function test_c>\",\n                \"      <Module test_b.py>\",\n                \"        <Function test_b>\",\n                \"    <Module test_a.py>\",\n                \"      <Function test_a>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    def test_same_path_twice(self, pytester: Pytester) -> None:\n        \"\"\"Test that 'pytest a a' doesn't duplicate tests.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"a/test_a.py\": \"\"\"\n                    def test_a(): pass\n                \"\"\",\n            }\n        )\n\n        result = pytester.runpytest(\"--collect-only\", \"a\", \"a\")\n\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Dir a>\",\n                \"    <Module test_a.py>\",\n                \"      <Function test_a>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    def test_keep_duplicates_flag(self, pytester: Pytester) -> None:\n        \"\"\"Test that --keep-duplicates allows duplication.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"a/test_a.py\": \"\"\"\n                    def test_a(): pass\n                \"\"\",\n                \"a/b/test_b.py\": \"\"\"\n                    def test_b(): pass\n                \"\"\",\n            }\n        )\n\n        result = pytester.runpytest(\"--collect-only\", \"--keep-duplicates\", \"a\", \"a/b\")\n\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Dir a>\",\n                \"    <Dir b>\",\n                \"      <Module test_b.py>\",\n                \"        <Function test_b>\",\n                \"    <Module test_a.py>\",\n                \"      <Function test_a>\",\n                \"    <Dir b>\",\n                \"      <Module test_b.py>\",\n                \"        <Function test_b>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    def test_specific_file_then_parent_dir(self, pytester: Pytester) -> None:\n        \"\"\"Test that 'pytest a/test_a.py a' collects all tests from 'a'.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"a/test_a.py\": \"\"\"\n                    def test_a(): pass\n                \"\"\",\n                \"a/test_other.py\": \"\"\"\n                    def test_other(): pass\n                \"\"\",\n            }\n        )\n\n        result = pytester.runpytest(\"--collect-only\", \"a/test_a.py\", \"a\")\n\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Dir a>\",\n                \"    <Module test_a.py>\",\n                \"      <Function test_a>\",\n                \"    <Module test_other.py>\",\n                \"      <Function test_other>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    def test_package_scope_fixture_with_overlapping_paths(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Test that package-scoped fixtures work correctly with overlapping paths.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"pkg/__init__.py\": \"\",\n                \"pkg/test_pkg.py\": \"\"\"\n                    import pytest\n\n                    counter = {\"value\": 0}\n\n                    @pytest.fixture(scope=\"package\")\n                    def pkg_fixture():\n                        counter[\"value\"] += 1\n                        return counter[\"value\"]\n\n                    def test_pkg1(pkg_fixture):\n                        assert pkg_fixture == 1\n\n                    def test_pkg2(pkg_fixture):\n                        assert pkg_fixture == 1\n                \"\"\",\n                \"pkg/sub/__init__.py\": \"\",\n                \"pkg/sub/test_sub.py\": \"\"\"\n                    def test_sub(): pass\n                \"\"\",\n            }\n        )\n\n        # Package fixture should run only once even with overlapping paths.\n        result = pytester.runpytest(\"pkg\", \"pkg/sub\", \"pkg\", \"-v\")\n        result.assert_outcomes(passed=3)\n\n    def test_execution_order_preserved(self, pytester: Pytester) -> None:\n        \"\"\"Test that test execution order follows argument order.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"a/test_a.py\": \"\"\"\n                    def test_a(): pass\n                \"\"\",\n                \"b/test_b.py\": \"\"\"\n                    def test_b(): pass\n                \"\"\",\n            }\n        )\n\n        result = pytester.runpytest(\"--collect-only\", \"b\", \"a\", \"b/test_b.py::test_b\")\n\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Dir b>\",\n                \"    <Module test_b.py>\",\n                \"      <Function test_b>\",\n                \"  <Dir a>\",\n                \"    <Module test_a.py>\",\n                \"      <Function test_a>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    def test_overlapping_node_ids_class_and_method(self, pytester: Pytester) -> None:\n        \"\"\"Test that overlapping node IDs are handled correctly.\"\"\"\n        pytester.makepyfile(\n            test_nodeids=\"\"\"\n                class TestClass:\n                    def test_method1(self): pass\n                    def test_method2(self): pass\n                    def test_method3(self): pass\n\n                def test_function(): pass\n            \"\"\"\n        )\n\n        # Class then specific method.\n        result = pytester.runpytest(\n            \"--collect-only\",\n            \"test_nodeids.py::TestClass\",\n            \"test_nodeids.py::TestClass::test_method2\",\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Module test_nodeids.py>\",\n                \"    <Class TestClass>\",\n                \"      <Function test_method1>\",\n                \"      <Function test_method2>\",\n                \"      <Function test_method3>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        # Specific method then class.\n        result = pytester.runpytest(\n            \"--collect-only\",\n            \"test_nodeids.py::TestClass::test_method3\",\n            \"test_nodeids.py::TestClass\",\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Module test_nodeids.py>\",\n                \"    <Class TestClass>\",\n                \"      <Function test_method1>\",\n                \"      <Function test_method2>\",\n                \"      <Function test_method3>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    def test_overlapping_node_ids_file_and_class(self, pytester: Pytester) -> None:\n        \"\"\"Test that file-level and class-level selections work correctly.\"\"\"\n        pytester.makepyfile(\n            test_file=\"\"\"\n                class TestClass:\n                    def test_method(self): pass\n\n                class TestOther:\n                    def test_other(self): pass\n\n                def test_function(): pass\n            \"\"\"\n        )\n\n        # File then class.\n        result = pytester.runpytest(\n            \"--collect-only\", \"test_file.py\", \"test_file.py::TestClass\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Module test_file.py>\",\n                \"    <Class TestClass>\",\n                \"      <Function test_method>\",\n                \"    <Class TestOther>\",\n                \"      <Function test_other>\",\n                \"    <Function test_function>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        # Class then file.\n        result = pytester.runpytest(\n            \"--collect-only\", \"test_file.py::TestClass\", \"test_file.py\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Module test_file.py>\",\n                \"    <Class TestClass>\",\n                \"      <Function test_method>\",\n                \"    <Class TestOther>\",\n                \"      <Function test_other>\",\n                \"    <Function test_function>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    def test_same_node_id_twice(self, pytester: Pytester) -> None:\n        \"\"\"Test that the same node ID specified twice is collected only once.\"\"\"\n        pytester.makepyfile(\n            test_dup=\"\"\"\n                def test_one(): pass\n                def test_two(): pass\n            \"\"\"\n        )\n\n        result = pytester.runpytest(\n            \"--collect-only\",\n            \"test_dup.py::test_one\",\n            \"test_dup.py::test_one\",\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Module test_dup.py>\",\n                \"    <Function test_one>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    def test_overlapping_with_parametrization(self, pytester: Pytester) -> None:\n        \"\"\"Test overlapping with parametrized tests.\"\"\"\n        pytester.makepyfile(\n            test_param=\"\"\"\n                import pytest\n\n                @pytest.mark.parametrize(\"n\", [1, 2])\n                def test_param(n): pass\n\n                class TestClass:\n                    @pytest.mark.parametrize(\"x\", [\"a\", \"b\"])\n                    def test_method(self, x): pass\n            \"\"\"\n        )\n\n        result = pytester.runpytest(\n            \"--collect-only\",\n            \"test_param.py::test_param[2]\",\n            \"test_param.py::TestClass::test_method[a]\",\n            \"test_param.py\",\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Module test_param.py>\",\n                \"    <Function test_param[1]>\",\n                \"    <Function test_param[2]>\",\n                \"    <Class TestClass>\",\n                \"      <Function test_method[a]>\",\n                \"      <Function test_method[b]>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest(\n            \"--collect-only\",\n            \"test_param.py::test_param[2]\",\n            \"test_param.py::test_param\",\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Module test_param.py>\",\n                \"    <Function test_param[1]>\",\n                \"    <Function test_param[2]>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    @pytest.mark.parametrize(\"order\", [(\".\", \"a\"), (\"a\", \".\")])\n    def test_root_and_subdir(self, pytester: Pytester, order: tuple[str, ...]) -> None:\n        \"\"\"Test that '. a' and 'a .' both collect all tests.\"\"\"\n        pytester.makepyfile(\n            test_root=\"\"\"\n                def test_root(): pass\n            \"\"\",\n            **{\n                \"a/test_a.py\": \"\"\"\n                    def test_a(): pass\n                \"\"\",\n            },\n        )\n\n        result = pytester.runpytest(\"--collect-only\", *order)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Dir a>\",\n                \"    <Module test_a.py>\",\n                \"      <Function test_a>\",\n                \"  <Module test_root.py>\",\n                \"    <Function test_root>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n    def test_complex_combined_handling(self, pytester: Pytester) -> None:\n        \"\"\"Test some scenarios in a complex hierarchy.\"\"\"\n        pytester.makepyfile(\n            **{\n                \"top1/__init__.py\": \"\",\n                \"top1/test_1.py\": (\n                    \"\"\"\n                    def test_1(): pass\n\n                    class TestIt:\n                        def test_2(): pass\n\n                    def test_3(): pass\n                    \"\"\"\n                ),\n                \"top1/test_2.py\": (\n                    \"\"\"\n                    def test_1(): pass\n                    \"\"\"\n                ),\n                \"top2/__init__.py\": \"\",\n                \"top2/test_1.py\": (\n                    \"\"\"\n                    def test_1(): pass\n                    \"\"\"\n                ),\n            },\n        )\n\n        result = pytester.runpytest_inprocess(\"--collect-only\", \".\")\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top1>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                \"      <Class TestIt>\",\n                \"        <Function test_2>\",\n                \"      <Function test_3>\",\n                \"    <Module test_2.py>\",\n                \"      <Function test_1>\",\n                \"  <Package top2>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest_inprocess(\"--collect-only\", \"top2\", \"top1\")\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top2>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                \"  <Package top1>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                \"      <Class TestIt>\",\n                \"        <Function test_2>\",\n                \"      <Function test_3>\",\n                \"    <Module test_2.py>\",\n                \"      <Function test_1>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest_inprocess(\n            \"--collect-only\", \"top1\", \"top1/test_2.py\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top1>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                \"      <Class TestIt>\",\n                \"        <Function test_2>\",\n                \"      <Function test_3>\",\n                \"    <Module test_2.py>\",\n                \"      <Function test_1>\",\n                # NOTE: Also sensible arguably even without --keep-duplicates.\n                # \"    <Module test_2.py>\",\n                # \"      <Function test_1>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest_inprocess(\n            \"--collect-only\", \"top1/test_2.py\", \"top1\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top1>\",\n                # NOTE: Ideally test_2 would come before test_1 here.\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                \"      <Class TestIt>\",\n                \"        <Function test_2>\",\n                \"      <Function test_3>\",\n                \"    <Module test_2.py>\",\n                \"      <Function test_1>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest_inprocess(\n            \"--collect-only\", \"--keep-duplicates\", \"top1/test_2.py\", \"top1\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top1>\",\n                \"    <Module test_2.py>\",\n                \"      <Function test_1>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                \"      <Class TestIt>\",\n                \"        <Function test_2>\",\n                \"      <Function test_3>\",\n                \"    <Module test_2.py>\",\n                \"      <Function test_1>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest_inprocess(\n            \"--collect-only\", \"top1/test_2.py\", \"top1/test_2.py\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top1>\",\n                \"    <Module test_2.py>\",\n                \"      <Function test_1>\",\n                # NOTE: Also sensible arguably even without --keep-duplicates.\n                # \"    <Module test_2.py>\",\n                # \"      <Function test_1>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest_inprocess(\"--collect-only\", \"top2/\", \"top2/\")\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top2>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                # NOTE: Also sensible arguably even without --keep-duplicates.\n                # \"  <Package top2>\",\n                # \"    <Module test_1.py>\",\n                # \"      <Function test_1>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest_inprocess(\n            \"--collect-only\", \"top2/\", \"top2/\", \"top2/test_1.py\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top2>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                # NOTE: Also sensible arguably even without --keep-duplicates.\n                # \"  <Package top2>\",\n                # \"    <Module test_1.py>\",\n                # \"      <Function test_1>\",\n                # \"    <Module test_1.py>\",\n                # \"      <Function test_1>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest_inprocess(\n            \"--collect-only\", \"top1/test_1.py\", \"top1/test_1.py::test_3\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top1>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                \"      <Class TestIt>\",\n                \"        <Function test_2>\",\n                \"      <Function test_3>\",\n                # NOTE: Also sensible arguably even without --keep-duplicates.\n                # \"      <Function test_3>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest_inprocess(\n            \"--collect-only\", \"top1/test_1.py::test_3\", \"top1/test_1.py\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top1>\",\n                \"    <Module test_1.py>\",\n                # NOTE: Ideally test_3 would come before the others here.\n                \"      <Function test_1>\",\n                \"      <Class TestIt>\",\n                \"        <Function test_2>\",\n                \"      <Function test_3>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n        result = pytester.runpytest_inprocess(\n            \"--collect-only\",\n            \"--keep-duplicates\",\n            \"top1/test_1.py::test_3\",\n            \"top1/test_1.py\",\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir *>\",\n                \"  <Package top1>\",\n                # NOTE: That <Module test_1.py> is duplicated here is not great.\n                \"    <Module test_1.py>\",\n                \"      <Function test_3>\",\n                \"    <Module test_1.py>\",\n                \"      <Function test_1>\",\n                \"      <Class TestIt>\",\n                \"        <Function test_2>\",\n                \"      <Function test_3>\",\n                \"\",\n            ],\n            consecutive=True,\n        )\n\n\n@pytest.mark.parametrize(\n    [\"x_y\", \"expected_duplicates\"],\n    [\n        (\n            [(1, 1), (1, 1)],\n            [\"1-1\"],\n        ),\n        (\n            [(1, 1), (1, 2), (1, 1)],\n            [\"1-1\"],\n        ),\n        (\n            [(1, 1), (2, 2), (1, 1)],\n            [\"1-1\"],\n        ),\n        (\n            [(1, 1), (2, 2), (1, 2), (2, 1), (1, 1), (2, 1)],\n            [\"1-1\", \"2-1\"],\n        ),\n    ],\n)\n@pytest.mark.parametrize(\"option_name\", [\"strict_parametrization_ids\", \"strict\"])\ndef test_strict_parametrization_ids(\n    pytester: Pytester,\n    x_y: Sequence[tuple[int, int]],\n    expected_duplicates: Sequence[str],\n    option_name: str,\n) -> None:\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        {option_name} = true\n        \"\"\"\n    )\n    pytester.makepyfile(\n        f\"\"\"\n        import pytest\n\n        @pytest.mark.parametrize([\"x\", \"y\"], {x_y})\n        def test1(x, y):\n            pass\n        \"\"\"\n    )\n\n    result = pytester.runpytest()\n\n    assert result.ret == ExitCode.INTERRUPTED\n    expected_parametersets = \", \".join(str(list(p)) for p in x_y)\n    expected_ids = \", \".join(f\"{x}-{y}\" for x, y in x_y)\n    result.stdout.fnmatch_lines(\n        [\n            \"Duplicate parametrization IDs detected*\",\n            \"\",\n            \"Test name:      *::test1\",\n            \"Parameters:     x, y\",\n            f\"Parameter sets: {expected_parametersets}\",\n            f\"IDs:            {expected_ids}\",\n            f\"Duplicates:     {', '.join(expected_duplicates)}\",\n            \"\",\n            \"You can fix this problem using *\",\n        ]\n    )\n\n\ndef test_strict_parametrization_ids_with_hidden_param(pytester: Pytester) -> None:\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        strict_parametrization_ids = true\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.parametrize([\"x\"], [\"a\", pytest.param(\"a\", id=pytest.HIDDEN_PARAM), \"a\"])\n        def test1(x):\n            pass\n        \"\"\"\n    )\n\n    result = pytester.runpytest()\n\n    assert result.ret == ExitCode.INTERRUPTED\n    result.stdout.fnmatch_lines(\n        [\n            \"Duplicate parametrization IDs detected*\",\n            \"IDs:            a, <hidden>, a\",\n            \"Duplicates:     a\",\n        ]\n    )\n"
  },
  {
    "path": "testing/test_compat.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport enum\nfrom functools import cached_property\nfrom functools import partial\nfrom functools import wraps\nfrom typing import Literal\nimport warnings\n\nfrom _pytest.compat import assert_never\nfrom _pytest.compat import deprecated\nfrom _pytest.compat import get_real_func\nfrom _pytest.compat import safe_getattr\nfrom _pytest.compat import safe_isclass\nfrom _pytest.outcomes import OutcomeException\nimport pytest\n\n\ndef test_real_func_loop_limit() -> None:\n    class Evil:\n        def __init__(self):\n            self.left = 1000\n\n        def __repr__(self):\n            return f\"<Evil left={self.left}>\"\n\n        def __getattr__(self, attr):\n            if not self.left:\n                raise RuntimeError(\"it's over\")  # pragma: no cover\n            self.left -= 1\n            return self\n\n    evil = Evil()\n\n    with pytest.raises(\n        ValueError,\n        match=(\"wrapper loop when unwrapping <Evil left=998>\"),\n    ):\n        get_real_func(evil)\n\n\ndef test_get_real_func() -> None:\n    \"\"\"Check that get_real_func correctly unwraps decorators until reaching the real function\"\"\"\n\n    def decorator(f):\n        @wraps(f)\n        def inner():\n            pass  # pragma: no cover\n\n        return inner\n\n    def func():\n        pass  # pragma: no cover\n\n    wrapped_func = decorator(decorator(func))\n    assert get_real_func(wrapped_func) is func\n\n    wrapped_func2 = decorator(decorator(wrapped_func))\n    assert get_real_func(wrapped_func2) is func\n\n    # obtain the function up until the point a function was wrapped by pytest itself\n    @pytest.fixture\n    def wrapped_func3():\n        pass  # pragma: no cover\n\n    wrapped_func4 = decorator(wrapped_func3)\n    assert get_real_func(wrapped_func4) is wrapped_func3._get_wrapped_function()\n\n\ndef test_get_real_func_partial() -> None:\n    \"\"\"Test get_real_func handles partial instances correctly\"\"\"\n\n    def foo(x):\n        return x\n\n    assert get_real_func(foo) is foo\n    assert get_real_func(partial(foo)) is foo\n\n\nclass ErrorsHelper:\n    @property\n    def raise_baseexception(self):\n        raise BaseException(\"base exception should be raised\")\n\n    @property\n    def raise_exception(self):\n        raise Exception(\"exception should be caught\")\n\n    @property\n    def raise_fail_outcome(self):\n        pytest.fail(\"fail should be caught\")\n\n\ndef test_helper_failures() -> None:\n    helper = ErrorsHelper()\n    with pytest.raises(Exception):  # noqa: B017\n        _ = helper.raise_exception\n    with pytest.raises(OutcomeException):\n        _ = helper.raise_fail_outcome\n\n\ndef test_safe_getattr() -> None:\n    helper = ErrorsHelper()\n    assert safe_getattr(helper, \"raise_exception\", \"default\") == \"default\"\n    assert safe_getattr(helper, \"raise_fail_outcome\", \"default\") == \"default\"\n    with pytest.raises(BaseException):  # noqa: B017\n        assert safe_getattr(helper, \"raise_baseexception\", \"default\")\n\n\ndef test_safe_isclass() -> None:\n    assert safe_isclass(type) is True\n\n    class CrappyClass(Exception):\n        # Type ignored because it's bypassed intentionally.\n        @property  # type: ignore\n        def __class__(self):\n            assert False, \"Should be ignored\"\n\n    assert safe_isclass(CrappyClass()) is False\n\n\ndef test_cached_property() -> None:\n    ncalls = 0\n\n    class Class:\n        @cached_property\n        def prop(self) -> int:\n            nonlocal ncalls\n            ncalls += 1\n            return ncalls\n\n    c1 = Class()\n    assert ncalls == 0\n    assert c1.prop == 1\n    assert c1.prop == 1\n    c2 = Class()\n    assert ncalls == 1\n    assert c2.prop == 2\n    assert c1.prop == 1\n\n\ndef test_assert_never_union() -> None:\n    x: int | str = 10\n\n    if isinstance(x, int):\n        pass\n    else:\n        with pytest.raises(AssertionError):\n            assert_never(x)  # type: ignore[arg-type]\n\n    if isinstance(x, int):\n        pass\n    elif isinstance(x, str):\n        pass\n    else:\n        assert_never(x)\n\n\ndef test_assert_never_enum() -> None:\n    E = enum.Enum(\"E\", \"a b\")\n    x: E = E.a\n\n    if x is E.a:\n        pass\n    else:\n        with pytest.raises(AssertionError):\n            assert_never(x)  # type: ignore[arg-type]\n\n    if x is E.a:\n        pass\n    elif x is E.b:\n        pass\n    else:\n        assert_never(x)\n\n\ndef test_assert_never_literal() -> None:\n    x: Literal[\"a\", \"b\"] = \"a\"\n\n    if x == \"a\":\n        pass\n    else:\n        with pytest.raises(AssertionError):\n            assert_never(x)  # type: ignore[arg-type]\n\n    if x == \"a\":\n        pass\n    elif x == \"b\":\n        pass\n    else:\n        assert_never(x)\n\n\ndef test_deprecated() -> None:\n    # This test is mostly for coverage.\n\n    @deprecated(\"This is deprecated!\")\n    def old_way() -> str:\n        return \"human intelligence\"\n\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\", DeprecationWarning)\n        assert old_way() == \"human intelligence\"  # type: ignore[deprecated]\n"
  },
  {
    "path": "testing/test_config.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nimport dataclasses\nimport importlib.metadata\nimport os\nfrom pathlib import Path\nimport platform\nimport re\nimport sys\nimport textwrap\nfrom typing import Any\n\nimport _pytest._code\nfrom _pytest.config import _get_plugin_specs_as_list\nfrom _pytest.config import _iter_rewritable_modules\nfrom _pytest.config import _strtobool\nfrom _pytest.config import Config\nfrom _pytest.config import ConftestImportFailure\nfrom _pytest.config import ExitCode\nfrom _pytest.config import parse_warning_filter\nfrom _pytest.config.argparsing import get_ini_default_for_type\nfrom _pytest.config.argparsing import Parser\nfrom _pytest.config.exceptions import UsageError\nfrom _pytest.config.findpaths import ConfigValue\nfrom _pytest.config.findpaths import determine_setup\nfrom _pytest.config.findpaths import get_common_ancestor\nfrom _pytest.config.findpaths import locate_config\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pathlib import absolutepath\nfrom _pytest.pytester import Pytester\nfrom _pytest.warning_types import PytestDeprecationWarning\nimport pytest\n\n\nclass TestParseIni:\n    @pytest.mark.parametrize(\n        \"section, filename\", [(\"pytest\", \"pytest.ini\"), (\"tool:pytest\", \"setup.cfg\")]\n    )\n    def test_getcfg_and_config(\n        self,\n        pytester: Pytester,\n        tmp_path: Path,\n        section: str,\n        filename: str,\n        monkeypatch: MonkeyPatch,\n    ) -> None:\n        sub = tmp_path / \"sub\"\n        sub.mkdir()\n        monkeypatch.chdir(sub)\n        (tmp_path / filename).write_text(\n            textwrap.dedent(\n                f\"\"\"\\\n                [{section}]\n                name = value\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        _, _, cfg, _ = locate_config(Path.cwd(), [sub])\n        assert cfg[\"name\"] == ConfigValue(\"value\", origin=\"file\", mode=\"ini\")\n        config = pytester.parseconfigure(str(sub))\n        assert config._inicfg[\"name\"] == ConfigValue(\"value\", origin=\"file\", mode=\"ini\")\n\n    def test_setupcfg_uses_toolpytest_with_pytest(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\"def test(): pass\")\n        pytester.makefile(\n            \".cfg\",\n            setup=f\"\"\"\n                [tool:pytest]\n                testpaths={p1.name}\n                [pytest]\n                testpaths=ignored\n        \"\"\",\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"configfile: setup.cfg\", \"* 1 passed in *\"])\n        assert result.ret == 0\n\n    def test_append_parse_args(\n        self, pytester: Pytester, tmp_path: Path, monkeypatch: MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"PYTEST_ADDOPTS\", '--color no -rs --tb=\"short\"')\n        tmp_path.joinpath(\"pytest.ini\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                [pytest]\n                addopts = --verbose\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        config = pytester.parseconfig(tmp_path)\n        assert config.option.color == \"no\"\n        assert config.option.reportchars == \"s\"\n        assert config.option.tbstyle == \"short\"\n        assert config.option.verbose\n\n    @pytest.mark.parametrize(\"flag\", (\"-r\", \"--report-chars=\"))\n    @pytest.mark.parametrize(\"value\", (\"fE\", \"A\", \"fs\"))\n    def test_report_chars_option(\n        self,\n        pytester: Pytester,\n        tmp_path: Path,\n        monkeypatch: MonkeyPatch,\n        flag: str,\n        value: str,\n    ) -> None:\n        \"\"\"Test that -r/--report-chars is parsed correctly.\"\"\"\n        monkeypatch.setenv(\"PYTEST_ADDOPTS\", flag + value)\n        config = pytester.parseconfig(tmp_path)\n        assert config.option.reportchars == value\n\n    def test_tox_ini_wrong_version(self, pytester: Pytester) -> None:\n        pytester.makefile(\n            \".ini\",\n            tox=\"\"\"\n            [pytest]\n            minversion=999.0\n        \"\"\",\n        )\n        result = pytester.runpytest()\n        assert result.ret != 0\n        result.stderr.fnmatch_lines(\n            [\"*tox.ini: 'minversion' requires pytest-999.0, actual pytest-*\"]\n        )\n\n    @pytest.mark.parametrize(\n        \"section, name\",\n        [\n            (\"tool:pytest\", \"setup.cfg\"),\n            (\"pytest\", \"tox.ini\"),\n            (\"pytest\", \"pytest.ini\"),\n            (\"pytest\", \".pytest.ini\"),\n        ],\n    )\n    def test_ini_names(self, pytester: Pytester, name, section) -> None:\n        pytester.path.joinpath(name).write_text(\n            textwrap.dedent(\n                f\"\"\"\n            [{section}]\n            minversion = 3.36\n        \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        config = pytester.parseconfig()\n        assert config.getini(\"minversion\") == \"3.36\"\n\n    @pytest.mark.parametrize(\"name\", [\"pytest.toml\", \".pytest.toml\"])\n    def test_toml_config_names(self, pytester: Pytester, name: str) -> None:\n        pytester.path.joinpath(name).write_text(\n            textwrap.dedent(\n                \"\"\"\n            [pytest]\n            minversion = \"3.36\"\n        \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        config = pytester.parseconfig()\n        assert config.getini(\"minversion\") == \"3.36\"\n\n    def test_pyproject_toml(self, pytester: Pytester) -> None:\n        pyproject_toml = pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest.ini_options]\n            minversion = \"1.0\"\n        \"\"\"\n        )\n        config = pytester.parseconfig()\n        assert config.inipath == pyproject_toml\n        assert config.getini(\"minversion\") == \"1.0\"\n\n    def test_empty_pyproject_toml(self, pytester: Pytester) -> None:\n        \"\"\"An empty pyproject.toml is considered as config if no other option is found.\"\"\"\n        pyproject_toml = pytester.makepyprojecttoml(\"\")\n        config = pytester.parseconfig()\n        assert config.inipath == pyproject_toml\n\n    def test_empty_pyproject_toml_found_many(self, pytester: Pytester) -> None:\n        \"\"\"\n        In case we find multiple pyproject.toml files in our search, without a [tool.pytest]\n        table and without finding other candidates, the closest to where we started wins.\n        \"\"\"\n        pytester.makefile(\n            \".toml\",\n            **{\n                \"pyproject\": \"\",\n                \"foo/pyproject\": \"\",\n                \"foo/bar/pyproject\": \"\",\n            },\n        )\n        config = pytester.parseconfig(pytester.path / \"foo/bar\")\n        assert config.inipath == pytester.path / \"foo/bar/pyproject.toml\"\n\n    def test_pytest_toml(self, pytester: Pytester) -> None:\n        pytest_toml = pytester.path.joinpath(\"pytest.toml\")\n        pytest_toml = pytester.maketoml(\n            \"\"\"\n            [pytest]\n            minversion = \"1.0\"\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n        assert config.inipath == pytest_toml\n        assert config.getini(\"minversion\") == \"1.0\"\n\n    @pytest.mark.parametrize(\"name\", [\"pytest.toml\", \".pytest.toml\"])\n    def test_empty_pytest_toml(self, pytester: Pytester, name: str) -> None:\n        \"\"\"An empty pytest.toml is considered as config if no other option is found.\"\"\"\n        pytest_toml = pytester.path / name\n        pytest_toml.write_text(\"\", encoding=\"utf-8\")\n        config = pytester.parseconfig()\n        assert config.inipath == pytest_toml\n\n    def test_pytest_toml_trumps_pyproject_toml(self, pytester: Pytester) -> None:\n        \"\"\"A pytest.toml always takes precedence over a pyproject.toml file.\"\"\"\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest]\n            minversion = \"1.0\"\n            \"\"\"\n        )\n        pytest_toml = pytester.maketoml(\n            \"\"\"\n            [pytest]\n            minversion = \"2.0\"\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n        assert config.inipath == pytest_toml\n        assert config.getini(\"minversion\") == \"2.0\"\n\n    def test_pytest_toml_trumps_pytest_ini(self, pytester: Pytester) -> None:\n        \"\"\"A pytest.toml always takes precedence over a pytest.ini file.\"\"\"\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            minversion = 1.0\n            \"\"\",\n        )\n        pytest_toml = pytester.maketoml(\n            \"\"\"\n            [pytest]\n            minversion = \"2.0\"\n            \"\"\",\n        )\n        config = pytester.parseconfig()\n        assert config.inipath == pytest_toml\n        assert config.getini(\"minversion\") == \"2.0\"\n\n    def test_dot_pytest_toml_trumps_pytest_ini(self, pytester: Pytester) -> None:\n        \"\"\"A .pytest.toml always takes precedence over a pytest.ini file.\"\"\"\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            minversion = 1.0\n            \"\"\",\n        )\n        pytest_toml = pytester.maketoml(\n            \"\"\"\n            [pytest]\n            minversion = \"2.0\"\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n        assert config.inipath == pytest_toml\n        assert config.getini(\"minversion\") == \"2.0\"\n\n    def test_pytest_ini_trumps_pyproject_toml(self, pytester: Pytester) -> None:\n        \"\"\"A pytest.ini always take precedence over a pyproject.toml file.\"\"\"\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest]\n            minversion = \"1.0\"\n            \"\"\"\n        )\n        pytest_ini = pytester.makefile(\".ini\", pytest=\"\")\n        config = pytester.parseconfig()\n        assert config.inipath == pytest_ini\n\n    def test_toxini_before_lower_pytestini(self, pytester: Pytester) -> None:\n        sub = pytester.mkdir(\"sub\")\n        sub.joinpath(\"tox.ini\").write_text(\n            textwrap.dedent(\n                \"\"\"\n            [pytest]\n            minversion = 2.0\n        \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        pytester.path.joinpath(\"pytest.ini\").write_text(\n            textwrap.dedent(\n                \"\"\"\n            [pytest]\n            minversion = 1.5\n        \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        config = pytester.parseconfigure(sub)\n        assert config.getini(\"minversion\") == \"2.0\"\n\n    def test_ini_parse_error(self, pytester: Pytester) -> None:\n        pytester.path.joinpath(\"pytest.ini\").write_text(\n            \"addopts = -x\", encoding=\"utf-8\"\n        )\n        result = pytester.runpytest()\n        assert result.ret != 0\n        result.stderr.fnmatch_lines(\"ERROR: *pytest.ini:1: no section header defined\")\n\n    def test_toml_parse_error(self, pytester: Pytester) -> None:\n        pytester.makepyprojecttoml(\n            \"\"\"\n            \\\\\"\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.ret != 0\n        result.stderr.fnmatch_lines(\"ERROR: *pyproject.toml: Invalid statement*\")\n\n    def test_pytest_toml_parse_error(self, pytester: Pytester) -> None:\n        pytester.path.joinpath(\"pytest.toml\").write_text(\n            \"\"\"\n            \\\\\"\n            \"\"\",\n            encoding=\"utf-8\",\n        )\n        result = pytester.runpytest()\n        assert result.ret != 0\n        result.stderr.fnmatch_lines(\"ERROR: *pytest.toml: Invalid statement*\")\n\n    def test_confcutdir_default_without_configfile(self, pytester: Pytester) -> None:\n        # If --confcutdir is not specified, and there is no configfile, default\n        # to the rootpath.\n        sub = pytester.mkdir(\"sub\")\n        os.chdir(sub)\n        config = pytester.parseconfigure()\n        assert config.pluginmanager._confcutdir == sub\n\n    def test_confcutdir_default_with_configfile(self, pytester: Pytester) -> None:\n        # If --confcutdir is not specified, and there is a configfile, default\n        # to the configfile's directory.\n        pytester.makeini(\"[pytest]\")\n        sub = pytester.mkdir(\"sub\")\n        os.chdir(sub)\n        config = pytester.parseconfigure()\n        assert config.pluginmanager._confcutdir == pytester.path\n\n    @pytest.mark.xfail(reason=\"probably not needed\")\n    def test_confcutdir(self, pytester: Pytester) -> None:\n        sub = pytester.mkdir(\"sub\")\n        os.chdir(sub)\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            addopts = --qwe\n        \"\"\"\n        )\n        result = pytester.inline_run(\"--confcutdir=.\")\n        assert result.ret == 0\n\n    @pytest.mark.parametrize(\n        \"ini_file_text, invalid_keys, warning_output, exception_text\",\n        [\n            pytest.param(\n                \"\"\"\n                [pytest]\n                unknown_ini = value1\n                another_unknown_ini = value2\n                \"\"\",\n                [\"unknown_ini\", \"another_unknown_ini\"],\n                [\n                    \"=*= warnings summary =*=\",\n                    \"*PytestConfigWarning:*Unknown config option: another_unknown_ini\",\n                    \"*PytestConfigWarning:*Unknown config option: unknown_ini\",\n                ],\n                \"Unknown config option: another_unknown_ini\",\n                id=\"2-unknowns\",\n            ),\n            pytest.param(\n                \"\"\"\n                [pytest]\n                unknown_ini = value1\n                minversion = 5.0.0\n                \"\"\",\n                [\"unknown_ini\"],\n                [\n                    \"=*= warnings summary =*=\",\n                    \"*PytestConfigWarning:*Unknown config option: unknown_ini\",\n                ],\n                \"Unknown config option: unknown_ini\",\n                id=\"1-unknown\",\n            ),\n            pytest.param(\n                \"\"\"\n                [some_other_header]\n                unknown_ini = value1\n                [pytest]\n                minversion = 5.0.0\n                \"\"\",\n                [],\n                [],\n                \"\",\n                id=\"unknown-in-other-header\",\n            ),\n            pytest.param(\n                \"\"\"\n                [pytest]\n                minversion = 5.0.0\n                \"\"\",\n                [],\n                [],\n                \"\",\n                id=\"no-unknowns\",\n            ),\n            pytest.param(\n                \"\"\"\n                [pytest]\n                conftest_ini_key = 1\n                \"\"\",\n                [],\n                [],\n                \"\",\n                id=\"1-known\",\n            ),\n        ],\n    )\n    @pytest.mark.filterwarnings(\"default\")\n    def test_invalid_config_options(\n        self,\n        pytester: Pytester,\n        ini_file_text,\n        invalid_keys,\n        warning_output,\n        exception_text,\n    ) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"conftest_ini_key\", \"\")\n            \"\"\"\n        )\n        pytester.makepyfile(\"def test(): pass\")\n        pytester.makeini(ini_file_text)\n\n        config = pytester.parseconfig()\n        assert sorted(config._get_unknown_ini_keys()) == sorted(invalid_keys)\n\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(warning_output)\n\n        result = pytester.runpytest(\"--strict-config\")\n        if exception_text:\n            result.stderr.fnmatch_lines(\"ERROR: \" + exception_text)\n            assert result.ret == pytest.ExitCode.USAGE_ERROR\n        else:\n            result.stderr.no_fnmatch_line(exception_text)\n            assert result.ret == pytest.ExitCode.OK\n\n    @pytest.mark.filterwarnings(\"default\")\n    def test_silence_unknown_key_warning(self, pytester: Pytester) -> None:\n        \"\"\"Unknown config key warnings can be silenced using filterwarnings (#7620)\"\"\"\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            filterwarnings =\n                ignore:Unknown config option:pytest.PytestConfigWarning\n            foobar=1\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.no_fnmatch_line(\"*PytestConfigWarning*\")\n\n    @pytest.mark.parametrize(\"option_name\", [\"strict_config\", \"strict\"])\n    def test_strict_config_ini_option(\n        self, pytester: Pytester, option_name: str\n    ) -> None:\n        \"\"\"Test that strict_config and strict ini options enable strict config checking.\"\"\"\n        pytester.makeini(\n            f\"\"\"\n            [pytest]\n            unknown_option = 1\n            {option_name} = True\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stderr.fnmatch_lines(\"ERROR: Unknown config option: unknown_option\")\n        assert result.ret == pytest.ExitCode.USAGE_ERROR\n\n    @pytest.mark.filterwarnings(\"default::pytest.PytestConfigWarning\")\n    def test_disable_warnings_plugin_disables_config_warnings(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Disabling 'warnings' plugin also disables config time warnings\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            def pytest_configure(config):\n                config.issue_config_time_warning(\n                    pytest.PytestConfigWarning(\"custom config warning\"),\n                    stacklevel=2,\n                )\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-pno:warnings\")\n        result.stdout.no_fnmatch_line(\"*PytestConfigWarning*\")\n\n    @pytest.mark.parametrize(\n        \"ini_file_text, plugin_version, exception_text\",\n        [\n            pytest.param(\n                \"\"\"\n                [pytest]\n                required_plugins = a z\n                \"\"\",\n                \"1.5\",\n                \"Missing required plugins: a, z\",\n                id=\"2-missing\",\n            ),\n            pytest.param(\n                \"\"\"\n                [pytest]\n                required_plugins = a z myplugin\n                \"\"\",\n                \"1.5\",\n                \"Missing required plugins: a, z\",\n                id=\"2-missing-1-ok\",\n            ),\n            pytest.param(\n                \"\"\"\n                [pytest]\n                required_plugins = myplugin\n                \"\"\",\n                \"1.5\",\n                None,\n                id=\"1-ok\",\n            ),\n            pytest.param(\n                \"\"\"\n                [pytest]\n                required_plugins = myplugin==1.5\n                \"\"\",\n                \"1.5\",\n                None,\n                id=\"1-ok-pin-exact\",\n            ),\n            pytest.param(\n                \"\"\"\n                [pytest]\n                required_plugins = myplugin>1.0,<2.0\n                \"\"\",\n                \"1.5\",\n                None,\n                id=\"1-ok-pin-loose\",\n            ),\n            pytest.param(\n                \"\"\"\n                [pytest]\n                required_plugins = myplugin\n                \"\"\",\n                \"1.5a1\",\n                None,\n                id=\"1-ok-prerelease\",\n            ),\n            pytest.param(\n                \"\"\"\n                [pytest]\n                required_plugins = myplugin==1.6\n                \"\"\",\n                \"1.5\",\n                \"Missing required plugins: myplugin==1.6\",\n                id=\"missing-version\",\n            ),\n            pytest.param(\n                \"\"\"\n                [pytest]\n                required_plugins = myplugin==1.6 other==1.0\n                \"\"\",\n                \"1.5\",\n                \"Missing required plugins: myplugin==1.6, other==1.0\",\n                id=\"missing-versions\",\n            ),\n            pytest.param(\n                \"\"\"\n                [some_other_header]\n                required_plugins = won't be triggered\n                [pytest]\n                \"\"\",\n                \"1.5\",\n                None,\n                id=\"invalid-header\",\n            ),\n        ],\n    )\n    def test_missing_required_plugins(\n        self,\n        pytester: Pytester,\n        monkeypatch: MonkeyPatch,\n        ini_file_text: str,\n        plugin_version: str,\n        exception_text: str,\n    ) -> None:\n        \"\"\"Check 'required_plugins' option with various settings.\n\n        This test installs a mock \"myplugin-1.5\" which is used in the parametrized test cases.\n        \"\"\"\n\n        @dataclasses.dataclass\n        class DummyEntryPoint:\n            name: str\n            module: str\n            group: str = \"pytest11\"\n\n            def load(self):\n                return importlib.import_module(self.module)\n\n        entry_points = [\n            DummyEntryPoint(\"myplugin1\", \"myplugin1_module\"),\n        ]\n\n        @dataclasses.dataclass\n        class DummyDist:\n            entry_points: object\n            files: object = ()\n            version: str = plugin_version\n\n            @property\n            def metadata(self):\n                return {\"name\": \"myplugin\"}\n\n        def my_dists():\n            return [DummyDist(entry_points)]\n\n        pytester.makepyfile(myplugin1_module=\"# my plugin module\")\n        pytester.syspathinsert()\n\n        monkeypatch.setattr(importlib.metadata, \"distributions\", my_dists)\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n        pytester.makeini(ini_file_text)\n\n        if exception_text:\n            with pytest.raises(pytest.UsageError, match=exception_text):\n                pytester.parseconfig()\n        else:\n            pytester.parseconfig()\n\n    def test_early_config_cmdline(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"early_config contains options registered by third-party plugins.\n\n        This is a regression involving pytest-cov (and possibly others) introduced in #7700.\n        \"\"\"\n        pytester.makepyfile(\n            myplugin=\"\"\"\n            def pytest_addoption(parser):\n                parser.addoption('--foo', default=None, dest='foo')\n\n            def pytest_load_initial_conftests(early_config, parser, args):\n                assert early_config.known_args_namespace.foo == \"1\"\n            \"\"\"\n        )\n        monkeypatch.setenv(\"PYTEST_PLUGINS\", \"myplugin\")\n        pytester.syspathinsert()\n        result = pytester.runpytest(\"--foo=1\")\n        result.stdout.fnmatch_lines(\"* no tests ran in *\")\n\n    def test_args_source_args(self, pytester: Pytester):\n        config = pytester.parseconfig(\"--\", \"test_filename.py\")\n        assert config.args_source == Config.ArgsSource.ARGS\n\n    def test_args_source_invocation_dir(self, pytester: Pytester):\n        config = pytester.parseconfig()\n        assert config.args_source == Config.ArgsSource.INVOCATION_DIR\n\n    def test_args_source_testpaths(self, pytester: Pytester):\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            testpaths=*\n        \"\"\"\n        )\n        config = pytester.parseconfig()\n        assert config.args_source == Config.ArgsSource.TESTPATHS\n\n\nclass TestConfigCmdlineParsing:\n    def test_parsing_again_fails(self, pytester: Pytester) -> None:\n        config = pytester.parseconfig()\n        pytest.raises(AssertionError, lambda: config.parse([]))\n\n    def test_explicitly_specified_config_file_is_loaded(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"custom\", \"\")\n        \"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            custom = 0\n        \"\"\"\n        )\n        pytester.makefile(\n            \".ini\",\n            custom=\"\"\"\n            [pytest]\n            custom = 1\n        \"\"\",\n        )\n        config = pytester.parseconfig(\"-c\", \"custom.ini\")\n        assert config.getini(\"custom\") == \"1\"\n        config = pytester.parseconfig(\"--config-file\", \"custom.ini\")\n        assert config.getini(\"custom\") == \"1\"\n\n        pytester.makefile(\n            \".cfg\",\n            custom_tool_pytest_section=\"\"\"\n            [tool:pytest]\n            custom = 1\n        \"\"\",\n        )\n        config = pytester.parseconfig(\"-c\", \"custom_tool_pytest_section.cfg\")\n        assert config.getini(\"custom\") == \"1\"\n        config = pytester.parseconfig(\"--config-file\", \"custom_tool_pytest_section.cfg\")\n        assert config.getini(\"custom\") == \"1\"\n\n        pytester.makefile(\n            \".toml\",\n            custom=\"\"\"\n                [tool.pytest.ini_options]\n                custom = 1\n                value = [\n                ]  # this is here on purpose, as it makes this an invalid '.ini' file\n            \"\"\",\n        )\n        config = pytester.parseconfig(\"-c\", \"custom.toml\")\n        assert config.getini(\"custom\") == \"1\"\n        config = pytester.parseconfig(\"--config-file\", \"custom.toml\")\n        assert config.getini(\"custom\") == \"1\"\n\n    def test_absolute_win32_path(self, pytester: Pytester) -> None:\n        temp_ini_file = pytester.makeini(\"[pytest]\")\n        from os.path import normpath\n\n        temp_ini_file_norm = normpath(str(temp_ini_file))\n        ret = pytest.main([\"-c\", temp_ini_file_norm])\n        assert ret == ExitCode.NO_TESTS_COLLECTED\n        ret = pytest.main([\"--config-file\", temp_ini_file_norm])\n        assert ret == ExitCode.NO_TESTS_COLLECTED\n\n\nclass TestConfigAPI:\n    def test_config_trace(self, pytester: Pytester) -> None:\n        config = pytester.parseconfig()\n        values: list[str] = []\n        config.trace.root.setwriter(values.append)\n        config.trace(\"hello\")\n        assert len(values) == 1\n        assert values[0] == \"hello [config]\\n\"\n\n    def test_config_getoption_declared_option_name(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addoption(\"--hello\", \"-X\", dest=\"hello\")\n        \"\"\"\n        )\n        config = pytester.parseconfig(\"--hello=this\")\n        for x in (\"hello\", \"--hello\", \"-X\"):\n            assert config.getoption(x) == \"this\"\n        pytest.raises(ValueError, config.getoption, \"qweqwe\")\n\n        config_novalue = pytester.parseconfig()\n        assert config_novalue.getoption(\"hello\") is None\n        assert config_novalue.getoption(\"hello\", default=1) is None\n        assert config_novalue.getoption(\"hello\", default=1, skip=True) == 1\n\n    def test_config_getoption_undeclared_option_name(self, pytester: Pytester) -> None:\n        config = pytester.parseconfig()\n        with pytest.raises(ValueError):\n            config.getoption(\"x\")\n        assert config.getoption(\"x\", default=1) == 1\n        assert config.getoption(\"x\", default=1, skip=True) == 1\n\n    def test_config_getoption_unicode(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addoption('--hello', type=str)\n        \"\"\"\n        )\n        config = pytester.parseconfig(\"--hello=this\")\n        assert config.getoption(\"hello\") == \"this\"\n\n    def test_config_getvalueorskip(self, pytester: Pytester) -> None:\n        config = pytester.parseconfig()\n        pytest.raises(pytest.skip.Exception, config.getvalueorskip, \"hello\")\n        verbose = config.getvalueorskip(\"verbose\")\n        assert verbose == config.option.verbose\n\n    def test_config_getvalueorskip_None(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addoption(\"--hello\")\n        \"\"\"\n        )\n        config = pytester.parseconfig()\n        with pytest.raises(pytest.skip.Exception):\n            config.getvalueorskip(\"hello\")\n\n    def test_getconftest_pathlist(self, pytester: Pytester, tmp_path: Path) -> None:\n        somepath = tmp_path.joinpath(\"x\", \"y\", \"z\")\n        p = tmp_path.joinpath(\"conftest.py\")\n        p.write_text(f\"mylist = {['.', str(somepath)]}\", encoding=\"utf-8\")\n        config = pytester.parseconfigure(p)\n        assert config._getconftest_pathlist(\"notexist\", path=tmp_path) is None\n        assert config._getconftest_pathlist(\"mylist\", path=tmp_path) == [\n            tmp_path,\n            somepath,\n        ]\n\n    @pytest.mark.parametrize(\"maybe_type\", [\"not passed\", \"None\", '\"string\"'])\n    def test_addini(self, pytester: Pytester, maybe_type: str) -> None:\n        if maybe_type == \"not passed\":\n            type_string = \"\"\n        else:\n            type_string = f\", {maybe_type}\"\n\n        pytester.makeconftest(\n            f\"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"myname\", \"my new ini value\"{type_string})\n        \"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            myname=hello\n        \"\"\"\n        )\n        config = pytester.parseconfig()\n        val = config.getini(\"myname\")\n        assert val == \"hello\"\n        pytest.raises(ValueError, config.getini, \"other\")\n\n    @pytest.mark.parametrize(\"config_type\", [\"ini\", \"pyproject\"])\n    def test_addini_paths(self, pytester: Pytester, config_type: str) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"paths\", \"my new ini value\", type=\"paths\")\n                parser.addini(\"abc\", \"abc value\")\n        \"\"\"\n        )\n        if config_type == \"ini\":\n            inipath = pytester.makeini(\n                \"\"\"\n                [pytest]\n                paths=hello world/sub.py\n            \"\"\"\n            )\n        elif config_type == \"pyproject\":\n            inipath = pytester.makepyprojecttoml(\n                \"\"\"\n                [tool.pytest.ini_options]\n                paths=[\"hello\", \"world/sub.py\"]\n            \"\"\"\n            )\n        config = pytester.parseconfig()\n        values = config.getini(\"paths\")\n        assert len(values) == 2\n        assert values[0] == inipath.parent.joinpath(\"hello\")\n        assert values[1] == inipath.parent.joinpath(\"world/sub.py\")\n        pytest.raises(ValueError, config.getini, \"other\")\n\n    def make_conftest_for_args(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"args\", \"new args\", type=\"args\")\n                parser.addini(\"a2\", \"\", \"args\", default=\"1 2 3\".split())\n        \"\"\"\n        )\n\n    def test_addini_args_ini_files(self, pytester: Pytester) -> None:\n        self.make_conftest_for_args(pytester)\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            args=123 \"123 hello\" \"this\"\n            \"\"\"\n        )\n        self.check_config_args(pytester)\n\n    def test_addini_args_pyproject_toml(self, pytester: Pytester) -> None:\n        self.make_conftest_for_args(pytester)\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest.ini_options]\n            args = [\"123\", \"123 hello\", \"this\"]\n            \"\"\"\n        )\n        self.check_config_args(pytester)\n\n    def check_config_args(self, pytester: Pytester) -> None:\n        config = pytester.parseconfig()\n        values = config.getini(\"args\")\n        assert values == [\"123\", \"123 hello\", \"this\"]\n        values = config.getini(\"a2\")\n        assert values == list(\"123\")\n\n    def make_conftest_for_linelist(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"xy\", \"\", type=\"linelist\")\n                parser.addini(\"a2\", \"\", \"linelist\")\n        \"\"\"\n        )\n\n    def test_addini_linelist_ini_files(self, pytester: Pytester) -> None:\n        self.make_conftest_for_linelist(pytester)\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            xy= 123 345\n                second line\n        \"\"\"\n        )\n        self.check_config_linelist(pytester)\n\n    def test_addini_linelist_pprojecttoml(self, pytester: Pytester) -> None:\n        self.make_conftest_for_linelist(pytester)\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest.ini_options]\n            xy = [\"123 345\", \"second line\"]\n        \"\"\"\n        )\n        self.check_config_linelist(pytester)\n\n    def check_config_linelist(self, pytester: Pytester) -> None:\n        config = pytester.parseconfig()\n        values = config.getini(\"xy\")\n        assert len(values) == 2\n        assert values == [\"123 345\", \"second line\"]\n        values = config.getini(\"a2\")\n        assert values == []\n\n    @pytest.mark.parametrize(\n        \"str_val, bool_val\", [(\"True\", True), (\"no\", False), (\"no-ini\", True)]\n    )\n    def test_addini_bool(\n        self, pytester: Pytester, str_val: str, bool_val: bool\n    ) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"strip\", \"\", type=\"bool\", default=True)\n        \"\"\"\n        )\n        if str_val != \"no-ini\":\n            pytester.makeini(\n                f\"\"\"\n                [pytest]\n                strip={str_val}\n            \"\"\"\n            )\n        config = pytester.parseconfig()\n        assert config.getini(\"strip\") is bool_val\n\n    @pytest.mark.parametrize(\"str_val, int_val\", [(\"10\", 10), (\"no-ini\", 2)])\n    def test_addini_int(self, pytester: Pytester, str_val: str, int_val: bool) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"ini_param\", \"\", type=\"int\", default=2)\n        \"\"\"\n        )\n        if str_val != \"no-ini\":\n            pytester.makeini(\n                f\"\"\"\n                [pytest]\n                ini_param={str_val}\n            \"\"\"\n            )\n        config = pytester.parseconfig()\n        assert config.getini(\"ini_param\") == int_val\n\n    def test_addini_int_invalid(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"ini_param\", \"\", type=\"int\", default=2)\n        \"\"\"\n        )\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest.ini_options]\n            ini_param=[\"foo\"]\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n        with pytest.raises(\n            TypeError, match=\"Expected an int string for option ini_param\"\n        ):\n            _ = config.getini(\"ini_param\")\n\n    @pytest.mark.parametrize(\"str_val, float_val\", [(\"10.5\", 10.5), (\"no-ini\", 2.2)])\n    def test_addini_float(\n        self, pytester: Pytester, str_val: str, float_val: bool\n    ) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"ini_param\", \"\", type=\"float\", default=2.2)\n        \"\"\"\n        )\n        if str_val != \"no-ini\":\n            pytester.makeini(\n                f\"\"\"\n                [pytest]\n                ini_param={str_val}\n            \"\"\"\n            )\n        config = pytester.parseconfig()\n        assert config.getini(\"ini_param\") == float_val\n\n    def test_addini_float_invalid(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"ini_param\", \"\", type=\"float\", default=2.2)\n        \"\"\"\n        )\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest.ini_options]\n            ini_param=[\"foo\"]\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n        with pytest.raises(\n            TypeError, match=\"Expected a float string for option ini_param\"\n        ):\n            _ = config.getini(\"ini_param\")\n\n    def test_addinivalue_line_existing(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"xy\", \"\", type=\"linelist\")\n        \"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            xy= 123\n        \"\"\"\n        )\n        config = pytester.parseconfig()\n        values = config.getini(\"xy\")\n        assert len(values) == 1\n        assert values == [\"123\"]\n        config.addinivalue_line(\"xy\", \"456\")\n        values = config.getini(\"xy\")\n        assert len(values) == 2\n        assert values == [\"123\", \"456\"]\n\n    def test_addinivalue_line_new(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"xy\", \"\", type=\"linelist\")\n        \"\"\"\n        )\n        config = pytester.parseconfig()\n        assert not config.getini(\"xy\")\n        config.addinivalue_line(\"xy\", \"456\")\n        values = config.getini(\"xy\")\n        assert len(values) == 1\n        assert values == [\"456\"]\n        config.addinivalue_line(\"xy\", \"123\")\n        values = config.getini(\"xy\")\n        assert len(values) == 2\n        assert values == [\"456\", \"123\"]\n\n    def test_addini_default_values(self, pytester: Pytester) -> None:\n        \"\"\"Tests the default values for configuration based on\n        config type\n        \"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"linelist1\", \"\", type=\"linelist\")\n                parser.addini(\"paths1\", \"\", type=\"paths\")\n                parser.addini(\"pathlist1\", \"\", type=\"pathlist\")\n                parser.addini(\"args1\", \"\", type=\"args\")\n                parser.addini(\"bool1\", \"\", type=\"bool\")\n                parser.addini(\"string1\", \"\", type=\"string\")\n                parser.addini(\"none_1\", \"\", type=\"linelist\", default=None)\n                parser.addini(\"none_2\", \"\", default=None)\n                parser.addini(\"no_type\", \"\")\n        \"\"\"\n        )\n\n        config = pytester.parseconfig()\n        # default for linelist, paths, pathlist and args is []\n        value = config.getini(\"linelist1\")\n        assert value == []\n        value = config.getini(\"paths1\")\n        assert value == []\n        value = config.getini(\"pathlist1\")\n        assert value == []\n        value = config.getini(\"args1\")\n        assert value == []\n        # default for bool is False\n        value = config.getini(\"bool1\")\n        assert value is False\n        # default for string is \"\"\n        value = config.getini(\"string1\")\n        assert value == \"\"\n        # should return None if None is explicitly set as default value\n        # irrespective of the type argument\n        value = config.getini(\"none_1\")\n        assert value is None\n        value = config.getini(\"none_2\")\n        assert value is None\n        # in case no type is provided and no default set\n        # treat it as string and default value will be \"\"\n        value = config.getini(\"no_type\")\n        assert value == \"\"\n\n    def test_addini_with_aliases(self, pytester: Pytester) -> None:\n        \"\"\"Test that ini options can have aliases.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"new_name\", \"my option\", aliases=[\"old_name\"])\n            \"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            old_name = hello\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n        # Should be able to access via canonical name.\n        assert config.getini(\"new_name\") == \"hello\"\n        # Should also be able to access via alias.\n        assert config.getini(\"old_name\") == \"hello\"\n\n    def test_addini_aliases_with_canonical_in_file(self, pytester: Pytester) -> None:\n        \"\"\"Test that canonical name takes precedence over alias in configuration file.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"new_name\", \"my option\", aliases=[\"old_name\"])\n            \"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            old_name = from_alias\n            new_name = from_canonical\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n        # Canonical name should take precedence.\n        assert config.getini(\"new_name\") == \"from_canonical\"\n        assert config.getini(\"old_name\") == \"from_canonical\"\n\n    def test_addini_aliases_multiple(self, pytester: Pytester) -> None:\n        \"\"\"Test that ini option can have multiple aliases.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"current_name\", \"my option\", aliases=[\"old_name\", \"legacy_name\"])\n            \"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            old_name = value1\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n        assert config.getini(\"current_name\") == \"value1\"\n        assert config.getini(\"old_name\") == \"value1\"\n        assert config.getini(\"legacy_name\") == \"value1\"\n\n    def test_addini_aliases_with_override_of_old(self, pytester: Pytester) -> None:\n        \"\"\"Test that aliases work with --override-ini -- ini sets old.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"new_name\", \"my option\", aliases=[\"old_name\"])\n            \"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            old_name = from_file\n            \"\"\"\n        )\n        # Override using alias.\n        config = pytester.parseconfig(\"-o\", \"old_name=overridden\")\n        assert config.getini(\"new_name\") == \"overridden\"\n        assert config.getini(\"old_name\") == \"overridden\"\n\n        # Override using canonical name.\n        config = pytester.parseconfig(\"-o\", \"new_name=overridden2\")\n        assert config.getini(\"new_name\") == \"overridden2\"\n\n    def test_addini_aliases_with_override_of_new(self, pytester: Pytester) -> None:\n        \"\"\"Test that aliases work with --override-ini -- ini sets new.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"new_name\", \"my option\", aliases=[\"old_name\"])\n            \"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            new_name = from_file\n            \"\"\"\n        )\n        # Override using alias.\n        config = pytester.parseconfig(\"-o\", \"old_name=overridden\")\n        assert config.getini(\"new_name\") == \"overridden\"\n        assert config.getini(\"old_name\") == \"overridden\"\n\n        # Override using canonical name.\n        config = pytester.parseconfig(\"-o\", \"new_name=overridden2\")\n        assert config.getini(\"new_name\") == \"overridden2\"\n\n    def test_addini_aliases_with_types(self, pytester: Pytester) -> None:\n        \"\"\"Test that aliases work with different types.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"mylist\", \"list option\", type=\"linelist\", aliases=[\"oldlist\"])\n                parser.addini(\"mybool\", \"bool option\", type=\"bool\", aliases=[\"oldbool\"])\n            \"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            oldlist = line1\n                line2\n            oldbool = true\n        \"\"\"\n        )\n        config = pytester.parseconfig()\n        assert config.getini(\"mylist\") == [\"line1\", \"line2\"]\n        assert config.getini(\"oldlist\") == [\"line1\", \"line2\"]\n        assert config.getini(\"mybool\") is True\n        assert config.getini(\"oldbool\") is True\n\n    def test_addini_aliases_conflict_error(self, pytester: Pytester) -> None:\n        \"\"\"Test that registering an alias that conflicts with an existing option raises an error.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"existing\", \"first option\")\n\n                try:\n                    parser.addini(\"new_option\", \"second option\", aliases=[\"existing\"])\n                except ValueError as e:\n                    assert \"alias 'existing' conflicts with existing configuration option\" in str(e)\n                else:\n                    assert False, \"Should have raised ValueError\"\n            \"\"\"\n        )\n        pytester.parseconfig()\n\n    def test_addini_aliases_duplicate_error(self, pytester: Pytester) -> None:\n        \"\"\"Test that registering the same alias twice raises an error.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"option1\", \"first option\", aliases=[\"shared_alias\"])\n                try:\n                    parser.addini(\"option2\", \"second option\", aliases=[\"shared_alias\"])\n                    raise AssertionError(\"Should have raised ValueError\")\n                except ValueError as e:\n                    assert \"'shared_alias' is already an alias of 'option1'\" in str(e)\n            \"\"\"\n        )\n        pytester.parseconfig()\n\n    @pytest.mark.parametrize(\n        \"type, expected\",\n        [\n            pytest.param(None, \"\", id=\"None\"),\n            pytest.param(\"string\", \"\", id=\"string\"),\n            pytest.param(\"paths\", [], id=\"paths\"),\n            pytest.param(\"pathlist\", [], id=\"pathlist\"),\n            pytest.param(\"args\", [], id=\"args\"),\n            pytest.param(\"linelist\", [], id=\"linelist\"),\n            pytest.param(\"bool\", False, id=\"bool\"),\n        ],\n    )\n    def test_get_ini_default_for_type(self, type: Any, expected: Any) -> None:\n        assert get_ini_default_for_type(type) == expected\n\n    def test_confcutdir_check_isdir(self, pytester: Pytester) -> None:\n        \"\"\"Give an error if --confcutdir is not a valid directory (#2078)\"\"\"\n        exp_match = r\"^--confcutdir must be a directory, given: \"\n        with pytest.raises(pytest.UsageError, match=exp_match):\n            pytester.parseconfig(\"--confcutdir\", pytester.path.joinpath(\"file\"))\n        with pytest.raises(pytest.UsageError, match=exp_match):\n            pytester.parseconfig(\"--confcutdir\", pytester.path.joinpath(\"nonexistent\"))\n\n        p = pytester.mkdir(\"dir\")\n        config = pytester.parseconfig(\"--confcutdir\", p)\n        assert config.getoption(\"confcutdir\") == str(p)\n\n    @pytest.mark.parametrize(\n        \"names, expected\",\n        [\n            # dist-info based distributions root are files as will be put in PYTHONPATH\n            ([\"bar.py\"], [\"bar\"]),\n            ([\"foo/bar.py\"], [\"bar\"]),\n            ([\"foo/bar.pyc\"], []),\n            ([\"foo/__init__.py\"], [\"foo\"]),\n            ([\"bar/__init__.py\", \"xz.py\"], [\"bar\", \"xz\"]),\n            ([\"setup.py\"], []),\n            # egg based distributions root contain the files from the dist root\n            ([\"src/bar/__init__.py\"], [\"bar\"]),\n            ([\"src/bar/__init__.py\", \"setup.py\"], [\"bar\"]),\n            ([\"source/python/bar/__init__.py\", \"setup.py\"], [\"bar\"]),\n            # editable installation finder modules\n            ([\"__editable___xyz_finder.py\"], []),\n            ([\"bar/__init__.py\", \"__editable___xyz_finder.py\"], [\"bar\"]),\n        ],\n    )\n    def test_iter_rewritable_modules(self, names, expected) -> None:\n        assert list(_iter_rewritable_modules(names)) == expected\n\n    def test_add_cleanup(self, pytester: Pytester) -> None:\n        config = Config.fromdictargs({}, [])\n        config._do_configure()\n        report = []\n\n        class MyError(BaseException):\n            pass\n\n        @config.add_cleanup\n        def cleanup_last():\n            report.append(\"cleanup_last\")\n\n        @config.add_cleanup\n        def raise_2():\n            report.append(\"raise_2\")\n            raise MyError(\"raise_2\")\n\n        @config.add_cleanup\n        def raise_1():\n            report.append(\"raise_1\")\n            raise MyError(\"raise_1\")\n\n        @config.add_cleanup\n        def cleanup_first():\n            report.append(\"cleanup_first\")\n\n        with pytest.raises(MyError, match=r\"raise_2\"):\n            config._ensure_unconfigure()\n\n        assert report == [\"cleanup_first\", \"raise_1\", \"raise_2\", \"cleanup_last\"]\n\n\nclass TestConfigFromdictargs:\n    def test_basic_behavior(self, _sys_snapshot) -> None:\n        option_dict = {\"verbose\": 444, \"foo\": \"bar\", \"capture\": \"no\"}\n        args = [\"a\", \"b\"]\n\n        config = Config.fromdictargs(option_dict, args)\n        with pytest.raises(AssertionError):\n            config.parse([\"should refuse to parse again\"])\n        assert config.option.verbose == 444\n        assert config.option.foo == \"bar\"\n        assert config.option.capture == \"no\"\n        assert config.args == args\n\n    def test_invocation_params_args(self, _sys_snapshot) -> None:\n        \"\"\"Show that fromdictargs can handle args in their \"orig\" format\"\"\"\n        option_dict: dict[str, object] = {}\n        args = [\"-vvvv\", \"-s\", \"a\", \"b\"]\n\n        config = Config.fromdictargs(option_dict, args)\n        assert config.args == [\"a\", \"b\"]\n        assert config.invocation_params.args == tuple(args)\n        assert config.option.verbose == 4\n        assert config.option.capture == \"no\"\n\n    def test_inifilename(self, tmp_path: Path) -> None:\n        d1 = tmp_path.joinpath(\"foo\")\n        d1.mkdir()\n        p1 = d1.joinpath(\"bar.ini\")\n        p1.touch()\n        p1.write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                [pytest]\n                name = value\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        inifilename = \"../../foo/bar.ini\"\n        option_dict = {\"inifilename\": inifilename, \"capture\": \"no\"}\n\n        cwd = tmp_path.joinpath(\"a/b\")\n        cwd.mkdir(parents=True)\n        p2 = cwd.joinpath(\"pytest.ini\")\n        p2.touch()\n        p2.write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                [pytest]\n                name = wrong-value\n                should_not_be_set = true\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        with MonkeyPatch.context() as mp:\n            mp.chdir(cwd)\n            config = Config.fromdictargs(option_dict, [])\n            inipath = absolutepath(inifilename)\n\n        assert config.args == [str(cwd)]\n        assert config.option.inifilename == inifilename\n        assert config.option.capture == \"no\"\n\n        # this indicates this is the file used for getting configuration values\n        assert config.inipath == inipath\n        assert config._inicfg.get(\"name\") == ConfigValue(\n            \"value\", origin=\"file\", mode=\"ini\"\n        )\n        assert config._inicfg.get(\"should_not_be_set\") is None\n\n\ndef test_options_on_small_file_do_not_blow_up(pytester: Pytester) -> None:\n    def runfiletest(opts: Sequence[str]) -> None:\n        reprec = pytester.inline_run(*opts)\n        passed, skipped, failed = reprec.countoutcomes()\n        assert failed == 2\n        assert skipped == passed == 0\n\n    path = str(\n        pytester.makepyfile(\n            \"\"\"\n        def test_f1(): assert 0\n        def test_f2(): assert 0\n    \"\"\"\n        )\n    )\n\n    runfiletest([path])\n    runfiletest([\"-l\", path])\n    runfiletest([\"-s\", path])\n    runfiletest([\"--tb=no\", path])\n    runfiletest([\"--tb=short\", path])\n    runfiletest([\"--tb=long\", path])\n    runfiletest([\"--fulltrace\", path])\n    runfiletest([\"--traceconfig\", path])\n    runfiletest([\"-v\", path])\n    runfiletest([\"-v\", \"-v\", path])\n\n\ndef test_preparse_ordering_with_setuptools(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n    class EntryPoint:\n        name = \"mytestplugin\"\n        group = \"pytest11\"\n\n        def load(self):\n            class PseudoPlugin:\n                x = 42\n\n            return PseudoPlugin()\n\n    class Dist:\n        files = ()\n        metadata = {\"name\": \"foo\"}\n        entry_points = (EntryPoint(),)\n\n    def my_dists():\n        return (Dist,)\n\n    monkeypatch.setattr(importlib.metadata, \"distributions\", my_dists)\n    pytester.makeconftest(\n        \"\"\"\n        pytest_plugins = \"mytestplugin\",\n    \"\"\"\n    )\n    monkeypatch.setenv(\"PYTEST_PLUGINS\", \"mytestplugin\")\n    config = pytester.parseconfig()\n    plugin = config.pluginmanager.getplugin(\"mytestplugin\")\n    assert plugin.x == 42\n\n\ndef test_setuptools_importerror_issue1479(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n    class DummyEntryPoint:\n        name = \"mytestplugin\"\n        group = \"pytest11\"\n\n        def load(self):\n            raise ImportError(\"Don't hide me!\")\n\n    class Distribution:\n        version = \"1.0\"\n        files = (\"foo.txt\",)\n        metadata = {\"name\": \"foo\"}\n        entry_points = (DummyEntryPoint(),)\n\n    def distributions():\n        return (Distribution(),)\n\n    monkeypatch.setattr(importlib.metadata, \"distributions\", distributions)\n    with pytest.raises(ImportError):\n        pytester.parseconfig()\n\n\ndef test_importlib_metadata_broken_distribution(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    \"\"\"Integration test for broken distributions with 'files' metadata being None (#5389)\"\"\"\n    monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n    class DummyEntryPoint:\n        name = \"mytestplugin\"\n        group = \"pytest11\"\n\n        def load(self):\n            return object()\n\n    class Distribution:\n        version = \"1.0\"\n        files = None\n        metadata = {\"name\": \"foo\"}\n        entry_points = (DummyEntryPoint(),)\n\n    def distributions():\n        return (Distribution(),)\n\n    monkeypatch.setattr(importlib.metadata, \"distributions\", distributions)\n    pytester.parseconfig()\n\n\n@pytest.mark.parametrize(\"block_it\", [True, False])\ndef test_plugin_preparse_prevents_setuptools_loading(\n    pytester: Pytester, monkeypatch: MonkeyPatch, block_it: bool\n) -> None:\n    monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n\n    plugin_module_placeholder = object()\n\n    class DummyEntryPoint:\n        name = \"mytestplugin\"\n        group = \"pytest11\"\n\n        def load(self):\n            return plugin_module_placeholder\n\n    class Distribution:\n        version = \"1.0\"\n        files = (\"foo.txt\",)\n        metadata = {\"name\": \"foo\"}\n        entry_points = (DummyEntryPoint(),)\n\n    def distributions():\n        return (Distribution(),)\n\n    monkeypatch.setattr(importlib.metadata, \"distributions\", distributions)\n    args = (\"-p\", \"no:mytestplugin\") if block_it else ()\n    config = pytester.parseconfig(*args)\n    config.pluginmanager.import_plugin(\"mytestplugin\")\n    if block_it:\n        assert \"mytestplugin\" not in sys.modules\n        assert config.pluginmanager.get_plugin(\"mytestplugin\") is None\n    else:\n        assert (\n            config.pluginmanager.get_plugin(\"mytestplugin\") is plugin_module_placeholder\n        )\n\n\n@pytest.mark.parametrize(\"disable_plugin_method\", [\"env_var\", \"flag\", \"\"])\n@pytest.mark.parametrize(\"enable_plugin_method\", [\"env_var\", \"flag\", \"\"])\ndef test_disable_plugin_autoload(\n    pytester: Pytester,\n    monkeypatch: MonkeyPatch,\n    enable_plugin_method: str,\n    disable_plugin_method: str,\n) -> None:\n    class DummyEntryPoint:\n        project_name = name = \"mytestplugin\"\n        group = \"pytest11\"\n        version = \"1.0\"\n\n        def load(self):\n            return sys.modules[self.name]\n\n    class Distribution:\n        metadata = {\"name\": \"foo\"}\n        entry_points = (DummyEntryPoint(),)\n        files = ()\n\n    class PseudoPlugin:\n        x = 42\n\n        attrs_used = []\n\n        def __getattr__(self, name):\n            assert name in (\"__loader__\", \"__spec__\")\n            self.attrs_used.append(name)\n            return object()\n\n    def distributions():\n        return (Distribution(),)\n\n    parse_args: list[str] = []\n\n    if disable_plugin_method == \"env_var\":\n        monkeypatch.setenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", \"1\")\n    elif disable_plugin_method == \"flag\":\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\")\n        parse_args.append(\"--disable-plugin-autoload\")\n    else:\n        assert disable_plugin_method == \"\"\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\")\n\n    if enable_plugin_method == \"env_var\":\n        monkeypatch.setenv(\"PYTEST_PLUGINS\", \"mytestplugin\")\n    elif enable_plugin_method == \"flag\":\n        parse_args.extend([\"-p\", \"mytestplugin\"])\n    else:\n        assert enable_plugin_method == \"\"\n\n    monkeypatch.setattr(importlib.metadata, \"distributions\", distributions)\n    monkeypatch.setitem(sys.modules, \"mytestplugin\", PseudoPlugin())\n    config = pytester.parseconfig(*parse_args)\n\n    has_loaded = config.pluginmanager.get_plugin(\"mytestplugin\") is not None\n    # it should load if it's enabled, or we haven't disabled autoloading\n    assert has_loaded == (bool(enable_plugin_method) or not disable_plugin_method)\n\n    # The reason for the discrepancy between 'has_loaded' and __loader__ being accessed\n    # appears to be the monkeypatching of importlib.metadata.distributions; where\n    # files being empty means that _mark_plugins_for_rewrite doesn't find the plugin.\n    # But enable_method==flag ends up in mark_rewrite being called and __loader__\n    # being accessed.\n    assert (\"__loader__\" in PseudoPlugin.attrs_used) == (\n        has_loaded\n        and not (enable_plugin_method in (\"env_var\", \"\") and not disable_plugin_method)\n    )\n\n    # __spec__ is accessed in AssertionRewritingHook.exec_module, which would be\n    # eventually called if we did a full pytest run; but it's only accessed with\n    # enable_plugin_method==\"env_var\" because that will early-load it.\n    # Except when autoloads aren't disabled, in which case PytestPluginManager.import_plugin\n    # bails out before importing it.. because it knows it'll be loaded later?\n    # The above seems a bit weird, but I *think* it's true.\n    if platform.python_implementation() != \"PyPy\":\n        assert (\"__spec__\" in PseudoPlugin.attrs_used) == bool(\n            enable_plugin_method == \"env_var\" and disable_plugin_method\n        )\n    # __spec__ is present when testing locally on pypy, but not in CI ????\n\n\ndef test_plugin_loading_order(pytester: Pytester) -> None:\n    \"\"\"Test order of plugin loading with `-p`.\"\"\"\n    p1 = pytester.makepyfile(\n        \"\"\"\n        def test_terminal_plugin(request):\n            import myplugin\n            assert myplugin.terminal_plugin == [False, True]\n        \"\"\",\n        myplugin=\"\"\"\n            terminal_plugin = []\n\n            def pytest_configure(config):\n                terminal_plugin.append(bool(config.pluginmanager.get_plugin(\"terminalreporter\")))\n\n            def pytest_sessionstart(session):\n                config = session.config\n                terminal_plugin.append(bool(config.pluginmanager.get_plugin(\"terminalreporter\")))\n            \"\"\",\n    )\n    pytester.syspathinsert()\n    result = pytester.runpytest(\"-p\", \"myplugin\", str(p1))\n    assert result.ret == 0\n\n\ndef test_invalid_options_show_extra_information(pytester: Pytester) -> None:\n    \"\"\"Display extra information when pytest exits due to unrecognized\n    options in the command-line.\"\"\"\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        addopts = --invalid-option\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stderr.fnmatch_lines(\n        [\n            \"*error: unrecognized arguments: --invalid-option*\",\n            \"*  inifile: {}*\".format(pytester.path.joinpath(\"tox.ini\")),\n            f\"*  rootdir: {pytester.path}*\",\n        ]\n    )\n\n\n@pytest.mark.parametrize(\n    \"args\",\n    [\n        [\"dir1\", \"dir2\", \"-v\"],\n        [\"dir1\", \"-v\", \"dir2\"],\n        [\"dir2\", \"-v\", \"dir1\"],\n        [\"-v\", \"dir2\", \"dir1\"],\n    ],\n)\ndef test_consider_args_after_options_for_rootdir(\n    pytester: Pytester, args: list[str]\n) -> None:\n    \"\"\"\n    Consider all arguments in the command-line for rootdir\n    discovery, even if they happen to occur after an option. #949\n    \"\"\"\n    # replace \"dir1\" and \"dir2\" from \"args\" into their real directory\n    root = pytester.mkdir(\"myroot\")\n    d1 = root.joinpath(\"dir1\")\n    d1.mkdir()\n    d2 = root.joinpath(\"dir2\")\n    d2.mkdir()\n    for i, arg in enumerate(args):\n        if arg == \"dir1\":\n            args[i] = str(d1)\n        elif arg == \"dir2\":\n            args[i] = str(d2)\n    with MonkeyPatch.context() as mp:\n        mp.chdir(root)\n        result = pytester.runpytest(*args)\n    result.stdout.fnmatch_lines([\"*rootdir: *myroot\"])\n\n\ndef test_toolongargs_issue224(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"-m\", \"hello\" * 500)\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_config_in_subdirectory_colon_command_line_issue2148(\n    pytester: Pytester,\n) -> None:\n    conftest_source = \"\"\"\n        def pytest_addoption(parser):\n            parser.addini('foo', 'foo')\n    \"\"\"\n\n    pytester.makefile(\n        \".ini\",\n        **{\"pytest\": \"[pytest]\\nfoo = root\", \"subdir/pytest\": \"[pytest]\\nfoo = subdir\"},\n    )\n\n    pytester.makepyfile(\n        **{\n            \"conftest\": conftest_source,\n            \"subdir/conftest\": conftest_source,\n            \"subdir/test_foo\": \"\"\"\\\n            def test_foo(pytestconfig):\n                assert pytestconfig.getini('foo') == 'subdir'\n            \"\"\",\n        }\n    )\n\n    result = pytester.runpytest(\"subdir/test_foo.py::test_foo\")\n    assert result.ret == 0\n\n\ndef test_notify_exception(pytester: Pytester, capfd) -> None:\n    config = pytester.parseconfig()\n    with pytest.raises(ValueError) as excinfo:\n        raise ValueError(1)\n    config.notify_exception(excinfo, config.option)\n    _, err = capfd.readouterr()\n    assert \"ValueError\" in err\n\n    class A:\n        def pytest_internalerror(self):\n            return True\n\n    config.pluginmanager.register(A())\n    config.notify_exception(excinfo, config.option)\n    _, err = capfd.readouterr()\n    assert not err\n\n    config = pytester.parseconfig(\"-p\", \"no:terminal\")\n    with pytest.raises(ValueError) as excinfo:\n        raise ValueError(1)\n    config.notify_exception(excinfo, config.option)\n    _, err = capfd.readouterr()\n    assert \"ValueError\" in err\n\n\ndef test_no_terminal_discovery_error(pytester: Pytester) -> None:\n    pytester.makepyfile(\"raise TypeError('oops!')\")\n    result = pytester.runpytest(\"-p\", \"no:terminal\", \"--collect-only\")\n    assert result.ret == ExitCode.INTERRUPTED\n\n\ndef test_load_initial_conftest_last_ordering(_config_for_test):\n    pm = _config_for_test.pluginmanager\n\n    class My:\n        def pytest_load_initial_conftests(self):\n            pass\n\n    m = My()\n    pm.register(m)\n    hc = pm.hook.pytest_load_initial_conftests\n    hookimpls = [\n        (\n            hookimpl.function.__module__,\n            \"wrapper\" if (hookimpl.wrapper or hookimpl.hookwrapper) else \"nonwrapper\",\n        )\n        for hookimpl in hc.get_hookimpls()\n    ]\n    assert hookimpls == [\n        (\"_pytest.config\", \"nonwrapper\"),\n        (m.__module__, \"nonwrapper\"),\n        (\"_pytest.legacypath\", \"nonwrapper\"),\n        (\"_pytest.capture\", \"wrapper\"),\n        (\"_pytest.warnings\", \"wrapper\"),\n    ]\n\n\ndef test_get_plugin_specs_as_list() -> None:\n    def exp_match(val: object) -> str:\n        return (\n            f\"Plugins may be specified as a sequence or a ','-separated string \"\n            f\"of plugin names. Got: {re.escape(repr(val))}\"\n        )\n\n    with pytest.raises(pytest.UsageError, match=exp_match({\"foo\"})):\n        _get_plugin_specs_as_list({\"foo\"})  # type: ignore[arg-type]\n    with pytest.raises(pytest.UsageError, match=exp_match({})):\n        _get_plugin_specs_as_list(dict())  # type: ignore[arg-type]\n\n    assert _get_plugin_specs_as_list(None) == []\n    assert _get_plugin_specs_as_list(\"\") == []\n    assert _get_plugin_specs_as_list(\"foo\") == [\"foo\"]\n    assert _get_plugin_specs_as_list(\"foo,bar\") == [\"foo\", \"bar\"]\n    assert _get_plugin_specs_as_list([\"foo\", \"bar\"]) == [\"foo\", \"bar\"]\n    assert _get_plugin_specs_as_list((\"foo\", \"bar\")) == [\"foo\", \"bar\"]\n\n\ndef test_collect_pytest_prefix_bug_integration(pytester: Pytester) -> None:\n    \"\"\"Integration test for issue #3775\"\"\"\n    p = pytester.copy_example(\"config/collect_pytest_prefix\")\n    result = pytester.runpytest(p)\n    result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n\ndef test_collect_pytest_prefix_bug(pytestconfig):\n    \"\"\"Ensure we collect only actual functions from conftest files (#3775)\"\"\"\n\n    class Dummy:\n        class pytest_something:\n            pass\n\n    pm = pytestconfig.pluginmanager\n    assert pm.parse_hookimpl_opts(Dummy(), \"pytest_something\") is None\n\n\nclass TestRootdir:\n    def test_simple_noini(self, tmp_path: Path, monkeypatch: MonkeyPatch) -> None:\n        assert get_common_ancestor(Path.cwd(), [tmp_path]) == tmp_path\n        a = tmp_path / \"a\"\n        a.mkdir()\n        assert get_common_ancestor(Path.cwd(), [a, tmp_path]) == tmp_path\n        assert get_common_ancestor(Path.cwd(), [tmp_path, a]) == tmp_path\n        monkeypatch.chdir(tmp_path)\n        assert get_common_ancestor(Path.cwd(), []) == tmp_path\n        no_path = tmp_path / \"does-not-exist\"\n        assert get_common_ancestor(Path.cwd(), [no_path]) == tmp_path\n        assert get_common_ancestor(Path.cwd(), [no_path / \"a\"]) == tmp_path\n\n    @pytest.mark.parametrize(\n        \"name, contents\",\n        [\n            pytest.param(\"pytest.ini\", \"[pytest]\\nx=10\", id=\"pytest.ini\"),\n            pytest.param(\n                \"pyproject.toml\", \"[tool.pytest.ini_options]\\nx=10\", id=\"pyproject.toml\"\n            ),\n            pytest.param(\"tox.ini\", \"[pytest]\\nx=10\", id=\"tox.ini\"),\n            pytest.param(\"setup.cfg\", \"[tool:pytest]\\nx=10\", id=\"setup.cfg\"),\n        ],\n    )\n    def test_with_ini(self, tmp_path: Path, name: str, contents: str) -> None:\n        inipath = tmp_path / name\n        inipath.write_text(contents, encoding=\"utf-8\")\n\n        a = tmp_path / \"a\"\n        a.mkdir()\n        b = a / \"b\"\n        b.mkdir()\n        for args in ([str(tmp_path)], [str(a)], [str(b)]):\n            rootpath, parsed_inipath, *_ = determine_setup(\n                inifile=None,\n                override_ini=None,\n                args=args,\n                rootdir_cmd_arg=None,\n                invocation_dir=Path.cwd(),\n            )\n            assert rootpath == tmp_path\n            assert parsed_inipath == inipath\n        rootpath, parsed_inipath, ini_config, _ = determine_setup(\n            inifile=None,\n            override_ini=None,\n            args=[str(b), str(a)],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == tmp_path\n        assert parsed_inipath == inipath\n        assert ini_config[\"x\"] == ConfigValue(\"10\", origin=\"file\", mode=\"ini\")\n\n    @pytest.mark.parametrize(\"pytest_ini\", [\"pytest.ini\", \".pytest.ini\"])\n    @pytest.mark.parametrize(\"other\", [\"setup.cfg\", \"tox.ini\"])\n    def test_pytestini_overrides_empty_other(\n        self, tmp_path: Path, pytest_ini: str, other: str\n    ) -> None:\n        inipath = tmp_path / pytest_ini\n        inipath.touch()\n        a = tmp_path / \"a\"\n        a.mkdir()\n        (a / other).touch()\n        rootpath, parsed_inipath, *_ = determine_setup(\n            inifile=None,\n            override_ini=None,\n            args=[str(a)],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == tmp_path\n        assert parsed_inipath == inipath\n\n    def test_setuppy_fallback(self, tmp_path: Path) -> None:\n        a = tmp_path / \"a\"\n        a.mkdir()\n        (a / \"setup.cfg\").touch()\n        (tmp_path / \"setup.py\").touch()\n        rootpath, inipath, inicfg, _ = determine_setup(\n            inifile=None,\n            override_ini=None,\n            args=[str(a)],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == tmp_path\n        assert inipath is None\n        assert inicfg == {}\n\n    def test_nothing(self, tmp_path: Path, monkeypatch: MonkeyPatch) -> None:\n        monkeypatch.chdir(tmp_path)\n        rootpath, inipath, inicfg, _ = determine_setup(\n            inifile=None,\n            override_ini=None,\n            args=[str(tmp_path)],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == tmp_path\n        assert inipath is None\n        assert inicfg == {}\n\n    @pytest.mark.parametrize(\n        \"name, contents\",\n        [\n            # pytest.param(\"pytest.ini\", \"[pytest]\\nx=10\", id=\"pytest.ini\"),\n            pytest.param(\n                \"pyproject.toml\", \"[tool.pytest.ini_options]\\nx=10\", id=\"pyproject.toml\"\n            ),\n            # pytest.param(\"tox.ini\", \"[pytest]\\nx=10\", id=\"tox.ini\"),\n            # pytest.param(\"setup.cfg\", \"[tool:pytest]\\nx=10\", id=\"setup.cfg\"),\n        ],\n    )\n    def test_with_specific_inifile(\n        self, tmp_path: Path, name: str, contents: str\n    ) -> None:\n        p = tmp_path / name\n        p.touch()\n        p.write_text(contents, encoding=\"utf-8\")\n        rootpath, inipath, ini_config, _ = determine_setup(\n            inifile=str(p),\n            override_ini=None,\n            args=[str(tmp_path)],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == tmp_path\n        assert inipath == p\n        assert ini_config[\"x\"] == ConfigValue(\"10\", origin=\"file\", mode=\"ini\")\n\n    def test_explicit_config_file_sets_rootdir(\n        self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        tests_dir = tmp_path / \"tests\"\n        tests_dir.mkdir()\n\n        monkeypatch.chdir(tmp_path)\n\n        # No config file is explicitly given: rootdir is determined to be cwd.\n        rootpath, found_inipath, *_ = determine_setup(\n            inifile=None,\n            override_ini=None,\n            args=[str(tests_dir)],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == tmp_path\n        assert found_inipath is None\n\n        # Config file is explicitly given: rootdir is determined to be inifile's directory.\n        inipath = tmp_path / \"pytest.ini\"\n        inipath.touch()\n        rootpath, found_inipath, *_ = determine_setup(\n            inifile=str(inipath),\n            override_ini=None,\n            args=[str(tests_dir)],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == tmp_path\n        assert found_inipath == inipath\n\n    def test_with_arg_outside_cwd_without_inifile(\n        self, tmp_path: Path, monkeypatch: MonkeyPatch\n    ) -> None:\n        monkeypatch.chdir(tmp_path)\n        a = tmp_path / \"a\"\n        a.mkdir()\n        b = tmp_path / \"b\"\n        b.mkdir()\n        rootpath, inifile, *_ = determine_setup(\n            inifile=None,\n            override_ini=None,\n            args=[str(a), str(b)],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == tmp_path\n        assert inifile is None\n\n    def test_with_arg_outside_cwd_with_inifile(self, tmp_path: Path) -> None:\n        a = tmp_path / \"a\"\n        a.mkdir()\n        b = tmp_path / \"b\"\n        b.mkdir()\n        inipath = a / \"pytest.ini\"\n        inipath.touch()\n        rootpath, parsed_inipath, *_ = determine_setup(\n            inifile=None,\n            override_ini=None,\n            args=[str(a), str(b)],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == a\n        assert inipath == parsed_inipath\n\n    @pytest.mark.parametrize(\"dirs\", ([], [\"does-not-exist\"], [\"a/does-not-exist\"]))\n    def test_with_non_dir_arg(\n        self, dirs: Sequence[str], tmp_path: Path, monkeypatch: MonkeyPatch\n    ) -> None:\n        monkeypatch.chdir(tmp_path)\n        rootpath, inipath, *_ = determine_setup(\n            inifile=None,\n            override_ini=None,\n            args=dirs,\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == tmp_path\n        assert inipath is None\n\n    def test_with_existing_file_in_subdir(\n        self, tmp_path: Path, monkeypatch: MonkeyPatch\n    ) -> None:\n        a = tmp_path / \"a\"\n        a.mkdir()\n        (a / \"exists\").touch()\n        monkeypatch.chdir(tmp_path)\n        rootpath, inipath, *_ = determine_setup(\n            inifile=None,\n            override_ini=None,\n            args=[\"a/exist\"],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n        assert rootpath == tmp_path\n        assert inipath is None\n\n    def test_with_config_also_in_parent_directory(\n        self, tmp_path: Path, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"Regression test for #7807.\"\"\"\n        (tmp_path / \"setup.cfg\").write_text(\"[tool:pytest]\\n\", \"utf-8\")\n        (tmp_path / \"myproject\").mkdir()\n        (tmp_path / \"myproject\" / \"setup.cfg\").write_text(\"[tool:pytest]\\n\", \"utf-8\")\n        (tmp_path / \"myproject\" / \"tests\").mkdir()\n        monkeypatch.chdir(tmp_path / \"myproject\")\n\n        rootpath, inipath, *_ = determine_setup(\n            inifile=None,\n            override_ini=None,\n            args=[\"tests/\"],\n            rootdir_cmd_arg=None,\n            invocation_dir=Path.cwd(),\n        )\n\n        assert rootpath == tmp_path / \"myproject\"\n        assert inipath == tmp_path / \"myproject\" / \"setup.cfg\"\n\n\nclass TestOverrideIniArgs:\n    @pytest.mark.parametrize(\"name\", \"setup.cfg tox.ini pytest.ini\".split())\n    def test_override_ini_names(self, pytester: Pytester, name: str) -> None:\n        section = \"[pytest]\" if name != \"setup.cfg\" else \"[tool:pytest]\"\n        pytester.path.joinpath(name).write_text(\n            textwrap.dedent(\n                f\"\"\"\n            {section}\n            custom = 1.0\"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"custom\", \"\")\"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_pass(pytestconfig):\n                ini_val = pytestconfig.getini(\"custom\")\n                print('\\\\ncustom_option:%s\\\\n' % ini_val)\"\"\"\n        )\n\n        result = pytester.runpytest(\"--override-ini\", \"custom=2.0\", \"-s\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"custom_option:2.0\"])\n\n        result = pytester.runpytest(\n            \"--override-ini\", \"custom=2.0\", \"--override-ini=custom=3.0\", \"-s\"\n        )\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"custom_option:3.0\"])\n\n    def test_override_ini_paths(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"paths\", \"my new ini value\", type=\"paths\")\"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            paths=blah.py\"\"\"\n        )\n        pytester.makepyfile(\n            r\"\"\"\n            def test_overridden(pytestconfig):\n                config_paths = pytestconfig.getini(\"paths\")\n                print(config_paths)\n                for cpf in config_paths:\n                    print('\\nuser_path:%s' % cpf.name)\n            \"\"\"\n        )\n        result = pytester.runpytest(\n            \"--override-ini\", \"paths=foo/bar1.py foo/bar2.py\", \"-s\"\n        )\n        result.stdout.fnmatch_lines([\"user_path:bar1.py\", \"user_path:bar2.py\"])\n\n    def test_override_multiple_and_default(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                addini = parser.addini\n                addini(\"custom_option_1\", \"\", default=\"o1\")\n                addini(\"custom_option_2\", \"\", default=\"o2\")\n                addini(\"custom_option_3\", \"\", default=False, type=\"bool\")\n                addini(\"custom_option_4\", \"\", default=True, type=\"bool\")\"\"\"\n        )\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            custom_option_1=custom_option_1\n            custom_option_2=custom_option_2\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_multiple_options(pytestconfig):\n                prefix = \"custom_option\"\n                for x in range(1, 5):\n                    ini_value=pytestconfig.getini(\"%s_%d\" % (prefix, x))\n                    print('\\\\nini%d:%s' % (x, ini_value))\n        \"\"\"\n        )\n        result = pytester.runpytest(\n            \"--override-ini\",\n            \"custom_option_1=fulldir=/tmp/user1\",\n            \"-o\",\n            \"custom_option_2=url=/tmp/user2?a=b&d=e\",\n            \"-o\",\n            \"custom_option_3=True\",\n            \"-o\",\n            \"custom_option_4=no\",\n            \"-s\",\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"ini1:fulldir=/tmp/user1\",\n                \"ini2:url=/tmp/user2?a=b&d=e\",\n                \"ini3:True\",\n                \"ini4:False\",\n            ]\n        )\n\n    def test_override_ini_usage_error_bad_style(self, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            xdist_strict=False\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--override-ini\", \"xdist_strict\", \"True\")\n        result.stderr.fnmatch_lines(\n            [\n                \"ERROR: -o/--override-ini expects option=value style (got: 'xdist_strict').\",\n            ]\n        )\n\n    @pytest.mark.parametrize(\"with_ini\", [True, False])\n    def test_override_ini_handled_asap(\n        self, pytester: Pytester, with_ini: bool\n    ) -> None:\n        \"\"\"-o should be handled as soon as possible and always override what's in config files (#2238)\"\"\"\n        if with_ini:\n            pytester.makeini(\n                \"\"\"\n                [pytest]\n                python_files=test_*.py\n            \"\"\"\n            )\n        pytester.makepyfile(\n            unittest_ini_handle=\"\"\"\n            def test():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--override-ini\", \"python_files=unittest_*.py\")\n        result.stdout.fnmatch_lines([\"*1 passed in*\"])\n\n    def test_addopts_before_initini(\n        self, monkeypatch: MonkeyPatch, _config_for_test, _sys_snapshot\n    ) -> None:\n        cache_dir = \".custom_cache\"\n        monkeypatch.setenv(\"PYTEST_ADDOPTS\", f\"-o cache_dir={cache_dir}\")\n        config = _config_for_test\n        config.parse([], addopts=True)\n        assert config._inicfg.get(\"cache_dir\") == ConfigValue(\n            cache_dir, origin=\"override\", mode=\"ini\"\n        )\n\n    def test_addopts_from_env_not_concatenated(\n        self, monkeypatch: MonkeyPatch, _config_for_test\n    ) -> None:\n        \"\"\"PYTEST_ADDOPTS should not take values from normal args (#4265).\"\"\"\n        monkeypatch.setenv(\"PYTEST_ADDOPTS\", \"-o\")\n        config = _config_for_test\n        with pytest.raises(UsageError) as excinfo:\n            config.parse([\"cache_dir=ignored\"], addopts=True)\n        assert (\n            \"error: argument -o/--override-ini: expected one argument\"\n            in excinfo.value.args[0]\n        )\n        assert \"via PYTEST_ADDOPTS\" in excinfo.value.args[0]\n\n    def test_addopts_from_ini_not_concatenated(self, pytester: Pytester) -> None:\n        \"\"\"`addopts` from configuration should not take values from normal args (#4265).\"\"\"\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            addopts=-o\n        \"\"\"\n        )\n        result = pytester.runpytest(\"cache_dir=ignored\")\n        result.stderr.fnmatch_lines(\n            [\n                \"*: error: argument -o/--override-ini: expected one argument\",\n                \"  config source: via addopts config\",\n            ]\n        )\n        assert result.ret == _pytest.config.ExitCode.USAGE_ERROR\n\n    def test_override_ini_does_not_contain_paths(\n        self, _config_for_test, _sys_snapshot\n    ) -> None:\n        \"\"\"Check that -o no longer swallows all options after it (#3103)\"\"\"\n        config = _config_for_test\n        config.parse([\"-o\", \"cache_dir=/cache\", \"/some/test/path\"])\n        assert config._inicfg.get(\"cache_dir\") == ConfigValue(\n            \"/cache\", origin=\"override\", mode=\"ini\"\n        )\n\n    def test_multiple_override_ini_options(self, pytester: Pytester) -> None:\n        \"\"\"Ensure a file path following a '-o' option does not generate an error (#3103)\"\"\"\n        pytester.makepyfile(\n            **{\n                \"conftest.py\": \"\"\"\n                def pytest_addoption(parser):\n                    parser.addini('foo', default=None, help='some option')\n                    parser.addini('bar', default=None, help='some option')\n            \"\"\",\n                \"test_foo.py\": \"\"\"\n                def test(pytestconfig):\n                    assert pytestconfig.getini('foo') == '1'\n                    assert pytestconfig.getini('bar') == '0'\n            \"\"\",\n                \"test_bar.py\": \"\"\"\n                def test():\n                    assert False\n            \"\"\",\n            }\n        )\n        result = pytester.runpytest(\"-o\", \"foo=1\", \"-o\", \"bar=0\", \"test_foo.py\")\n        assert \"ERROR:\" not in result.stderr.str()\n        result.stdout.fnmatch_lines([\"collected 1 item\", \"*= 1 passed in *=\"])\n\n    def test_override_ini_without_config_file(self, pytester: Pytester) -> None:\n        pytester.makepyfile(**{\"src/override_ini_without_config_file.py\": \"\"})\n        pytester.makepyfile(\n            **{\n                \"tests/test_override_ini_without_config_file.py\": (\n                    \"import override_ini_without_config_file\\ndef test(): pass\"\n                ),\n            }\n        )\n        result = pytester.runpytest(\"--override-ini\", \"pythonpath=src\")\n        result.assert_outcomes(passed=1)\n\n    def test_override_ini_invalid_option(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"--override-ini\", \"doesnotexist=true\")\n        result.stdout.fnmatch_lines(\n            [\n                \"=*= warnings summary =*=\",\n                \"*PytestConfigWarning:*Unknown config option: doesnotexist\",\n            ]\n        )\n\n\ndef test_help_via_addopts(pytester: Pytester) -> None:\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        addopts = --unknown-option-should-allow-for-help --help\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.stdout.fnmatch_lines(\n        [\n            \"usage: *\",\n            \"positional arguments:\",\n            # Displays full/default help.\n            \"to see available markers type: pytest --markers\",\n        ]\n    )\n\n\ndef test_help_and_version_after_argument_error(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        def validate(arg):\n            raise argparse.ArgumentTypeError(\"argerror\")\n\n        def pytest_addoption(parser):\n            group = parser.getgroup('cov')\n            group.addoption(\n                \"--invalid-option-should-allow-for-help\",\n                type=validate,\n            )\n        \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        addopts = --invalid-option-should-allow-for-help\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--help\")\n    result.stdout.fnmatch_lines(\n        [\n            \"usage: *\",\n            \"positional arguments:\",\n            \"NOTE: displaying only minimal help due to UsageError.\",\n        ]\n    )\n    result.stderr.fnmatch_lines(\n        [\n            \"ERROR: usage: *\",\n            \"*: error: argument --invalid-option-should-allow-for-help: expected one argument\",\n        ]\n    )\n    # Does not display full/default help.\n    assert \"to see available markers type: pytest --markers\" not in result.stdout.lines\n    assert result.ret == ExitCode.USAGE_ERROR\n\n    result = pytester.runpytest(\"--version\")\n    result.stdout.fnmatch_lines([f\"pytest {pytest.__version__}\"])\n    assert result.ret == ExitCode.OK\n\n\ndef test_help_formatter_uses_py_get_terminal_width(monkeypatch: MonkeyPatch) -> None:\n    from _pytest.config.argparsing import DropShorterLongHelpFormatter\n\n    monkeypatch.setenv(\"COLUMNS\", \"90\")\n    formatter = DropShorterLongHelpFormatter(\"prog\")\n    assert formatter._width == 90\n\n    monkeypatch.setattr(\"_pytest._io.get_terminal_width\", lambda: 160)\n    formatter = DropShorterLongHelpFormatter(\"prog\")\n    assert formatter._width == 160\n\n    formatter = DropShorterLongHelpFormatter(\"prog\", width=42)\n    assert formatter._width == 42\n\n\ndef test_config_does_not_load_blocked_plugin_from_args(pytester: Pytester) -> None:\n    \"\"\"This tests that pytest's config setup handles \"-p no:X\".\"\"\"\n    p = pytester.makepyfile(\"def test(capfd): pass\")\n    result = pytester.runpytest(str(p), \"-pno:capture\")\n    result.stdout.fnmatch_lines([\"E       fixture 'capfd' not found\"])\n    assert result.ret == ExitCode.TESTS_FAILED\n\n    result = pytester.runpytest(str(p), \"-pno:capture\", \"-s\")\n    result.stderr.fnmatch_lines([\"*: error: unrecognized arguments: -s\"])\n    assert result.ret == ExitCode.USAGE_ERROR\n\n    result = pytester.runpytest(str(p), \"-p no:capture\", \"-s\")\n    result.stderr.fnmatch_lines([\"*: error: unrecognized arguments: -s\"])\n    assert result.ret == ExitCode.USAGE_ERROR\n\n    result = pytester.runpytest(str(p), \"-p no:/path/to/conftest.py\", \"-s\")\n    result.stderr.fnmatch_lines([\"ERROR:*Blocking conftest files*\"])\n    assert result.ret == ExitCode.USAGE_ERROR\n\n\ndef test_invocation_args(pytester: Pytester) -> None:\n    \"\"\"Ensure that Config.invocation_* arguments are correctly defined\"\"\"\n\n    class DummyPlugin:\n        pass\n\n    p = pytester.makepyfile(\"def test(): pass\")\n    plugin = DummyPlugin()\n    rec = pytester.inline_run(p, \"-v\", plugins=[plugin])\n    calls = rec.getcalls(\"pytest_runtest_protocol\")\n    assert len(calls) == 1\n    call = calls[0]\n    config = call.item.config\n\n    assert config.invocation_params.args == (str(p), \"-v\")\n    assert config.invocation_params.dir == pytester.path\n\n    plugins = config.invocation_params.plugins\n    assert len(plugins) == 2\n    assert plugins[0] is plugin\n    # Installed by pytester.inline_run().\n    assert type(plugins[1]).__name__ == \"PytesterHelperPlugin\"\n\n    # args cannot be None\n    with pytest.raises(TypeError):\n        Config.InvocationParams(args=None, plugins=None, dir=Path())  # type: ignore[arg-type]\n\n\n@pytest.mark.parametrize(\n    \"plugin\",\n    [\n        x\n        for x in _pytest.config.default_plugins\n        if x not in _pytest.config.essential_plugins\n    ],\n)\ndef test_config_blocked_default_plugins(pytester: Pytester, plugin: str) -> None:\n    p = pytester.makepyfile(\"def test(): pass\")\n    result = pytester.runpytest(str(p), f\"-pno:{plugin}\")\n\n    if plugin == \"python\":\n        assert result.ret == ExitCode.USAGE_ERROR\n        result.stderr.fnmatch_lines(\n            [\n                \"ERROR: not found: */test_config_blocked_default_plugins.py\",\n                \"(no match in any of *<Dir *>*\",\n            ]\n        )\n        return\n\n    assert result.ret == ExitCode.OK\n    if plugin != \"terminal\":\n        result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n    p = pytester.makepyfile(\"def test(): assert 0\")\n    result = pytester.runpytest(str(p), f\"-pno:{plugin}\")\n    assert result.ret == ExitCode.TESTS_FAILED\n    if plugin != \"terminal\":\n        result.stdout.fnmatch_lines([\"* 1 failed in *\"])\n    else:\n        assert result.stdout.lines == []\n\n\nclass TestSetupCfg:\n    def test_pytest_setup_cfg_unsupported(self, pytester: Pytester) -> None:\n        pytester.makefile(\n            \".cfg\",\n            setup=\"\"\"\n            [pytest]\n            addopts = --verbose\n        \"\"\",\n        )\n        with pytest.raises(pytest.fail.Exception):\n            pytester.runpytest()\n\n    def test_pytest_custom_cfg_unsupported(self, pytester: Pytester) -> None:\n        pytester.makefile(\n            \".cfg\",\n            custom=\"\"\"\n            [pytest]\n            addopts = --verbose\n        \"\"\",\n        )\n        with pytest.raises(pytest.fail.Exception):\n            pytester.runpytest(\"-c\", \"custom.cfg\")\n\n        with pytest.raises(pytest.fail.Exception):\n            pytester.runpytest(\"--config-file\", \"custom.cfg\")\n\n\nclass TestPytestPluginsVariable:\n    def test_pytest_plugins_in_non_top_level_conftest_unsupported(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            **{\n                \"subdirectory/conftest.py\": \"\"\"\n            pytest_plugins=['capture']\n        \"\"\"\n            }\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_func():\n                pass\n        \"\"\"\n        )\n        res = pytester.runpytest()\n        assert res.ret == 2\n        msg = \"Defining 'pytest_plugins' in a non-top-level conftest is no longer supported\"\n        res.stdout.fnmatch_lines([f\"*{msg}*\", f\"*subdirectory{os.sep}conftest.py*\"])\n\n    @pytest.mark.parametrize(\"use_pyargs\", [True, False])\n    def test_pytest_plugins_in_non_top_level_conftest_unsupported_pyargs(\n        self, pytester: Pytester, use_pyargs: bool\n    ) -> None:\n        \"\"\"When using --pyargs, do not emit the warning about non-top-level conftest warnings (#4039, #4044)\"\"\"\n        files = {\n            \"src/pkg/__init__.py\": \"\",\n            \"src/pkg/conftest.py\": \"\",\n            \"src/pkg/test_root.py\": \"def test(): pass\",\n            \"src/pkg/sub/__init__.py\": \"\",\n            \"src/pkg/sub/conftest.py\": \"pytest_plugins=['capture']\",\n            \"src/pkg/sub/test_bar.py\": \"def test(): pass\",\n        }\n        pytester.makepyfile(**files)\n        pytester.syspathinsert(pytester.path.joinpath(\"src\"))\n\n        args = (\"--pyargs\", \"pkg\") if use_pyargs else ()\n        res = pytester.runpytest(*args)\n        assert res.ret == (0 if use_pyargs else 2)\n        msg = \"Defining 'pytest_plugins' in a non-top-level conftest is no longer supported\"\n        if use_pyargs:\n            assert msg not in res.stdout.str()\n        else:\n            res.stdout.fnmatch_lines([f\"*{msg}*\"])\n\n    def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_top_level_conftest(\n        self, pytester: Pytester\n    ) -> None:\n        subdirectory = pytester.path.joinpath(\"subdirectory\")\n        subdirectory.mkdir()\n        pytester.makeconftest(\n            \"\"\"\n            pytest_plugins=['capture']\n        \"\"\"\n        )\n        pytester.path.joinpath(\"conftest.py\").rename(\n            subdirectory.joinpath(\"conftest.py\")\n        )\n\n        pytester.makepyfile(\n            \"\"\"\n            def test_func():\n                pass\n        \"\"\"\n        )\n\n        res = pytester.runpytest_subprocess()\n        assert res.ret == 2\n        msg = \"Defining 'pytest_plugins' in a non-top-level conftest is no longer supported\"\n        res.stdout.fnmatch_lines([f\"*{msg}*\", f\"*subdirectory{os.sep}conftest.py*\"])\n\n    def test_pytest_plugins_in_non_top_level_conftest_unsupported_no_false_positives(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"def test_func(): pass\",\n            **{\n                \"subdirectory/conftest\": \"pass\",\n                \"conftest\": \"\"\"\n                    import warnings\n                    warnings.filterwarnings('always', category=DeprecationWarning)\n                    pytest_plugins=['capture']\n                    \"\"\",\n            },\n        )\n        res = pytester.runpytest_subprocess()\n        assert res.ret == 0\n        msg = \"Defining 'pytest_plugins' in a non-top-level conftest is no longer supported\"\n        assert msg not in res.stdout.str()\n\n\ndef test_conftest_import_error_repr(tmp_path: Path) -> None:\n    \"\"\"`ConftestImportFailure` should use a short error message and readable\n    path to the failed conftest.py file.\"\"\"\n    path = tmp_path.joinpath(\"foo/conftest.py\")\n    with pytest.raises(\n        ConftestImportFailure,\n        match=re.escape(f\"RuntimeError: some error (from {path})\"),\n    ):\n        try:\n            raise RuntimeError(\"some error\")\n        except Exception as exc:\n            raise ConftestImportFailure(path, cause=exc) from exc\n\n\ndef test_strtobool() -> None:\n    assert _strtobool(\"YES\")\n    assert not _strtobool(\"NO\")\n    with pytest.raises(ValueError):\n        _strtobool(\"unknown\")\n\n\n@pytest.mark.parametrize(\n    \"arg, escape, expected\",\n    [\n        (\"ignore\", False, (\"ignore\", \"\", Warning, \"\", 0)),\n        (\n            \"ignore::DeprecationWarning\",\n            False,\n            (\"ignore\", \"\", DeprecationWarning, \"\", 0),\n        ),\n        (\n            \"ignore:some msg:DeprecationWarning\",\n            False,\n            (\"ignore\", \"some msg\", DeprecationWarning, \"\", 0),\n        ),\n        (\n            \"ignore::DeprecationWarning:mod\",\n            False,\n            (\"ignore\", \"\", DeprecationWarning, \"mod\", 0),\n        ),\n        (\n            \"ignore::DeprecationWarning:mod:42\",\n            False,\n            (\"ignore\", \"\", DeprecationWarning, \"mod\", 42),\n        ),\n        (\"error:some\\\\msg:::\", True, (\"error\", \"some\\\\\\\\msg\", Warning, \"\", 0)),\n        (\"error:::mod\\\\foo:\", True, (\"error\", \"\", Warning, \"mod\\\\\\\\foo\\\\Z\", 0)),\n    ],\n)\ndef test_parse_warning_filter(\n    arg: str, escape: bool, expected: tuple[str, str, type[Warning], str, int]\n) -> None:\n    assert parse_warning_filter(arg, escape=escape) == expected\n\n\n@pytest.mark.parametrize(\n    \"arg\",\n    [\n        # Too much parts.\n        \":\" * 5,\n        # Invalid action.\n        \"FOO::\",\n        # Class is not a Warning subclass.\n        \"::list::\",\n        # Negative line number.\n        \"::::-1\",\n        # Not a line number.\n        \"::::not-a-number\",\n    ],\n)\ndef test_parse_warning_filter_failure(arg: str) -> None:\n    with pytest.raises(pytest.UsageError):\n        parse_warning_filter(arg, escape=True)\n\n\nclass TestDebugOptions:\n    def test_without_debug_does_not_write_log(self, pytester: Pytester) -> None:\n        result = pytester.runpytest()\n        result.stderr.no_fnmatch_line(\n            \"*writing pytest debug information to*pytestdebug.log\"\n        )\n        result.stderr.no_fnmatch_line(\n            \"*wrote pytest debug information to*pytestdebug.log\"\n        )\n        assert not [f.name for f in pytester.path.glob(\"**/*.log\")]\n\n    def test_with_only_debug_writes_pytestdebug_log(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"--debug\")\n        result.stderr.fnmatch_lines(\n            [\n                \"*writing pytest debug information to*pytestdebug.log\",\n                \"*wrote pytest debug information to*pytestdebug.log\",\n            ]\n        )\n        assert \"pytestdebug.log\" in [f.name for f in pytester.path.glob(\"**/*.log\")]\n\n    def test_multiple_custom_debug_logs(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"--debug\", \"bar.log\")\n        result.stderr.fnmatch_lines(\n            [\n                \"*writing pytest debug information to*bar.log\",\n                \"*wrote pytest debug information to*bar.log\",\n            ]\n        )\n        result = pytester.runpytest(\"--debug\", \"foo.log\")\n        result.stderr.fnmatch_lines(\n            [\n                \"*writing pytest debug information to*foo.log\",\n                \"*wrote pytest debug information to*foo.log\",\n            ]\n        )\n\n        assert {\"bar.log\", \"foo.log\"} == {\n            f.name for f in pytester.path.glob(\"**/*.log\")\n        }\n\n    def test_debug_help(self, pytester: Pytester) -> None:\n        result = pytester.runpytest(\"-h\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*Store internal tracing debug information in this log*\",\n                \"*file. This file is opened with 'w' and truncated as a*\",\n                \"*Default: pytestdebug.log.\",\n            ]\n        )\n\n\nclass TestVerbosity:\n    SOME_OUTPUT_TYPE = Config.VERBOSITY_ASSERTIONS\n    SOME_OUTPUT_VERBOSITY_LEVEL = 5\n\n    class VerbosityIni:\n        def pytest_addoption(self, parser: Parser) -> None:\n            Config._add_verbosity_ini(\n                parser, TestVerbosity.SOME_OUTPUT_TYPE, help=\"some help text\"\n            )\n\n    def test_level_matches_verbose_when_not_specified(\n        self, pytester: Pytester, tmp_path: Path\n    ) -> None:\n        tmp_path.joinpath(\"pytest.ini\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                [pytest]\n                addopts = --verbose\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        pytester.plugins = [TestVerbosity.VerbosityIni()]\n\n        config = pytester.parseconfig(tmp_path)\n\n        assert (\n            config.get_verbosity(TestVerbosity.SOME_OUTPUT_TYPE)\n            == config.option.verbose\n        )\n\n    def test_level_matches_verbose_when_not_known_type(\n        self, pytester: Pytester, tmp_path: Path\n    ) -> None:\n        tmp_path.joinpath(\"pytest.ini\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                [pytest]\n                addopts = --verbose\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        pytester.plugins = [TestVerbosity.VerbosityIni()]\n\n        config = pytester.parseconfig(tmp_path)\n\n        assert config.get_verbosity(\"some fake verbosity type\") == config.option.verbose\n\n    def test_level_matches_specified_override(\n        self, pytester: Pytester, tmp_path: Path\n    ) -> None:\n        setting_name = f\"verbosity_{TestVerbosity.SOME_OUTPUT_TYPE}\"\n        tmp_path.joinpath(\"pytest.ini\").write_text(\n            textwrap.dedent(\n                f\"\"\"\\\n                [pytest]\n                addopts = --verbose\n                {setting_name} = {TestVerbosity.SOME_OUTPUT_VERBOSITY_LEVEL}\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        pytester.plugins = [TestVerbosity.VerbosityIni()]\n\n        config = pytester.parseconfig(tmp_path)\n\n        assert (\n            config.get_verbosity(TestVerbosity.SOME_OUTPUT_TYPE)\n            == TestVerbosity.SOME_OUTPUT_VERBOSITY_LEVEL\n        )\n\n\nclass TestNativeTomlConfig:\n    \"\"\"Test native TOML configuration parsing.\"\"\"\n\n    def test_values(self, pytester: Pytester) -> None:\n        \"\"\"Test that values are parsed as expected in TOML mode.\"\"\"\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest]\n            test_bool = true\n            test_int = 5\n            test_float = 30.5\n            test_args = [\"tests\", \"integration\"]\n            test_paths = [\"src\", \"lib\"]\n            \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"test_bool\", \"Test boolean config\", type=\"bool\", default=False)\n                parser.addini(\"test_int\", \"Test integer config\", type=\"int\", default=0)\n                parser.addini(\"test_float\", \"Test float config\", type=\"float\", default=0.0)\n                parser.addini(\"test_args\", \"Test args config\", type=\"args\")\n                parser.addini(\"test_paths\", \"Test paths config\", type=\"paths\")\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n        assert config.getini(\"test_bool\") is True\n        assert config.getini(\"test_int\") == 5\n        assert config.getini(\"test_float\") == 30.5\n        assert config.getini(\"test_args\") == [\"tests\", \"integration\"]\n        paths = config.getini(\"test_paths\")\n        assert len(paths) == 2\n        # Paths should be resolved relative to pyproject.toml location.\n        assert all(isinstance(p, Path) for p in paths)\n\n    def test_override_with_list(self, pytester: Pytester) -> None:\n        \"\"\"Test that -o overrides work with INI-style list syntax even when\n        config uses TOML mode.\"\"\"\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest]\n            test_override_list = [\"tests\"]\n            \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"test_override_list\", \"Test override list\", type=\"args\")\n            \"\"\"\n        )\n        # -o uses INI mode, so uses space-separated syntax.\n        config = pytester.parseconfig(\"-o\", \"test_override_list=tests integration\")\n        assert config.getini(\"test_override_list\") == [\"tests\", \"integration\"]\n\n    def test_conflict_between_native_and_ini_options(self, pytester: Pytester) -> None:\n        \"\"\"Test that using both [tool.pytest] and [tool.pytest.ini_options] fails.\"\"\"\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest]\n            test_conflict_1 = true\n\n            [tool.pytest.ini_options]\n            test_conflict_2 = true\n            \"\"\",\n        )\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"test_conflict_1\", \"Test conflict config 1\", type=\"bool\")\n                parser.addini(\"test_conflict_2\", \"Test conflict config 2\", type=\"bool\")\n            \"\"\"\n        )\n        with pytest.raises(UsageError, match=\"Cannot use both\"):\n            pytester.parseconfig()\n\n    def test_type_errors(self, pytester: Pytester) -> None:\n        \"\"\"Test all possible TypeError cases in getini.\"\"\"\n        pytester.maketoml(\n            \"\"\"\n            [pytest]\n            paths_not_list = \"should_be_list\"\n            paths_list_with_int = [1, 2]\n\n            args_not_list = 123\n            args_list_with_int = [\"valid\", 456]\n\n            linelist_not_list = true\n            linelist_list_with_bool = [\"valid\", false]\n\n            bool_not_bool = \"true\"\n\n            int_not_int = \"123\"\n            int_is_bool = true\n\n            float_not_float = \"3.14\"\n            float_is_bool = false\n\n            string_not_string = 123\n            \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addini(\"paths_not_list\", \"test\", type=\"paths\")\n                parser.addini(\"paths_list_with_int\", \"test\", type=\"paths\")\n                parser.addini(\"args_not_list\", \"test\", type=\"args\")\n                parser.addini(\"args_list_with_int\", \"test\", type=\"args\")\n                parser.addini(\"linelist_not_list\", \"test\", type=\"linelist\")\n                parser.addini(\"linelist_list_with_bool\", \"test\", type=\"linelist\")\n                parser.addini(\"bool_not_bool\", \"test\", type=\"bool\")\n                parser.addini(\"int_not_int\", \"test\", type=\"int\")\n                parser.addini(\"int_is_bool\", \"test\", type=\"int\")\n                parser.addini(\"float_not_float\", \"test\", type=\"float\")\n                parser.addini(\"float_is_bool\", \"test\", type=\"float\")\n                parser.addini(\"string_not_string\", \"test\", type=\"string\")\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n\n        with pytest.raises(\n            TypeError, match=r\"expects a list for type 'paths'.*got str\"\n        ):\n            config.getini(\"paths_not_list\")\n\n        with pytest.raises(\n            TypeError, match=r\"expects a list of strings.*item at index 0 is int\"\n        ):\n            config.getini(\"paths_list_with_int\")\n\n        with pytest.raises(TypeError, match=r\"expects a list for type 'args'.*got int\"):\n            config.getini(\"args_not_list\")\n\n        with pytest.raises(\n            TypeError, match=r\"expects a list of strings.*item at index 1 is int\"\n        ):\n            config.getini(\"args_list_with_int\")\n\n        with pytest.raises(\n            TypeError, match=r\"expects a list for type 'linelist'.*got bool\"\n        ):\n            config.getini(\"linelist_not_list\")\n\n        with pytest.raises(\n            TypeError, match=r\"expects a list of strings.*item at index 1 is bool\"\n        ):\n            config.getini(\"linelist_list_with_bool\")\n\n        with pytest.raises(TypeError, match=r\"expects a bool.*got str\"):\n            config.getini(\"bool_not_bool\")\n\n        with pytest.raises(TypeError, match=r\"expects an int.*got str\"):\n            config.getini(\"int_not_int\")\n\n        with pytest.raises(TypeError, match=r\"expects an int.*got bool\"):\n            config.getini(\"int_is_bool\")\n\n        with pytest.raises(TypeError, match=r\"expects a float.*got str\"):\n            config.getini(\"float_not_float\")\n\n        with pytest.raises(TypeError, match=r\"expects a float.*got bool\"):\n            config.getini(\"float_is_bool\")\n\n        with pytest.raises(TypeError, match=r\"expects a string.*got int\"):\n            config.getini(\"string_not_string\")\n\n\nclass TestInicfgDeprecation:\n    \"\"\"Tests for the deprecation of config.inicfg.\"\"\"\n\n    def test_inicfg_deprecated(self, pytester: Pytester) -> None:\n        \"\"\"Test that accessing config.inicfg issues a deprecation warning.\"\"\"\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            minversion = 3.0\n            \"\"\"\n        )\n        config = pytester.parseconfig()\n\n        with pytest.warns(\n            PytestDeprecationWarning, match=r\"config\\.inicfg is deprecated\"\n        ):\n            inicfg = config.inicfg  # type: ignore[deprecated]\n\n        assert config.getini(\"minversion\") == \"3.0\"\n        assert inicfg[\"minversion\"] == \"3.0\"\n        assert inicfg.get(\"minversion\") == \"3.0\"\n        del inicfg[\"minversion\"]\n        inicfg[\"minversion\"] = \"4.0\"\n        assert list(inicfg.keys()) == [\"minversion\"]\n        assert list(inicfg.items()) == [(\"minversion\", \"4.0\")]\n        assert len(inicfg) == 1\n\n    def test_issue_13946_setting_bool_no_longer_crashes(\n        self, pytester: Pytester\n    ) -> None:\n        \"\"\"Regression test for #13946 - setting inicfg doesn't cause a crash.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def pytest_configure(config):\n                config.inicfg[\"xfail_strict\"] = True\n\n            def test():\n                pass\n            \"\"\"\n        )\n\n        result = pytester.runpytest()\n        assert result.ret == 0\n"
  },
  {
    "path": "testing/test_conftest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nfrom collections.abc import Sequence\nimport os\nfrom pathlib import Path\nimport textwrap\nfrom typing import cast\n\nfrom _pytest.config import ExitCode\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pathlib import symlink_or_skip\nfrom _pytest.pytester import Pytester\nfrom _pytest.tmpdir import TempPathFactory\nimport pytest\n\n\ndef ConftestWithSetinitial(path) -> PytestPluginManager:\n    conftest = PytestPluginManager()\n    conftest_setinitial(conftest, [path])\n    return conftest\n\n\ndef conftest_setinitial(\n    conftest: PytestPluginManager,\n    args: Sequence[str | Path],\n    confcutdir: Path | None = None,\n) -> None:\n    conftest._set_initial_conftests(\n        args=args,\n        pyargs=False,\n        noconftest=False,\n        rootpath=Path(args[0]),\n        confcutdir=confcutdir,\n        invocation_dir=Path.cwd(),\n        importmode=\"prepend\",\n        consider_namespace_packages=False,\n    )\n\n\n@pytest.mark.usefixtures(\"_sys_snapshot\")\nclass TestConftestValueAccessGlobal:\n    @pytest.fixture(scope=\"module\", params=[\"global\", \"inpackage\"])\n    def basedir(self, request, tmp_path_factory: TempPathFactory) -> Generator[Path]:\n        tmp_path = tmp_path_factory.mktemp(\"basedir\", numbered=True)\n        tmp_path.joinpath(\"adir/b\").mkdir(parents=True)\n        tmp_path.joinpath(\"adir/conftest.py\").write_text(\n            \"a=1 ; Directory = 3\", encoding=\"utf-8\"\n        )\n        tmp_path.joinpath(\"adir/b/conftest.py\").write_text(\n            \"b=2 ; a = 1.5\", encoding=\"utf-8\"\n        )\n        if request.param == \"inpackage\":\n            tmp_path.joinpath(\"adir/__init__.py\").touch()\n            tmp_path.joinpath(\"adir/b/__init__.py\").touch()\n\n        yield tmp_path\n\n    def test_basic_init(self, basedir: Path) -> None:\n        conftest = PytestPluginManager()\n        p = basedir / \"adir\"\n        conftest._loadconftestmodules(\n            p, importmode=\"prepend\", rootpath=basedir, consider_namespace_packages=False\n        )\n        assert conftest._rget_with_confmod(\"a\", p)[1] == 1\n\n    def test_immediate_initialization_and_incremental_are_the_same(\n        self, basedir: Path\n    ) -> None:\n        conftest = PytestPluginManager()\n        assert not len(conftest._dirpath2confmods)\n        conftest._loadconftestmodules(\n            basedir,\n            importmode=\"prepend\",\n            rootpath=basedir,\n            consider_namespace_packages=False,\n        )\n        snap1 = len(conftest._dirpath2confmods)\n        assert snap1 == 1\n        conftest._loadconftestmodules(\n            basedir / \"adir\",\n            importmode=\"prepend\",\n            rootpath=basedir,\n            consider_namespace_packages=False,\n        )\n        assert len(conftest._dirpath2confmods) == snap1 + 1\n        conftest._loadconftestmodules(\n            basedir / \"b\",\n            importmode=\"prepend\",\n            rootpath=basedir,\n            consider_namespace_packages=False,\n        )\n        assert len(conftest._dirpath2confmods) == snap1 + 2\n\n    def test_value_access_not_existing(self, basedir: Path) -> None:\n        conftest = ConftestWithSetinitial(basedir)\n        with pytest.raises(KeyError):\n            conftest._rget_with_confmod(\"a\", basedir)\n\n    def test_value_access_by_path(self, basedir: Path) -> None:\n        conftest = ConftestWithSetinitial(basedir)\n        adir = basedir / \"adir\"\n        conftest._loadconftestmodules(\n            adir,\n            importmode=\"prepend\",\n            rootpath=basedir,\n            consider_namespace_packages=False,\n        )\n        assert conftest._rget_with_confmod(\"a\", adir)[1] == 1\n        conftest._loadconftestmodules(\n            adir / \"b\",\n            importmode=\"prepend\",\n            rootpath=basedir,\n            consider_namespace_packages=False,\n        )\n        assert conftest._rget_with_confmod(\"a\", adir / \"b\")[1] == 1.5\n\n    def test_value_access_with_confmod(self, basedir: Path) -> None:\n        startdir = basedir / \"adir\" / \"b\"\n        startdir.joinpath(\"xx\").mkdir()\n        conftest = ConftestWithSetinitial(startdir)\n        mod, value = conftest._rget_with_confmod(\"a\", startdir)\n        assert value == 1.5\n        assert mod.__file__ is not None\n        path = Path(mod.__file__)\n        assert path.parent == basedir / \"adir\" / \"b\"\n        assert path.stem == \"conftest\"\n\n\ndef test_conftest_in_nonpkg_with_init(tmp_path: Path, _sys_snapshot) -> None:\n    tmp_path.joinpath(\"adir-1.0/b\").mkdir(parents=True)\n    tmp_path.joinpath(\"adir-1.0/conftest.py\").write_text(\n        \"a=1 ; Directory = 3\", encoding=\"utf-8\"\n    )\n    tmp_path.joinpath(\"adir-1.0/b/conftest.py\").write_text(\n        \"b=2 ; a = 1.5\", encoding=\"utf-8\"\n    )\n    tmp_path.joinpath(\"adir-1.0/b/__init__.py\").touch()\n    tmp_path.joinpath(\"adir-1.0/__init__.py\").touch()\n    ConftestWithSetinitial(tmp_path.joinpath(\"adir-1.0\", \"b\"))\n\n\ndef test_doubledash_considered(pytester: Pytester) -> None:\n    conf = pytester.mkdir(\"--option\")\n    conf.joinpath(\"conftest.py\").touch()\n    conftest = PytestPluginManager()\n    conftest_setinitial(conftest, [conf.name, conf.name])\n    values = conftest._getconftestmodules(conf)\n    assert len(values) == 1\n\n\ndef test_issue151_load_all_conftests(pytester: Pytester) -> None:\n    names = \"code proj src\".split()\n    for name in names:\n        p = pytester.mkdir(name)\n        p.joinpath(\"conftest.py\").touch()\n\n    pm = PytestPluginManager()\n    conftest_setinitial(pm, names)\n    assert len(set(pm.get_plugins()) - {pm}) == len(names)\n\n\ndef test_conftest_global_import(pytester: Pytester) -> None:\n    pytester.makeconftest(\"x=3\")\n    p = pytester.makepyfile(\n        \"\"\"\n        from pathlib import Path\n        import pytest\n        from _pytest.config import PytestPluginManager\n        conf = PytestPluginManager()\n        mod = conf._importconftest(\n            Path(\"conftest.py\"),\n            importmode=\"prepend\",\n            rootpath=Path.cwd(),\n            consider_namespace_packages=False,\n        )\n        assert mod.x == 3\n        import conftest\n        assert conftest is mod, (conftest, mod)\n        sub = Path(\"sub\")\n        sub.mkdir()\n        subconf = sub / \"conftest.py\"\n        subconf.write_text(\"y=4\", encoding=\"utf-8\")\n        mod2 = conf._importconftest(\n            subconf,\n            importmode=\"prepend\",\n            rootpath=Path.cwd(),\n            consider_namespace_packages=False,\n        )\n        assert mod != mod2\n        assert mod2.y == 4\n        import conftest\n        assert conftest is mod2, (conftest, mod)\n    \"\"\"\n    )\n    res = pytester.runpython(p)\n    assert res.ret == 0\n\n\ndef test_conftestcutdir(pytester: Pytester) -> None:\n    conf = pytester.makeconftest(\"\")\n    p = pytester.mkdir(\"x\")\n    conftest = PytestPluginManager()\n    conftest_setinitial(conftest, [pytester.path], confcutdir=p)\n    conftest._loadconftestmodules(\n        p,\n        importmode=\"prepend\",\n        rootpath=pytester.path,\n        consider_namespace_packages=False,\n    )\n    values = conftest._getconftestmodules(p)\n    assert len(values) == 0\n    conftest._loadconftestmodules(\n        conf.parent,\n        importmode=\"prepend\",\n        rootpath=pytester.path,\n        consider_namespace_packages=False,\n    )\n    values = conftest._getconftestmodules(conf.parent)\n    assert len(values) == 0\n    assert not conftest.has_plugin(str(conf))\n    # but we can still import a conftest directly\n    conftest._importconftest(\n        conf,\n        importmode=\"prepend\",\n        rootpath=pytester.path,\n        consider_namespace_packages=False,\n    )\n    values = conftest._getconftestmodules(conf.parent)\n    assert values[0].__file__ is not None\n    assert values[0].__file__.startswith(str(conf))\n    # and all sub paths get updated properly\n    values = conftest._getconftestmodules(p)\n    assert len(values) == 1\n    assert values[0].__file__ is not None\n    assert values[0].__file__.startswith(str(conf))\n\n\ndef test_conftestcutdir_inplace_considered(pytester: Pytester) -> None:\n    conf = pytester.makeconftest(\"\")\n    conftest = PytestPluginManager()\n    conftest_setinitial(conftest, [conf.parent], confcutdir=conf.parent)\n    values = conftest._getconftestmodules(conf.parent)\n    assert len(values) == 1\n    assert values[0].__file__ is not None\n    assert values[0].__file__.startswith(str(conf))\n\n\n@pytest.mark.parametrize(\"name\", \"test tests whatever .dotdir\".split())\ndef test_setinitial_conftest_subdirs(pytester: Pytester, name: str) -> None:\n    sub = pytester.mkdir(name)\n    subconftest = sub.joinpath(\"conftest.py\")\n    subconftest.touch()\n    pm = PytestPluginManager()\n    conftest_setinitial(pm, [sub.parent], confcutdir=pytester.path)\n    key = subconftest.resolve()\n    if name not in (\"whatever\", \".dotdir\"):\n        assert pm.has_plugin(str(key))\n        assert len(set(pm.get_plugins()) - {pm}) == 1\n    else:\n        assert not pm.has_plugin(str(key))\n        assert len(set(pm.get_plugins()) - {pm}) == 0\n\n\ndef test_conftest_confcutdir(pytester: Pytester) -> None:\n    pytester.makeconftest(\"assert 0\")\n    x = pytester.mkdir(\"x\")\n    x.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            def pytest_addoption(parser):\n                parser.addoption(\"--xyz\", action=\"store_true\")\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    result = pytester.runpytest(\"-h\", f\"--confcutdir={x}\", x)\n    result.stdout.fnmatch_lines([\"*--xyz*\"])\n    result.stdout.no_fnmatch_line(\"*warning: could not load initial*\")\n\n\ndef test_installed_conftest_is_picked_up(pytester: Pytester, tmp_path: Path) -> None:\n    \"\"\"When using `--pyargs` to run tests in an installed packages (located e.g.\n    in a site-packages in the PYTHONPATH), conftest files in there are picked\n    up.\n\n    Regression test for #9767.\n    \"\"\"\n    # pytester dir - the source tree.\n    # tmp_path - the simulated site-packages dir (not in source tree).\n\n    pytester.syspathinsert(tmp_path)\n    pytester.makepyprojecttoml(\"[tool.pytest.ini_options]\")\n    tmp_path.joinpath(\"foo\").mkdir()\n    tmp_path.joinpath(\"foo\", \"__init__.py\").touch()\n    tmp_path.joinpath(\"foo\", \"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            import pytest\n            @pytest.fixture\n            def fix(): return None\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    tmp_path.joinpath(\"foo\", \"test_it.py\").write_text(\n        \"def test_it(fix): pass\", encoding=\"utf-8\"\n    )\n    result = pytester.runpytest(\"--pyargs\", \"foo\")\n    assert result.ret == 0\n\n\ndef test_conftest_symlink(pytester: Pytester) -> None:\n    \"\"\"`conftest.py` discovery follows normal path resolution and does not resolve symlinks.\"\"\"\n    # Structure:\n    # /real\n    # /real/conftest.py\n    # /real/app\n    # /real/app/tests\n    # /real/app/tests/test_foo.py\n\n    # Links:\n    # /symlinktests -> /real/app/tests (running at symlinktests should fail)\n    # /symlink -> /real (running at /symlink should work)\n\n    real = pytester.mkdir(\"real\")\n    realtests = real.joinpath(\"app/tests\")\n    realtests.mkdir(parents=True)\n    symlink_or_skip(realtests, pytester.path.joinpath(\"symlinktests\"))\n    symlink_or_skip(real, pytester.path.joinpath(\"symlink\"))\n    pytester.makepyfile(\n        **{\n            \"real/app/tests/test_foo.py\": \"def test1(fixture): pass\",\n            \"real/conftest.py\": textwrap.dedent(\n                \"\"\"\n                import pytest\n\n                print(\"conftest_loaded\")\n\n                @pytest.fixture\n                def fixture():\n                    print(\"fixture_used\")\n                \"\"\"\n            ),\n        }\n    )\n\n    # Should fail because conftest cannot be found from the link structure.\n    result = pytester.runpytest(\"-vs\", \"symlinktests\")\n    result.stdout.fnmatch_lines([\"*fixture 'fixture' not found*\"])\n    assert result.ret == ExitCode.TESTS_FAILED\n\n    # Should not cause \"ValueError: Plugin already registered\" (#4174).\n    result = pytester.runpytest(\"-vs\", \"symlink\")\n    assert result.ret == ExitCode.OK\n\n\ndef test_conftest_symlink_files(pytester: Pytester) -> None:\n    \"\"\"Symlinked conftest.py are found when pytest is executed in a directory with symlinked\n    files.\"\"\"\n    real = pytester.mkdir(\"real\")\n    source = {\n        \"app/test_foo.py\": \"def test1(fixture): pass\",\n        \"app/__init__.py\": \"\",\n        \"app/conftest.py\": textwrap.dedent(\n            \"\"\"\n            import pytest\n\n            print(\"conftest_loaded\")\n\n            @pytest.fixture\n            def fixture():\n                print(\"fixture_used\")\n            \"\"\"\n        ),\n    }\n    pytester.makepyfile(**{f\"real/{k}\": v for k, v in source.items()})\n\n    # Create a build directory that contains symlinks to actual files\n    # but doesn't symlink actual directories.\n    build = pytester.mkdir(\"build\")\n    build.joinpath(\"app\").mkdir()\n    for f in source:\n        symlink_or_skip(real.joinpath(f), build.joinpath(f))\n    os.chdir(build)\n    result = pytester.runpytest(\"-vs\", \"app/test_foo.py\")\n    result.stdout.fnmatch_lines([\"*conftest_loaded*\", \"PASSED\"])\n    assert result.ret == ExitCode.OK\n\n\n@pytest.mark.skipif(\n    os.path.normcase(\"x\") != os.path.normcase(\"X\"),\n    reason=\"only relevant for case-insensitive file systems\",\n)\ndef test_conftest_badcase(pytester: Pytester) -> None:\n    \"\"\"Check conftest.py loading when directory casing is wrong (#5792).\"\"\"\n    pytester.path.joinpath(\"JenkinsRoot/test\").mkdir(parents=True)\n    source = {\"setup.py\": \"\", \"test/__init__.py\": \"\", \"test/conftest.py\": \"\"}\n    pytester.makepyfile(**{f\"JenkinsRoot/{k}\": v for k, v in source.items()})\n\n    os.chdir(pytester.path.joinpath(\"jenkinsroot/test\"))\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_conftest_uppercase(pytester: Pytester) -> None:\n    \"\"\"Check conftest.py whose qualified name contains uppercase characters (#5819)\"\"\"\n    source = {\"__init__.py\": \"\", \"Foo/conftest.py\": \"\", \"Foo/__init__.py\": \"\"}\n    pytester.makepyfile(**source)\n\n    os.chdir(pytester.path)\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_no_conftest(pytester: Pytester) -> None:\n    pytester.makeconftest(\"assert 0\")\n    result = pytester.runpytest(\"--noconftest\")\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.USAGE_ERROR\n\n\ndef test_conftest_existing_junitxml(pytester: Pytester) -> None:\n    x = pytester.mkdir(\"tests\")\n    x.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            def pytest_addoption(parser):\n                parser.addoption(\"--xyz\", action=\"store_true\")\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    pytester.makefile(ext=\".xml\", junit=\"\")  # Writes junit.xml\n    result = pytester.runpytest(\"-h\", \"--junitxml\", \"junit.xml\")\n    result.stdout.fnmatch_lines([\"*--xyz*\"])\n\n\ndef test_conftest_import_order(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n    ct1 = pytester.makeconftest(\"\")\n    sub = pytester.mkdir(\"sub\")\n    ct2 = sub / \"conftest.py\"\n    ct2.write_text(\"\", encoding=\"utf-8\")\n\n    def impct(p, importmode, root, consider_namespace_packages):\n        return p\n\n    conftest = PytestPluginManager()\n    conftest._confcutdir = pytester.path\n    monkeypatch.setattr(conftest, \"_importconftest\", impct)\n    conftest._loadconftestmodules(\n        sub,\n        importmode=\"prepend\",\n        rootpath=pytester.path,\n        consider_namespace_packages=False,\n    )\n    mods = cast(list[Path], conftest._getconftestmodules(sub))\n    expected = [ct1, ct2]\n    assert mods == expected\n\n\ndef test_fixture_dependency(pytester: Pytester) -> None:\n    pytester.makeconftest(\"\")\n    pytester.path.joinpath(\"__init__.py\").touch()\n    sub = pytester.mkdir(\"sub\")\n    sub.joinpath(\"__init__.py\").touch()\n    sub.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            import pytest\n\n            @pytest.fixture\n            def not_needed():\n                assert False, \"Should not be called!\"\n\n            @pytest.fixture\n            def foo():\n                assert False, \"Should not be called!\"\n\n            @pytest.fixture\n            def bar(foo):\n                return 'bar'\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    subsub = sub.joinpath(\"subsub\")\n    subsub.mkdir()\n    subsub.joinpath(\"__init__.py\").touch()\n    subsub.joinpath(\"test_bar.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            import pytest\n\n            @pytest.fixture\n            def bar():\n                return 'sub bar'\n\n            def test_event_fixture(bar):\n                assert bar == 'sub bar'\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    result = pytester.runpytest(\"sub\")\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_conftest_found_with_double_dash(pytester: Pytester) -> None:\n    sub = pytester.mkdir(\"sub\")\n    sub.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            def pytest_addoption(parser):\n                parser.addoption(\"--hello-world\", action=\"store_true\")\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    p = sub.joinpath(\"test_hello.py\")\n    p.write_text(\"def test_hello(): pass\", encoding=\"utf-8\")\n    result = pytester.runpytest(str(p) + \"::test_hello\", \"-h\")\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        *--hello-world*\n    \"\"\"\n    )\n\n\nclass TestConftestVisibility:\n    def _setup_tree(self, pytester: Pytester) -> dict[str, Path]:  # for issue616\n        # example mostly taken from:\n        # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html\n        runner = pytester.mkdir(\"empty\")\n        package = pytester.mkdir(\"package\")\n\n        package.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n                @pytest.fixture\n                def fxtr():\n                    return \"from-package\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        package.joinpath(\"test_pkgroot.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                def test_pkgroot(fxtr):\n                    assert fxtr == \"from-package\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        swc = package.joinpath(\"swc\")\n        swc.mkdir()\n        swc.joinpath(\"__init__.py\").touch()\n        swc.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import pytest\n                @pytest.fixture\n                def fxtr():\n                    return \"from-swc\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        swc.joinpath(\"test_with_conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                def test_with_conftest(fxtr):\n                    assert fxtr == \"from-swc\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        snc = package.joinpath(\"snc\")\n        snc.mkdir()\n        snc.joinpath(\"__init__.py\").touch()\n        snc.joinpath(\"test_no_conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                def test_no_conftest(fxtr):\n                    assert fxtr == \"from-package\"   # No local conftest.py, so should\n                                                    # use value from parent dir's\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        print(\"created directory structure:\")\n        for x in pytester.path.glob(\"**/\"):\n            print(\"   \" + str(x.relative_to(pytester.path)))\n\n        return {\"runner\": runner, \"package\": package, \"swc\": swc, \"snc\": snc}\n\n    # N.B.: \"swc\" stands for \"subdir with conftest.py\"\n    #       \"snc\" stands for \"subdir no [i.e. without] conftest.py\"\n    @pytest.mark.parametrize(\n        \"chdir,testarg,expect_ntests_passed\",\n        [\n            # Effective target: package/..\n            (\"runner\", \"..\", 3),\n            (\"package\", \"..\", 3),\n            (\"swc\", \"../..\", 3),\n            (\"snc\", \"../..\", 3),\n            # Effective target: package\n            (\"runner\", \"../package\", 3),\n            (\"package\", \".\", 3),\n            (\"swc\", \"..\", 3),\n            (\"snc\", \"..\", 3),\n            # Effective target: package/swc\n            (\"runner\", \"../package/swc\", 1),\n            (\"package\", \"./swc\", 1),\n            (\"swc\", \".\", 1),\n            (\"snc\", \"../swc\", 1),\n            # Effective target: package/snc\n            (\"runner\", \"../package/snc\", 1),\n            (\"package\", \"./snc\", 1),\n            (\"swc\", \"../snc\", 1),\n            (\"snc\", \".\", 1),\n        ],\n    )\n    def test_parsefactories_relative_node_ids(\n        self, pytester: Pytester, chdir: str, testarg: str, expect_ntests_passed: int\n    ) -> None:\n        \"\"\"#616\"\"\"\n        dirs = self._setup_tree(pytester)\n        print(f\"pytest run in cwd: {dirs[chdir].relative_to(pytester.path)}\")\n        print(f\"pytestarg        : {testarg}\")\n        print(f\"expected pass    : {expect_ntests_passed}\")\n        os.chdir(dirs[chdir])\n        reprec = pytester.inline_run(\n            testarg,\n            \"-q\",\n            \"--traceconfig\",\n            \"--confcutdir\",\n            pytester.path,\n        )\n        reprec.assertoutcome(passed=expect_ntests_passed)\n\n\n@pytest.mark.parametrize(\n    \"confcutdir,passed,error\", [(\".\", 2, 0), (\"src\", 1, 1), (None, 1, 1)]\n)\ndef test_search_conftest_up_to_inifile(\n    pytester: Pytester, confcutdir: str, passed: int, error: int\n) -> None:\n    \"\"\"Test that conftest files are detected only up to a configuration file, unless\n    an explicit --confcutdir option is given.\n    \"\"\"\n    root = pytester.path\n    src = root.joinpath(\"src\")\n    src.mkdir()\n    src.joinpath(\"pytest.ini\").write_text(\"[pytest]\", encoding=\"utf-8\")\n    src.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            import pytest\n            @pytest.fixture\n            def fix1(): pass\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    src.joinpath(\"test_foo.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            def test_1(fix1):\n                pass\n            def test_2(out_of_reach):\n                pass\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    root.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            import pytest\n            @pytest.fixture\n            def out_of_reach(): pass\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n\n    args = [str(src)]\n    if confcutdir:\n        args = [f\"--confcutdir={root.joinpath(confcutdir)}\"]\n    result = pytester.runpytest(*args)\n    match = \"\"\n    if passed:\n        match += f\"*{passed} passed*\"\n    if error:\n        match += f\"*{error} error*\"\n    result.stdout.fnmatch_lines(match)\n\n\ndef test_issue1073_conftest_special_objects(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\\\n        class DontTouchMe(object):\n            def __getattr__(self, x):\n                raise Exception('cant touch me')\n\n        x = DontTouchMe()\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\\\n        def test_some():\n            pass\n        \"\"\"\n    )\n    res = pytester.runpytest()\n    assert res.ret == 0\n\n\ndef test_conftest_exception_handling(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\\\n        raise ValueError()\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\\\n        def test_some():\n            pass\n        \"\"\"\n    )\n    res = pytester.runpytest()\n    assert res.ret == 4\n    assert \"raise ValueError()\" in [line.strip() for line in res.errlines]\n\n\ndef test_hook_proxy(pytester: Pytester) -> None:\n    \"\"\"Session's gethookproxy() would cache conftests incorrectly (#2016).\n    It was decided to remove the cache altogether.\n    \"\"\"\n    pytester.makepyfile(\n        **{\n            \"root/demo-0/test_foo1.py\": \"def test1(): pass\",\n            \"root/demo-a/test_foo2.py\": \"def test1(): pass\",\n            \"root/demo-a/conftest.py\": \"\"\"\\\n            def pytest_ignore_collect(collection_path, config):\n                return True\n            \"\"\",\n            \"root/demo-b/test_foo3.py\": \"def test1(): pass\",\n            \"root/demo-c/test_foo4.py\": \"def test1(): pass\",\n        }\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\"*test_foo1.py*\", \"*test_foo3.py*\", \"*test_foo4.py*\", \"*3 passed*\"]\n    )\n\n\ndef test_required_option_help(pytester: Pytester) -> None:\n    pytester.makeconftest(\"assert 0\")\n    x = pytester.mkdir(\"x\")\n    x.joinpath(\"conftest.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n            def pytest_addoption(parser):\n                parser.addoption(\"--xyz\", action=\"store_true\", required=True)\n            \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    result = pytester.runpytest(\"-h\", x)\n    result.stdout.no_fnmatch_line(\"*argument --xyz is required*\")\n    assert \"general:\" in result.stdout.str()\n"
  },
  {
    "path": "testing/test_debugging.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport sys\n\nimport _pytest._code\nfrom _pytest.debugging import _validate_usepdb_cls\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\n@pytest.fixture(autouse=True)\ndef pdb_env(request):\n    if \"pytester\" in request.fixturenames:\n        # Disable pdb++ with inner tests.\n        pytester = request.getfixturevalue(\"pytester\")\n        pytester._monkeypatch.setenv(\"PDBPP_HIJACK_PDB\", \"0\")\n\n\ndef runpdb(pytester: Pytester, source: str):\n    p = pytester.makepyfile(source)\n    return pytester.runpytest_inprocess(\"--pdb\", p)\n\n\ndef runpdb_and_get_stdout(pytester: Pytester, source: str):\n    result = runpdb(pytester, source)\n    return result.stdout.str()\n\n\ndef runpdb_and_get_report(pytester: Pytester, source: str):\n    result = runpdb(pytester, source)\n    reports = result.reprec.getreports(\"pytest_runtest_logreport\")\n    assert len(reports) == 3, reports  # setup/call/teardown\n    return reports[1]\n\n\n@pytest.fixture\ndef custom_pdb_calls() -> list[str]:\n    called = []\n\n    # install dummy debugger class and track which methods were called on it\n    class _CustomPdb:\n        quitting = False\n\n        def __init__(self, *args, **kwargs):\n            called.append(\"init\")\n\n        def reset(self):\n            called.append(\"reset\")\n\n        def interaction(self, *args):\n            called.append(\"interaction\")\n\n        # Methods which we copy docstrings to.\n        def do_debug(self, *args):  # pragma: no cover\n            pass\n\n        def do_continue(self, *args):  # pragma: no cover\n            pass\n\n        def do_quit(self, *args):  # pragma: no cover\n            pass\n\n    _pytest._CustomPdb = _CustomPdb  # type: ignore\n    return called\n\n\n@pytest.fixture\ndef custom_debugger_hook():\n    called = []\n\n    # install dummy debugger class and track which methods were called on it\n    class _CustomDebugger:\n        def __init__(self, *args, **kwargs):\n            called.append(\"init\")\n\n        def reset(self):\n            called.append(\"reset\")\n\n        def interaction(self, *args):\n            called.append(\"interaction\")\n\n        def set_trace(self, frame):\n            print(\"**CustomDebugger**\")\n            called.append(\"set_trace\")\n\n        # Methods which we copy docstrings to.\n        def do_debug(self, *args):  # pragma: no cover\n            pass\n\n        def do_continue(self, *args):  # pragma: no cover\n            pass\n\n        def do_quit(self, *args):  # pragma: no cover\n            pass\n\n    _pytest._CustomDebugger = _CustomDebugger  # type: ignore\n    yield called\n    del _pytest._CustomDebugger  # type: ignore\n\n\nclass TestPDB:\n    @pytest.fixture\n    def pdblist(self, request):\n        monkeypatch = request.getfixturevalue(\"monkeypatch\")\n        pdblist = []\n\n        def mypdb(*args):\n            pdblist.append(args)\n\n        plugin = request.config.pluginmanager.getplugin(\"debugging\")\n        monkeypatch.setattr(plugin, \"post_mortem\", mypdb)\n        return pdblist\n\n    def test_pdb_on_fail(self, pytester: Pytester, pdblist) -> None:\n        rep = runpdb_and_get_report(\n            pytester,\n            \"\"\"\n            def test_func():\n                assert 0\n        \"\"\",\n        )\n        assert rep.failed\n        assert len(pdblist) == 1\n        if sys.version_info < (3, 13):\n            tb = _pytest._code.Traceback(pdblist[0][0])\n        else:\n            tb = _pytest._code.Traceback(pdblist[0][0].__traceback__)\n        assert tb[-1].name == \"test_func\"\n\n    def test_pdb_on_xfail(self, pytester: Pytester, pdblist) -> None:\n        rep = runpdb_and_get_report(\n            pytester,\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail\n            def test_func():\n                assert 0\n        \"\"\",\n        )\n        assert \"xfail\" in rep.keywords\n        assert not pdblist\n\n    def test_pdb_on_skip(self, pytester, pdblist) -> None:\n        rep = runpdb_and_get_report(\n            pytester,\n            \"\"\"\n            import pytest\n            def test_func():\n                pytest.skip(\"hello\")\n        \"\"\",\n        )\n        assert rep.skipped\n        assert len(pdblist) == 0\n\n    def test_pdb_on_top_level_raise_skiptest(self, pytester, pdblist) -> None:\n        stdout = runpdb_and_get_stdout(\n            pytester,\n            \"\"\"\n            import unittest\n            raise unittest.SkipTest(\"This is a common way to skip an entire file.\")\n        \"\"\",\n        )\n        assert \"entering PDB\" not in stdout, stdout\n\n    def test_pdb_on_BdbQuit(self, pytester, pdblist) -> None:\n        rep = runpdb_and_get_report(\n            pytester,\n            \"\"\"\n            import bdb\n            def test_func():\n                raise bdb.BdbQuit\n        \"\"\",\n        )\n        assert rep.failed\n        assert len(pdblist) == 0\n\n    def test_pdb_on_KeyboardInterrupt(self, pytester, pdblist) -> None:\n        rep = runpdb_and_get_report(\n            pytester,\n            \"\"\"\n            def test_func():\n                raise KeyboardInterrupt\n        \"\"\",\n        )\n        assert rep.failed\n        assert len(pdblist) == 1\n\n    @staticmethod\n    def flush(child):\n        if child.isalive():\n            # Read if the test has not (e.g. test_pdb_unittest_skip).\n            child.read()\n            child.wait()\n        assert not child.isalive()\n\n    def test_pdb_unittest_postmortem(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import unittest\n            class Blub(unittest.TestCase):\n                def tearDown(self):\n                    self.filename = None\n                def test_false(self):\n                    self.filename = 'debug' + '.me'\n                    assert 0\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--pdb {p1}\")\n        child.expect(\"Pdb\")\n        child.sendline(\"p self.filename\")\n        child.sendeof()\n        rest = child.read().decode(\"utf8\")\n        assert \"debug.me\" in rest\n        self.flush(child)\n\n    def test_pdb_unittest_skip(self, pytester: Pytester) -> None:\n        \"\"\"Test for issue #2137\"\"\"\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import unittest\n            @unittest.skipIf(True, 'Skipping also with pdb active')\n            class MyTestCase(unittest.TestCase):\n                def test_one(self):\n                    assert 0\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"-rs --pdb {p1}\")\n        child.expect(\"Skipping also with pdb active\")\n        child.expect_exact(\"= 1 skipped in\")\n        child.sendeof()\n        self.flush(child)\n\n    def test_pdb_print_captured_stdout_and_stderr(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                import sys\n                sys.stderr.write(\"get\\\\x20rekt\")\n                print(\"get\\\\x20rekt\")\n                assert False\n\n            def test_not_called_due_to_quit():\n                pass\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--pdb {p1}\")\n        child.expect(\"captured stdout\")\n        child.expect(\"get rekt\")\n        child.expect(\"captured stderr\")\n        child.expect(\"get rekt\")\n        child.expect(\"traceback\")\n        child.expect(\"def test_1\")\n        child.expect(\"Pdb\")\n        child.sendeof()\n        rest = child.read().decode(\"utf8\")\n        assert \"Exit: Quitting debugger\" in rest\n        assert \"= 1 failed in\" in rest\n        assert \"def test_1\" not in rest\n        assert \"get rekt\" not in rest\n        self.flush(child)\n\n    def test_pdb_dont_print_empty_captured_stdout_and_stderr(\n        self, pytester: Pytester\n    ) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                assert False\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--pdb {p1}\")\n        child.expect(\"Pdb\")\n        output = child.before.decode(\"utf8\")\n        child.sendeof()\n        assert \"captured stdout\" not in output\n        assert \"captured stderr\" not in output\n        self.flush(child)\n\n    @pytest.mark.parametrize(\"showcapture\", [\"all\", \"no\", \"log\"])\n    def test_pdb_print_captured_logs(self, pytester, showcapture: str) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                import logging\n                logging.warning(\"get \" + \"rekt\")\n                assert False\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--show-capture={showcapture} --pdb {p1}\")\n        if showcapture in (\"all\", \"log\"):\n            child.expect(\"captured log\")\n            child.expect(\"get rekt\")\n        child.expect(\"Pdb\")\n        child.sendeof()\n        rest = child.read().decode(\"utf8\")\n        assert \"1 failed\" in rest\n        self.flush(child)\n\n    def test_pdb_print_captured_logs_nologging(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                import logging\n                logging.warning(\"get \" + \"rekt\")\n                assert False\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--show-capture=all --pdb -p no:logging {p1}\")\n        child.expect(\"get rekt\")\n        output = child.before.decode(\"utf8\")\n        assert \"captured log\" not in output\n        child.expect(\"Pdb\")\n        child.sendeof()\n        rest = child.read().decode(\"utf8\")\n        assert \"1 failed\" in rest\n        self.flush(child)\n\n    def test_pdb_interaction_exception(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def globalfunc():\n                pass\n            def test_1():\n                pytest.raises(ValueError, globalfunc)\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--pdb {p1}\")\n        child.expect(\".*def test_1\")\n        child.expect(\".*pytest.raises.*globalfunc\")\n        child.expect(\"Pdb\")\n        child.sendline(\"globalfunc\")\n        child.expect(\".*function\")\n        child.sendeof()\n        child.expect(\"1 failed\")\n        self.flush(child)\n\n    def test_pdb_interaction_on_collection_issue181(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            xxx\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--pdb {p1}\")\n        # child.expect(\".*import pytest.*\")\n        child.expect(\"Pdb\")\n        child.sendline(\"c\")\n        child.expect(\"1 error\")\n        self.flush(child)\n\n    def test_pdb_interaction_on_internal_error(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_runtest_protocol():\n                0/0\n        \"\"\"\n        )\n        p1 = pytester.makepyfile(\"def test_func(): pass\")\n        child = pytester.spawn_pytest(f\"--pdb {p1}\")\n        child.expect(\"Pdb\")\n\n        # INTERNALERROR is only displayed once via terminal reporter.\n        assert (\n            len(\n                [\n                    x\n                    for x in child.before.decode().splitlines()\n                    if x.startswith(\"INTERNALERROR> Traceback\")\n                ]\n            )\n            == 1\n        )\n\n        child.sendeof()\n        self.flush(child)\n\n    def test_pdb_prevent_ConftestImportFailure_hiding_exception(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\"def test_func(): pass\")\n        sub_dir = pytester.path.joinpath(\"ns\")\n        sub_dir.mkdir()\n        sub_dir.joinpath(\"conftest\").with_suffix(\".py\").write_text(\n            \"import unknown\", \"utf-8\"\n        )\n        sub_dir.joinpath(\"test_file\").with_suffix(\".py\").write_text(\n            \"def test_func(): pass\", \"utf-8\"\n        )\n\n        result = pytester.runpytest_subprocess(\"--pdb\", \".\")\n        result.stdout.fnmatch_lines([\"-> import unknown\"])\n\n    @pytest.mark.xfail(reason=\"#10042\", strict=False)\n    def test_pdb_interaction_capturing_simple(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_1():\n                i = 0\n                print(\"hello17\")\n                pytest.set_trace()\n                i == 1\n                assert 0\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(str(p1))\n        child.expect(r\"test_1\\(\\)\")\n        child.expect(\"i == 1\")\n        child.expect(\"Pdb\")\n        child.sendline(\"c\")\n        rest = child.read().decode(\"utf-8\")\n        assert \"AssertionError\" in rest\n        assert \"1 failed\" in rest\n        assert \"def test_1\" in rest\n        assert \"hello17\" in rest  # out is captured\n        self.flush(child)\n\n    def test_pdb_set_trace_kwargs(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_1():\n                i = 0\n                print(\"hello17\")\n                pytest.set_trace(header=\"== my_header ==\")\n                x = 3\n                assert 0\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(str(p1))\n        child.expect(\"== my_header ==\")\n        assert \"PDB set_trace\" not in child.before.decode()\n        child.expect(\"Pdb\")\n        child.sendline(\"c\")\n        rest = child.read().decode(\"utf-8\")\n        assert \"1 failed\" in rest\n        assert \"def test_1\" in rest\n        assert \"hello17\" in rest  # out is captured\n        self.flush(child)\n\n    def test_pdb_set_trace_interception(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pdb\n            def test_1():\n                pdb.set_trace()\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(str(p1))\n        child.expect(\"test_1\")\n        child.expect(\"Pdb\")\n        child.sendline(\"q\")\n        rest = child.read().decode(\"utf8\")\n        assert \"no tests ran\" in rest\n        assert \"reading from stdin while output\" not in rest\n        assert \"BdbQuit\" not in rest\n        self.flush(child)\n\n    def test_pdb_and_capsys(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_1(capsys):\n                print(\"hello1\")\n                pytest.set_trace()\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(str(p1))\n        child.expect(\"test_1\")\n        child.send(\"capsys.readouterr()\\n\")\n        child.expect(\"hello1\")\n        child.sendeof()\n        child.read()\n        self.flush(child)\n\n    def test_pdb_with_caplog_on_pdb_invocation(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_1(capsys, caplog):\n                import logging\n                logging.getLogger(__name__).warning(\"some_warning\")\n                assert 0\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--pdb {p1!s}\")\n        child.send(\"caplog.record_tuples\\n\")\n        child.expect_exact(\n            \"[('test_pdb_with_caplog_on_pdb_invocation', 30, 'some_warning')]\"\n        )\n        child.sendeof()\n        child.read()\n        self.flush(child)\n\n    def test_set_trace_capturing_afterwards(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pdb\n            def test_1():\n                pdb.set_trace()\n            def test_2():\n                print(\"hello\")\n                assert 0\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(str(p1))\n        child.expect(\"test_1\")\n        child.send(\"c\\n\")\n        child.expect(\"test_2\")\n        child.expect(\"Captured\")\n        child.expect(\"hello\")\n        child.sendeof()\n        child.read()\n        self.flush(child)\n\n    def test_pdb_interaction_doctest(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def function_1():\n                '''\n                >>> i = 0\n                >>> assert i == 1\n                '''\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--doctest-modules --pdb {p1}\")\n        child.expect(\"Pdb\")\n\n        assert \"UNEXPECTED EXCEPTION: AssertionError()\" in child.before.decode(\"utf8\")\n\n        child.sendline(\"'i=%i.' % i\")\n        child.expect(\"Pdb\")\n        assert \"\\r\\n'i=0.'\\r\\n\" in child.before.decode(\"utf8\")\n\n        child.sendeof()\n        rest = child.read().decode(\"utf8\")\n        assert \"! _pytest.outcomes.Exit: Quitting debugger !\" in rest\n        assert \"BdbQuit\" not in rest\n        assert \"1 failed\" in rest\n        self.flush(child)\n\n    def test_doctest_set_trace_quit(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def function_1():\n                '''\n                >>> __import__('pdb').set_trace()\n                '''\n        \"\"\"\n        )\n        # NOTE: does not use pytest.set_trace, but Python's patched pdb,\n        #       therefore \"-s\" is required.\n        child = pytester.spawn_pytest(f\"--doctest-modules --pdb -s {p1}\")\n        child.expect(\"Pdb\")\n        child.sendline(\"q\")\n        rest = child.read().decode(\"utf8\")\n\n        assert \"! _pytest.outcomes.Exit: Quitting debugger !\" in rest\n        assert \"= no tests ran in\" in rest\n        assert \"BdbQuit\" not in rest\n        assert \"UNEXPECTED EXCEPTION\" not in rest\n\n    @pytest.mark.xfail(reason=\"#10042\", strict=False)\n    def test_pdb_interaction_capturing_twice(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_1():\n                i = 0\n                print(\"hello17\")\n                pytest.set_trace()\n                x = 3\n                print(\"hello18\")\n                pytest.set_trace()\n                x = 4\n                assert 0\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(str(p1))\n        child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n        child.expect(\"test_1\")\n        child.expect(\"x = 3\")\n        child.expect(\"Pdb\")\n        child.sendline(\"c\")\n        child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n        child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n        child.expect(\"x = 4\")\n        child.expect(\"Pdb\")\n        child.sendline(\"c\")\n        child.expect(\"_ test_1 _\")\n        child.expect(\"def test_1\")\n        rest = child.read().decode(\"utf8\")\n        assert \"Captured stdout call\" in rest\n        assert \"hello17\" in rest  # out is captured\n        assert \"hello18\" in rest  # out is captured\n        assert \"1 failed\" in rest\n        self.flush(child)\n\n    @pytest.mark.xfail(reason=\"#10042\", strict=False)\n    def test_pdb_with_injected_do_debug(self, pytester: Pytester) -> None:\n        \"\"\"Simulates pdbpp, which injects Pdb into do_debug, and uses\n        self.__class__ in do_continue.\n        \"\"\"\n        p1 = pytester.makepyfile(\n            mytest=\"\"\"\n            import pdb\n            import pytest\n\n            count_continue = 0\n\n            class CustomPdb(pdb.Pdb, object):\n                def do_debug(self, arg):\n                    import sys\n                    import types\n\n                    do_debug_func = pdb.Pdb.do_debug\n\n                    newglobals = do_debug_func.__globals__.copy()\n                    newglobals['Pdb'] = self.__class__\n                    orig_do_debug = types.FunctionType(\n                        do_debug_func.__code__, newglobals,\n                        do_debug_func.__name__, do_debug_func.__defaults__,\n                    )\n                    return orig_do_debug(self, arg)\n                do_debug.__doc__ = pdb.Pdb.do_debug.__doc__\n\n                def do_continue(self, *args, **kwargs):\n                    global count_continue\n                    count_continue += 1\n                    return super(CustomPdb, self).do_continue(*args, **kwargs)\n\n            def foo():\n                print(\"print_from_foo\")\n\n            def test_1():\n                i = 0\n                print(\"hello17\")\n                pytest.set_trace()\n                x = 3\n                print(\"hello18\")\n\n                assert count_continue == 2, \"unexpected_failure: %d != 2\" % count_continue\n                pytest.fail(\"expected_failure\")\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--pdbcls=mytest:CustomPdb {p1!s}\")\n        child.expect(r\"PDB set_trace \\(IO-capturing turned off\\)\")\n        child.expect(r\"\\n\\(Pdb\")\n        child.sendline(\"debug foo()\")\n        child.expect(\"ENTERING RECURSIVE DEBUGGER\")\n        child.expect(r\"\\n\\(\\(Pdb\")\n        child.sendline(\"c\")\n        child.expect(\"LEAVING RECURSIVE DEBUGGER\")\n        assert b\"PDB continue\" not in child.before\n        # No extra newline.\n        assert child.before.endswith(b\"c\\r\\nprint_from_foo\\r\\n\")\n\n        # set_debug should not raise outcomes. Exit, if used recursively.\n        child.sendline(\"debug 42\")\n        child.sendline(\"q\")\n        child.expect(\"LEAVING RECURSIVE DEBUGGER\")\n        assert b\"ENTERING RECURSIVE DEBUGGER\" in child.before\n        assert b\"Quitting debugger\" not in child.before\n\n        child.sendline(\"c\")\n        child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n        rest = child.read().decode(\"utf8\")\n        assert \"hello17\" in rest  # out is captured\n        assert \"hello18\" in rest  # out is captured\n        assert \"1 failed\" in rest\n        assert \"Failed: expected_failure\" in rest\n        assert \"AssertionError: unexpected_failure\" not in rest\n        self.flush(child)\n\n    def test_pdb_without_capture(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_1():\n                pytest.set_trace()\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"-s {p1}\")\n        child.expect(r\">>> PDB set_trace >>>\")\n        child.expect(\"Pdb\")\n        child.sendline(\"c\")\n        child.expect(r\">>> PDB continue >>>\")\n        child.expect(\"1 passed\")\n        self.flush(child)\n\n    @pytest.mark.parametrize(\"capture_arg\", (\"\", \"-s\", \"-p no:capture\"))\n    def test_pdb_continue_with_recursive_debug(\n        self, capture_arg, pytester: Pytester\n    ) -> None:\n        \"\"\"Full coverage for do_debug without capturing.\n\n        This is very similar to test_pdb_interaction_continue_recursive in general,\n        but mocks out ``pdb.set_trace`` for providing more coverage.\n        \"\"\"\n        p1 = pytester.makepyfile(\n            \"\"\"\n            try:\n                input = raw_input\n            except NameError:\n                pass\n\n            def set_trace():\n                __import__('pdb').set_trace()\n\n            def test_1(monkeypatch):\n                import _pytest.debugging\n\n                class pytestPDBTest(_pytest.debugging.pytestPDB):\n                    @classmethod\n                    def set_trace(cls, *args, **kwargs):\n                        # Init PytestPdbWrapper to handle capturing.\n                        _pdb = cls._init_pdb(\"set_trace\", *args, **kwargs)\n\n                        # Mock out pdb.Pdb.do_continue.\n                        import pdb\n                        pdb.Pdb.do_continue = lambda self, arg: None\n\n                        print(\"===\" + \" SET_TRACE ===\")\n                        assert input() == \"debug set_trace()\"\n\n                        # Simulate PytestPdbWrapper.do_debug\n                        cls._recursive_debug += 1\n                        print(\"ENTERING RECURSIVE DEBUGGER\")\n                        print(\"===\" + \" SET_TRACE_2 ===\")\n\n                        assert input() == \"c\"\n                        _pdb.do_continue(\"\")\n                        print(\"===\" + \" SET_TRACE_3 ===\")\n\n                        # Simulate PytestPdbWrapper.do_debug\n                        print(\"LEAVING RECURSIVE DEBUGGER\")\n                        cls._recursive_debug -= 1\n\n                        print(\"===\" + \" SET_TRACE_4 ===\")\n                        assert input() == \"c\"\n                        _pdb.do_continue(\"\")\n\n                    def do_continue(self, arg):\n                        print(\"=== do_continue\")\n\n                monkeypatch.setattr(_pytest.debugging, \"pytestPDB\", pytestPDBTest)\n\n                import pdb\n                monkeypatch.setattr(pdb, \"set_trace\", pytestPDBTest.set_trace)\n\n                set_trace()\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--tb=short {p1} {capture_arg}\")\n        child.expect(\"=== SET_TRACE ===\")\n        before = child.before.decode(\"utf8\")\n        if not capture_arg:\n            assert \">>> PDB set_trace (IO-capturing turned off) >>>\" in before\n        else:\n            assert \">>> PDB set_trace >>>\" in before\n        child.sendline(\"debug set_trace()\")\n        child.expect(\"=== SET_TRACE_2 ===\")\n        before = child.before.decode(\"utf8\")\n        assert \"\\r\\nENTERING RECURSIVE DEBUGGER\\r\\n\" in before\n        child.sendline(\"c\")\n        child.expect(\"=== SET_TRACE_3 ===\")\n\n        # No continue message with recursive debugging.\n        before = child.before.decode(\"utf8\")\n        assert \">>> PDB continue \" not in before\n\n        child.sendline(\"c\")\n        child.expect(\"=== SET_TRACE_4 ===\")\n        before = child.before.decode(\"utf8\")\n        assert \"\\r\\nLEAVING RECURSIVE DEBUGGER\\r\\n\" in before\n        child.sendline(\"c\")\n        rest = child.read().decode(\"utf8\")\n        if not capture_arg:\n            assert \"> PDB continue (IO-capturing resumed) >\" in rest\n        else:\n            assert \"> PDB continue >\" in rest\n        assert \"= 1 passed in\" in rest\n\n    def test_pdb_used_outside_test(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            pytest.set_trace()\n            x = 5\n        \"\"\"\n        )\n        if sys.version_info[:2] >= (3, 13):\n            break_line = \"pytest.set_trace()\"\n        else:\n            break_line = \"x = 5\"\n        child = pytester.spawn(f\"{sys.executable} {p1}\")\n        child.expect_exact(break_line)\n        child.expect_exact(\"Pdb\")\n        child.sendeof()\n        self.flush(child)\n\n    def test_pdb_used_in_generate_tests(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def pytest_generate_tests(metafunc):\n                pytest.set_trace()\n                x = 5\n            def test_foo(a):\n                pass\n        \"\"\"\n        )\n        if sys.version_info[:2] >= (3, 13):\n            break_line = \"pytest.set_trace()\"\n        else:\n            break_line = \"x = 5\"\n        child = pytester.spawn_pytest(str(p1))\n        child.expect_exact(break_line)\n        child.expect_exact(\"Pdb\")\n        child.sendeof()\n        self.flush(child)\n\n    def test_pdb_collection_failure_is_shown(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\"xxx\")\n        result = pytester.runpytest_subprocess(\"--pdb\", p1)\n        result.stdout.fnmatch_lines(\n            [\"E   NameError: *xxx*\", \"*! *Exit: Quitting debugger !*\"]  # due to EOF\n        )\n\n    @pytest.mark.parametrize(\"post_mortem\", (False, True))\n    def test_enter_leave_pdb_hooks_are_called(\n        self, post_mortem, pytester: Pytester\n    ) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            mypdb = None\n\n            def pytest_configure(config):\n                config.testing_verification = 'configured'\n\n            def pytest_enter_pdb(config, pdb):\n                assert config.testing_verification == 'configured'\n                print('enter_pdb_hook')\n\n                global mypdb\n                mypdb = pdb\n                mypdb.set_attribute = \"bar\"\n\n            def pytest_leave_pdb(config, pdb):\n                assert config.testing_verification == 'configured'\n                print('leave_pdb_hook')\n\n                global mypdb\n                assert mypdb is pdb\n                assert mypdb.set_attribute == \"bar\"\n        \"\"\"\n        )\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def test_set_trace():\n                pytest.set_trace()\n                assert 0\n\n            def test_post_mortem():\n                assert 0\n        \"\"\"\n        )\n        if post_mortem:\n            child = pytester.spawn_pytest(str(p1) + \" --pdb -s -k test_post_mortem\")\n        else:\n            child = pytester.spawn_pytest(str(p1) + \" -k test_set_trace\")\n        child.expect(\"enter_pdb_hook\")\n        child.sendline(\"c\")\n        if post_mortem:\n            child.expect(r\"PDB continue\")\n        else:\n            child.expect(r\"PDB continue \\(IO-capturing resumed\\)\")\n            child.expect(\"Captured stdout call\")\n        rest = child.read().decode(\"utf8\")\n        assert \"leave_pdb_hook\" in rest\n        assert \"1 failed\" in rest\n        self.flush(child)\n\n    def test_pdb_custom_cls(\n        self, pytester: Pytester, custom_pdb_calls: list[str]\n    ) -> None:\n        p1 = pytester.makepyfile(\"\"\"xxx \"\"\")\n        result = pytester.runpytest_inprocess(\n            \"--pdb\", \"--pdbcls=_pytest:_CustomPdb\", p1\n        )\n        result.stdout.fnmatch_lines([\"*NameError*xxx*\", \"*1 error*\"])\n        assert custom_pdb_calls == [\"init\", \"reset\", \"interaction\"]\n\n    def test_pdb_custom_cls_invalid(self, pytester: Pytester) -> None:\n        result = pytester.runpytest_inprocess(\"--pdbcls=invalid\")\n        result.stderr.fnmatch_lines(\n            [\n                \"*: error: argument --pdbcls: 'invalid' is not in the format 'modname:classname'\"\n            ]\n        )\n\n    def test_pdb_validate_usepdb_cls(self):\n        assert _validate_usepdb_cls(\"os.path:dirname.__name__\") == (\n            \"os.path\",\n            \"dirname.__name__\",\n        )\n\n        assert _validate_usepdb_cls(\"pdb:DoesNotExist\") == (\"pdb\", \"DoesNotExist\")\n\n    def test_pdb_custom_cls_without_pdb(\n        self, pytester: Pytester, custom_pdb_calls: list[str]\n    ) -> None:\n        p1 = pytester.makepyfile(\"\"\"xxx \"\"\")\n        result = pytester.runpytest_inprocess(\"--pdbcls=_pytest:_CustomPdb\", p1)\n        result.stdout.fnmatch_lines([\"*NameError*xxx*\", \"*1 error*\"])\n        assert custom_pdb_calls == []\n\n    def test_pdb_custom_cls_with_set_trace(\n        self,\n        pytester: Pytester,\n        monkeypatch: MonkeyPatch,\n    ) -> None:\n        pytester.makepyfile(\n            custom_pdb=\"\"\"\n            class CustomPdb(object):\n                def __init__(self, *args, **kwargs):\n                    skip = kwargs.pop(\"skip\")\n                    assert skip == [\"foo.*\"]\n                    print(\"__init__\")\n                    super(CustomPdb, self).__init__(*args, **kwargs)\n\n                def set_trace(*args, **kwargs):\n                    print('custom set_trace>')\n         \"\"\"\n        )\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def test_foo():\n                pytest.set_trace(skip=['foo.*'])\n        \"\"\"\n        )\n        monkeypatch.setenv(\"PYTHONPATH\", str(pytester.path))\n        child = pytester.spawn_pytest(f\"--pdbcls=custom_pdb:CustomPdb {p1!s}\")\n\n        child.expect(\"__init__\")\n        child.expect(\"custom set_trace>\")\n        self.flush(child)\n\n    @pytest.mark.skipif(\n        sys.version_info < (3, 13),\n        reason=\"Navigating exception chains was introduced in 3.13\",\n    )\n    def test_pdb_exception_chain_navigation(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def inner_raise():\n                is_inner = True\n                raise RuntimeError(\"Woops\")\n\n            def outer_raise():\n                is_inner = False\n                try:\n                    inner_raise()\n                except RuntimeError:\n                    raise RuntimeError(\"Woopsie\")\n\n            def test_1():\n                outer_raise()\n                assert True\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(f\"--pdb {p1}\")\n        child.expect(\"Pdb\")\n        child.sendline(\"is_inner\")\n        child.expect_exact(\"False\")\n        child.sendline(\"exceptions 0\")\n        child.sendline(\"is_inner\")\n        child.expect_exact(\"True\")\n        child.sendeof()\n        self.flush(child)\n\n    def test_pdb_wrapped_commands_docstrings(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                assert False\n            \"\"\"\n        )\n\n        child = pytester.spawn_pytest(f\"--pdb {p1}\")\n        child.expect(\"Pdb\")\n\n        # Verify no undocumented commands\n        child.sendline(\"help\")\n        child.expect(\"Documented commands\")\n        assert \"Undocumented commands\" not in child.before.decode()\n\n        child.sendline(\"help continue\")\n        child.expect(\"Continue execution\")\n        child.expect(\"Pdb\")\n\n        child.sendline(\"help debug\")\n        child.expect(\"Enter a recursive debugger\")\n        child.expect(\"Pdb\")\n\n        child.sendline(\"c\")\n        child.sendeof()\n        self.flush(child)\n\n\nclass TestDebuggingBreakpoints:\n    @pytest.mark.parametrize(\"arg\", [\"--pdb\", \"\"])\n    def test_sys_breakpointhook_configure_and_unconfigure(\n        self, pytester: Pytester, arg: str\n    ) -> None:\n        \"\"\"\n        Test that sys.breakpointhook is set to the custom Pdb class once configured, test that\n        hook is reset to system value once pytest has been unconfigured\n        \"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import sys\n            from pytest import hookimpl\n            from _pytest.debugging import pytestPDB\n\n            def pytest_configure(config):\n                config.add_cleanup(check_restored)\n\n            def check_restored():\n                assert sys.breakpointhook == sys.__breakpointhook__\n\n            def test_check():\n                assert sys.breakpointhook == pytestPDB.set_trace\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_nothing(): pass\n        \"\"\"\n        )\n        args = (arg,) if arg else ()\n        result = pytester.runpytest_subprocess(*args)\n        result.stdout.fnmatch_lines([\"*1 passed in *\"])\n\n    def test_pdb_custom_cls(\n        self, pytester: Pytester, custom_debugger_hook, monkeypatch: MonkeyPatch\n    ) -> None:\n        monkeypatch.delenv(\"PYTHONBREAKPOINT\", raising=False)\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_nothing():\n                breakpoint()\n        \"\"\"\n        )\n        result = pytester.runpytest_inprocess(\n            \"--pdb\", \"--pdbcls=_pytest:_CustomDebugger\", p1\n        )\n        result.stdout.fnmatch_lines([\"*CustomDebugger*\", \"*1 passed*\"])\n        assert custom_debugger_hook == [\"init\", \"set_trace\"]\n\n    @pytest.mark.parametrize(\"arg\", [\"--pdb\", \"\"])\n    def test_environ_custom_class(\n        self, pytester: Pytester, custom_debugger_hook, arg: str\n    ) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import os\n            import sys\n\n            os.environ['PYTHONBREAKPOINT'] = '_pytest._CustomDebugger.set_trace'\n\n            def pytest_configure(config):\n                config.add_cleanup(check_restored)\n\n            def check_restored():\n                assert sys.breakpointhook == sys.__breakpointhook__\n\n            def test_check():\n                import _pytest\n                assert sys.breakpointhook is _pytest._CustomDebugger.set_trace\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_nothing(): pass\n        \"\"\"\n        )\n        args = (arg,) if arg else ()\n        result = pytester.runpytest_subprocess(*args)\n        result.stdout.fnmatch_lines([\"*1 passed in *\"])\n\n    def test_sys_breakpoint_interception(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        monkeypatch.delenv(\"PYTHONBREAKPOINT\", raising=False)\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                breakpoint()\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(str(p1))\n        child.expect(\"test_1\")\n        child.expect(\"Pdb\")\n        child.sendline(\"quit\")\n        rest = child.read().decode(\"utf8\")\n        assert \"Quitting debugger\" in rest\n        assert \"reading from stdin while output\" not in rest\n        TestPDB.flush(child)\n\n    @pytest.mark.xfail(reason=\"#10042\", strict=False)\n    def test_pdb_not_altered(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pdb\n            def test_1():\n                pdb.set_trace()\n                assert 0\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(str(p1))\n        child.expect(\"test_1\")\n        child.expect(\"Pdb\")\n        child.sendline(\"c\")\n        rest = child.read().decode(\"utf8\")\n        assert \"1 failed\" in rest\n        assert \"reading from stdin while output\" not in rest\n        TestPDB.flush(child)\n\n\nclass TestTraceOption:\n    def test_trace_sets_breakpoint(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                assert True\n\n            def test_2():\n                pass\n\n            def test_3():\n                pass\n            \"\"\"\n        )\n        child = pytester.spawn_pytest(\"--trace \" + str(p1))\n        child.expect(\"test_1\")\n        child.expect(\"Pdb\")\n        child.sendline(\"c\")\n        child.expect(\"test_2\")\n        child.expect(\"Pdb\")\n        child.sendline(\"c\")\n        child.expect(\"test_3\")\n        child.expect(\"Pdb\")\n        child.sendline(\"q\")\n        child.expect_exact(\"Exit: Quitting debugger\")\n        rest = child.read().decode(\"utf8\")\n        assert \"= 2 passed in\" in rest\n        assert \"reading from stdin while output\" not in rest\n        # Only printed once - not on stderr.\n        assert \"Exit: Quitting debugger\" not in child.before.decode(\"utf8\")\n        TestPDB.flush(child)\n\n    def test_trace_with_parametrize_handles_shared_fixtureinfo(\n        self, pytester: Pytester\n    ) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.parametrize('myparam', [1,2])\n            def test_1(myparam, request):\n                assert myparam in (1, 2)\n                assert request.function.__name__ == \"test_1\"\n            @pytest.mark.parametrize('func', [1,2])\n            def test_func(func, request):\n                assert func in (1, 2)\n                assert request.function.__name__ == \"test_func\"\n            @pytest.mark.parametrize('myparam', [1,2])\n            def test_func_kw(myparam, request, func=\"func_kw\"):\n                assert myparam in (1, 2)\n                assert func == \"func_kw\"\n                assert request.function.__name__ == \"test_func_kw\"\n            \"\"\"\n        )\n        child = pytester.spawn_pytest(\"--trace \" + str(p1))\n        for func, argname in [\n            (\"test_1\", \"myparam\"),\n            (\"test_func\", \"func\"),\n            (\"test_func_kw\", \"myparam\"),\n        ]:\n            child.expect_exact(\"> PDB runcall (IO-capturing turned off) >\")\n            child.expect_exact(func)\n            child.expect_exact(\"Pdb\")\n            child.sendline(\"args\")\n            child.expect_exact(f\"{argname} = 1\\r\\n\")\n            child.expect_exact(\"Pdb\")\n            child.sendline(\"c\")\n            child.expect_exact(\"Pdb\")\n            child.sendline(\"args\")\n            child.expect_exact(f\"{argname} = 2\\r\\n\")\n            child.expect_exact(\"Pdb\")\n            child.sendline(\"c\")\n            child.expect_exact(\"> PDB continue (IO-capturing resumed) >\")\n        rest = child.read().decode(\"utf8\")\n        assert \"= 6 passed in\" in rest\n        assert \"reading from stdin while output\" not in rest\n        # Only printed once - not on stderr.\n        assert \"Exit: Quitting debugger\" not in child.before.decode(\"utf8\")\n        TestPDB.flush(child)\n\n\ndef test_trace_after_runpytest(pytester: Pytester) -> None:\n    \"\"\"Test that debugging's pytest_configure is reentrant.\"\"\"\n    p1 = pytester.makepyfile(\n        \"\"\"\n        from _pytest.debugging import pytestPDB\n\n        def test_outer(pytester) -> None:\n            assert len(pytestPDB._saved) == 1\n\n            pytester.makepyfile(\n                \\\"\"\"\n                from _pytest.debugging import pytestPDB\n\n                def test_inner():\n                    assert len(pytestPDB._saved) == 2\n                    print()\n                    print(\"test_inner_\" + \"end\")\n                \\\"\"\"\n            )\n\n            result = pytester.runpytest(\"-s\", \"-k\", \"test_inner\")\n            assert result.ret == 0\n\n            assert len(pytestPDB._saved) == 1\n    \"\"\"\n    )\n    result = pytester.runpytest_subprocess(\"-s\", \"-p\", \"pytester\", str(p1))\n    result.stdout.fnmatch_lines([\"test_inner_end\"])\n    assert result.ret == 0\n\n\ndef test_quit_with_swallowed_SystemExit(pytester: Pytester) -> None:\n    \"\"\"Test that debugging's pytest_configure is reentrant.\"\"\"\n    p1 = pytester.makepyfile(\n        \"\"\"\n        def call_pdb_set_trace():\n            __import__('pdb').set_trace()\n\n\n        def test_1():\n            try:\n                call_pdb_set_trace()\n            except SystemExit:\n                pass\n\n\n        def test_2():\n            pass\n    \"\"\"\n    )\n    child = pytester.spawn_pytest(str(p1))\n    child.expect(\"Pdb\")\n    child.sendline(\"q\")\n    child.expect_exact(\"Exit: Quitting debugger\")\n    rest = child.read().decode(\"utf8\")\n    assert \"no tests ran\" in rest\n    TestPDB.flush(child)\n\n\n@pytest.mark.parametrize(\"fixture\", (\"capfd\", \"capsys\"))\n@pytest.mark.xfail(reason=\"#10042\", strict=False)\ndef test_pdb_suspends_fixture_capturing(pytester: Pytester, fixture: str) -> None:\n    \"\"\"Using \"-s\" with pytest should suspend/resume fixture capturing.\"\"\"\n    p1 = pytester.makepyfile(\n        f\"\"\"\n        def test_inner({fixture}):\n            import sys\n\n            print(\"out_inner_before\")\n            sys.stderr.write(\"err_inner_before\\\\n\")\n\n            __import__(\"pdb\").set_trace()\n\n            print(\"out_inner_after\")\n            sys.stderr.write(\"err_inner_after\\\\n\")\n\n            out, err = {fixture}.readouterr()\n            assert out ==\"out_inner_before\\\\nout_inner_after\\\\n\"\n            assert err ==\"err_inner_before\\\\nerr_inner_after\\\\n\"\n        \"\"\"\n    )\n\n    child = pytester.spawn_pytest(str(p1) + \" -s\")\n\n    child.expect(\"Pdb\")\n    before = child.before.decode(\"utf8\")\n    assert (\n        f\"> PDB set_trace (IO-capturing turned off for fixture {fixture}) >\" in before\n    )\n\n    # Test that capturing is really suspended.\n    child.sendline(\"p 40 + 2\")\n    child.expect(\"Pdb\")\n    assert \"\\r\\n42\\r\\n\" in child.before.decode(\"utf8\")\n\n    child.sendline(\"c\")\n    rest = child.read().decode(\"utf8\")\n    assert \"out_inner\" not in rest\n    assert \"err_inner\" not in rest\n\n    TestPDB.flush(child)\n    assert child.exitstatus == 0\n    assert \"= 1 passed in\" in rest\n    assert f\"> PDB continue (IO-capturing resumed for fixture {fixture}) >\" in rest\n\n\ndef test_pdbcls_via_local_module(pytester: Pytester) -> None:\n    \"\"\"It should be imported in pytest_configure or later only.\"\"\"\n    p1 = pytester.makepyfile(\n        \"\"\"\n        def test():\n            print(\"before_set_trace\")\n            __import__(\"pdb\").set_trace()\n        \"\"\",\n        mypdb=\"\"\"\n        class Wrapped:\n            class MyPdb:\n                def set_trace(self, *args):\n                    print(\"set_trace_called\", args)\n\n                def runcall(self, *args, **kwds):\n                    print(\"runcall_called\", args, kwds)\n\n                # Methods which we copy the docstring over.\n                def do_debug(self, *args):\n                    pass\n\n                def do_continue(self, *args):\n                    pass\n\n                def do_quit(self, *args):\n                    pass\n        \"\"\",\n    )\n    result = pytester.runpytest(\n        str(p1), \"--pdbcls=really.invalid:Value\", syspathinsert=True\n    )\n    result.stdout.fnmatch_lines(\n        [\n            \"*= FAILURES =*\",\n            \"E * --pdbcls: could not import 'really.invalid:Value': No module named *really*\",\n        ]\n    )\n    assert result.ret == 1\n\n    result = pytester.runpytest(\n        str(p1), \"--pdbcls=mypdb:Wrapped.MyPdb\", syspathinsert=True\n    )\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*set_trace_called*\", \"* 1 passed in *\"])\n\n    # Ensure that it also works with --trace.\n    result = pytester.runpytest(\n        str(p1), \"--pdbcls=mypdb:Wrapped.MyPdb\", \"--trace\", syspathinsert=True\n    )\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*runcall_called*\", \"* 1 passed in *\"])\n\n\n@pytest.mark.xfail(\n    sys.version_info >= (3, 14),\n    reason=\"C-D now quits the test session, rather than failing the test. See https://github.com/python/cpython/issues/124703\",\n)\ndef test_raises_bdbquit_with_eoferror(pytester: Pytester) -> None:\n    \"\"\"It is not guaranteed that DontReadFromInput's read is called.\"\"\"\n    p1 = pytester.makepyfile(\n        \"\"\"\n        def input_without_read(*args, **kwargs):\n            raise EOFError()\n\n        def test(monkeypatch):\n            import builtins\n            monkeypatch.setattr(builtins, \"input\", input_without_read)\n            __import__('pdb').set_trace()\n        \"\"\"\n    )\n    result = pytester.runpytest(str(p1))\n    result.assert_outcomes(failed=1)\n    result.stdout.fnmatch_lines([\"E *BdbQuit\", \"*= 1 failed in*\"])\n    assert result.ret == 1\n\n\ndef test_pdb_wrapper_class_is_reused(pytester: Pytester) -> None:\n    p1 = pytester.makepyfile(\n        \"\"\"\n        def test():\n            __import__(\"pdb\").set_trace()\n            __import__(\"pdb\").set_trace()\n\n            import mypdb\n            instances = mypdb.instances\n            assert len(instances) == 2\n            assert instances[0].__class__ is instances[1].__class__\n        \"\"\",\n        mypdb=\"\"\"\n        instances = []\n\n        class MyPdb:\n            def __init__(self, *args, **kwargs):\n                instances.append(self)\n\n            def set_trace(self, *args):\n                print(\"set_trace_called\", args)\n\n            # Methods which we copy the docstring over.\n            def do_debug(self, *args):\n                pass\n\n            def do_continue(self, *args):\n                pass\n\n            def do_quit(self, *args):\n                pass\n        \"\"\",\n    )\n    result = pytester.runpytest(str(p1), \"--pdbcls=mypdb:MyPdb\", syspathinsert=True)\n    assert result.ret == 0\n    result.stdout.fnmatch_lines(\n        [\"*set_trace_called*\", \"*set_trace_called*\", \"* 1 passed in *\"]\n    )\n"
  },
  {
    "path": "testing/test_doctest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nimport inspect\nfrom pathlib import Path\nimport sys\nimport textwrap\n\nfrom _pytest.doctest import _get_checker\nfrom _pytest.doctest import _is_main_py\nfrom _pytest.doctest import _is_mocked\nfrom _pytest.doctest import _is_setup_py\nfrom _pytest.doctest import _patch_unwrap_mock_aware\nfrom _pytest.doctest import DoctestItem\nfrom _pytest.doctest import DoctestModule\nfrom _pytest.doctest import DoctestTextfile\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nclass TestDoctests:\n    def test_collect_testtextfile(self, pytester: Pytester):\n        w = pytester.maketxtfile(whatever=\"\")\n        checkfile = pytester.maketxtfile(\n            test_something=\"\"\"\n            alskdjalsdk\n            >>> i = 5\n            >>> i-1\n            4\n        \"\"\"\n        )\n\n        for x in (pytester.path, checkfile):\n            # print \"checking that %s returns custom items\" % (x,)\n            items, _reprec = pytester.inline_genitems(x)\n            assert len(items) == 1\n            assert isinstance(items[0], DoctestItem)\n            assert isinstance(items[0].parent, DoctestTextfile)\n        # Empty file has no items.\n        items, _reprec = pytester.inline_genitems(w)\n        assert len(items) == 0\n\n    def test_collect_module_empty(self, pytester: Pytester):\n        path = pytester.makepyfile(whatever=\"#\")\n        for p in (path, pytester.path):\n            items, _reprec = pytester.inline_genitems(p, \"--doctest-modules\")\n            assert len(items) == 0\n\n    def test_collect_module_single_modulelevel_doctest(self, pytester: Pytester):\n        path = pytester.makepyfile(whatever='\"\"\">>> pass\"\"\"')\n        for p in (path, pytester.path):\n            items, _reprec = pytester.inline_genitems(p, \"--doctest-modules\")\n            assert len(items) == 1\n            assert isinstance(items[0], DoctestItem)\n            assert isinstance(items[0].parent, DoctestModule)\n\n    def test_collect_module_two_doctest_one_modulelevel(self, pytester: Pytester):\n        path = pytester.makepyfile(\n            whatever=\"\"\"\n            '>>> x = None'\n            def my_func():\n                \">>> magic = 42 \"\n        \"\"\"\n        )\n        for p in (path, pytester.path):\n            items, _reprec = pytester.inline_genitems(p, \"--doctest-modules\")\n            assert len(items) == 2\n            assert isinstance(items[0], DoctestItem)\n            assert isinstance(items[1], DoctestItem)\n            assert isinstance(items[0].parent, DoctestModule)\n            assert items[0].parent is items[1].parent\n\n    @pytest.mark.parametrize(\"filename\", [\"__init__\", \"whatever\"])\n    def test_collect_module_two_doctest_no_modulelevel(\n        self,\n        pytester: Pytester,\n        filename: str,\n    ) -> None:\n        path = pytester.makepyfile(\n            **{\n                filename: \"\"\"\n            '# Empty'\n            def my_func():\n                \">>> magic = 42 \"\n            def useless():\n                '''\n                # This is a function\n                # >>> # it doesn't have any doctest\n                '''\n            def another():\n                '''\n                # This is another function\n                >>> import os # this one does have a doctest\n                '''\n            \"\"\",\n            },\n        )\n        for p in (path, pytester.path):\n            items, _reprec = pytester.inline_genitems(p, \"--doctest-modules\")\n            assert len(items) == 2\n            assert isinstance(items[0], DoctestItem)\n            assert isinstance(items[1], DoctestItem)\n            assert isinstance(items[0].parent, DoctestModule)\n            assert items[0].parent is items[1].parent\n\n    def test_simple_doctestfile(self, pytester: Pytester):\n        p = pytester.maketxtfile(\n            test_doc=\"\"\"\n            >>> x = 1\n            >>> x == 1\n            False\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p)\n        reprec.assertoutcome(failed=1)\n\n    def test_importmode(self, pytester: Pytester):\n        pytester.makepyfile(\n            **{\n                \"src/namespacepkg/innerpkg/__init__.py\": \"\",\n                \"src/namespacepkg/innerpkg/a.py\": \"\"\"\n                  def some_func():\n                    return 42\n                \"\"\",\n                \"src/namespacepkg/innerpkg/b.py\": \"\"\"\n                  from namespacepkg.innerpkg.a import some_func\n                  def my_func():\n                    '''\n                    >>> my_func()\n                    42\n                    '''\n                    return some_func()\n                \"\"\",\n            }\n        )\n        # For 'namespacepkg' to be considered a namespace package, its containing directory\n        # needs to be reachable from sys.path:\n        # https://packaging.python.org/en/latest/guides/packaging-namespace-packages\n        pytester.syspathinsert(pytester.path / \"src\")\n        reprec = pytester.inline_run(\"--doctest-modules\", \"--import-mode=importlib\")\n        reprec.assertoutcome(passed=1)\n\n    def test_new_pattern(self, pytester: Pytester):\n        p = pytester.maketxtfile(\n            xdoc=\"\"\"\n            >>> x = 1\n            >>> x == 1\n            False\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-glob=x*.txt\")\n        reprec.assertoutcome(failed=1)\n\n    def test_multiple_patterns(self, pytester: Pytester):\n        \"\"\"Test support for multiple --doctest-glob arguments (#1255).\"\"\"\n        pytester.maketxtfile(\n            xdoc=\"\"\"\n            >>> 1\n            1\n        \"\"\"\n        )\n        pytester.makefile(\n            \".foo\",\n            test=\"\"\"\n            >>> 1\n            1\n        \"\"\",\n        )\n        pytester.maketxtfile(\n            test_normal=\"\"\"\n            >>> 1\n            1\n        \"\"\"\n        )\n        expected = {\"xdoc.txt\", \"test.foo\", \"test_normal.txt\"}\n        assert {x.name for x in pytester.path.iterdir()} == expected\n        args = [\"--doctest-glob=xdoc*.txt\", \"--doctest-glob=*.foo\"]\n        result = pytester.runpytest(*args)\n        result.stdout.fnmatch_lines([\"*test.foo *\", \"*xdoc.txt *\", \"*2 passed*\"])\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*test_normal.txt *\", \"*1 passed*\"])\n\n    @pytest.mark.parametrize(\n        \"   test_string,    encoding\",\n        [(\"foo\", \"ascii\"), (\"öäü\", \"latin1\"), (\"öäü\", \"utf-8\")],\n    )\n    def test_encoding(self, pytester, test_string, encoding):\n        \"\"\"Test support for doctest_encoding ini option.\"\"\"\n        pytester.makeini(\n            f\"\"\"\n            [pytest]\n            doctest_encoding={encoding}\n        \"\"\"\n        )\n        doctest = f\"\"\"\n            >>> \"{test_string}\"\n            {test_string!r}\n        \"\"\"\n        fn = pytester.path / \"test_encoding.txt\"\n        fn.write_text(doctest, encoding=encoding)\n\n        result = pytester.runpytest()\n\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_doctest_unexpected_exception(self, pytester: Pytester):\n        pytester.maketxtfile(\n            \"\"\"\n            >>> i = 0\n            >>> 0 / i\n            2\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.stdout.fnmatch_lines(\n            [\n                \"test_doctest_unexpected_exception.txt F *\",\n                \"\",\n                \"*= FAILURES =*\",\n                \"*_ [[]doctest[]] test_doctest_unexpected_exception.txt _*\",\n                \"001 >>> i = 0\",\n                \"002 >>> 0 / i\",\n                \"UNEXPECTED EXCEPTION: ZeroDivisionError*\",\n                \"Traceback (most recent call last):\",\n                *(\n                    ('  File \"*/doctest.py\", line *, in __run', \"    *\")\n                    if sys.version_info <= (3, 14)\n                    else ()\n                ),\n                *((\" *^^^^*\", \" *\", \" *\") if sys.version_info[:2] == (3, 13) else ()),\n                '  File \"<doctest test_doctest_unexpected_exception.txt[1]>\", line 1, in <module>',\n                \"ZeroDivisionError: division by zero\",\n                \"*/test_doctest_unexpected_exception.txt:2: UnexpectedException\",\n            ],\n            consecutive=True,\n        )\n\n    def test_doctest_outcomes(self, pytester: Pytester):\n        pytester.maketxtfile(\n            test_skip=\"\"\"\n            >>> 1\n            1\n            >>> import pytest\n            >>> pytest.skip(\"\")\n            >>> 2\n            3\n            \"\"\",\n            test_xfail=\"\"\"\n            >>> import pytest\n            >>> pytest.xfail(\"xfail_reason\")\n            >>> foo\n            bar\n            \"\"\",\n            test_importorskip=\"\"\"\n            >>> import pytest\n            >>> pytest.importorskip(\"doesnotexist\")\n            >>> foo\n            bar\n            \"\"\",\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 3 items\",\n                \"\",\n                \"test_importorskip.txt s *\",\n                \"test_skip.txt s *\",\n                \"test_xfail.txt x *\",\n                \"\",\n                \"*= 2 skipped, 1 xfailed in *\",\n            ]\n        )\n\n    def test_docstring_partial_context_around_error(self, pytester: Pytester):\n        \"\"\"Test that we show some context before the actual line of a failing\n        doctest.\n        \"\"\"\n        pytester.makepyfile(\n            '''\n            def foo():\n                \"\"\"\n                text-line-1\n                text-line-2\n                text-line-3\n                text-line-4\n                text-line-5\n                text-line-6\n                text-line-7\n                text-line-8\n                text-line-9\n                text-line-10\n                text-line-11\n                >>> 1 + 1\n                3\n\n                text-line-after\n                \"\"\"\n        '''\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*docstring_partial_context_around_error*\",\n                \"005*text-line-3\",\n                \"006*text-line-4\",\n                \"013*text-line-11\",\n                \"014*>>> 1 + 1\",\n                \"Expected:\",\n                \"    3\",\n                \"Got:\",\n                \"    2\",\n            ]\n        )\n        # lines below should be trimmed out\n        result.stdout.no_fnmatch_line(\"*text-line-2*\")\n        result.stdout.no_fnmatch_line(\"*text-line-after*\")\n\n    def test_docstring_full_context_around_error(self, pytester: Pytester):\n        \"\"\"Test that we show the whole context before the actual line of a failing\n        doctest, provided that the context is up to 10 lines long.\n        \"\"\"\n        pytester.makepyfile(\n            '''\n            def foo():\n                \"\"\"\n                text-line-1\n                text-line-2\n\n                >>> 1 + 1\n                3\n                \"\"\"\n        '''\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*docstring_full_context_around_error*\",\n                \"003*text-line-1\",\n                \"004*text-line-2\",\n                \"006*>>> 1 + 1\",\n                \"Expected:\",\n                \"    3\",\n                \"Got:\",\n                \"    2\",\n            ]\n        )\n\n    def test_doctest_linedata_missing(self, pytester: Pytester):\n        pytester.path.joinpath(\"hello.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                class Fun(object):\n                    @property\n                    def test(self):\n                        '''\n                        >>> a = 1\n                        >>> 1/0\n                        '''\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.stdout.fnmatch_lines(\n            [\"*hello*\", \"006*>>> 1/0*\", \"*UNEXPECTED*ZeroDivision*\", \"*1 failed*\"]\n        )\n\n    def test_doctest_linedata_on_property(self, pytester: Pytester):\n        pytester.makepyfile(\n            \"\"\"\n            class Sample(object):\n                @property\n                def some_property(self):\n                    '''\n                    >>> Sample().some_property\n                    'another thing'\n                    '''\n                    return 'something'\n            \"\"\"\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*= FAILURES =*\",\n                \"*_ [[]doctest[]] test_doctest_linedata_on_property.Sample.some_property _*\",\n                \"004 \",\n                \"005 *>>> Sample().some_property\",\n                \"Expected:\",\n                \"    'another thing'\",\n                \"Got:\",\n                \"    'something'\",\n                \"\",\n                \"*/test_doctest_linedata_on_property.py:5: DocTestFailure\",\n                \"*= 1 failed in *\",\n            ]\n        )\n\n    def test_doctest_no_linedata_on_overridden_property(self, pytester: Pytester):\n        pytester.makepyfile(\n            \"\"\"\n            class Sample(object):\n                @property\n                def some_property(self):\n                    '''\n                    >>> Sample().some_property\n                    'another thing'\n                    '''\n                    return 'something'\n                some_property = property(some_property.__get__, None, None, some_property.__doc__)\n            \"\"\"\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*= FAILURES =*\",\n                \"*_ [[]doctest[]] test_doctest_no_linedata_on_overridden_property.Sample.some_property _*\",\n                \"EXAMPLE LOCATION UNKNOWN, not showing all tests of that example\",\n                \"[?][?][?] >>> Sample().some_property\",\n                \"Expected:\",\n                \"    'another thing'\",\n                \"Got:\",\n                \"    'something'\",\n                \"\",\n                \"*/test_doctest_no_linedata_on_overridden_property.py:None: DocTestFailure\",\n                \"*= 1 failed in *\",\n            ]\n        )\n\n    def test_doctest_unex_importerror_only_txt(self, pytester: Pytester):\n        pytester.maketxtfile(\n            \"\"\"\n            >>> import asdalsdkjaslkdjasd\n            >>>\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        # doctest is never executed because of error during hello.py collection\n        result.stdout.fnmatch_lines(\n            [\n                \"*>>> import asdals*\",\n                \"*UNEXPECTED*ModuleNotFoundError*\",\n                \"ModuleNotFoundError: No module named *asdal*\",\n            ]\n        )\n\n    def test_doctest_unex_importerror_with_module(self, pytester: Pytester):\n        pytester.path.joinpath(\"hello.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                import asdalsdkjaslkdjasd\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        pytester.maketxtfile(\n            \"\"\"\n            >>> import hello\n            >>>\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        # doctest is never executed because of error during hello.py collection\n        result.stdout.fnmatch_lines(\n            [\n                \"*ERROR collecting hello.py*\",\n                \"*ModuleNotFoundError: No module named *asdals*\",\n                \"*Interrupted: 1 error during collection*\",\n            ]\n        )\n\n    def test_doctestmodule(self, pytester: Pytester):\n        p = pytester.makepyfile(\n            \"\"\"\n            '''\n                >>> x = 1\n                >>> x == 1\n                False\n\n            '''\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-modules\")\n        reprec.assertoutcome(failed=1)\n\n    def test_doctest_cached_property(self, pytester: Pytester):\n        p = pytester.makepyfile(\n            \"\"\"\n            import functools\n\n            class Foo:\n                @functools.cached_property\n                def foo(self):\n                    '''\n                    >>> assert False, \"Tacos!\"\n                    '''\n                    ...\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"--doctest-modules\")\n        result.assert_outcomes(failed=1)\n        assert \"Tacos!\" in result.stdout.str()\n\n    def test_doctestmodule_external_and_issue116(self, pytester: Pytester):\n        p = pytester.mkpydir(\"hello\")\n        p.joinpath(\"__init__.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                def somefunc():\n                    '''\n                        >>> i = 0\n                        >>> i + 1\n                        2\n                    '''\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        result = pytester.runpytest(p, \"--doctest-modules\")\n        result.stdout.fnmatch_lines(\n            [\n                \"003 *>>> i = 0\",\n                \"004 *>>> i + 1\",\n                \"*Expected:\",\n                \"*    2\",\n                \"*Got:\",\n                \"*    1\",\n                \"*:4: DocTestFailure\",\n            ]\n        )\n\n    def test_txtfile_failing(self, pytester: Pytester):\n        p = pytester.maketxtfile(\n            \"\"\"\n            >>> i = 0\n            >>> i + 1\n            2\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-s\")\n        result.stdout.fnmatch_lines(\n            [\n                \"001 >>> i = 0\",\n                \"002 >>> i + 1\",\n                \"Expected:\",\n                \"    2\",\n                \"Got:\",\n                \"    1\",\n                \"*test_txtfile_failing.txt:2: DocTestFailure\",\n            ]\n        )\n\n    def test_txtfile_with_fixtures(self, pytester: Pytester):\n        p = pytester.maketxtfile(\n            \"\"\"\n            >>> p = getfixture('tmp_path')\n            >>> p.is_dir()\n            True\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p)\n        reprec.assertoutcome(passed=1)\n\n    def test_txtfile_with_usefixtures_in_ini(self, pytester: Pytester):\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            usefixtures = myfixture\n        \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def myfixture(monkeypatch):\n                monkeypatch.setenv(\"HELLO\", \"WORLD\")\n        \"\"\"\n        )\n\n        p = pytester.maketxtfile(\n            \"\"\"\n            >>> import os\n            >>> os.environ[\"HELLO\"]\n            'WORLD'\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p)\n        reprec.assertoutcome(passed=1)\n\n    def test_doctestmodule_with_fixtures(self, pytester: Pytester):\n        p = pytester.makepyfile(\n            \"\"\"\n            '''\n                >>> p = getfixture('tmp_path')\n                >>> p.is_dir()\n                True\n            '''\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-modules\")\n        reprec.assertoutcome(passed=1)\n\n    def test_doctestmodule_three_tests(self, pytester: Pytester):\n        p = pytester.makepyfile(\n            \"\"\"\n            '''\n            >>> p = getfixture('tmp_path')\n            >>> p.is_dir()\n            True\n            '''\n            def my_func():\n                '''\n                >>> magic = 42\n                >>> magic - 42\n                0\n                '''\n            def useless():\n                pass\n            def another():\n                '''\n                >>> import os\n                >>> os is os\n                True\n                '''\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-modules\")\n        reprec.assertoutcome(passed=3)\n\n    def test_doctestmodule_two_tests_one_fail(self, pytester: Pytester):\n        p = pytester.makepyfile(\n            \"\"\"\n            class MyClass(object):\n                def bad_meth(self):\n                    '''\n                    >>> magic = 42\n                    >>> magic\n                    0\n                    '''\n                def nice_meth(self):\n                    '''\n                    >>> magic = 42\n                    >>> magic - 42\n                    0\n                    '''\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-modules\")\n        reprec.assertoutcome(failed=1, passed=1)\n\n    def test_ignored_whitespace(self, pytester: Pytester):\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE\n        \"\"\"\n        )\n        p = pytester.makepyfile(\n            \"\"\"\n            class MyClass(object):\n                '''\n                >>> a = \"foo    \"\n                >>> print(a)\n                foo\n                '''\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-modules\")\n        reprec.assertoutcome(passed=1)\n\n    def test_non_ignored_whitespace(self, pytester: Pytester):\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            doctest_optionflags = ELLIPSIS\n        \"\"\"\n        )\n        p = pytester.makepyfile(\n            \"\"\"\n            class MyClass(object):\n                '''\n                >>> a = \"foo    \"\n                >>> print(a)\n                foo\n                '''\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-modules\")\n        reprec.assertoutcome(failed=1, passed=0)\n\n    def test_ignored_whitespace_glob(self, pytester: Pytester):\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            doctest_optionflags = ELLIPSIS NORMALIZE_WHITESPACE\n        \"\"\"\n        )\n        p = pytester.maketxtfile(\n            xdoc=\"\"\"\n            >>> a = \"foo    \"\n            >>> print(a)\n            foo\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-glob=x*.txt\")\n        reprec.assertoutcome(passed=1)\n\n    def test_non_ignored_whitespace_glob(self, pytester: Pytester):\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            doctest_optionflags = ELLIPSIS\n        \"\"\"\n        )\n        p = pytester.maketxtfile(\n            xdoc=\"\"\"\n            >>> a = \"foo    \"\n            >>> print(a)\n            foo\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-glob=x*.txt\")\n        reprec.assertoutcome(failed=1, passed=0)\n\n    def test_contains_unicode(self, pytester: Pytester):\n        \"\"\"Fix internal error with docstrings containing non-ascii characters.\"\"\"\n        pytester.makepyfile(\n            '''\\\n            def foo():\n                \"\"\"\n                >>> name = 'с' # not letter 'c' but instead Cyrillic 's'.\n                'anything'\n                \"\"\"\n            '''  # noqa: RUF001\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.stdout.fnmatch_lines([\"Got nothing\", \"* 1 failed in*\"])\n\n    def test_ignore_import_errors_on_doctest(self, pytester: Pytester):\n        p = pytester.makepyfile(\n            \"\"\"\n            import asdf\n\n            def add_one(x):\n                '''\n                >>> add_one(1)\n                2\n                '''\n                return x + 1\n        \"\"\"\n        )\n\n        reprec = pytester.inline_run(\n            p, \"--doctest-modules\", \"--doctest-ignore-import-errors\"\n        )\n        reprec.assertoutcome(skipped=1, failed=1, passed=0)\n\n    def test_junit_report_for_doctest(self, pytester: Pytester):\n        \"\"\"#713: Fix --junit-xml option when used with --doctest-modules.\"\"\"\n        p = pytester.makepyfile(\n            \"\"\"\n            def foo():\n                '''\n                >>> 1 + 1\n                3\n                '''\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-modules\", \"--junit-xml=junit.xml\")\n        reprec.assertoutcome(failed=1)\n\n    def test_unicode_doctest(self, pytester: Pytester):\n        \"\"\"\n        Test case for issue 2434: DecodeError on Python 2 when doctest contains non-ascii\n        characters.\n        \"\"\"\n        p = pytester.maketxtfile(\n            test_unicode_doctest=\"\"\"\n            .. doctest::\n\n                >>> print(\"Hi\\\\n\\\\nByé\")\n                Hi\n                ...\n                Byé\n                >>> 1 / 0  # Byé\n                1\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines(\n            [\"*UNEXPECTED EXCEPTION: ZeroDivisionError*\", \"*1 failed*\"]\n        )\n\n    def test_unicode_doctest_module(self, pytester: Pytester):\n        \"\"\"\n        Test case for issue 2434: DecodeError on Python 2 when doctest docstring\n        contains non-ascii characters.\n        \"\"\"\n        p = pytester.makepyfile(\n            test_unicode_doctest_module=\"\"\"\n            def fix_bad_unicode(text):\n                '''\n                    >>> print(fix_bad_unicode('Ãºnico'))\n                    único\n                '''\n                return \"único\"\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"--doctest-modules\")\n        result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n    def test_print_unicode_value(self, pytester: Pytester):\n        \"\"\"\n        Test case for issue 3583: Printing Unicode in doctest under Python 2.7\n        doesn't work\n        \"\"\"\n        p = pytester.maketxtfile(\n            test_print_unicode_value=r\"\"\"\n            Here is a doctest::\n\n                >>> print('\\xE5\\xE9\\xEE\\xF8\\xFC')\n                åéîøü\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n    def test_reportinfo(self, pytester: Pytester):\n        \"\"\"Make sure that DoctestItem.reportinfo() returns lineno.\"\"\"\n        p = pytester.makepyfile(\n            test_reportinfo=\"\"\"\n            def foo(x):\n                '''\n                    >>> foo('a')\n                    'b'\n                '''\n                return 'c'\n        \"\"\"\n        )\n        items, _reprec = pytester.inline_genitems(p, \"--doctest-modules\")\n        reportinfo = items[0].reportinfo()\n        assert reportinfo[1] == 1\n\n    def test_valid_setup_py(self, pytester: Pytester):\n        \"\"\"\n        Test to make sure that pytest ignores valid setup.py files when ran\n        with --doctest-modules\n        \"\"\"\n        p = pytester.makepyfile(\n            setup=\"\"\"\n            if __name__ == '__main__':\n                from setuptools import setup, find_packages\n                setup(name='sample',\n                      version='0.0',\n                      description='description',\n                      packages=find_packages()\n                )\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"--doctest-modules\")\n        result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n\n    def test_main_py_does_not_cause_import_errors(self, pytester: Pytester):\n        p = pytester.copy_example(\"doctest/main_py\")\n        result = pytester.runpytest(p, \"--doctest-modules\")\n        result.stdout.fnmatch_lines([\"*collected 2 items*\", \"*1 failed, 1 passed*\"])\n\n    def test_invalid_setup_py(self, pytester: Pytester):\n        \"\"\"\n        Test to make sure that pytest reads setup.py files that are not used\n        for python packages when ran with --doctest-modules\n        \"\"\"\n        p = pytester.makepyfile(\n            setup=\"\"\"\n            def test_foo():\n                return 'bar'\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"--doctest-modules\")\n        result.stdout.fnmatch_lines([\"*collected 1 item*\"])\n\n    def test_setup_module(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #12011 - setup_module not executed when running\n        with `--doctest-modules`.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            CONSTANT = 0\n\n            def setup_module():\n                global CONSTANT\n                CONSTANT = 1\n\n            def test():\n                assert CONSTANT == 1\n            \"\"\"\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        assert result.ret == 0\n        result.assert_outcomes(passed=1)\n\n\nclass TestLiterals:\n    @pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n    def test_allow_unicode(self, pytester, config_mode):\n        \"\"\"Test that doctests which output unicode work in all python versions\n        tested by pytest when the ALLOW_UNICODE option is used (either in\n        the configuration file or by an inline comment).\n        \"\"\"\n        if config_mode == \"ini\":\n            pytester.makeini(\n                \"\"\"\n            [pytest]\n            doctest_optionflags = ALLOW_UNICODE\n            \"\"\"\n            )\n            comment = \"\"\n        else:\n            comment = \"#doctest: +ALLOW_UNICODE\"\n\n        pytester.maketxtfile(\n            test_doc=f\"\"\"\n            >>> b'12'.decode('ascii') {comment}\n            '12'\n        \"\"\"\n        )\n        pytester.makepyfile(\n            foo=f\"\"\"\n            def foo():\n              '''\n              >>> b'12'.decode('ascii') {comment}\n              '12'\n              '''\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"--doctest-modules\")\n        reprec.assertoutcome(passed=2)\n\n    @pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n    def test_allow_bytes(self, pytester, config_mode):\n        \"\"\"Test that doctests which output bytes work in all python versions\n        tested by pytest when the ALLOW_BYTES option is used (either in\n        the configuration file or by an inline comment)(#1287).\n        \"\"\"\n        if config_mode == \"ini\":\n            pytester.makeini(\n                \"\"\"\n            [pytest]\n            doctest_optionflags = ALLOW_BYTES\n            \"\"\"\n            )\n            comment = \"\"\n        else:\n            comment = \"#doctest: +ALLOW_BYTES\"\n\n        pytester.maketxtfile(\n            test_doc=f\"\"\"\n            >>> b'foo'  {comment}\n            'foo'\n        \"\"\"\n        )\n        pytester.makepyfile(\n            foo=f\"\"\"\n            def foo():\n              '''\n              >>> b'foo'  {comment}\n              'foo'\n              '''\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"--doctest-modules\")\n        reprec.assertoutcome(passed=2)\n\n    def test_unicode_string(self, pytester: Pytester):\n        \"\"\"Test that doctests which output unicode fail in Python 2 when\n        the ALLOW_UNICODE option is not used. The same test should pass\n        in Python 3.\n        \"\"\"\n        pytester.maketxtfile(\n            test_doc=\"\"\"\n            >>> b'12'.decode('ascii')\n            '12'\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_bytes_literal(self, pytester: Pytester):\n        \"\"\"Test that doctests which output bytes fail in Python 3 when\n        the ALLOW_BYTES option is not used. (#1287).\n        \"\"\"\n        pytester.maketxtfile(\n            test_doc=\"\"\"\n            >>> b'foo'\n            'foo'\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(failed=1)\n\n    def test_number_re(self) -> None:\n        _number_re = _get_checker()._number_re  # type: ignore\n        for s in [\n            \"1.\",\n            \"+1.\",\n            \"-1.\",\n            \".1\",\n            \"+.1\",\n            \"-.1\",\n            \"0.1\",\n            \"+0.1\",\n            \"-0.1\",\n            \"1e5\",\n            \"+1e5\",\n            \"1e+5\",\n            \"+1e+5\",\n            \"1e-5\",\n            \"+1e-5\",\n            \"-1e-5\",\n            \"1.2e3\",\n            \"-1.2e-3\",\n        ]:\n            print(s)\n            m = _number_re.match(s)\n            assert m is not None\n            assert float(m.group()) == pytest.approx(float(s))\n        for s in [\"1\", \"abc\"]:\n            print(s)\n            assert _number_re.match(s) is None\n\n    @pytest.mark.parametrize(\"config_mode\", [\"ini\", \"comment\"])\n    def test_number_precision(self, pytester, config_mode):\n        \"\"\"Test the NUMBER option.\"\"\"\n        if config_mode == \"ini\":\n            pytester.makeini(\n                \"\"\"\n                [pytest]\n                doctest_optionflags = NUMBER\n                \"\"\"\n            )\n            comment = \"\"\n        else:\n            comment = \"#doctest: +NUMBER\"\n\n        pytester.maketxtfile(\n            test_doc=f\"\"\"\n\n            Scalars:\n\n            >>> import math\n            >>> math.pi {comment}\n            3.141592653589793\n            >>> math.pi {comment}\n            3.1416\n            >>> math.pi {comment}\n            3.14\n            >>> -math.pi {comment}\n            -3.14\n            >>> math.pi {comment}\n            3.\n            >>> 3. {comment}\n            3.0\n            >>> 3. {comment}\n            3.\n            >>> 3. {comment}\n            3.01\n            >>> 3. {comment}\n            2.99\n            >>> .299 {comment}\n            .3\n            >>> .301 {comment}\n            .3\n            >>> 951. {comment}\n            1e3\n            >>> 1049. {comment}\n            1e3\n            >>> -1049. {comment}\n            -1e3\n            >>> 1e3 {comment}\n            1e3\n            >>> 1e3 {comment}\n            1000.\n\n            Lists:\n\n            >>> [3.1415, 0.097, 13.1, 7, 8.22222e5, 0.598e-2] {comment}\n            [3.14, 0.1, 13., 7, 8.22e5, 6.0e-3]\n            >>> [[0.333, 0.667], [0.999, 1.333]] {comment}\n            [[0.33, 0.667], [0.999, 1.333]]\n            >>> [[[0.101]]] {comment}\n            [[[0.1]]]\n\n            Doesn't barf on non-numbers:\n\n            >>> 'abc' {comment}\n            'abc'\n            >>> None {comment}\n            \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    @pytest.mark.parametrize(\n        \"expression,output\",\n        [\n            # ints shouldn't match floats:\n            (\"3.0\", \"3\"),\n            (\"3e0\", \"3\"),\n            (\"1e3\", \"1000\"),\n            (\"3\", \"3.0\"),\n            # Rounding:\n            (\"3.1\", \"3.0\"),\n            (\"3.1\", \"3.2\"),\n            (\"3.1\", \"4.0\"),\n            (\"8.22e5\", \"810000.0\"),\n            # Only the actual output is rounded up, not the expected output:\n            (\"3.0\", \"2.98\"),\n            (\"1e3\", \"999\"),\n            # The current implementation doesn't understand that numbers inside\n            # strings shouldn't be treated as numbers:\n            pytest.param(\"'3.1416'\", \"'3.14'\", marks=pytest.mark.xfail),\n        ],\n    )\n    def test_number_non_matches(self, pytester, expression, output):\n        pytester.maketxtfile(\n            test_doc=f\"\"\"\n            >>> {expression} #doctest: +NUMBER\n            {output}\n            \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=0, failed=1)\n\n    def test_number_and_allow_unicode(self, pytester: Pytester):\n        pytester.maketxtfile(\n            test_doc=\"\"\"\n            >>> from collections import namedtuple\n            >>> T = namedtuple('T', 'a b c')\n            >>> T(a=0.2330000001, b=u'str', c=b'bytes') # doctest: +ALLOW_UNICODE, +ALLOW_BYTES, +NUMBER\n            T(a=0.233, b=u'str', c='bytes')\n            \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n\nclass TestDoctestSkips:\n    \"\"\"\n    If all examples in a doctest are skipped due to the SKIP option, then\n    the tests should be SKIPPED rather than PASSED. (#957)\n    \"\"\"\n\n    @pytest.fixture(params=[\"text\", \"module\"])\n    def makedoctest(self, pytester, request):\n        def makeit(doctest):\n            mode = request.param\n            if mode == \"text\":\n                pytester.maketxtfile(doctest)\n            else:\n                assert mode == \"module\"\n                pytester.makepyfile(f'\"\"\"\\n{doctest}\"\"\"')\n\n        return makeit\n\n    def test_one_skipped(self, pytester, makedoctest):\n        makedoctest(\n            \"\"\"\n            >>> 1 + 1  # doctest: +SKIP\n            2\n            >>> 2 + 2\n            4\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"--doctest-modules\")\n        reprec.assertoutcome(passed=1)\n\n    def test_one_skipped_failed(self, pytester, makedoctest):\n        makedoctest(\n            \"\"\"\n            >>> 1 + 1  # doctest: +SKIP\n            2\n            >>> 2 + 2\n            200\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"--doctest-modules\")\n        reprec.assertoutcome(failed=1)\n\n    def test_all_skipped(self, pytester, makedoctest):\n        makedoctest(\n            \"\"\"\n            >>> 1 + 1  # doctest: +SKIP\n            2\n            >>> 2 + 2  # doctest: +SKIP\n            200\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"--doctest-modules\")\n        reprec.assertoutcome(skipped=1)\n\n    def test_vacuous_all_skipped(self, pytester, makedoctest):\n        makedoctest(\"\")\n        reprec = pytester.inline_run(\"--doctest-modules\")\n        reprec.assertoutcome(passed=0, skipped=0)\n\n    def test_continue_on_failure(self, pytester: Pytester):\n        pytester.maketxtfile(\n            test_something=\"\"\"\n            >>> i = 5\n            >>> def foo():\n            ...     raise ValueError('error1')\n            >>> foo()\n            >>> i\n            >>> i + 2\n            7\n            >>> i + 1\n        \"\"\"\n        )\n        result = pytester.runpytest(\n            \"--doctest-modules\", \"--doctest-continue-on-failure\"\n        )\n        result.assert_outcomes(passed=0, failed=1)\n        # The lines that contains the failure are 4, 5, and 8.  The first one\n        # is a stack trace and the other two are mismatches.\n        result.stdout.fnmatch_lines(\n            [\"*4: UnexpectedException*\", \"*5: DocTestFailure*\", \"*8: DocTestFailure*\"]\n        )\n\n    def test_skipping_wrapped_test(self, pytester):\n        \"\"\"\n        Issue 8796: INTERNALERROR raised when skipping a decorated DocTest\n        through pytest_collection_modifyitems.\n        \"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            from _pytest.doctest import DoctestItem\n\n            def pytest_collection_modifyitems(config, items):\n                skip_marker = pytest.mark.skip()\n\n                for item in items:\n                    if isinstance(item, DoctestItem):\n                        item.add_marker(skip_marker)\n            \"\"\"\n        )\n\n        pytester.makepyfile(\n            \"\"\"\n            from contextlib import contextmanager\n\n            @contextmanager\n            def my_config_context():\n                '''\n                >>> import os\n                '''\n            \"\"\"\n        )\n\n        result = pytester.runpytest(\"--doctest-modules\")\n        assert \"INTERNALERROR\" not in result.stdout.str()\n        result.assert_outcomes(skipped=1)\n\n\nclass TestDoctestAutoUseFixtures:\n    SCOPES = [\"module\", \"session\", \"class\", \"function\"]\n\n    def test_doctest_module_session_fixture(self, pytester: Pytester):\n        \"\"\"Test that session fixtures are initialized for doctest modules (#768).\"\"\"\n        # session fixture which changes some global data, which will\n        # be accessed by doctests in a module\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            import sys\n\n            @pytest.fixture(autouse=True, scope='session')\n            def myfixture():\n                assert not hasattr(sys, 'pytest_session_data')\n                sys.pytest_session_data = 1\n                yield\n                del sys.pytest_session_data\n        \"\"\"\n        )\n        pytester.makepyfile(\n            foo=\"\"\"\n            import sys\n\n            def foo():\n              '''\n              >>> assert sys.pytest_session_data == 1\n              '''\n\n            def bar():\n              '''\n              >>> assert sys.pytest_session_data == 1\n              '''\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n    @pytest.mark.parametrize(\"scope\", SCOPES)\n    @pytest.mark.parametrize(\"enable_doctest\", [True, False])\n    def test_fixture_scopes(self, pytester, scope, enable_doctest):\n        \"\"\"Test that auto-use fixtures work properly with doctest modules.\n        See #1057 and #1100.\n        \"\"\"\n        pytester.makeconftest(\n            f\"\"\"\n            import pytest\n\n            @pytest.fixture(autouse=True, scope=\"{scope}\")\n            def auto(request):\n                return 99\n        \"\"\"\n        )\n        pytester.makepyfile(\n            test_1='''\n            def test_foo():\n                \"\"\"\n                >>> getfixture('auto') + 1\n                100\n                \"\"\"\n            def test_bar():\n                assert 1\n        '''\n        )\n        params = (\"--doctest-modules\",) if enable_doctest else ()\n        passes = 3 if enable_doctest else 2\n        result = pytester.runpytest(*params)\n        result.stdout.fnmatch_lines([f\"*=== {passes} passed in *\"])\n\n    @pytest.mark.parametrize(\"scope\", SCOPES)\n    @pytest.mark.parametrize(\"autouse\", [True, False])\n    @pytest.mark.parametrize(\"use_fixture_in_doctest\", [True, False])\n    def test_fixture_module_doctest_scopes(\n        self, pytester, scope, autouse, use_fixture_in_doctest\n    ):\n        \"\"\"Test that auto-use fixtures work properly with doctest files.\n        See #1057 and #1100.\n        \"\"\"\n        pytester.makeconftest(\n            f\"\"\"\n            import pytest\n\n            @pytest.fixture(autouse={autouse}, scope=\"{scope}\")\n            def auto(request):\n                return 99\n        \"\"\"\n        )\n        if use_fixture_in_doctest:\n            pytester.maketxtfile(\n                test_doc=\"\"\"\n                >>> getfixture('auto')\n                99\n            \"\"\"\n            )\n        else:\n            pytester.maketxtfile(\n                test_doc=\"\"\"\n                >>> 1 + 1\n                2\n            \"\"\"\n            )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.stdout.no_fnmatch_line(\"*FAILURES*\")\n        result.stdout.fnmatch_lines([\"*=== 1 passed in *\"])\n\n    @pytest.mark.parametrize(\"scope\", SCOPES)\n    def test_auto_use_request_attributes(self, pytester, scope):\n        \"\"\"Check that all attributes of a request in an autouse fixture\n        behave as expected when requested for a doctest item.\n        \"\"\"\n        pytester.makeconftest(\n            f\"\"\"\n            import pytest\n\n            @pytest.fixture(autouse=True, scope=\"{scope}\")\n            def auto(request):\n                if \"{scope}\" == 'module':\n                    assert request.module is None\n                if \"{scope}\" == 'class':\n                    assert request.cls is None\n                if \"{scope}\" == 'function':\n                    assert request.function is None\n                return 99\n        \"\"\"\n        )\n        pytester.maketxtfile(\n            test_doc=\"\"\"\n            >>> 1 + 1\n            2\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        str(result.stdout.no_fnmatch_line(\"*FAILURES*\"))\n        result.stdout.fnmatch_lines([\"*=== 1 passed in *\"])\n\n    @pytest.mark.parametrize(\"scope\", [*SCOPES, \"package\"])\n    def test_auto_use_defined_in_same_module(\n        self, pytester: Pytester, scope: str\n    ) -> None:\n        \"\"\"Autouse fixtures defined in the same module as the doctest get picked\n        up properly.\n\n        Regression test for #11929.\n        \"\"\"\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest\n\n            AUTO = \"the fixture did not run\"\n\n            @pytest.fixture(autouse=True, scope=\"{scope}\")\n            def auto(request):\n                global AUTO\n                AUTO = \"the fixture ran\"\n\n            def my_doctest():\n                '''My doctest.\n\n                >>> my_doctest()\n                'the fixture ran'\n                '''\n                return AUTO\n            \"\"\"\n        )\n        result = pytester.runpytest(\"--doctest-modules\")\n        result.assert_outcomes(passed=1)\n\n\nclass TestDoctestNamespaceFixture:\n    SCOPES = [\"module\", \"session\", \"class\", \"function\"]\n\n    @pytest.mark.parametrize(\"scope\", SCOPES)\n    def test_namespace_doctestfile(self, pytester, scope):\n        \"\"\"\n        Check that inserting something into the namespace works in a\n        simple text file doctest\n        \"\"\"\n        pytester.makeconftest(\n            f\"\"\"\n            import pytest\n            import contextlib\n\n            @pytest.fixture(autouse=True, scope=\"{scope}\")\n            def add_contextlib(doctest_namespace):\n                doctest_namespace['cl'] = contextlib\n        \"\"\"\n        )\n        p = pytester.maketxtfile(\n            \"\"\"\n            >>> print(cl.__name__)\n            contextlib\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p)\n        reprec.assertoutcome(passed=1)\n\n    @pytest.mark.parametrize(\"scope\", SCOPES)\n    def test_namespace_pyfile(self, pytester, scope):\n        \"\"\"\n        Check that inserting something into the namespace works in a\n        simple Python file docstring doctest\n        \"\"\"\n        pytester.makeconftest(\n            f\"\"\"\n            import pytest\n            import contextlib\n\n            @pytest.fixture(autouse=True, scope=\"{scope}\")\n            def add_contextlib(doctest_namespace):\n                doctest_namespace['cl'] = contextlib\n        \"\"\"\n        )\n        p = pytester.makepyfile(\n            \"\"\"\n            def foo():\n                '''\n                >>> print(cl.__name__)\n                contextlib\n                '''\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p, \"--doctest-modules\")\n        reprec.assertoutcome(passed=1)\n\n\nclass TestDoctestReportingOption:\n    def _run_doctest_report(self, pytester, format):\n        pytester.makepyfile(\n            \"\"\"\n            def foo():\n                '''\n                >>> foo()\n                   a  b\n                0  1  4\n                1  2  4\n                2  3  6\n                '''\n                print('   a  b\\\\n'\n                      '0  1  4\\\\n'\n                      '1  2  5\\\\n'\n                      '2  3  6')\n            \"\"\"\n        )\n        return pytester.runpytest(\"--doctest-modules\", \"--doctest-report\", format)\n\n    @pytest.mark.parametrize(\"format\", [\"udiff\", \"UDIFF\", \"uDiFf\"])\n    def test_doctest_report_udiff(self, pytester, format):\n        result = self._run_doctest_report(pytester, format)\n        result.stdout.fnmatch_lines(\n            [\"     0  1  4\", \"    -1  2  4\", \"    +1  2  5\", \"     2  3  6\"]\n        )\n\n    def test_doctest_report_cdiff(self, pytester: Pytester):\n        result = self._run_doctest_report(pytester, \"cdiff\")\n        result.stdout.fnmatch_lines(\n            [\n                \"         a  b\",\n                \"      0  1  4\",\n                \"    ! 1  2  4\",\n                \"      2  3  6\",\n                \"    --- 1,4 ----\",\n                \"         a  b\",\n                \"      0  1  4\",\n                \"    ! 1  2  5\",\n                \"      2  3  6\",\n            ]\n        )\n\n    def test_doctest_report_ndiff(self, pytester: Pytester):\n        result = self._run_doctest_report(pytester, \"ndiff\")\n        result.stdout.fnmatch_lines(\n            [\n                \"         a  b\",\n                \"      0  1  4\",\n                \"    - 1  2  4\",\n                \"    ?       ^\",\n                \"    + 1  2  5\",\n                \"    ?       ^\",\n                \"      2  3  6\",\n            ]\n        )\n\n    @pytest.mark.parametrize(\"format\", [\"none\", \"only_first_failure\"])\n    def test_doctest_report_none_or_only_first_failure(self, pytester, format):\n        result = self._run_doctest_report(pytester, format)\n        result.stdout.fnmatch_lines(\n            [\n                \"Expected:\",\n                \"       a  b\",\n                \"    0  1  4\",\n                \"    1  2  4\",\n                \"    2  3  6\",\n                \"Got:\",\n                \"       a  b\",\n                \"    0  1  4\",\n                \"    1  2  5\",\n                \"    2  3  6\",\n            ]\n        )\n\n    def test_doctest_report_invalid(self, pytester: Pytester):\n        result = self._run_doctest_report(pytester, \"obviously_invalid_format\")\n        result.stderr.fnmatch_lines(\n            [\n                \"*error: argument --doctest-report: invalid choice: 'obviously_invalid_format' (choose from*\"\n            ]\n        )\n\n\n@pytest.mark.parametrize(\"mock_module\", [\"mock\", \"unittest.mock\"])\ndef test_doctest_mock_objects_dont_recurse_missbehaved(mock_module, pytester: Pytester):\n    pytest.importorskip(mock_module)\n    pytester.makepyfile(\n        f\"\"\"\n        from {mock_module} import call\n        class Example(object):\n            '''\n            >>> 1 + 1\n            2\n            '''\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--doctest-modules\")\n    result.stdout.fnmatch_lines([\"* 1 passed *\"])\n\n\nclass Broken:\n    def __getattr__(self, _):\n        raise KeyError(\"This should be an AttributeError\")\n\n\n@pytest.mark.parametrize(  # pragma: no branch (lambdas are not called)\n    \"stop\",\n    [\n        None,\n        pytest.param(_is_mocked, id=\"is_mocked\"),\n        pytest.param(lambda f: None, id=\"lambda_none\"),\n        pytest.param(lambda f: False, id=\"lambda_false\"),\n        pytest.param(lambda f: True, id=\"lambda_true\"),\n    ],\n)\ndef test_warning_on_unwrap_of_broken_object(\n    stop: Callable[[object], object] | None,\n) -> None:\n    bad_instance = Broken()\n    assert inspect.unwrap.__module__ == \"inspect\"\n    with _patch_unwrap_mock_aware():\n        assert inspect.unwrap.__module__ != \"inspect\"\n        with pytest.warns(\n            pytest.PytestWarning, match=\"^Got KeyError.* when unwrapping\"\n        ):\n            with pytest.raises(KeyError):\n                inspect.unwrap(bad_instance, stop=stop)  # type: ignore[arg-type]\n    assert inspect.unwrap.__module__ == \"inspect\"\n\n\ndef test_is_setup_py_not_named_setup_py(tmp_path: Path) -> None:\n    not_setup_py = tmp_path.joinpath(\"not_setup.py\")\n    not_setup_py.write_text(\n        'from setuptools import setup; setup(name=\"foo\")', encoding=\"utf-8\"\n    )\n    assert not _is_setup_py(not_setup_py)\n\n\n@pytest.mark.parametrize(\"mod\", (\"setuptools\", \"distutils.core\"))\ndef test_is_setup_py_is_a_setup_py(tmp_path: Path, mod: str) -> None:\n    setup_py = tmp_path.joinpath(\"setup.py\")\n    setup_py.write_text(f'from {mod} import setup; setup(name=\"foo\")', \"utf-8\")\n    assert _is_setup_py(setup_py)\n\n\n@pytest.mark.parametrize(\"mod\", (\"setuptools\", \"distutils.core\"))\ndef test_is_setup_py_different_encoding(tmp_path: Path, mod: str) -> None:\n    setup_py = tmp_path.joinpath(\"setup.py\")\n    contents = (\n        \"# -*- coding: cp1252 -*-\\n\"\n        f'from {mod} import setup; setup(name=\"foo\", description=\"€\")\\n'\n    )\n    setup_py.write_bytes(contents.encode(\"cp1252\"))\n    assert _is_setup_py(setup_py)\n\n\n@pytest.mark.parametrize(\n    \"name, expected\", [(\"__main__.py\", True), (\"__init__.py\", False)]\n)\ndef test_is_main_py(tmp_path: Path, name: str, expected: bool) -> None:\n    dunder_main = tmp_path.joinpath(name)\n    assert _is_main_py(dunder_main) == expected\n"
  },
  {
    "path": "testing/test_entry_points.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport importlib.metadata\n\n\ndef test_pytest_entry_points_are_identical():\n    dist = importlib.metadata.distribution(\"pytest\")\n    entry_map = {ep.name: ep for ep in dist.entry_points}\n    assert entry_map[\"pytest\"].value == entry_map[\"py.test\"].value\n"
  },
  {
    "path": "testing/test_error_diffs.py",
    "content": "\"\"\"\nTests and examples for correct \"+/-\" usage in error diffs.\n\nSee https://github.com/pytest-dev/pytest/issues/3333 for details.\n\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nTESTCASES = [\n    pytest.param(\n        \"\"\"\n        def test_this():\n            result =   [1, 4, 3]\n            expected = [1, 2, 3]\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       assert [1, 4, 3] == [1, 2, 3]\n        E         At index 1 diff: 4 != 2\n        E         Full diff:\n        E           [\n        E               1,\n        E         -     2,\n        E         ?     ^\n        E         +     4,\n        E         ?     ^\n        E               3,\n        E           ]\n        \"\"\",\n        id=\"Compare lists, one item differs\",\n    ),\n    pytest.param(\n        \"\"\"\n        def test_this():\n            result =   [1, 2, 3]\n            expected = [1, 2]\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       assert [1, 2, 3] == [1, 2]\n        E         Left contains one more item: 3\n        E         Full diff:\n        E           [\n        E               1,\n        E               2,\n        E         +     3,\n        E           ]\n        \"\"\",\n        id=\"Compare lists, one extra item\",\n    ),\n    pytest.param(\n        \"\"\"\n        def test_this():\n            result =   [1, 3]\n            expected = [1, 2, 3]\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       assert [1, 3] == [1, 2, 3]\n        E         At index 1 diff: 3 != 2\n        E         Right contains one more item: 3\n        E         Full diff:\n        E           [\n        E               1,\n        E         -     2,\n        E               3,\n        E           ]\n        \"\"\",\n        id=\"Compare lists, one item missing\",\n    ),\n    pytest.param(\n        \"\"\"\n        def test_this():\n            result =   (1, 4, 3)\n            expected = (1, 2, 3)\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       assert (1, 4, 3) == (1, 2, 3)\n        E         At index 1 diff: 4 != 2\n        E         Full diff:\n        E           (\n        E               1,\n        E         -     2,\n        E         ?     ^\n        E         +     4,\n        E         ?     ^\n        E               3,\n        E           )\n        \"\"\",\n        id=\"Compare tuples\",\n    ),\n    pytest.param(\n        \"\"\"\n        def test_this():\n            result =   {1, 3, 4}\n            expected = {1, 2, 3}\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       assert {1, 3, 4} == {1, 2, 3}\n        E         Extra items in the left set:\n        E         4\n        E         Extra items in the right set:\n        E         2\n        E         Full diff:\n        E           {\n        E               1,\n        E         -     2,\n        E               3,\n        E         +     4,\n        E           }\n        \"\"\",\n        id=\"Compare sets\",\n    ),\n    pytest.param(\n        \"\"\"\n        def test_this():\n            result =   {1: 'spam', 3: 'eggs'}\n            expected = {1: 'spam', 2: 'eggs'}\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       AssertionError: assert {1: 'spam', 3: 'eggs'} == {1: 'spam', 2: 'eggs'}\n        E         Common items:\n        E         {1: 'spam'}\n        E         Left contains 1 more item:\n        E         {3: 'eggs'}\n        E         Right contains 1 more item:\n        E         {2: 'eggs'}\n        E         Full diff:\n        E           {\n        E               1: 'spam',\n        E         -     2: 'eggs',\n        E         ?     ^\n        E         +     3: 'eggs',\n        E         ?     ^\n        E           }\n        \"\"\",\n        id=\"Compare dicts with differing keys\",\n    ),\n    pytest.param(\n        \"\"\"\n        def test_this():\n            result =   {1: 'spam', 2: 'eggs'}\n            expected = {1: 'spam', 2: 'bacon'}\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       AssertionError: assert {1: 'spam', 2: 'eggs'} == {1: 'spam', 2: 'bacon'}\n        E         Common items:\n        E         {1: 'spam'}\n        E         Differing items:\n        E         {2: 'eggs'} != {2: 'bacon'}\n        E         Full diff:\n        E           {\n        E               1: 'spam',\n        E         -     2: 'bacon',\n        E         +     2: 'eggs',\n        E           }\n        \"\"\",\n        id=\"Compare dicts with differing values\",\n    ),\n    pytest.param(\n        \"\"\"\n        def test_this():\n            result =   {1: 'spam', 2: 'eggs'}\n            expected = {1: 'spam', 3: 'bacon'}\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       AssertionError: assert {1: 'spam', 2: 'eggs'} == {1: 'spam', 3: 'bacon'}\n        E         Common items:\n        E         {1: 'spam'}\n        E         Left contains 1 more item:\n        E         {2: 'eggs'}\n        E         Right contains 1 more item:\n        E         {3: 'bacon'}\n        E         Full diff:\n        E           {\n        E               1: 'spam',\n        E         -     3: 'bacon',\n        E         +     2: 'eggs',\n        E           }\n        \"\"\",\n        id=\"Compare dicts with differing items\",\n    ),\n    pytest.param(\n        \"\"\"\n        def test_this():\n            result =   \"spmaeggs\"\n            expected = \"spameggs\"\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       AssertionError: assert 'spmaeggs' == 'spameggs'\n        E         - spameggs\n        E         ?    -\n        E         + spmaeggs\n        E         ?   +\n        \"\"\",\n        id=\"Compare strings\",\n    ),\n    pytest.param(\n        \"\"\"\n        def test_this():\n            result =   \"spam bacon eggs\"\n            assert \"bacon\" not in result\n        \"\"\",\n        \"\"\"\n        >       assert \"bacon\" not in result\n        E       AssertionError: assert 'bacon' not in 'spam bacon eggs'\n        E         'bacon' is contained here:\n        E           spam bacon eggs\n        E         ?      +++++\n        \"\"\",\n        id='Test \"not in\" string',\n    ),\n    pytest.param(\n        \"\"\"\n        from dataclasses import dataclass\n\n        @dataclass\n        class A:\n            a: int\n            b: str\n\n        def test_this():\n            result =   A(1, 'spam')\n            expected = A(2, 'spam')\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       AssertionError: assert A(a=1, b='spam') == A(a=2, b='spam')\n        E         Matching attributes:\n        E         ['b']\n        E         Differing attributes:\n        E         ['a']\n        E         Drill down into differing attribute a:\n        E           a: 1 != 2\n        \"\"\",\n        id=\"Compare data classes\",\n    ),\n    pytest.param(\n        \"\"\"\n        import attr\n\n        @attr.s(auto_attribs=True)\n        class A:\n            a: int\n            b: str\n\n        def test_this():\n            result =   A(1, 'spam')\n            expected = A(1, 'eggs')\n            assert result == expected\n        \"\"\",\n        \"\"\"\n        >       assert result == expected\n        E       AssertionError: assert A(a=1, b='spam') == A(a=1, b='eggs')\n        E         Matching attributes:\n        E         ['a']\n        E         Differing attributes:\n        E         ['b']\n        E         Drill down into differing attribute b:\n        E           b: 'spam' != 'eggs'\n        E           - eggs\n        E           + spam\n        \"\"\",\n        id=\"Compare attrs classes\",\n    ),\n]\n\n\n@pytest.mark.parametrize(\"code, expected\", TESTCASES)\ndef test_error_diff(code: str, expected: str, pytester: Pytester) -> None:\n    expected_lines = [line.lstrip() for line in expected.splitlines()]\n    p = pytester.makepyfile(code)\n    result = pytester.runpytest(p, \"-vv\")\n    result.stdout.fnmatch_lines(expected_lines)\n    assert result.ret == 1\n"
  },
  {
    "path": "testing/test_faulthandler.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport io\nimport os\nimport sys\n\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\ndef test_enabled(pytester: Pytester) -> None:\n    \"\"\"Test single crashing test displays a traceback.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n    import faulthandler\n    def test_crash():\n        faulthandler._sigabrt()\n    \"\"\"\n    )\n    result = pytester.runpytest_subprocess()\n    result.stderr.fnmatch_lines([\"*Fatal Python error*\"])\n    assert result.ret != 0\n\n\ndef setup_crashing_test(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import faulthandler\n        import atexit\n        def test_ok():\n            atexit.register(faulthandler._sigabrt)\n        \"\"\"\n    )\n\n\ndef test_crash_during_shutdown_captured(pytester: Pytester) -> None:\n    \"\"\"\n    Re-enable faulthandler if pytest encountered it enabled during configure.\n    We should be able to then see crashes during interpreter shutdown.\n    \"\"\"\n    setup_crashing_test(pytester)\n    args = (sys.executable, \"-Xfaulthandler\", \"-mpytest\")\n    result = pytester.run(*args)\n    result.stderr.fnmatch_lines([\"*Fatal Python error*\"])\n    assert result.ret != 0\n\n\ndef test_crash_during_shutdown_not_captured(pytester: Pytester) -> None:\n    \"\"\"\n    Check that pytest leaves faulthandler disabled if it was not enabled during configure.\n    This prevents us from seeing crashes during interpreter shutdown (see #8260).\n    \"\"\"\n    setup_crashing_test(pytester)\n    args = (sys.executable, \"-mpytest\")\n    result = pytester.run(*args)\n    result.stderr.no_fnmatch_line(\"*Fatal Python error*\")\n    assert result.ret != 0\n\n\ndef test_disabled(pytester: Pytester) -> None:\n    \"\"\"Test option to disable fault handler in the command line.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n    import faulthandler\n    def test_disabled():\n        assert not faulthandler.is_enabled()\n    \"\"\"\n    )\n    result = pytester.runpytest_subprocess(\"-p\", \"no:faulthandler\")\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n    assert result.ret == 0\n\n\n@pytest.mark.keep_ci_var\n@pytest.mark.parametrize(\n    \"enabled\",\n    [\n        pytest.param(\n            True,\n            marks=pytest.mark.skipif(\n                bool(os.environ.get(\"CI\"))\n                and sys.platform == \"linux\"\n                and sys.version_info >= (3, 14),\n                reason=\"sometimes crashes on CI because of truncated outputs (#7022)\",\n            ),\n        ),\n        False,\n    ],\n)\ndef test_timeout(pytester: Pytester, enabled: bool) -> None:\n    \"\"\"Test option to dump tracebacks after a certain timeout.\n\n    If faulthandler is disabled, no traceback will be dumped.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n    import os, time\n    def test_timeout():\n        time.sleep(1 if \"CI\" in os.environ else 0.1)\n    \"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        faulthandler_timeout = 0.01\n        \"\"\"\n    )\n    args = [\"-p\", \"no:faulthandler\"] if not enabled else []\n\n    result = pytester.runpytest_subprocess(*args)\n    tb_output = \"most recent call first\"\n    if enabled:\n        result.stderr.fnmatch_lines([f\"*{tb_output}*\"])\n    else:\n        assert tb_output not in result.stderr.str()\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n    assert result.ret == 0\n\n\n@pytest.mark.keep_ci_var\n@pytest.mark.skipif(\n    \"CI\" in os.environ and sys.platform == \"linux\" and sys.version_info >= (3, 14),\n    reason=\"sometimes crashes on CI because of truncated outputs (#7022)\",\n)\n@pytest.mark.parametrize(\"exit_on_timeout\", [True, False])\ndef test_timeout_and_exit(pytester: Pytester, exit_on_timeout: bool) -> None:\n    \"\"\"Test option to force exit pytest process after a certain timeout.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n    import os, time\n    def test_long_sleep_and_raise():\n        time.sleep(1 if \"CI\" in os.environ else 0.1)\n        raise AssertionError(\n            \"This test should have been interrupted before reaching this point.\"\n        )\n    \"\"\"\n    )\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        faulthandler_timeout = 0.01\n        faulthandler_exit_on_timeout = {\"true\" if exit_on_timeout else \"false\"}\n        \"\"\"\n    )\n    result = pytester.runpytest_subprocess()\n    tb_output = \"most recent call first\"\n    result.stderr.fnmatch_lines([f\"*{tb_output}*\"])\n    if exit_on_timeout:\n        result.stdout.no_fnmatch_line(\"*1 failed*\")\n        result.stdout.no_fnmatch_line(\"*AssertionError*\")\n    else:\n        result.stdout.fnmatch_lines([\"*1 failed*\"])\n        result.stdout.fnmatch_lines([\"*AssertionError*\"])\n    assert result.ret == 1\n\n\n@pytest.mark.parametrize(\"hook_name\", [\"pytest_enter_pdb\", \"pytest_exception_interact\"])\ndef test_cancel_timeout_on_hook(monkeypatch, hook_name) -> None:\n    \"\"\"Make sure that we are cancelling any scheduled traceback dumping due\n    to timeout before entering pdb (pytest-dev/pytest-faulthandler#12) or any\n    other interactive exception (pytest-dev/pytest-faulthandler#14).\"\"\"\n    import faulthandler\n\n    from _pytest import faulthandler as faulthandler_plugin\n\n    called = []\n\n    monkeypatch.setattr(\n        faulthandler, \"cancel_dump_traceback_later\", lambda: called.append(1)\n    )\n\n    # call our hook explicitly, we can trust that pytest will call the hook\n    # for us at the appropriate moment\n    hook_func = getattr(faulthandler_plugin, hook_name)\n    hook_func()\n    assert called == [1]\n\n\ndef test_already_initialized_crash(pytester: Pytester) -> None:\n    \"\"\"Even if faulthandler is already initialized, we still dump tracebacks on crashes (#8258).\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        def test():\n            import faulthandler\n            faulthandler._sigabrt()\n    \"\"\"\n    )\n    result = pytester.run(\n        sys.executable,\n        \"-X\",\n        \"faulthandler\",\n        \"-mpytest\",\n        pytester.path,\n    )\n    result.stderr.fnmatch_lines([\"*Fatal Python error*\"])\n    assert result.ret != 0\n\n\ndef test_get_stderr_fileno_invalid_fd() -> None:\n    \"\"\"Test for faulthandler being able to handle invalid file descriptors for stderr (#8249).\"\"\"\n    from _pytest.faulthandler import get_stderr_fileno\n\n    class StdErrWrapper(io.StringIO):\n        \"\"\"\n        Mimic ``twisted.logger.LoggingFile`` to simulate returning an invalid file descriptor.\n\n        https://github.com/twisted/twisted/blob/twisted-20.3.0/src/twisted/logger/_io.py#L132-L139\n        \"\"\"\n\n        def fileno(self):\n            return -1\n\n    wrapper = StdErrWrapper()\n\n    with pytest.MonkeyPatch.context() as mp:\n        mp.setattr(\"sys.stderr\", wrapper)\n\n        # Even when the stderr wrapper signals an invalid file descriptor,\n        # ``_get_stderr_fileno()`` should return the real one.\n        assert get_stderr_fileno() == 2\n"
  },
  {
    "path": "testing/test_findpaths.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport os\nfrom pathlib import Path\nfrom textwrap import dedent\n\nfrom _pytest.config import UsageError\nfrom _pytest.config.findpaths import ConfigValue\nfrom _pytest.config.findpaths import get_common_ancestor\nfrom _pytest.config.findpaths import get_dirs_from_args\nfrom _pytest.config.findpaths import is_fs_root\nfrom _pytest.config.findpaths import load_config_dict_from_file\nimport pytest\n\n\nclass TestLoadConfigDictFromFile:\n    @pytest.mark.parametrize(\"filename\", [\"pytest.ini\", \".pytest.ini\"])\n    def test_empty_pytest_ini(self, tmp_path: Path, filename: str) -> None:\n        \"\"\"pytest.ini files are always considered for configuration, even if empty\"\"\"\n        fn = tmp_path / filename\n        fn.write_text(\"\", encoding=\"utf-8\")\n        assert load_config_dict_from_file(fn) == {}\n\n    def test_pytest_ini(self, tmp_path: Path) -> None:\n        \"\"\"[pytest] section in pytest.ini files is read correctly\"\"\"\n        fn = tmp_path / \"pytest.ini\"\n        fn.write_text(\"[pytest]\\nx=1\", encoding=\"utf-8\")\n        assert load_config_dict_from_file(fn) == {\n            \"x\": ConfigValue(\"1\", origin=\"file\", mode=\"ini\")\n        }\n\n    def test_custom_ini(self, tmp_path: Path) -> None:\n        \"\"\"[pytest] section in any .ini file is read correctly\"\"\"\n        fn = tmp_path / \"custom.ini\"\n        fn.write_text(\"[pytest]\\nx=1\", encoding=\"utf-8\")\n        assert load_config_dict_from_file(fn) == {\n            \"x\": ConfigValue(\"1\", origin=\"file\", mode=\"ini\")\n        }\n\n    def test_custom_ini_without_section(self, tmp_path: Path) -> None:\n        \"\"\"Custom .ini files without [pytest] section are not considered for configuration\"\"\"\n        fn = tmp_path / \"custom.ini\"\n        fn.write_text(\"[custom]\", encoding=\"utf-8\")\n        assert load_config_dict_from_file(fn) is None\n\n    def test_custom_cfg_file(self, tmp_path: Path) -> None:\n        \"\"\"Custom .cfg files without [tool:pytest] section are not considered for configuration\"\"\"\n        fn = tmp_path / \"custom.cfg\"\n        fn.write_text(\"[custom]\", encoding=\"utf-8\")\n        assert load_config_dict_from_file(fn) is None\n\n    def test_valid_cfg_file(self, tmp_path: Path) -> None:\n        \"\"\"Custom .cfg files with [tool:pytest] section are read correctly\"\"\"\n        fn = tmp_path / \"custom.cfg\"\n        fn.write_text(\"[tool:pytest]\\nx=1\", encoding=\"utf-8\")\n        assert load_config_dict_from_file(fn) == {\n            \"x\": ConfigValue(\"1\", origin=\"file\", mode=\"ini\")\n        }\n\n    def test_unsupported_pytest_section_in_cfg_file(self, tmp_path: Path) -> None:\n        \"\"\".cfg files with [pytest] section are no longer supported and should fail to alert users\"\"\"\n        fn = tmp_path / \"custom.cfg\"\n        fn.write_text(\"[pytest]\", encoding=\"utf-8\")\n        with pytest.raises(pytest.fail.Exception):\n            load_config_dict_from_file(fn)\n\n    def test_invalid_toml_file(self, tmp_path: Path) -> None:\n        \"\"\"Invalid .toml files should raise `UsageError`.\"\"\"\n        fn = tmp_path / \"myconfig.toml\"\n        fn.write_text(\"]invalid toml[\", encoding=\"utf-8\")\n        with pytest.raises(UsageError):\n            load_config_dict_from_file(fn)\n\n    def test_custom_toml_file(self, tmp_path: Path) -> None:\n        \"\"\".toml files without [tool.pytest] are not considered for configuration.\"\"\"\n        fn = tmp_path / \"myconfig.toml\"\n        fn.write_text(\n            dedent(\n                \"\"\"\n            [build_system]\n            x = 1\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        assert load_config_dict_from_file(fn) is None\n\n    def test_valid_toml_file(self, tmp_path: Path) -> None:\n        \"\"\".toml files with [tool.pytest.ini_options] are read correctly, including changing\n        data types to str/list for compatibility with other configuration options.\"\"\"\n        fn = tmp_path / \"myconfig.toml\"\n        fn.write_text(\n            dedent(\n                \"\"\"\n            [tool.pytest.ini_options]\n            x = 1\n            y = 20.0\n            values = [\"tests\", \"integration\"]\n            name = \"foo\"\n            heterogeneous_array = [1, \"str\"]\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        assert load_config_dict_from_file(fn) == {\n            \"x\": ConfigValue(\"1\", origin=\"file\", mode=\"ini\"),\n            \"y\": ConfigValue(\"20.0\", origin=\"file\", mode=\"ini\"),\n            \"values\": ConfigValue([\"tests\", \"integration\"], origin=\"file\", mode=\"ini\"),\n            \"name\": ConfigValue(\"foo\", origin=\"file\", mode=\"ini\"),\n            \"heterogeneous_array\": ConfigValue([1, \"str\"], origin=\"file\", mode=\"ini\"),\n        }\n\n    def test_native_toml_config(self, tmp_path: Path) -> None:\n        \"\"\"[tool.pytest] sections with native types are parsed correctly without coercion.\"\"\"\n        fn = tmp_path / \"pyproject.toml\"\n        fn.write_text(\n            dedent(\n                \"\"\"\n                [tool.pytest]\n                minversion = \"7.0\"\n                xfail_strict = true\n                testpaths = [\"tests\", \"integration\"]\n                python_files = [\"test_*.py\", \"*_test.py\"]\n                verbosity_assertions = 2\n                maxfail = 5\n                timeout = 300.5\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        result = load_config_dict_from_file(fn)\n        assert result == {\n            \"minversion\": ConfigValue(\"7.0\", origin=\"file\", mode=\"toml\"),\n            \"xfail_strict\": ConfigValue(True, origin=\"file\", mode=\"toml\"),\n            \"testpaths\": ConfigValue(\n                [\"tests\", \"integration\"], origin=\"file\", mode=\"toml\"\n            ),\n            \"python_files\": ConfigValue(\n                [\"test_*.py\", \"*_test.py\"], origin=\"file\", mode=\"toml\"\n            ),\n            \"verbosity_assertions\": ConfigValue(2, origin=\"file\", mode=\"toml\"),\n            \"maxfail\": ConfigValue(5, origin=\"file\", mode=\"toml\"),\n            \"timeout\": ConfigValue(300.5, origin=\"file\", mode=\"toml\"),\n        }\n\n    def test_native_and_ini_conflict(self, tmp_path: Path) -> None:\n        \"\"\"Using both [tool.pytest] and [tool.pytest.ini_options] should raise an error.\"\"\"\n        fn = tmp_path / \"pyproject.toml\"\n        fn.write_text(\n            dedent(\n                \"\"\"\n            [tool.pytest]\n            xfail_strict = true\n\n            [tool.pytest.ini_options]\n            minversion = \"7.0\"\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        with pytest.raises(UsageError, match=\"Cannot use both\"):\n            load_config_dict_from_file(fn)\n\n    def test_invalid_suffix(self, tmp_path: Path) -> None:\n        \"\"\"A file with an unknown suffix is ignored.\"\"\"\n        fn = tmp_path / \"pytest.config\"\n        fn.write_text(\"\", encoding=\"utf-8\")\n        assert load_config_dict_from_file(fn) is None\n\n\nclass TestCommonAncestor:\n    def test_has_ancestor(self, tmp_path: Path) -> None:\n        fn1 = tmp_path / \"foo\" / \"bar\" / \"test_1.py\"\n        fn1.parent.mkdir(parents=True)\n        fn1.touch()\n        fn2 = tmp_path / \"foo\" / \"zaz\" / \"test_2.py\"\n        fn2.parent.mkdir(parents=True)\n        fn2.touch()\n        cwd = Path.cwd()\n        assert get_common_ancestor(cwd, [fn1, fn2]) == tmp_path / \"foo\"\n        assert get_common_ancestor(cwd, [fn1.parent, fn2]) == tmp_path / \"foo\"\n        assert get_common_ancestor(cwd, [fn1.parent, fn2.parent]) == tmp_path / \"foo\"\n        assert get_common_ancestor(cwd, [fn1, fn2.parent]) == tmp_path / \"foo\"\n\n    def test_single_dir(self, tmp_path: Path) -> None:\n        assert get_common_ancestor(Path.cwd(), [tmp_path]) == tmp_path\n\n    def test_single_file(self, tmp_path: Path) -> None:\n        fn = tmp_path / \"foo.py\"\n        fn.touch()\n        assert get_common_ancestor(Path.cwd(), [fn]) == tmp_path\n\n\ndef test_get_dirs_from_args(tmp_path):\n    \"\"\"get_dirs_from_args() skips over non-existing directories and files\"\"\"\n    fn = tmp_path / \"foo.py\"\n    fn.touch()\n    d = tmp_path / \"tests\"\n    d.mkdir()\n    option = \"--foobar=/foo.txt\"\n    # xdist uses options in this format for its rsync feature (#7638)\n    xdist_rsync_option = \"popen=c:/dest\"\n    assert get_dirs_from_args(\n        [str(fn), str(tmp_path / \"does_not_exist\"), str(d), option, xdist_rsync_option]\n    ) == [fn.parent, d]\n\n\n@pytest.mark.parametrize(\n    \"path, expected\",\n    [\n        pytest.param(\n            f\"e:{os.sep}\", True, marks=pytest.mark.skipif(\"sys.platform != 'win32'\")\n        ),\n        (f\"{os.sep}\", True),\n        (f\"e:{os.sep}projects\", False),\n        (f\"{os.sep}projects\", False),\n    ],\n)\ndef test_is_fs_root(path: Path, expected: bool) -> None:\n    assert is_fs_root(Path(path)) is expected\n"
  },
  {
    "path": "testing/test_helpconfig.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom _pytest.config import ExitCode\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\ndef test_version_verbose(pytester: Pytester, pytestconfig, monkeypatch) -> None:\n    monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\")\n    monkeypatch.delenv(\"PYTEST_PLUGINS\", raising=False)\n    result = pytester.runpytest(\"--version\", \"--version\")\n    assert result.ret == ExitCode.OK\n    result.stdout.fnmatch_lines([f\"*pytest*{pytest.__version__}*imported from*\"])\n    if pytestconfig.pluginmanager.list_plugin_distinfo():\n        result.stdout.fnmatch_lines([\"*registered third-party plugins:\", \"*at*\"])\n\n\ndef test_version_less_verbose(pytester: Pytester) -> None:\n    \"\"\"Single ``--version`` parameter should display only the pytest version, without loading plugins (#13574).\"\"\"\n    pytester.makeconftest(\"print('This should not be printed')\")\n    result = pytester.runpytest_subprocess(\"--version\")\n    assert result.ret == ExitCode.OK\n    assert result.stdout.str().strip() == f\"pytest {pytest.__version__}\"\n\n\ndef test_versions() -> None:\n    \"\"\"Regression check for the public version attributes in pytest.\"\"\"\n    assert isinstance(pytest.__version__, str)\n    assert isinstance(pytest.version_tuple, tuple)\n\n\ndef test_help(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--help\")\n    assert result.ret == ExitCode.OK\n    result.stdout.fnmatch_lines(\n        \"\"\"\n          -m MARKEXPR           Only run tests matching given mark expression. For\n                                example: -m 'mark1 and not mark2'.\n        Reporting:\n          --durations=N *\n          -V, --version         Display pytest version and information about plugins.\n                                When given twice, also display information about\n                                plugins.\n        *setup.cfg*\n        *minversion*\n        *to see*markers*pytest --markers*\n        *to see*fixtures*pytest --fixtures*\n    \"\"\"\n    )\n\n\ndef test_none_help_param_raises_exception(pytester: Pytester) -> None:\n    \"\"\"Test that a None help param raises a TypeError.\"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_addoption(parser):\n            parser.addini(\"test_ini\", None, default=True, type=\"bool\")\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--help\")\n    result.stderr.fnmatch_lines(\n        [\"*TypeError: help argument cannot be None for test_ini*\"]\n    )\n\n\ndef test_empty_help_param(pytester: Pytester) -> None:\n    \"\"\"Test that an empty help param is displayed correctly.\"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_addoption(parser):\n            parser.addini(\"test_ini\", \"\", default=True, type=\"bool\")\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--help\")\n    assert result.ret == ExitCode.OK\n    lines = [\n        \"  required_plugins (args):\",\n        \"                        Plugins that must be present for pytest to run*\",\n        \"  test_ini (bool):*\",\n        \"Environment variables:\",\n    ]\n    result.stdout.fnmatch_lines(lines, consecutive=True)\n\n\ndef test_parse_known_args_doesnt_quit_on_help(pytester: Pytester) -> None:\n    \"\"\"`parse_known_args` shouldn't exit on `--help`, unlike `parse`.\"\"\"\n    config = pytester.parseconfig()\n    # Doesn't raise or exit!\n    config._parser.parse_known_args([\"--help\"])\n    config._parser.parse_known_and_unknown_args([\"--help\"])\n\n\ndef test_hookvalidation_unknown(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_hello(xyz):\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret != ExitCode.OK\n    result.stdout.fnmatch_lines([\"*unknown hook*pytest_hello*\"])\n\n\ndef test_hookvalidation_optional(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n        @pytest.hookimpl(optionalhook=True)\n        def pytest_hello(xyz):\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_traceconfig(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--traceconfig\")\n    result.stdout.fnmatch_lines([\"*using*pytest*\", \"*active plugins*\"])\n\n\ndef test_debug(pytester: Pytester) -> None:\n    result = pytester.runpytest_subprocess(\"--debug\")\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n    p = pytester.path.joinpath(\"pytestdebug.log\")\n    assert \"pytest_sessionstart\" in p.read_text(\"utf-8\")\n\n\ndef test_PYTEST_DEBUG(pytester: Pytester, monkeypatch) -> None:\n    monkeypatch.setenv(\"PYTEST_DEBUG\", \"1\")\n    result = pytester.runpytest_subprocess()\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n    result.stderr.fnmatch_lines(\n        [\"*pytest_plugin_registered*\", \"*manager*PluginManager*\"]\n    )\n"
  },
  {
    "path": "testing/test_junitxml.py",
    "content": "from __future__ import annotations\n\nfrom datetime import datetime\nfrom datetime import timezone\nimport os\nfrom pathlib import Path\nimport platform\nfrom typing import Any\nfrom typing import cast\nfrom typing import TYPE_CHECKING\nfrom xml.dom import minidom\n\nimport xmlschema\n\nfrom _pytest.config import Config\nfrom _pytest.junitxml import bin_xml_escape\nfrom _pytest.junitxml import LogXML\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nfrom _pytest.pytester import RunResult\nfrom _pytest.reports import BaseReport\nfrom _pytest.reports import TestReport\nfrom _pytest.stash import Stash\nimport _pytest.timing\nimport pytest\n\n\n@pytest.fixture(scope=\"session\")\ndef schema() -> xmlschema.XMLSchema:\n    \"\"\"Return an xmlschema.XMLSchema object for the junit-10.xsd file.\"\"\"\n    fn = Path(__file__).parent / \"example_scripts/junit-10.xsd\"\n    with fn.open(encoding=\"utf-8\") as f:\n        return xmlschema.XMLSchema(f)\n\n\nclass RunAndParse:\n    def __init__(self, pytester: Pytester, schema: xmlschema.XMLSchema) -> None:\n        self.pytester = pytester\n        self.schema = schema\n\n    def __call__(\n        self, *args: str | os.PathLike[str], family: str | None = \"xunit1\"\n    ) -> tuple[RunResult, DomDocument]:\n        if family:\n            args = (\"-o\", \"junit_family=\" + family, *args)\n        xml_path = self.pytester.path.joinpath(\"junit.xml\")\n        result = self.pytester.runpytest(f\"--junitxml={xml_path}\", *args)\n        if family == \"xunit2\":\n            with xml_path.open(encoding=\"utf-8\") as f:\n                self.schema.validate(f)\n        xmldoc = minidom.parse(str(xml_path))\n        return result, DomDocument(xmldoc)\n\n\n@pytest.fixture\ndef run_and_parse(pytester: Pytester, schema: xmlschema.XMLSchema) -> RunAndParse:\n    \"\"\"Fixture that returns a function that can be used to execute pytest and\n    return the parsed ``DomNode`` of the root xml node.\n\n    The ``family`` parameter is used to configure the ``junit_family`` of the written report.\n    \"xunit2\" is also automatically validated against the schema.\n    \"\"\"\n    return RunAndParse(pytester, schema)\n\n\ndef assert_attr(node: minidom.Element, **kwargs: object) -> None:\n    __tracebackhide__ = True\n\n    def nodeval(node: minidom.Element, name: str) -> str | None:\n        anode = node.getAttributeNode(name)\n        return anode.value if anode is not None else None\n\n    expected = {name: str(value) for name, value in kwargs.items()}\n    on_node = {name: nodeval(node, name) for name in expected}\n    assert on_node == expected\n\n\nclass DomDocument:\n    _node: minidom.Document | minidom.Element\n\n    def __init__(self, dom: minidom.Document) -> None:\n        self._node = dom\n\n    def find_first_by_tag(self, tag: str) -> DomNode | None:\n        return self.find_nth_by_tag(tag, 0)\n\n    def get_first_by_tag(self, tag: str) -> DomNode:\n        maybe = self.find_first_by_tag(tag)\n        if maybe is None:\n            raise LookupError(tag)\n        else:\n            return maybe\n\n    def find_nth_by_tag(self, tag: str, n: int) -> DomNode | None:\n        items = self._node.getElementsByTagName(tag)\n        try:\n            nth = items[n]\n        except IndexError:\n            return None\n        else:\n            return DomNode(nth)\n\n    def find_by_tag(self, tag: str) -> list[DomNode]:\n        return [DomNode(x) for x in self._node.getElementsByTagName(tag)]\n\n    @property\n    def children(self) -> list[DomNode]:\n        return [\n            DomNode(x) for x in self._node.childNodes if isinstance(x, minidom.Element)\n        ]\n\n    @property\n    def get_unique_child(self) -> DomNode:\n        children = self.children\n        assert len(children) == 1\n        return children[0]\n\n    def toxml(self) -> str:\n        return self._node.toxml()\n\n\nclass DomNode(DomDocument):\n    _node: minidom.Element\n\n    def __init__(self, dom: minidom.Element) -> None:\n        self._node = dom\n\n    def __repr__(self) -> str:\n        return self.toxml()\n\n    def __getitem__(self, key: str) -> str:\n        node = self._node.getAttributeNode(key)\n        if node is not None:\n            return node.value\n        else:\n            raise KeyError(key)\n\n    def assert_attr(self, **kwargs: object) -> None:\n        __tracebackhide__ = True\n        return assert_attr(self._node, **kwargs)\n\n    @property\n    def text(self) -> str:\n        text = self._node.childNodes[0]\n        assert isinstance(text, minidom.Text)\n        return text.wholeText\n\n    @property\n    def tag(self) -> str:\n        return self._node.tagName\n\n\nclass TestJunitHelpers:\n    \"\"\"minimal test to increase coverage for methods that are used in debugging\"\"\"\n\n    @pytest.fixture\n    def document(self) -> DomDocument:\n        doc = minidom.parseString(\"\"\"\n        <root>\n          <item name=\"a\"></item>\n          <item name=\"b\"></item>\n        </root>\n\"\"\")\n        return DomDocument(doc)\n\n    def test_uc_root(self, document: DomDocument) -> None:\n        assert document.get_unique_child.tag == \"root\"\n\n    def test_node_assert_attr(self, document: DomDocument) -> None:\n        item = document.get_first_by_tag(\"item\")\n\n        item.assert_attr(name=\"a\")\n\n        with pytest.raises(AssertionError):\n            item.assert_attr(missing=\"foo\")\n\n    def test_node_getitem(self, document: DomDocument) -> None:\n        item = document.get_first_by_tag(\"item\")\n        assert item[\"name\"] == \"a\"\n\n        with pytest.raises(KeyError, match=\"missing\"):\n            item[\"missing\"]\n\n    def test_node_get_first_lookup(self, document: DomDocument) -> None:\n        with pytest.raises(LookupError, match=\"missing\"):\n            document.get_first_by_tag(\"missing\")\n\n    def test_node_repr(self, document: DomDocument) -> None:\n        item = document.get_first_by_tag(\"item\")\n\n        assert repr(item) == item.toxml()\n        assert item.toxml() == '<item name=\"a\"/>'\n\n\nparametrize_families = pytest.mark.parametrize(\"xunit_family\", [\"xunit1\", \"xunit2\"])\n\n\nclass TestPython:\n    @parametrize_families\n    def test_summing_simple(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_pass():\n                pass\n            def test_fail():\n                assert 0\n            def test_skip():\n                pytest.skip(\"\")\n            @pytest.mark.xfail\n            def test_xfail():\n                assert 0\n            @pytest.mark.xfail\n            def test_xpass():\n                assert 1\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(name=\"pytest\", errors=0, failures=1, skipped=2, tests=5)\n\n    @parametrize_families\n    def test_summing_simple_with_errors(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def fixture():\n                raise Exception()\n            def test_pass():\n                pass\n            def test_fail():\n                assert 0\n            def test_error(fixture):\n                pass\n            @pytest.mark.xfail\n            def test_xfail():\n                assert False\n            @pytest.mark.xfail(strict=True)\n            def test_xpass():\n                assert True\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(name=\"pytest\", errors=1, failures=2, skipped=1, tests=5)\n\n    @parametrize_families\n    def test_hostname_in_xml(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_pass():\n                pass\n        \"\"\"\n        )\n        _result, dom = run_and_parse(family=xunit_family)\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(hostname=platform.node())\n\n    @parametrize_families\n    def test_timestamp_in_xml(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_pass():\n                pass\n        \"\"\"\n        )\n        start_time = datetime.now(timezone.utc)\n        _result, dom = run_and_parse(family=xunit_family)\n        node = dom.get_first_by_tag(\"testsuite\")\n        timestamp = datetime.fromisoformat(node[\"timestamp\"])\n        assert start_time <= timestamp < datetime.now(timezone.utc)\n\n    def test_timing_function(\n        self,\n        pytester: Pytester,\n        run_and_parse: RunAndParse,\n        mock_timing: _pytest.timing.MockTiming,\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            from _pytest import timing\n            def setup_module():\n                timing.sleep(1)\n            def teardown_module():\n                timing.sleep(2)\n            def test_sleep():\n                timing.sleep(4)\n        \"\"\"\n        )\n        _result, dom = run_and_parse()\n        node = dom.get_first_by_tag(\"testsuite\")\n        tnode = node.get_first_by_tag(\"testcase\")\n        val = tnode[\"time\"]\n        assert val is not None\n        assert float(val) == 7.0\n\n    @pytest.mark.parametrize(\"duration_report\", [\"call\", \"total\"])\n    def test_junit_duration_report(\n        self,\n        pytester: Pytester,\n        monkeypatch: MonkeyPatch,\n        duration_report: str,\n        run_and_parse: RunAndParse,\n    ) -> None:\n        # mock LogXML.node_reporter so it always sets a known duration to each test report object\n        original_node_reporter = LogXML.node_reporter\n\n        def node_reporter_wrapper(s: Any, report: TestReport) -> Any:\n            report.duration = 1.0\n            reporter = original_node_reporter(s, report)\n            return reporter\n\n        monkeypatch.setattr(LogXML, \"node_reporter\", node_reporter_wrapper)\n\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                pass\n        \"\"\"\n        )\n        _result, dom = run_and_parse(\"-o\", f\"junit_duration_report={duration_report}\")\n        node = dom.get_first_by_tag(\"testsuite\")\n        tnode = node.get_first_by_tag(\"testcase\")\n        val = float(tnode[\"time\"])\n        if duration_report == \"total\":\n            assert val == 3.0\n        else:\n            assert duration_report == \"call\"\n            assert val == 1.0\n\n    @parametrize_families\n    def test_setup_error(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def arg(request):\n                raise ValueError(\"Error reason\")\n            def test_function(arg):\n                pass\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(errors=1, tests=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"test_setup_error\", name=\"test_function\")\n        fnode = tnode.get_first_by_tag(\"error\")\n        fnode.assert_attr(message='failed on setup with \"ValueError: Error reason\"')\n        assert \"ValueError\" in fnode.toxml()\n\n    @parametrize_families\n    def test_teardown_error(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def arg():\n                yield\n                raise ValueError('Error reason')\n            def test_function(arg):\n                pass\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"test_teardown_error\", name=\"test_function\")\n        fnode = tnode.get_first_by_tag(\"error\")\n        fnode.assert_attr(message='failed on teardown with \"ValueError: Error reason\"')\n        assert \"ValueError\" in fnode.toxml()\n\n    @parametrize_families\n    def test_call_failure_teardown_error(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def arg():\n                yield\n                raise Exception(\"Teardown Exception\")\n            def test_function(arg):\n                raise Exception(\"Call Exception\")\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(errors=1, failures=1, tests=1)\n        first, second = dom.find_by_tag(\"testcase\")\n        assert first\n        assert second\n        assert first != second\n        fnode = first.get_first_by_tag(\"failure\")\n        fnode.assert_attr(message=\"Exception: Call Exception\")\n        snode = second.get_first_by_tag(\"error\")\n        snode.assert_attr(\n            message='failed on teardown with \"Exception: Teardown Exception\"'\n        )\n\n    @parametrize_families\n    def test_skip_contains_name_reason(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_skip():\n                pytest.skip(\"hello23\")\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret == 0\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(skipped=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"test_skip_contains_name_reason\", name=\"test_skip\")\n        snode = tnode.get_first_by_tag(\"skipped\")\n        snode.assert_attr(type=\"pytest.skip\", message=\"hello23\")\n\n    @parametrize_families\n    def test_mark_skip_contains_name_reason(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skip(reason=\"hello24\")\n            def test_skip():\n                assert True\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret == 0\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(skipped=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(\n            classname=\"test_mark_skip_contains_name_reason\", name=\"test_skip\"\n        )\n        snode = tnode.get_first_by_tag(\"skipped\")\n        snode.assert_attr(type=\"pytest.skip\", message=\"hello24\")\n\n    @parametrize_families\n    def test_mark_skipif_contains_name_reason(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            GLOBAL_CONDITION = True\n            @pytest.mark.skipif(GLOBAL_CONDITION, reason=\"hello25\")\n            def test_skip():\n                assert True\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret == 0\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(skipped=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(\n            classname=\"test_mark_skipif_contains_name_reason\", name=\"test_skip\"\n        )\n        snode = tnode.get_first_by_tag(\"skipped\")\n        snode.assert_attr(type=\"pytest.skip\", message=\"hello25\")\n\n    @parametrize_families\n    def test_mark_skip_doesnt_capture_output(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skip(reason=\"foo\")\n            def test_skip():\n                print(\"bar!\")\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret == 0\n        node_xml = dom.get_first_by_tag(\"testsuite\").toxml()\n        assert \"bar!\" not in node_xml\n\n    @parametrize_families\n    def test_classname_instance(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            class TestClass(object):\n                def test_method(self):\n                    assert 0\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(failures=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(\n            classname=\"test_classname_instance.TestClass\", name=\"test_method\"\n        )\n\n    @parametrize_families\n    def test_classname_nested_dir(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        p = pytester.mkdir(\"sub\").joinpath(\"test_hello.py\")\n        p.write_text(\"def test_func(): 0/0\", encoding=\"utf-8\")\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(failures=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"sub.test_hello\", name=\"test_func\")\n\n    @parametrize_families\n    def test_internal_error(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makeconftest(\"def pytest_runtest_protocol(): 0 / 0\")\n        pytester.makepyfile(\"def test_function(): pass\")\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(errors=1, tests=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"pytest\", name=\"internal\")\n        fnode = tnode.get_first_by_tag(\"error\")\n        fnode.assert_attr(message=\"internal error\")\n        assert \"Division\" in fnode.toxml()\n\n    @pytest.mark.parametrize(\n        \"junit_logging\", [\"no\", \"log\", \"system-out\", \"system-err\", \"out-err\", \"all\"]\n    )\n    @parametrize_families\n    def test_failure_function(\n        self,\n        pytester: Pytester,\n        junit_logging: str,\n        run_and_parse: RunAndParse,\n        xunit_family: str,\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import logging\n            import sys\n\n            def test_fail():\n                print(\"hello-stdout\")\n                sys.stderr.write(\"hello-stderr\\\\n\")\n                logging.info('info msg')\n                logging.warning('warning msg')\n                raise ValueError(42)\n        \"\"\"\n        )\n\n        result, dom = run_and_parse(\n            \"-o\", f\"junit_logging={junit_logging}\", family=xunit_family\n        )\n        assert result.ret, \"Expected ret > 0\"\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(failures=1, tests=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"test_failure_function\", name=\"test_fail\")\n        fnode = tnode.get_first_by_tag(\"failure\")\n        fnode.assert_attr(message=\"ValueError: 42\")\n        assert \"ValueError\" in fnode.toxml(), \"ValueError not included\"\n\n        if junit_logging in [\"log\", \"all\"]:\n            logdata = tnode.get_first_by_tag(\"system-out\")\n            log_xml = logdata.toxml()\n            assert logdata.tag == \"system-out\", \"Expected tag: system-out\"\n            assert \"info msg\" not in log_xml, \"Unexpected INFO message\"\n            assert \"warning msg\" in log_xml, \"Missing WARN message\"\n        if junit_logging in [\"system-out\", \"out-err\", \"all\"]:\n            systemout = tnode.get_first_by_tag(\"system-out\")\n            systemout_xml = systemout.toxml()\n            assert systemout.tag == \"system-out\", \"Expected tag: system-out\"\n            assert \"info msg\" not in systemout_xml, \"INFO message found in system-out\"\n            assert \"hello-stdout\" in systemout_xml, (\n                \"Missing 'hello-stdout' in system-out\"\n            )\n        if junit_logging in [\"system-err\", \"out-err\", \"all\"]:\n            systemerr = tnode.get_first_by_tag(\"system-err\")\n            systemerr_xml = systemerr.toxml()\n            assert systemerr.tag == \"system-err\", \"Expected tag: system-err\"\n            assert \"info msg\" not in systemerr_xml, \"INFO message found in system-err\"\n            assert \"hello-stderr\" in systemerr_xml, (\n                \"Missing 'hello-stderr' in system-err\"\n            )\n            assert \"warning msg\" not in systemerr_xml, (\n                \"WARN message found in system-err\"\n            )\n        if junit_logging == \"no\":\n            assert not tnode.find_by_tag(\"log\"), \"Found unexpected content: log\"\n            assert not tnode.find_by_tag(\"system-out\"), (\n                \"Found unexpected content: system-out\"\n            )\n            assert not tnode.find_by_tag(\"system-err\"), (\n                \"Found unexpected content: system-err\"\n            )\n\n    @parametrize_families\n    def test_failure_verbose_message(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import sys\n            def test_fail():\n                assert 0, \"An error\"\n        \"\"\"\n        )\n        _result, dom = run_and_parse(family=xunit_family)\n        node = dom.get_first_by_tag(\"testsuite\")\n        tnode = node.get_first_by_tag(\"testcase\")\n        fnode = tnode.get_first_by_tag(\"failure\")\n        fnode.assert_attr(message=\"AssertionError: An error\\nassert 0\")\n\n    @parametrize_families\n    def test_failure_escape(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.parametrize('arg1', \"<&'\", ids=\"<&'\")\n            def test_func(arg1):\n                print(arg1)\n                assert 0\n        \"\"\"\n        )\n        result, dom = run_and_parse(\n            \"-o\", \"junit_logging=system-out\", family=xunit_family\n        )\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(failures=3, tests=3)\n        tnodes = node.find_by_tag(\"testcase\")\n        for tnode, char in zip(tnodes, \"<&'\", strict=True):\n            tnode.assert_attr(\n                classname=\"test_failure_escape\", name=f\"test_func[{char}]\"\n            )\n            sysout = tnode.get_first_by_tag(\"system-out\")\n            text = sysout.text\n            assert f\"{char}\\n\" in text\n\n    @parametrize_families\n    def test_junit_prefixing(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_func():\n                assert 0\n            class TestHello(object):\n                def test_hello(self):\n                    pass\n        \"\"\"\n        )\n        result, dom = run_and_parse(\"--junitprefix=xyz\", family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(failures=1, tests=2)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"xyz.test_junit_prefixing\", name=\"test_func\")\n        tnode = node.find_by_tag(\"testcase\")[1]\n        tnode.assert_attr(\n            classname=\"xyz.test_junit_prefixing.TestHello\", name=\"test_hello\"\n        )\n\n    @parametrize_families\n    def test_xfailure_function(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_xfail():\n                pytest.xfail(\"42\")\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert not result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(skipped=1, tests=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"test_xfailure_function\", name=\"test_xfail\")\n        fnode = tnode.get_first_by_tag(\"skipped\")\n        fnode.assert_attr(type=\"pytest.xfail\", message=\"42\")\n\n    @parametrize_families\n    def test_xfailure_marker(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail(reason=\"42\")\n            def test_xfail():\n                assert False\n        \"\"\"\n        )\n        result, dom = run_and_parse(family=xunit_family)\n        assert not result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(skipped=1, tests=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"test_xfailure_marker\", name=\"test_xfail\")\n        fnode = tnode.get_first_by_tag(\"skipped\")\n        fnode.assert_attr(type=\"pytest.xfail\", message=\"42\")\n\n    @pytest.mark.parametrize(\n        \"junit_logging\", [\"no\", \"log\", \"system-out\", \"system-err\", \"out-err\", \"all\"]\n    )\n    def test_xfail_captures_output_once(\n        self, pytester: Pytester, junit_logging: str, run_and_parse: RunAndParse\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import sys\n            import pytest\n\n            @pytest.mark.xfail()\n            def test_fail():\n                sys.stdout.write('XFAIL This is stdout')\n                sys.stderr.write('XFAIL This is stderr')\n                assert 0\n        \"\"\"\n        )\n        _result, dom = run_and_parse(\"-o\", f\"junit_logging={junit_logging}\")\n        node = dom.get_first_by_tag(\"testsuite\")\n        tnode = node.get_first_by_tag(\"testcase\")\n\n        has_err_logging = junit_logging in [\"system-err\", \"out-err\", \"all\"]\n        expected_err_output_len = 1 if has_err_logging else 0\n        assert len(tnode.find_by_tag(\"system-err\")) == expected_err_output_len\n\n        has_out_logigng = junit_logging in (\"log\", \"system-out\", \"out-err\", \"all\")\n        expected_out_output_len = 1 if has_out_logigng else 0\n\n        assert len(tnode.find_by_tag(\"system-out\")) == expected_out_output_len\n\n    @parametrize_families\n    def test_xfailure_xpass(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail\n            def test_xpass():\n                pass\n        \"\"\"\n        )\n        _result, dom = run_and_parse(family=xunit_family)\n        # assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(skipped=0, tests=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"test_xfailure_xpass\", name=\"test_xpass\")\n\n    @parametrize_families\n    def test_xfailure_xpass_strict(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail(strict=True, reason=\"This needs to fail!\")\n            def test_xpass():\n                pass\n        \"\"\"\n        )\n        _result, dom = run_and_parse(family=xunit_family)\n        # assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(skipped=0, tests=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(classname=\"test_xfailure_xpass_strict\", name=\"test_xpass\")\n        fnode = tnode.get_first_by_tag(\"failure\")\n        fnode.assert_attr(message=\"[XPASS(strict)] This needs to fail!\")\n\n    @parametrize_families\n    def test_collect_error(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makepyfile(\"syntax error\")\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(errors=1, tests=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        fnode = tnode.get_first_by_tag(\"error\")\n        fnode.assert_attr(message=\"collection failure\")\n        assert \"SyntaxError\" in fnode.toxml()\n\n    def test_unicode(self, pytester: Pytester, run_and_parse: RunAndParse) -> None:\n        value = \"hx\\xc4\\x85\\xc4\\x87\\n\"\n        pytester.makepyfile(\n            f\"\"\"\\\n            # coding: latin1\n            def test_hello():\n                print({value!r})\n                assert 0\n            \"\"\"\n        )\n        result, dom = run_and_parse()\n        assert result.ret == 1\n        tnode = dom.get_first_by_tag(\"testcase\")\n        fnode = tnode.get_first_by_tag(\"failure\")\n        assert \"hx\" in fnode.toxml()\n\n    def test_assertion_binchars(\n        self, pytester: Pytester, run_and_parse: RunAndParse\n    ) -> None:\n        \"\"\"This test did fail when the escaping wasn't strict.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n\n            M1 = '\\x01\\x02\\x03\\x04'\n            M2 = '\\x01\\x02\\x03\\x05'\n\n            def test_str_compare():\n                assert M1 == M2\n            \"\"\"\n        )\n        _result, dom = run_and_parse()\n        print(dom.toxml())\n\n    @pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-out\"])\n    def test_pass_captures_stdout(\n        self, pytester: Pytester, run_and_parse: RunAndParse, junit_logging: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_pass():\n                print('hello-stdout')\n        \"\"\"\n        )\n        _result, dom = run_and_parse(\"-o\", f\"junit_logging={junit_logging}\")\n        node = dom.get_first_by_tag(\"testsuite\")\n        pnode = node.get_first_by_tag(\"testcase\")\n        if junit_logging == \"no\":\n            assert not node.find_by_tag(\"system-out\"), (\n                \"system-out should not be generated\"\n            )\n        if junit_logging == \"system-out\":\n            systemout = pnode.get_first_by_tag(\"system-out\")\n            assert \"hello-stdout\" in systemout.toxml(), (\n                \"'hello-stdout' should be in system-out\"\n            )\n\n    @pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-err\"])\n    def test_pass_captures_stderr(\n        self, pytester: Pytester, run_and_parse: RunAndParse, junit_logging: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import sys\n            def test_pass():\n                sys.stderr.write('hello-stderr')\n        \"\"\"\n        )\n        _result, dom = run_and_parse(\"-o\", f\"junit_logging={junit_logging}\")\n        node = dom.get_first_by_tag(\"testsuite\")\n        pnode = node.get_first_by_tag(\"testcase\")\n        if junit_logging == \"no\":\n            assert not node.find_by_tag(\"system-err\"), (\n                \"system-err should not be generated\"\n            )\n        if junit_logging == \"system-err\":\n            systemerr = pnode.get_first_by_tag(\"system-err\")\n            assert \"hello-stderr\" in systemerr.toxml(), (\n                \"'hello-stderr' should be in system-err\"\n            )\n\n    @pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-out\"])\n    def test_setup_error_captures_stdout(\n        self, pytester: Pytester, run_and_parse: RunAndParse, junit_logging: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def arg(request):\n                print('hello-stdout')\n                raise ValueError()\n            def test_function(arg):\n                pass\n        \"\"\"\n        )\n        _result, dom = run_and_parse(\"-o\", f\"junit_logging={junit_logging}\")\n        node = dom.get_first_by_tag(\"testsuite\")\n        pnode = node.get_first_by_tag(\"testcase\")\n        if junit_logging == \"no\":\n            assert not node.find_by_tag(\"system-out\"), (\n                \"system-out should not be generated\"\n            )\n        if junit_logging == \"system-out\":\n            systemout = pnode.get_first_by_tag(\"system-out\")\n            assert \"hello-stdout\" in systemout.toxml(), (\n                \"'hello-stdout' should be in system-out\"\n            )\n\n    @pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-err\"])\n    def test_setup_error_captures_stderr(\n        self, pytester: Pytester, run_and_parse: RunAndParse, junit_logging: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import sys\n            import pytest\n\n            @pytest.fixture\n            def arg(request):\n                sys.stderr.write('hello-stderr')\n                raise ValueError()\n            def test_function(arg):\n                pass\n        \"\"\"\n        )\n        _result, dom = run_and_parse(\"-o\", f\"junit_logging={junit_logging}\")\n        node = dom.get_first_by_tag(\"testsuite\")\n        pnode = node.get_first_by_tag(\"testcase\")\n        if junit_logging == \"no\":\n            assert not node.find_by_tag(\"system-err\"), (\n                \"system-err should not be generated\"\n            )\n        if junit_logging == \"system-err\":\n            systemerr = pnode.get_first_by_tag(\"system-err\")\n            assert \"hello-stderr\" in systemerr.toxml(), (\n                \"'hello-stderr' should be in system-err\"\n            )\n\n    @pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-out\"])\n    def test_avoid_double_stdout(\n        self, pytester: Pytester, run_and_parse: RunAndParse, junit_logging: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import sys\n            import pytest\n\n            @pytest.fixture\n            def arg(request):\n                yield\n                sys.stdout.write('hello-stdout teardown')\n                raise ValueError()\n            def test_function(arg):\n                sys.stdout.write('hello-stdout call')\n        \"\"\"\n        )\n        _result, dom = run_and_parse(\"-o\", f\"junit_logging={junit_logging}\")\n        node = dom.get_first_by_tag(\"testsuite\")\n        pnode = node.get_first_by_tag(\"testcase\")\n        if junit_logging == \"no\":\n            assert not node.find_by_tag(\"system-out\"), (\n                \"system-out should not be generated\"\n            )\n        if junit_logging == \"system-out\":\n            systemout = pnode.get_first_by_tag(\"system-out\")\n            assert \"hello-stdout call\" in systemout.toxml()\n            assert \"hello-stdout teardown\" in systemout.toxml()\n\n\ndef test_mangle_test_address() -> None:\n    from _pytest.junitxml import mangle_test_address\n\n    address = \"::\".join([\"a/my.py.thing.py\", \"Class\", \"method\", \"[a-1-::]\"])\n    newnames = mangle_test_address(address)\n    assert newnames == [\"a.my.py.thing\", \"Class\", \"method\", \"[a-1-::]\"]\n\n\ndef test_dont_configure_on_workers(tmp_path: Path) -> None:\n    gotten: list[object] = []\n\n    class FakeConfig:\n        if TYPE_CHECKING:\n            workerinput = None\n\n        def __init__(self) -> None:\n            self.pluginmanager = self\n            self.option = self\n            self.stash = Stash()\n\n        def getini(self, name: str) -> str:\n            return \"pytest\"\n\n        junitprefix = None\n        # XXX: shouldn't need tmp_path ?\n        xmlpath = str(tmp_path.joinpath(\"junix.xml\"))\n        register = gotten.append\n\n    fake_config = cast(Config, FakeConfig())\n    from _pytest import junitxml\n\n    junitxml.pytest_configure(fake_config)\n    assert len(gotten) == 1\n    FakeConfig.workerinput = None\n    junitxml.pytest_configure(fake_config)\n    assert len(gotten) == 1\n\n\nclass TestNonPython:\n    @parametrize_families\n    def test_summing_simple(\n        self, pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n    ) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            def pytest_collect_file(file_path, parent):\n                if file_path.suffix == \".xyz\":\n                    return MyItem.from_parent(name=file_path.name, parent=parent)\n            class MyItem(pytest.Item):\n                def runtest(self):\n                    raise ValueError(42)\n                def repr_failure(self, excinfo):\n                    return \"custom item runtest failed\"\n        \"\"\"\n        )\n        pytester.path.joinpath(\"myfile.xyz\").write_text(\"hello\", encoding=\"utf-8\")\n        result, dom = run_and_parse(family=xunit_family)\n        assert result.ret\n        node = dom.get_first_by_tag(\"testsuite\")\n        node.assert_attr(errors=0, failures=1, skipped=0, tests=1)\n        tnode = node.get_first_by_tag(\"testcase\")\n        tnode.assert_attr(name=\"myfile.xyz\")\n        fnode = tnode.get_first_by_tag(\"failure\")\n        fnode.assert_attr(message=\"custom item runtest failed\")\n        assert \"custom item runtest failed\" in fnode.toxml()\n\n\n@pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-out\"])\ndef test_nullbyte(pytester: Pytester, junit_logging: str) -> None:\n    # A null byte cannot occur in XML (see section 2.2 of the spec)\n    pytester.makepyfile(\n        \"\"\"\n        import sys\n        def test_print_nullbyte():\n            sys.stdout.write('Here the null -->' + chr(0) + '<--')\n            sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')\n            assert False\n    \"\"\"\n    )\n    xmlf = pytester.path.joinpath(\"junit.xml\")\n    pytester.runpytest(f\"--junitxml={xmlf}\", \"-o\", f\"junit_logging={junit_logging}\")\n    text = xmlf.read_text(encoding=\"utf-8\")\n    assert \"\\x00\" not in text\n    if junit_logging == \"system-out\":\n        assert \"#x00\" in text\n    if junit_logging == \"no\":\n        assert \"#x00\" not in text\n\n\n@pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-out\"])\ndef test_nullbyte_replace(pytester: Pytester, junit_logging: str) -> None:\n    # Check if the null byte gets replaced\n    pytester.makepyfile(\n        \"\"\"\n        import sys\n        def test_print_nullbyte():\n            sys.stdout.write('Here the null -->' + chr(0) + '<--')\n            sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')\n            assert False\n    \"\"\"\n    )\n    xmlf = pytester.path.joinpath(\"junit.xml\")\n    pytester.runpytest(f\"--junitxml={xmlf}\", \"-o\", f\"junit_logging={junit_logging}\")\n    text = xmlf.read_text(encoding=\"utf-8\")\n    if junit_logging == \"system-out\":\n        assert \"#x0\" in text\n    if junit_logging == \"no\":\n        assert \"#x0\" not in text\n\n\ndef test_invalid_xml_escape() -> None:\n    # Test some more invalid xml chars, the full range should be\n    # tested really but let's just test the edges of the ranges\n    # instead.\n    # XXX This only tests low unicode character points for now as\n    #     there are some issues with the testing infrastructure for\n    #     the higher ones.\n    # XXX Testing 0xD (\\r) is tricky as it overwrites the just written\n    #     line in the output, so we skip it too.\n    invalid = (\n        0x00,\n        0x1,\n        0xB,\n        0xC,\n        0xE,\n        0x19,\n        27,  # issue #126\n        0xD800,\n        0xDFFF,\n        0xFFFE,\n        0x0FFFF,\n    )  # , 0x110000)\n    valid = (0x9, 0xA, 0x20)\n    # 0xD, 0xD7FF, 0xE000, 0xFFFD, 0x10000, 0x10FFFF)\n\n    for i in invalid:\n        got = bin_xml_escape(chr(i))\n        if i <= 0xFF:\n            expected = f\"#x{i:02X}\"\n        else:\n            expected = f\"#x{i:04X}\"\n        assert got == expected\n    for i in valid:\n        assert chr(i) == bin_xml_escape(chr(i))\n\n\ndef test_logxml_path_expansion(tmp_path: Path, monkeypatch: MonkeyPatch) -> None:\n    home_tilde = Path(os.path.expanduser(\"~\")).joinpath(\"test.xml\")\n    xml_tilde = LogXML(Path(\"~\", \"test.xml\"), None)\n    assert xml_tilde.logfile == str(home_tilde)\n\n    monkeypatch.setenv(\"HOME\", str(tmp_path))\n    home_var = os.path.normpath(os.path.expandvars(\"$HOME/test.xml\"))\n    xml_var = LogXML(Path(\"$HOME\", \"test.xml\"), None)\n    assert xml_var.logfile == str(home_var)\n\n\ndef test_logxml_changingdir(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_func():\n            import os\n            os.chdir(\"a\")\n    \"\"\"\n    )\n    pytester.mkdir(\"a\")\n    result = pytester.runpytest(\"--junitxml=a/x.xml\")\n    assert result.ret == 0\n    assert pytester.path.joinpath(\"a/x.xml\").exists()\n\n\ndef test_logxml_makedir(pytester: Pytester) -> None:\n    \"\"\"--junitxml should automatically create directories for the xml file\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        def test_pass():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--junitxml=path/to/results.xml\")\n    assert result.ret == 0\n    assert pytester.path.joinpath(\"path/to/results.xml\").exists()\n\n\ndef test_logxml_check_isdir(pytester: Pytester) -> None:\n    \"\"\"Give an error if --junit-xml is a directory (#2089)\"\"\"\n    result = pytester.runpytest(\"--junit-xml=.\")\n    result.stderr.fnmatch_lines([\"*--junitxml must be a filename*\"])\n\n\ndef test_escaped_parametrized_names_xml(\n    pytester: Pytester, run_and_parse: RunAndParse\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\\\n        import pytest\n        @pytest.mark.parametrize('char', [\"\\\\x00\"])\n        def test_func(char):\n            assert char\n        \"\"\"\n    )\n    result, dom = run_and_parse()\n    assert result.ret == 0\n    node = dom.get_first_by_tag(\"testcase\")\n    node.assert_attr(name=\"test_func[\\\\x00]\")\n\n\ndef test_double_colon_split_function_issue469(\n    pytester: Pytester, run_and_parse: RunAndParse\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.parametrize('param', [\"double::colon\"])\n        def test_func(param):\n            pass\n    \"\"\"\n    )\n    result, dom = run_and_parse()\n    assert result.ret == 0\n    node = dom.get_first_by_tag(\"testcase\")\n    node.assert_attr(classname=\"test_double_colon_split_function_issue469\")\n    node.assert_attr(name=\"test_func[double::colon]\")\n\n\ndef test_double_colon_split_method_issue469(\n    pytester: Pytester, run_and_parse: RunAndParse\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        class TestClass(object):\n            @pytest.mark.parametrize('param', [\"double::colon\"])\n            def test_func(self, param):\n                pass\n    \"\"\"\n    )\n    result, dom = run_and_parse()\n    assert result.ret == 0\n    node = dom.get_first_by_tag(\"testcase\")\n    node.assert_attr(classname=\"test_double_colon_split_method_issue469.TestClass\")\n    node.assert_attr(name=\"test_func[double::colon]\")\n\n\ndef test_unicode_issue368(pytester: Pytester) -> None:\n    path = pytester.path.joinpath(\"test.xml\")\n    log = LogXML(str(path), None)\n    ustr = \"ВНИ!\"\n\n    class Report(BaseReport):\n        longrepr = ustr\n        sections: list[tuple[str, str]] = []\n        nodeid = \"something\"\n        location = \"tests/filename.py\", 42, \"TestClass.method\"\n        when = \"teardown\"\n\n    test_report = cast(TestReport, Report())\n\n    # hopefully this is not too brittle ...\n    log.pytest_sessionstart()\n    node_reporter = log._opentestcase(test_report)\n    node_reporter.append_failure(test_report)\n    node_reporter.append_collect_error(test_report)\n    node_reporter.append_collect_skipped(test_report)\n    node_reporter.append_error(test_report)\n    test_report.longrepr = \"filename\", 1, ustr\n    node_reporter.append_skipped(test_report)\n    test_report.longrepr = \"filename\", 1, \"Skipped: 卡嘣嘣\"\n    node_reporter.append_skipped(test_report)\n    test_report.wasxfail = ustr\n    node_reporter.append_skipped(test_report)\n    log.pytest_sessionfinish()\n\n\ndef test_record_property(pytester: Pytester, run_and_parse: RunAndParse) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def other(record_property):\n            record_property(\"bar\", 1)\n        def test_record(record_property, other):\n            record_property(\"foo\", \"<1\");\n    \"\"\"\n    )\n    result, dom = run_and_parse()\n    node = dom.get_first_by_tag(\"testsuite\")\n    tnode = node.get_first_by_tag(\"testcase\")\n    psnode = tnode.get_first_by_tag(\"properties\")\n    pnodes = psnode.find_by_tag(\"property\")\n    pnodes[0].assert_attr(name=\"bar\", value=\"1\")\n    pnodes[1].assert_attr(name=\"foo\", value=\"<1\")\n    result.stdout.fnmatch_lines([\"*= 1 passed in *\"])\n\n\ndef test_record_property_on_test_and_teardown_failure(\n    pytester: Pytester, run_and_parse: RunAndParse\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def other(record_property):\n            record_property(\"bar\", 1)\n            yield\n            assert 0\n\n        def test_record(record_property, other):\n            record_property(\"foo\", \"<1\")\n            assert 0\n    \"\"\"\n    )\n    result, dom = run_and_parse()\n    node = dom.get_first_by_tag(\"testsuite\")\n    tnodes = node.find_by_tag(\"testcase\")\n    for tnode in tnodes:\n        psnode = tnode.get_first_by_tag(\"properties\")\n        assert psnode, f\"testcase didn't had expected properties:\\n{tnode}\"\n        pnodes = psnode.find_by_tag(\"property\")\n        pnodes[0].assert_attr(name=\"bar\", value=\"1\")\n        pnodes[1].assert_attr(name=\"foo\", value=\"<1\")\n    result.stdout.fnmatch_lines([\"*= 1 failed, 1 error *\"])\n\n\ndef test_record_property_same_name(\n    pytester: Pytester, run_and_parse: RunAndParse\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_record_with_same_name(record_property):\n            record_property(\"foo\", \"bar\")\n            record_property(\"foo\", \"baz\")\n    \"\"\"\n    )\n    _result, dom = run_and_parse()\n    node = dom.get_first_by_tag(\"testsuite\")\n    tnode = node.get_first_by_tag(\"testcase\")\n    psnode = tnode.get_first_by_tag(\"properties\")\n    pnodes = psnode.find_by_tag(\"property\")\n    pnodes[0].assert_attr(name=\"foo\", value=\"bar\")\n    pnodes[1].assert_attr(name=\"foo\", value=\"baz\")\n\n\n@pytest.mark.parametrize(\"fixture_name\", [\"record_property\", \"record_xml_attribute\"])\ndef test_record_fixtures_without_junitxml(\n    pytester: Pytester, fixture_name: str\n) -> None:\n    pytester.makepyfile(\n        f\"\"\"\n        def test_record({fixture_name}):\n            {fixture_name}(\"foo\", \"bar\")\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_record_attribute(pytester: Pytester, run_and_parse: RunAndParse) -> None:\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        junit_family = xunit1\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def other(record_xml_attribute):\n            record_xml_attribute(\"bar\", 1)\n        def test_record(record_xml_attribute, other):\n            record_xml_attribute(\"foo\", \"<1\");\n    \"\"\"\n    )\n    result, dom = run_and_parse()\n    node = dom.get_first_by_tag(\"testsuite\")\n    tnode = node.get_first_by_tag(\"testcase\")\n    tnode.assert_attr(bar=\"1\")\n    tnode.assert_attr(foo=\"<1\")\n    result.stdout.fnmatch_lines(\n        [\"*test_record_attribute.py:6:*record_xml_attribute is an experimental feature\"]\n    )\n\n\n@pytest.mark.filterwarnings(\"default\")\n@pytest.mark.parametrize(\"fixture_name\", [\"record_xml_attribute\", \"record_property\"])\ndef test_record_fixtures_xunit2(\n    pytester: Pytester, fixture_name: str, run_and_parse: RunAndParse\n) -> None:\n    \"\"\"Ensure record_xml_attribute and record_property drop values when outside of legacy family.\"\"\"\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        junit_family = xunit2\n    \"\"\"\n    )\n    pytester.makepyfile(\n        f\"\"\"\n        import pytest\n\n        @pytest.fixture\n        def other({fixture_name}):\n            {fixture_name}(\"bar\", 1)\n        def test_record({fixture_name}, other):\n            {fixture_name}(\"foo\", \"<1\");\n    \"\"\"\n    )\n\n    result, _dom = run_and_parse(family=None)\n    expected_lines = []\n    if fixture_name == \"record_xml_attribute\":\n        expected_lines.append(\n            \"*test_record_fixtures_xunit2.py:6:*record_xml_attribute is an experimental feature\"\n        )\n    expected_lines = [\n        f\"*test_record_fixtures_xunit2.py:6:*{fixture_name} is incompatible \"\n        \"with junit_family 'xunit2' (use 'legacy' or 'xunit1')\"\n    ]\n    result.stdout.fnmatch_lines(expected_lines)\n\n\ndef test_random_report_log_xdist(\n    pytester: Pytester, monkeypatch: MonkeyPatch, run_and_parse: RunAndParse\n) -> None:\n    \"\"\"`xdist` calls pytest_runtest_logreport as they are executed by the workers,\n    with nodes from several nodes overlapping, so junitxml must cope with that\n    to produce correct reports (#1064).\"\"\"\n    pytest.importorskip(\"xdist\")\n    monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n    pytester.makepyfile(\n        \"\"\"\n        import pytest, time\n        @pytest.mark.parametrize('i', list(range(30)))\n        def test_x(i):\n            assert i != 22\n    \"\"\"\n    )\n    _, dom = run_and_parse(\"-n2\")\n    suite_node = dom.get_first_by_tag(\"testsuite\")\n    failed = []\n    for case_node in suite_node.find_by_tag(\"testcase\"):\n        if case_node.find_first_by_tag(\"failure\"):\n            failed.append(case_node[\"name\"])\n\n    assert failed == [\"test_x[22]\"]\n\n\n@parametrize_families\ndef test_root_testsuites_tag(\n    pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_x():\n            pass\n    \"\"\"\n    )\n    _, dom = run_and_parse(family=xunit_family)\n    root = dom.get_unique_child\n    assert root.tag == \"testsuites\"\n    root.assert_attr(name=\"pytest tests\")\n    suite_node = root.get_unique_child\n    assert suite_node.tag == \"testsuite\"\n\n\ndef test_runs_twice(pytester: Pytester, run_and_parse: RunAndParse) -> None:\n    f = pytester.makepyfile(\n        \"\"\"\n        def test_pass():\n            pass\n    \"\"\"\n    )\n\n    result, dom = run_and_parse(\"--keep-duplicates\", f, f)\n    result.stdout.no_fnmatch_line(\"*INTERNALERROR*\")\n    first, second = (x[\"classname\"] for x in dom.find_by_tag(\"testcase\"))\n    assert first == second\n\n\ndef test_runs_twice_xdist(\n    pytester: Pytester, monkeypatch: MonkeyPatch, run_and_parse: RunAndParse\n) -> None:\n    pytest.importorskip(\"xdist\")\n    monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\")\n    f = pytester.makepyfile(\n        \"\"\"\n        def test_pass():\n            pass\n    \"\"\"\n    )\n\n    result, dom = run_and_parse(f, \"--dist\", \"each\", \"--tx\", \"2*popen\")\n    result.stdout.no_fnmatch_line(\"*INTERNALERROR*\")\n    first, second = (x[\"classname\"] for x in dom.find_by_tag(\"testcase\"))\n    assert first == second\n\n\ndef test_fancy_items_regression(pytester: Pytester, run_and_parse: RunAndParse) -> None:\n    # issue 1259\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n        class FunItem(pytest.Item):\n            def runtest(self):\n                pass\n        class NoFunItem(pytest.Item):\n            def runtest(self):\n                pass\n\n        class FunCollector(pytest.File):\n            def collect(self):\n                return [\n                    FunItem.from_parent(name='a', parent=self),\n                    NoFunItem.from_parent(name='a', parent=self),\n                    NoFunItem.from_parent(name='b', parent=self),\n                ]\n\n        def pytest_collect_file(file_path, parent):\n            if file_path.suffix == '.py':\n                return FunCollector.from_parent(path=file_path, parent=parent)\n    \"\"\"\n    )\n\n    pytester.makepyfile(\n        \"\"\"\n        def test_pass():\n            pass\n    \"\"\"\n    )\n\n    result, dom = run_and_parse()\n\n    result.stdout.no_fnmatch_line(\"*INTERNALERROR*\")\n\n    items = sorted(\n        f\"{x['classname']} {x['name']}\"\n        # dom is a DomNode not a mapping, it's not possible to ** it.\n        for x in dom.find_by_tag(\"testcase\")\n    )\n\n    import pprint\n\n    pprint.pprint(items)\n    assert items == [\n        \"conftest a\",\n        \"conftest a\",\n        \"conftest b\",\n        \"test_fancy_items_regression a\",\n        \"test_fancy_items_regression a\",\n        \"test_fancy_items_regression b\",\n        \"test_fancy_items_regression test_pass\",\n    ]\n\n\n@parametrize_families\ndef test_global_properties(pytester: Pytester, xunit_family: str) -> None:\n    path = pytester.path.joinpath(\"test_global_properties.xml\")\n    log = LogXML(str(path), None, family=xunit_family)\n\n    class Report(BaseReport):\n        sections: list[tuple[str, str]] = []\n        nodeid = \"test_node_id\"\n\n    log.pytest_sessionstart()\n    log.add_global_property(\"foo\", \"1\")\n    log.add_global_property(\"bar\", \"2\")\n    log.pytest_sessionfinish()\n\n    dom = minidom.parse(str(path))\n\n    properties = dom.getElementsByTagName(\"properties\")\n\n    assert properties.length == 1, \"There must be one <properties> node\"\n\n    property_list = dom.getElementsByTagName(\"property\")\n\n    assert property_list.length == 2, \"There most be only 2 property nodes\"\n\n    expected = {\"foo\": \"1\", \"bar\": \"2\"}\n    actual = {}\n\n    for p in property_list:\n        k = str(p.getAttribute(\"name\"))\n        v = str(p.getAttribute(\"value\"))\n        actual[k] = v\n\n    assert actual == expected\n\n\ndef test_url_property(pytester: Pytester) -> None:\n    test_url = \"http://www.github.com/pytest-dev\"\n    path = pytester.path.joinpath(\"test_url_property.xml\")\n    log = LogXML(str(path), None)\n\n    class Report(BaseReport):\n        longrepr = \"FooBarBaz\"\n        sections: list[tuple[str, str]] = []\n        nodeid = \"something\"\n        location = \"tests/filename.py\", 42, \"TestClass.method\"\n        url = test_url\n\n    test_report = cast(TestReport, Report())\n\n    log.pytest_sessionstart()\n    node_reporter = log._opentestcase(test_report)\n    node_reporter.append_failure(test_report)\n    log.pytest_sessionfinish()\n\n    test_case = minidom.parse(str(path)).getElementsByTagName(\"testcase\")[0]\n\n    assert test_case.getAttribute(\"url\") == test_url, (\n        \"The URL did not get written to the xml\"\n    )\n\n\n@parametrize_families\ndef test_record_testsuite_property(\n    pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_func1(record_testsuite_property):\n            record_testsuite_property(\"stats\", \"all good\")\n\n        def test_func2(record_testsuite_property):\n            record_testsuite_property(\"stats\", 10)\n    \"\"\"\n    )\n    result, dom = run_and_parse(family=xunit_family)\n    assert result.ret == 0\n    node = dom.get_first_by_tag(\"testsuite\")\n    properties_node = node.get_first_by_tag(\"properties\")\n    p1_node, p2_node = properties_node.find_by_tag(\n        \"property\",\n    )[:2]\n    p1_node.assert_attr(name=\"stats\", value=\"all good\")\n    p2_node.assert_attr(name=\"stats\", value=\"10\")\n\n\ndef test_record_testsuite_property_junit_disabled(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_func1(record_testsuite_property):\n            record_testsuite_property(\"stats\", \"all good\")\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n\n\n@pytest.mark.parametrize(\"junit\", [True, False])\ndef test_record_testsuite_property_type_checking(\n    pytester: Pytester, junit: bool\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_func1(record_testsuite_property):\n            record_testsuite_property(1, 2)\n    \"\"\"\n    )\n    args = (\"--junitxml=tests.xml\",) if junit else ()\n    result = pytester.runpytest(*args)\n    assert result.ret == 1\n    result.stdout.fnmatch_lines(\n        [\"*TypeError: name parameter needs to be a string, but int given\"]\n    )\n\n\n@pytest.mark.parametrize(\"suite_name\", [\"my_suite\", \"\"])\n@parametrize_families\ndef test_set_suite_name(\n    pytester: Pytester, suite_name: str, run_and_parse: RunAndParse, xunit_family: str\n) -> None:\n    if suite_name:\n        pytester.makeini(\n            f\"\"\"\n            [pytest]\n            junit_suite_name={suite_name}\n            junit_family={xunit_family}\n        \"\"\"\n        )\n        expected = suite_name\n    else:\n        expected = \"pytest\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def test_func():\n            pass\n    \"\"\"\n    )\n    result, dom = run_and_parse(family=xunit_family)\n    assert result.ret == 0\n    node = dom.get_first_by_tag(\"testsuite\")\n    node.assert_attr(name=expected)\n\n\ndef test_escaped_skipreason_issue3533(\n    pytester: Pytester, run_and_parse: RunAndParse\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.skip(reason='1 <> 2')\n        def test_skip():\n            pass\n    \"\"\"\n    )\n    _, dom = run_and_parse()\n    node = dom.get_first_by_tag(\"testcase\")\n    snode = node.get_first_by_tag(\"skipped\")\n    assert \"1 <> 2\" in snode.text\n    snode.assert_attr(message=\"1 <> 2\")\n\n\ndef test_bin_escaped_skipreason(pytester: Pytester, run_and_parse: RunAndParse) -> None:\n    \"\"\"Escape special characters from mark.skip reason (#11842).\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.skip(\"\\33[31;1mred\\33[0m\")\n        def test_skip():\n            pass\n    \"\"\"\n    )\n    _, dom = run_and_parse()\n    node = dom.get_first_by_tag(\"testcase\")\n    snode = node.get_first_by_tag(\"skipped\")\n    assert \"#x1B[31;1mred#x1B[0m\" in snode.text\n    snode.assert_attr(message=\"#x1B[31;1mred#x1B[0m\")\n\n\ndef test_escaped_setup_teardown_error(\n    pytester: Pytester, run_and_parse: RunAndParse\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture()\n        def my_setup():\n            raise Exception(\"error: \\033[31mred\\033[m\")\n\n        def test_esc(my_setup):\n            pass\n    \"\"\"\n    )\n    _, dom = run_and_parse()\n    node = dom.get_first_by_tag(\"testcase\")\n    snode = node.get_first_by_tag(\"error\")\n    assert \"#x1B[31mred#x1B[m\" in snode[\"message\"]\n    assert \"#x1B[31mred#x1B[m\" in snode.text\n\n\n@parametrize_families\ndef test_logging_passing_tests_disabled_does_not_log_test_output(\n    pytester: Pytester, run_and_parse: RunAndParse, xunit_family: str\n) -> None:\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        junit_log_passing_tests=False\n        junit_logging=system-out\n        junit_family={xunit_family}\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        import sys\n\n        def test_func():\n            sys.stdout.write('This is stdout')\n            sys.stderr.write('This is stderr')\n            logging.warning('hello')\n    \"\"\"\n    )\n    result, dom = run_and_parse(family=xunit_family)\n    assert result.ret == 0\n    node = dom.get_first_by_tag(\"testcase\")\n    assert len(node.find_by_tag(\"system-err\")) == 0\n    assert len(node.find_by_tag(\"system-out\")) == 0\n\n\n@parametrize_families\n@pytest.mark.parametrize(\"junit_logging\", [\"no\", \"system-out\", \"system-err\"])\ndef test_logging_passing_tests_disabled_logs_output_for_failing_test_issue5430(\n    pytester: Pytester,\n    junit_logging: str,\n    run_and_parse: RunAndParse,\n    xunit_family: str,\n) -> None:\n    pytester.makeini(\n        f\"\"\"\n        [pytest]\n        junit_log_passing_tests=False\n        junit_family={xunit_family}\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import logging\n        import sys\n\n        def test_func():\n            logging.warning('hello')\n            assert 0\n    \"\"\"\n    )\n    result, dom = run_and_parse(\n        \"-o\", f\"junit_logging={junit_logging}\", family=xunit_family\n    )\n    assert result.ret == 1\n    node = dom.get_first_by_tag(\"testcase\")\n    if junit_logging == \"system-out\":\n        assert len(node.find_by_tag(\"system-err\")) == 0\n        assert len(node.find_by_tag(\"system-out\")) == 1\n    elif junit_logging == \"system-err\":\n        assert len(node.find_by_tag(\"system-err\")) == 1\n        assert len(node.find_by_tag(\"system-out\")) == 0\n    else:\n        assert junit_logging == \"no\"\n        assert len(node.find_by_tag(\"system-err\")) == 0\n        assert len(node.find_by_tag(\"system-out\")) == 0\n\n\ndef test_no_message_quiet(pytester: Pytester) -> None:\n    \"\"\"Do not show the summary banner when --quiet is given (#13700).\"\"\"\n    pytester.makepyfile(\"def test(): pass\")\n    result = pytester.runpytest(\"--junitxml=pytest.xml\")\n    result.stdout.fnmatch_lines(\"* generated xml file: *\")\n\n    result = pytester.runpytest(\"--junitxml=pytest.xml\", \"--quiet\")\n    result.stdout.no_fnmatch_line(\"* generated xml file: *\")\n"
  },
  {
    "path": "testing/test_legacypath.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom pathlib import Path\n\nfrom _pytest.compat import LEGACY_PATH\nfrom _pytest.fixtures import TopRequest\nfrom _pytest.legacypath import TempdirFactory\nfrom _pytest.legacypath import Testdir\nimport pytest\n\n\ndef test_item_fspath(pytester: pytest.Pytester) -> None:\n    pytester.makepyfile(\"def test_func(): pass\")\n    items, _hookrec = pytester.inline_genitems()\n    assert len(items) == 1\n    (item,) = items\n    items2, _hookrec = pytester.inline_genitems(item.nodeid)\n    (item2,) = items2\n    assert item2.name == item.name\n    assert item2.fspath == item.fspath\n    assert item2.path == item.path\n\n\ndef test_testdir_testtmproot(testdir: Testdir) -> None:\n    \"\"\"Check test_tmproot is a py.path attribute for backward compatibility.\"\"\"\n    assert testdir.test_tmproot.check(dir=1)\n\n\ndef test_testdir_makefile_dot_prefixes_extension_silently(\n    testdir: Testdir,\n) -> None:\n    \"\"\"For backwards compat #8192\"\"\"\n    p1 = testdir.makefile(\"foo.bar\", \"\")\n    assert \".foo.bar\" in str(p1)\n\n\ndef test_testdir_makefile_ext_none_raises_type_error(testdir: Testdir) -> None:\n    \"\"\"For backwards compat #8192\"\"\"\n    with pytest.raises(TypeError):\n        testdir.makefile(None, \"\")\n\n\ndef test_testdir_makefile_ext_empty_string_makes_file(testdir: Testdir) -> None:\n    \"\"\"For backwards compat #8192\"\"\"\n    p1 = testdir.makefile(\"\", \"\")\n    assert \"test_testdir_makefile\" in str(p1)\n\n\ndef attempt_symlink_to(path: str, to_path: str) -> None:\n    \"\"\"Try to make a symlink from \"path\" to \"to_path\", skipping in case this platform\n    does not support it or we don't have sufficient privileges (common on Windows).\"\"\"\n    try:\n        Path(path).symlink_to(Path(to_path))\n    except OSError:\n        pytest.skip(\"could not create symbolic link\")\n\n\ndef test_tmpdir_factory(\n    tmpdir_factory: TempdirFactory,\n    tmp_path_factory: pytest.TempPathFactory,\n) -> None:\n    assert str(tmpdir_factory.getbasetemp()) == str(tmp_path_factory.getbasetemp())\n    dir = tmpdir_factory.mktemp(\"foo\")\n    assert dir.exists()\n\n\ndef test_tmpdir_equals_tmp_path(tmpdir: LEGACY_PATH, tmp_path: Path) -> None:\n    assert Path(tmpdir) == tmp_path\n\n\ndef test_tmpdir_always_is_realpath(pytester: pytest.Pytester) -> None:\n    # See test_tmp_path_always_is_realpath.\n    realtemp = pytester.mkdir(\"myrealtemp\")\n    linktemp = pytester.path.joinpath(\"symlinktemp\")\n    attempt_symlink_to(str(linktemp), str(realtemp))\n    p = pytester.makepyfile(\n        \"\"\"\n        def test_1(tmpdir):\n            import os\n            assert os.path.realpath(str(tmpdir)) == str(tmpdir)\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-s\", p, f\"--basetemp={linktemp}/bt\")\n    assert not result.ret\n\n\ndef test_cache_makedir(cache: pytest.Cache) -> None:\n    dir = cache.makedir(\"foo\")  # type: ignore[attr-defined]\n    assert dir.exists()\n    dir.remove()\n\n\ndef test_fixturerequest_getmodulepath(pytester: pytest.Pytester) -> None:\n    modcol = pytester.getmodulecol(\"def test_somefunc(): pass\")\n    (item,) = pytester.genitems([modcol])\n    assert isinstance(item, pytest.Function)\n    req = TopRequest(item, _ispytest=True)\n    assert req.path == modcol.path\n    assert req.fspath == modcol.fspath  # type: ignore[attr-defined]\n\n\nclass TestFixtureRequestSessionScoped:\n    @pytest.fixture(scope=\"session\")\n    def session_request(self, request):\n        return request\n\n    def test_session_scoped_unavailable_attributes(self, session_request):\n        with pytest.raises(\n            AttributeError,\n            match=\"path not available in session-scoped context\",\n        ):\n            _ = session_request.fspath\n\n\n@pytest.mark.parametrize(\"config_type\", [\"ini\", \"toml\"])\ndef test_addini_paths(pytester: pytest.Pytester, config_type: str) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_addoption(parser):\n            parser.addini(\"paths\", \"my new ini value\", type=\"pathlist\")\n            parser.addini(\"abc\", \"abc value\")\n    \"\"\"\n    )\n    if config_type == \"ini\":\n        inipath = pytester.makeini(\n            \"\"\"\n            [pytest]\n            paths = hello world/sub.py\n            \"\"\"\n        )\n    else:\n        inipath = pytester.maketoml(\n            \"\"\"\n            [pytest]\n            paths = [\"hello\", \"world/sub.py\"]\n            \"\"\"\n        )\n    config = pytester.parseconfig()\n    values = config.getini(\"paths\")\n    assert len(values) == 2\n    assert values[0] == inipath.parent.joinpath(\"hello\")\n    assert values[1] == inipath.parent.joinpath(\"world/sub.py\")\n    pytest.raises(ValueError, config.getini, \"other\")\n\n\ndef test_override_ini_paths(pytester: pytest.Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_addoption(parser):\n            parser.addini(\"paths\", \"my new ini value\", type=\"pathlist\")\"\"\"\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        paths=blah.py\"\"\"\n    )\n    pytester.makepyfile(\n        r\"\"\"\n        def test_overridden(pytestconfig):\n            config_paths = pytestconfig.getini(\"paths\")\n            print(config_paths)\n            for cpf in config_paths:\n                print('\\nuser_path:%s' % cpf.basename)\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--override-ini\", \"paths=foo/bar1.py foo/bar2.py\", \"-s\")\n    result.stdout.fnmatch_lines([\"user_path:bar1.py\", \"user_path:bar2.py\"])\n\n\ndef test_inifile_from_cmdline_main_hook(pytester: pytest.Pytester) -> None:\n    \"\"\"Ensure Config.inifile is available during pytest_cmdline_main (#9396).\"\"\"\n    p = pytester.makeini(\n        \"\"\"\n        [pytest]\n        \"\"\"\n    )\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_cmdline_main(config):\n            print(\"pytest_cmdline_main inifile =\", config.inifile)\n        \"\"\"\n    )\n    result = pytester.runpytest_subprocess(\"-s\")\n    result.stdout.fnmatch_lines(f\"*pytest_cmdline_main inifile = {p}\")\n"
  },
  {
    "path": "testing/test_link_resolve.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom contextlib import contextmanager\nimport os.path\nfrom pathlib import Path\nfrom string import ascii_lowercase\nimport subprocess\nimport sys\nimport textwrap\n\nfrom _pytest.pytester import Pytester\n\n\n@contextmanager\ndef subst_path_windows(filepath: Path):\n    for c in ascii_lowercase[7:]:  # Create a subst drive from H-Z.\n        c += \":\"\n        if not os.path.exists(c):\n            drive = c\n            break\n    else:\n        raise AssertionError(\"Unable to find suitable drive letter for subst.\")\n\n    directory = filepath.parent\n    basename = filepath.name\n\n    args = [\"subst\", drive, str(directory)]\n    subprocess.check_call(args)\n    assert os.path.exists(drive)\n    try:\n        filename = Path(drive, os.sep, basename)\n        yield filename\n    finally:\n        args = [\"subst\", \"/D\", drive]\n        subprocess.check_call(args)\n\n\n@contextmanager\ndef subst_path_linux(filepath: Path):\n    directory = filepath.parent\n    basename = filepath.name\n\n    target = directory / \"..\" / \"sub2\"\n    os.symlink(str(directory), str(target), target_is_directory=True)\n    try:\n        filename = target / basename\n        yield filename\n    finally:\n        # We don't need to unlink (it's all in the tempdir).\n        pass\n\n\ndef test_link_resolve(pytester: Pytester) -> None:\n    \"\"\"See: https://github.com/pytest-dev/pytest/issues/5965.\"\"\"\n    sub1 = pytester.mkpydir(\"sub1\")\n    p = sub1.joinpath(\"test_foo.py\")\n    p.write_text(\n        textwrap.dedent(\n            \"\"\"\n        import pytest\n        def test_foo():\n            raise AssertionError()\n        \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n\n    subst = subst_path_linux\n    if sys.platform == \"win32\":\n        subst = subst_path_windows\n\n    with subst(p) as subst_p:\n        result = pytester.runpytest(str(subst_p), \"-v\")\n        # i.e.: Make sure that the error is reported as a relative path, not as a\n        # resolved path.\n        # See: https://github.com/pytest-dev/pytest/issues/5965\n        stdout = result.stdout.str()\n        assert \"sub1/test_foo.py\" not in stdout\n\n        # i.e.: Expect drive on windows because we just have drive:filename, whereas\n        # we expect a relative path on Linux.\n        expect = f\"*{subst_p}*\" if sys.platform == \"win32\" else \"*sub2/test_foo.py*\"\n        result.stdout.fnmatch_lines([expect])\n"
  },
  {
    "path": "testing/test_main.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport argparse\nimport os\nfrom pathlib import Path\nimport re\n\nfrom _pytest.config import ExitCode\nfrom _pytest.config import UsageError\nfrom _pytest.main import CollectionArgument\nfrom _pytest.main import resolve_collection_argument\nfrom _pytest.main import validate_basetemp\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\n@pytest.mark.parametrize(\n    \"ret_exc\",\n    (\n        pytest.param((None, ValueError)),\n        pytest.param((42, SystemExit)),\n        pytest.param((False, SystemExit)),\n    ),\n)\ndef test_wrap_session_notify_exception(ret_exc, pytester: Pytester) -> None:\n    returncode, exc = ret_exc\n    c1 = pytester.makeconftest(\n        f\"\"\"\n        import pytest\n\n        def pytest_sessionstart():\n            raise {exc.__name__}(\"boom\")\n\n        def pytest_internalerror(excrepr, excinfo):\n            returncode = {returncode!r}\n            if returncode is not False:\n                pytest.exit(\"exiting after %s...\" % excinfo.typename, returncode={returncode!r})\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    if returncode:\n        assert result.ret == returncode\n    else:\n        assert result.ret == ExitCode.INTERNAL_ERROR\n    assert result.stdout.lines[0] == \"INTERNALERROR> Traceback (most recent call last):\"\n\n    end_lines = result.stdout.lines[-3:]\n\n    if exc == SystemExit:\n        assert end_lines == [\n            f'INTERNALERROR>   File \"{c1}\", line 4, in pytest_sessionstart',\n            'INTERNALERROR>     raise SystemExit(\"boom\")',\n            \"INTERNALERROR> SystemExit: boom\",\n        ]\n    else:\n        assert end_lines == [\n            f'INTERNALERROR>   File \"{c1}\", line 4, in pytest_sessionstart',\n            'INTERNALERROR>     raise ValueError(\"boom\")',\n            \"INTERNALERROR> ValueError: boom\",\n        ]\n    if returncode is False:\n        assert result.stderr.lines == [\"mainloop: caught unexpected SystemExit!\"]\n    else:\n        assert result.stderr.lines == [f\"Exit: exiting after {exc.__name__}...\"]\n\n\n@pytest.mark.parametrize(\"returncode\", (None, 42))\ndef test_wrap_session_exit_sessionfinish(\n    returncode: int | None, pytester: Pytester\n) -> None:\n    pytester.makeconftest(\n        f\"\"\"\n        import pytest\n        def pytest_sessionfinish():\n            pytest.exit(reason=\"exit_pytest_sessionfinish\", returncode={returncode})\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    if returncode:\n        assert result.ret == returncode\n    else:\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n    assert result.stdout.lines[-1] == \"collected 0 items\"\n    assert result.stderr.lines == [\"Exit: exit_pytest_sessionfinish\"]\n\n\n@pytest.mark.parametrize(\"basetemp\", [\"foo\", \"foo/bar\"])\ndef test_validate_basetemp_ok(tmp_path, basetemp, monkeypatch):\n    monkeypatch.chdir(str(tmp_path))\n    validate_basetemp(tmp_path / basetemp)\n\n\n@pytest.mark.parametrize(\"basetemp\", [\"\", \".\", \"..\"])\ndef test_validate_basetemp_fails(tmp_path, basetemp, monkeypatch):\n    monkeypatch.chdir(str(tmp_path))\n    msg = \"basetemp must not be empty, the current working directory or any parent directory of it\"\n    with pytest.raises(argparse.ArgumentTypeError, match=msg):\n        if basetemp:\n            basetemp = tmp_path / basetemp\n        validate_basetemp(basetemp)\n\n\ndef test_validate_basetemp_integration(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--basetemp=.\")\n    result.stderr.fnmatch_lines(\"*basetemp must not be*\")\n\n\nclass TestResolveCollectionArgument:\n    @pytest.fixture\n    def invocation_path(self, pytester: Pytester) -> Path:\n        pytester.syspathinsert(pytester.path / \"src\")\n        pytester.chdir()\n\n        pkg = pytester.path.joinpath(\"src/pkg\")\n        pkg.mkdir(parents=True)\n        pkg.joinpath(\"__init__.py\").touch()\n        pkg.joinpath(\"test.py\").touch()\n        return pytester.path\n\n    def test_file(self, invocation_path: Path) -> None:\n        \"\"\"File and parts.\"\"\"\n        assert resolve_collection_argument(\n            invocation_path, \"src/pkg/test.py\", 0\n        ) == CollectionArgument(\n            path=invocation_path / \"src/pkg/test.py\",\n            parts=[],\n            parametrization=None,\n            module_name=None,\n            original_index=0,\n        )\n        assert resolve_collection_argument(\n            invocation_path, \"src/pkg/test.py::\", 10\n        ) == CollectionArgument(\n            path=invocation_path / \"src/pkg/test.py\",\n            parts=[\"\"],\n            parametrization=None,\n            module_name=None,\n            original_index=10,\n        )\n        assert resolve_collection_argument(\n            invocation_path, \"src/pkg/test.py::foo::bar\", 20\n        ) == CollectionArgument(\n            path=invocation_path / \"src/pkg/test.py\",\n            parts=[\"foo\", \"bar\"],\n            parametrization=None,\n            module_name=None,\n            original_index=20,\n        )\n        assert resolve_collection_argument(\n            invocation_path, \"src/pkg/test.py::foo::bar::\", 30\n        ) == CollectionArgument(\n            path=invocation_path / \"src/pkg/test.py\",\n            parts=[\"foo\", \"bar\", \"\"],\n            parametrization=None,\n            module_name=None,\n            original_index=30,\n        )\n        assert resolve_collection_argument(\n            invocation_path, \"src/pkg/test.py::foo::bar[a,b,c]\", 40\n        ) == CollectionArgument(\n            path=invocation_path / \"src/pkg/test.py\",\n            parts=[\"foo\", \"bar\"],\n            parametrization=\"[a,b,c]\",\n            module_name=None,\n            original_index=40,\n        )\n\n    def test_dir(self, invocation_path: Path) -> None:\n        \"\"\"Directory and parts.\"\"\"\n        assert resolve_collection_argument(\n            invocation_path, \"src/pkg\", 0\n        ) == CollectionArgument(\n            path=invocation_path / \"src/pkg\",\n            parts=[],\n            parametrization=None,\n            module_name=None,\n            original_index=0,\n        )\n\n        with pytest.raises(\n            UsageError, match=r\"directory argument cannot contain :: selection parts\"\n        ):\n            resolve_collection_argument(invocation_path, \"src/pkg::\", 0)\n\n        with pytest.raises(\n            UsageError, match=r\"directory argument cannot contain :: selection parts\"\n        ):\n            resolve_collection_argument(invocation_path, \"src/pkg::foo::bar\", 0)\n\n    @pytest.mark.parametrize(\"namespace_package\", [False, True])\n    def test_pypath(self, namespace_package: bool, invocation_path: Path) -> None:\n        \"\"\"Dotted name and parts.\"\"\"\n        if namespace_package:\n            # Namespace package doesn't have to contain __init__py\n            (invocation_path / \"src/pkg/__init__.py\").unlink()\n\n        assert resolve_collection_argument(\n            invocation_path, \"pkg.test\", 0, as_pypath=True\n        ) == CollectionArgument(\n            path=invocation_path / \"src/pkg/test.py\",\n            parts=[],\n            parametrization=None,\n            module_name=\"pkg.test\",\n            original_index=0,\n        )\n        assert resolve_collection_argument(\n            invocation_path, \"pkg.test::foo::bar\", 0, as_pypath=True\n        ) == CollectionArgument(\n            path=invocation_path / \"src/pkg/test.py\",\n            parts=[\"foo\", \"bar\"],\n            parametrization=None,\n            module_name=\"pkg.test\",\n            original_index=0,\n        )\n        assert resolve_collection_argument(\n            invocation_path,\n            \"pkg\",\n            0,\n            as_pypath=True,\n            consider_namespace_packages=namespace_package,\n        ) == CollectionArgument(\n            path=invocation_path / \"src/pkg\",\n            parts=[],\n            parametrization=None,\n            module_name=\"pkg\",\n            original_index=0,\n        )\n\n        with pytest.raises(\n            UsageError, match=r\"package argument cannot contain :: selection parts\"\n        ):\n            resolve_collection_argument(\n                invocation_path,\n                \"pkg::foo::bar\",\n                0,\n                as_pypath=True,\n                consider_namespace_packages=namespace_package,\n            )\n\n    def test_parametrized_name_with_colons(self, invocation_path: Path) -> None:\n        assert resolve_collection_argument(\n            invocation_path, \"src/pkg/test.py::test[a::b]\", 0\n        ) == CollectionArgument(\n            path=invocation_path / \"src/pkg/test.py\",\n            parts=[\"test\"],\n            parametrization=\"[a::b]\",\n            module_name=None,\n            original_index=0,\n        )\n\n    @pytest.mark.parametrize(\n        \"arg\", [\"x.py[a]\", \"x.py[a]::foo\", \"x/y.py[a]::foo::bar\", \"x.py[a]::foo[b]\"]\n    )\n    def test_path_parametrization_not_allowed(\n        self, invocation_path: Path, arg: str\n    ) -> None:\n        with pytest.raises(\n            UsageError, match=r\"path cannot contain \\[\\] parametrization\"\n        ):\n            resolve_collection_argument(invocation_path, arg, 0)\n\n    def test_does_not_exist(self, invocation_path: Path) -> None:\n        \"\"\"Given a file/module that does not exist raises UsageError.\"\"\"\n        with pytest.raises(\n            UsageError, match=re.escape(\"file or directory not found: foobar\")\n        ):\n            resolve_collection_argument(invocation_path, \"foobar\", 0)\n\n        with pytest.raises(\n            UsageError,\n            match=re.escape(\n                \"module or package not found: foobar (missing __init__.py?)\"\n            ),\n        ):\n            resolve_collection_argument(invocation_path, \"foobar\", 0, as_pypath=True)\n\n    def test_absolute_paths_are_resolved_correctly(self, invocation_path: Path) -> None:\n        \"\"\"Absolute paths resolve back to absolute paths.\"\"\"\n        full_path = str(invocation_path / \"src\")\n        assert resolve_collection_argument(\n            invocation_path, full_path, 0\n        ) == CollectionArgument(\n            path=Path(os.path.abspath(\"src\")),\n            parts=[],\n            parametrization=None,\n            module_name=None,\n            original_index=0,\n        )\n\n        # ensure full paths given in the command-line without the drive letter resolve\n        # to the full path correctly (#7628)\n        _drive, full_path_without_drive = os.path.splitdrive(full_path)\n        assert resolve_collection_argument(\n            invocation_path, full_path_without_drive, 0\n        ) == CollectionArgument(\n            path=Path(os.path.abspath(\"src\")),\n            parts=[],\n            parametrization=None,\n            module_name=None,\n            original_index=0,\n        )\n\n\ndef test_module_full_path_without_drive(pytester: Pytester) -> None:\n    \"\"\"Collect and run test using full path except for the drive letter (#7628).\n\n    Passing a full path without a drive letter would trigger a bug in legacy_path\n    where it would keep the full path without the drive letter around, instead of resolving\n    to the full path, resulting in fixtures node ids not matching against test node ids correctly.\n    \"\"\"\n    pytester.makepyfile(\n        **{\n            \"project/conftest.py\": \"\"\"\n                import pytest\n                @pytest.fixture\n                def fix(): return 1\n            \"\"\",\n        }\n    )\n\n    pytester.makepyfile(\n        **{\n            \"project/tests/dummy_test.py\": \"\"\"\n                def test(fix):\n                    assert fix == 1\n            \"\"\"\n        }\n    )\n    fn = pytester.path.joinpath(\"project/tests/dummy_test.py\")\n    assert fn.is_file()\n\n    _drive, path = os.path.splitdrive(str(fn))\n\n    result = pytester.runpytest(path, \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            os.path.join(\"project\", \"tests\", \"dummy_test.py\") + \"::test PASSED *\",\n            \"* 1 passed in *\",\n        ]\n    )\n\n\ndef test_very_long_cmdline_arg(pytester: Pytester) -> None:\n    \"\"\"\n    Regression test for #11394.\n\n    Note: we could not manage to actually reproduce the error with this code, we suspect\n    GitHub runners are configured to support very long paths, however decided to leave\n    the test in place in case this ever regresses in the future.\n    \"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n\n        def pytest_addoption(parser):\n            parser.addoption(\"--long-list\", dest=\"long_list\", action=\"store\", default=\"all\", help=\"List of things\")\n\n        @pytest.fixture(scope=\"module\")\n        def specified_feeds(request):\n            list_string = request.config.getoption(\"--long-list\")\n            return list_string.split(',')\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        def test_foo(specified_feeds):\n            assert len(specified_feeds) == 100_000\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--long-list\", \",\".join([\"helloworld\"] * 100_000))\n    result.stdout.fnmatch_lines(\"* 1 passed *\")\n"
  },
  {
    "path": "testing/test_mark.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport os\nimport sys\nfrom unittest import mock\n\nfrom _pytest.config import ExitCode\nfrom _pytest.mark import MarkGenerator\nfrom _pytest.mark.structures import EMPTY_PARAMETERSET_OPTION\nfrom _pytest.nodes import Collector\nfrom _pytest.nodes import Node\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nclass TestMark:\n    @pytest.mark.parametrize(\"attr\", [\"mark\", \"param\"])\n    def test_pytest_exists_in_namespace_all(self, attr: str) -> None:\n        module = sys.modules[\"pytest\"]\n        assert attr in module.__all__\n\n    def test_pytest_mark_notcallable(self) -> None:\n        mark = MarkGenerator(_ispytest=True)\n        with pytest.raises(TypeError):\n            mark()  # type: ignore[operator]\n\n    def test_mark_with_param(self):\n        def some_function(abc):\n            pass\n\n        class SomeClass:\n            pass\n\n        assert pytest.mark.foo(some_function) is some_function\n        marked_with_args = pytest.mark.foo.with_args(some_function)\n        assert marked_with_args is not some_function\n\n        assert pytest.mark.foo(SomeClass) is SomeClass\n        assert pytest.mark.foo.with_args(SomeClass) is not SomeClass  # type: ignore[comparison-overlap]\n\n    def test_pytest_mark_name_starts_with_underscore(self) -> None:\n        mark = MarkGenerator(_ispytest=True)\n        with pytest.raises(AttributeError):\n            _ = mark._some_name\n\n\ndef test_marked_class_run_twice(pytester: Pytester) -> None:\n    \"\"\"Test fails file is run twice that contains marked class.\n    See issue#683.\n    \"\"\"\n    py_file = pytester.makepyfile(\n        \"\"\"\n    import pytest\n    @pytest.mark.parametrize('abc', [1, 2, 3])\n    class Test1(object):\n        def test_1(self, abc):\n            assert abc in [1, 2, 3]\n    \"\"\"\n    )\n    file_name = os.path.basename(py_file)\n    rec = pytester.inline_run(\"--keep-duplicates\", file_name, file_name)\n    rec.assertoutcome(passed=6)\n\n\ndef test_ini_markers(pytester: Pytester) -> None:\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        markers =\n            a1: this is a webtest marker\n            a2: this is a smoke marker\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        def test_markers(pytestconfig):\n            markers = pytestconfig.getini(\"markers\")\n            print(markers)\n            assert len(markers) >= 2\n            assert markers[0].startswith(\"a1:\")\n            assert markers[1].startswith(\"a2:\")\n    \"\"\"\n    )\n    rec = pytester.inline_run()\n    rec.assertoutcome(passed=1)\n\n\ndef test_markers_option(pytester: Pytester) -> None:\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        markers =\n            a1: this is a webtest marker\n            a1some: another marker\n            nodescription\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--markers\")\n    result.stdout.fnmatch_lines(\n        [\"*a1*this is a webtest*\", \"*a1some*another marker\", \"*nodescription*\"]\n    )\n\n\ndef test_ini_markers_whitespace(pytester: Pytester) -> None:\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        markers =\n            a1 : this is a whitespace marker\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.a1\n        def test_markers():\n            assert True\n    \"\"\"\n    )\n    rec = pytester.inline_run(\"--strict-markers\", \"-m\", \"a1\")\n    rec.assertoutcome(passed=1)\n\n\ndef test_marker_without_description(pytester: Pytester) -> None:\n    pytester.makefile(\n        \".cfg\",\n        setup=\"\"\"\n        [tool:pytest]\n        markers=slow\n    \"\"\",\n    )\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n        pytest.mark.xfail('FAIL')\n    \"\"\"\n    )\n    ftdir = pytester.mkdir(\"ft1_dummy\")\n    pytester.path.joinpath(\"conftest.py\").replace(ftdir.joinpath(\"conftest.py\"))\n    rec = pytester.runpytest(\"--strict-markers\")\n    rec.assert_outcomes()\n\n\ndef test_markers_option_with_plugin_in_current_dir(pytester: Pytester) -> None:\n    pytester.makeconftest('pytest_plugins = \"flip_flop\"')\n    pytester.makepyfile(\n        flip_flop=\"\"\"\\\n        def pytest_configure(config):\n            config.addinivalue_line(\"markers\", \"flip:flop\")\n\n        def pytest_generate_tests(metafunc):\n            try:\n                mark = metafunc.function.flipper\n            except AttributeError:\n                return\n            metafunc.parametrize(\"x\", (10, 20))\"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\\\n        import pytest\n        @pytest.mark.flipper\n        def test_example(x):\n            assert x\"\"\"\n    )\n\n    result = pytester.runpytest(\"--markers\")\n    result.stdout.fnmatch_lines([\"*flip*flop*\"])\n\n\ndef test_mark_on_pseudo_function(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.r(lambda x: 0/0)\n        def test_hello():\n            pass\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(passed=1)\n\n\n@pytest.mark.parametrize(\n    \"option_name\", [\"--strict-markers\", \"--strict\", \"strict_markers\", \"strict\"]\n)\ndef test_strict_prohibits_unregistered_markers(\n    pytester: Pytester, option_name: str\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.unregisteredmark\n        def test_hello():\n            pass\n    \"\"\"\n    )\n    if option_name in (\"strict_markers\", \"strict\"):\n        pytester.makeini(\n            f\"\"\"\n            [pytest]\n            {option_name} = true\n            \"\"\"\n        )\n        result = pytester.runpytest()\n    else:\n        result = pytester.runpytest(option_name)\n    assert result.ret != 0\n    result.stdout.fnmatch_lines(\n        [\"'unregisteredmark' not found in `markers` configuration option\"]\n    )\n\n\n@pytest.mark.parametrize(\n    (\"expr\", \"expected_passed\"),\n    [\n        (\"xyz\", [\"test_one\"]),\n        (\"(((  xyz))  )\", [\"test_one\"]),\n        (\"not not xyz\", [\"test_one\"]),\n        (\"xyz and xyz2\", []),\n        (\"xyz2\", [\"test_two\"]),\n        (\"xyz or xyz2\", [\"test_one\", \"test_two\"]),\n    ],\n)\ndef test_mark_option(\n    expr: str, expected_passed: list[str | None], pytester: Pytester\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.xyz\n        def test_one():\n            pass\n        @pytest.mark.xyz2\n        def test_two():\n            pass\n    \"\"\"\n    )\n    rec = pytester.inline_run(\"-m\", expr)\n    passed, _skipped, _fail = rec.listoutcomes()\n    passed_str = [x.nodeid.split(\"::\")[-1] for x in passed]\n    assert passed_str == expected_passed\n\n\n@pytest.mark.parametrize(\n    (\"expr\", \"expected_passed\"),\n    [\n        (\"car(color='red')\", [\"test_one\"]),\n        (\"car(color='red') or car(color='blue')\", [\"test_one\", \"test_two\"]),\n        (\"car and not car(temp=5)\", [\"test_one\", \"test_three\"]),\n        (\"car(temp=4)\", [\"test_one\"]),\n        (\"car(temp=4) or car(temp=5)\", [\"test_one\", \"test_two\"]),\n        (\"car(temp=4) and car(temp=5)\", []),\n        (\"car(temp=-5)\", [\"test_three\"]),\n        (\"car(ac=True)\", [\"test_one\"]),\n        (\"car(ac=False)\", [\"test_two\"]),\n        (\"car(ac=None)\", [\"test_three\"]),  # test NOT_NONE_SENTINEL\n    ],\n    ids=str,\n)\ndef test_mark_option_with_kwargs(\n    expr: str, expected_passed: list[str | None], pytester: Pytester\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.car\n        @pytest.mark.car(ac=True)\n        @pytest.mark.car(temp=4)\n        @pytest.mark.car(color=\"red\")\n        def test_one():\n            pass\n        @pytest.mark.car\n        @pytest.mark.car(ac=False)\n        @pytest.mark.car(temp=5)\n        @pytest.mark.car(color=\"blue\")\n        def test_two():\n            pass\n        @pytest.mark.car\n        @pytest.mark.car(ac=None)\n        @pytest.mark.car(temp=-5)\n        def test_three():\n            pass\n\n    \"\"\"\n    )\n    rec = pytester.inline_run(\"-m\", expr)\n    passed, _skipped, _fail = rec.listoutcomes()\n    passed_str = [x.nodeid.split(\"::\")[-1] for x in passed]\n    assert passed_str == expected_passed\n\n\n@pytest.mark.parametrize(\n    (\"expr\", \"expected_passed\"),\n    [(\"interface\", [\"test_interface\"]), (\"not interface\", [\"test_nointer\"])],\n)\ndef test_mark_option_custom(\n    expr: str, expected_passed: list[str], pytester: Pytester\n) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n        def pytest_collection_modifyitems(items):\n            for item in items:\n                if \"interface\" in item.nodeid:\n                    item.add_marker(pytest.mark.interface)\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        def test_interface():\n            pass\n        def test_nointer():\n            pass\n    \"\"\"\n    )\n    rec = pytester.inline_run(\"-m\", expr)\n    passed, _skipped, _fail = rec.listoutcomes()\n    passed_str = [x.nodeid.split(\"::\")[-1] for x in passed]\n    assert passed_str == expected_passed\n\n\n@pytest.mark.parametrize(\n    (\"expr\", \"expected_passed\"),\n    [\n        (\"interface\", [\"test_interface\"]),\n        (\"not interface\", [\"test_nointer\", \"test_pass\", \"test_1\", \"test_2\"]),\n        (\"pass\", [\"test_pass\"]),\n        (\"not pass\", [\"test_interface\", \"test_nointer\", \"test_1\", \"test_2\"]),\n        (\"not not not (pass)\", [\"test_interface\", \"test_nointer\", \"test_1\", \"test_2\"]),\n        (\"1 or 2\", [\"test_1\", \"test_2\"]),\n        (\"not (1 or 2)\", [\"test_interface\", \"test_nointer\", \"test_pass\"]),\n    ],\n)\ndef test_keyword_option_custom(\n    expr: str, expected_passed: list[str], pytester: Pytester\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_interface():\n            pass\n        def test_nointer():\n            pass\n        def test_pass():\n            pass\n        def test_1():\n            pass\n        def test_2():\n            pass\n    \"\"\"\n    )\n    rec = pytester.inline_run(\"-k\", expr)\n    passed, _skipped, _fail = rec.listoutcomes()\n    passed_str = [x.nodeid.split(\"::\")[-1] for x in passed]\n    assert passed_str == expected_passed\n\n\ndef test_keyword_option_considers_mark(pytester: Pytester) -> None:\n    pytester.copy_example(\"marks/marks_considered_keywords\")\n    rec = pytester.inline_run(\"-k\", \"foo\")\n    passed = rec.listoutcomes()[0]\n    assert len(passed) == 1\n\n\n@pytest.mark.parametrize(\n    (\"expr\", \"expected_passed\"),\n    [\n        (\"None\", [\"test_func[None]\"]),\n        (\"[1.3]\", [\"test_func[1.3]\"]),\n        (\"2-3\", [\"test_func[2-3]\"]),\n    ],\n)\ndef test_keyword_option_parametrize(\n    expr: str, expected_passed: list[str], pytester: Pytester\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.parametrize(\"arg\", [None, 1.3, \"2-3\"])\n        def test_func(arg):\n            pass\n    \"\"\"\n    )\n    rec = pytester.inline_run(\"-k\", expr)\n    passed, _skipped, _fail = rec.listoutcomes()\n    passed_str = [x.nodeid.split(\"::\")[-1] for x in passed]\n    assert passed_str == expected_passed\n\n\ndef test_parametrize_with_module(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.parametrize(\"arg\", [pytest,])\n        def test_func(arg):\n            pass\n    \"\"\"\n    )\n    rec = pytester.inline_run()\n    passed, _skipped, _fail = rec.listoutcomes()\n    expected_id = \"test_func[\" + pytest.__name__ + \"]\"\n    assert passed[0].nodeid.split(\"::\")[-1] == expected_id\n\n\n@pytest.mark.parametrize(\n    (\"expr\", \"expected_error\"),\n    [\n        (\n            \"foo or\",\n            \"at column 7: expected not OR left parenthesis OR identifier; got end of input\",\n        ),\n        (\n            \"foo or or\",\n            \"at column 8: expected not OR left parenthesis OR identifier; got or\",\n        ),\n        (\n            \"(foo\",\n            \"at column 5: expected right parenthesis; got end of input\",\n        ),\n        (\n            \"foo bar\",\n            \"at column 5: expected end of input; got identifier\",\n        ),\n        (\n            \"or or\",\n            \"at column 1: expected not OR left parenthesis OR identifier; got or\",\n        ),\n        (\n            \"not or\",\n            \"at column 5: expected not OR left parenthesis OR identifier; got or\",\n        ),\n        (\n            \"nonexistent_mark(non_supported='kwarg')\",\n            \"Keyword expressions do not support call parameters\",\n        ),\n    ],\n)\ndef test_keyword_option_wrong_arguments(\n    expr: str, expected_error: str, pytester: Pytester, capsys\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n            def test_func(arg):\n                pass\n        \"\"\"\n    )\n    pytester.inline_run(\"-k\", expr)\n    err = capsys.readouterr().err\n    assert expected_error in err\n\n\ndef test_parametrized_collected_from_command_line(pytester: Pytester) -> None:\n    \"\"\"Parametrized test not collected if test named specified in command\n    line issue#649.\"\"\"\n    py_file = pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.parametrize(\"arg\", [None, 1.3, \"2-3\"])\n        def test_func(arg):\n            pass\n    \"\"\"\n    )\n    file_name = os.path.basename(py_file)\n    rec = pytester.inline_run(file_name + \"::\" + \"test_func\")\n    rec.assertoutcome(passed=3)\n\n\ndef test_parametrized_collect_with_wrong_args(pytester: Pytester) -> None:\n    \"\"\"Test collect parametrized func with wrong number of args.\"\"\"\n    py_file = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.parametrize('foo, bar', [(1, 2, 3)])\n        def test_func(foo, bar):\n            pass\n    \"\"\"\n    )\n\n    result = pytester.runpytest(py_file)\n    result.stdout.fnmatch_lines(\n        [\n            'test_parametrized_collect_with_wrong_args.py::test_func: in \"parametrize\" the number of names (2):',\n            \"  ['foo', 'bar']\",\n            \"must be equal to the number of values (3):\",\n            \"  (1, 2, 3)\",\n        ]\n    )\n\n\ndef test_parametrized_with_kwargs(pytester: Pytester) -> None:\n    \"\"\"Test collect parametrized func with wrong number of args.\"\"\"\n    py_file = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture(params=[1,2])\n        def a(request):\n            return request.param\n\n        @pytest.mark.parametrize(argnames='b', argvalues=[1, 2])\n        def test_func(a, b):\n            pass\n    \"\"\"\n    )\n\n    result = pytester.runpytest(py_file)\n    assert result.ret == 0\n\n\ndef test_parametrize_iterator(pytester: Pytester) -> None:\n    \"\"\"`parametrize` should work with generators (#5354).\"\"\"\n    py_file = pytester.makepyfile(\n        \"\"\"\\\n        import pytest\n\n        def gen():\n            yield 1\n            yield 2\n            yield 3\n\n        @pytest.mark.parametrize('a', gen())\n        def test(a):\n            assert a >= 1\n        \"\"\"\n    )\n    result = pytester.runpytest(py_file)\n    assert result.ret == 0\n    # should not skip any tests\n    result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n\nclass TestFunctional:\n    def test_merging_markers_deep(self, pytester: Pytester) -> None:\n        # issue 199 - propagate markers into nested classes\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            class TestA(object):\n                pytestmark = pytest.mark.a\n                def test_b(self):\n                    assert True\n                class TestC(object):\n                    # this one didn't get marked\n                    def test_d(self):\n                        assert True\n        \"\"\"\n        )\n        items, _rec = pytester.inline_genitems(p)\n        for item in items:\n            print(item, item.keywords)\n            assert [x for x in item.iter_markers() if x.name == \"a\"]\n\n    def test_mark_decorator_subclass_does_not_propagate_to_base(\n        self, pytester: Pytester\n    ) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.a\n            class Base(object): pass\n\n            @pytest.mark.b\n            class Test1(Base):\n                def test_foo(self): pass\n\n            class Test2(Base):\n                def test_bar(self): pass\n        \"\"\"\n        )\n        items, _rec = pytester.inline_genitems(p)\n        self.assert_markers(items, test_foo=(\"a\", \"b\"), test_bar=(\"a\",))\n\n    def test_mark_should_not_pass_to_siebling_class(self, pytester: Pytester) -> None:\n        \"\"\"#568\"\"\"\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            class TestBase(object):\n                def test_foo(self):\n                    pass\n\n            @pytest.mark.b\n            class TestSub(TestBase):\n                pass\n\n\n            class TestOtherSub(TestBase):\n                pass\n\n        \"\"\"\n        )\n        items, _rec = pytester.inline_genitems(p)\n        base_item, sub_item, sub_item_other = items\n        print(items, [x.nodeid for x in items])\n        # new api segregates\n        assert not list(base_item.iter_markers(name=\"b\"))\n        assert not list(sub_item_other.iter_markers(name=\"b\"))\n        assert list(sub_item.iter_markers(name=\"b\"))\n\n    def test_mark_decorator_baseclasses_merged(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.a\n            class Base(object): pass\n\n            @pytest.mark.b\n            class Base2(Base): pass\n\n            @pytest.mark.c\n            class Test1(Base2):\n                def test_foo(self): pass\n\n            class Test2(Base2):\n                @pytest.mark.d\n                def test_bar(self): pass\n        \"\"\"\n        )\n        items, _rec = pytester.inline_genitems(p)\n        self.assert_markers(items, test_foo=(\"a\", \"b\", \"c\"), test_bar=(\"a\", \"b\", \"d\"))\n\n    def test_mark_closest(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.c(location=\"class\")\n            class Test:\n                @pytest.mark.c(location=\"function\")\n                def test_has_own(self):\n                    pass\n\n                def test_has_inherited(self):\n                    pass\n\n        \"\"\"\n        )\n        items, _rec = pytester.inline_genitems(p)\n        has_own, has_inherited = items\n        has_own_marker = has_own.get_closest_marker(\"c\")\n        has_inherited_marker = has_inherited.get_closest_marker(\"c\")\n        assert has_own_marker is not None\n        assert has_inherited_marker is not None\n        assert has_own_marker.kwargs == {\"location\": \"function\"}\n        assert has_inherited_marker.kwargs == {\"location\": \"class\"}\n        assert has_own.get_closest_marker(\"missing\") is None\n\n    def test_mark_with_wrong_marker(self, pytester: Pytester) -> None:\n        reprec = pytester.inline_runsource(\n            \"\"\"\n                import pytest\n                class pytestmark(object):\n                    pass\n                def test_func():\n                    pass\n        \"\"\"\n        )\n        values = reprec.getfailedcollections()\n        assert len(values) == 1\n        assert \"TypeError\" in str(values[0].longrepr)\n\n    def test_mark_dynamically_in_funcarg(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def arg(request):\n                request.applymarker(pytest.mark.hello)\n            def pytest_terminal_summary(terminalreporter):\n                values = terminalreporter.stats['passed']\n                terminalreporter._tw.line(\"keyword: %s\" % values[0].keywords)\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_func(arg):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"keyword: *hello*\"])\n\n    def test_no_marker_match_on_unmarked_names(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.shouldmatch\n            def test_marked():\n                assert 1\n\n            def test_unmarked():\n                assert 1\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-m\", \"test_unmarked\", p)\n        passed, skipped, failed = reprec.listoutcomes()\n        assert len(passed) + len(skipped) + len(failed) == 0\n        dlist = reprec.getcalls(\"pytest_deselected\")\n        deselected_tests = dlist[0].items\n        assert len(deselected_tests) == 2\n\n    def test_keywords_at_node_level(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture(scope=\"session\", autouse=True)\n            def some(request):\n                request.keywords[\"hello\"] = 42\n                assert \"world\" not in request.keywords\n\n            @pytest.fixture(scope=\"function\", autouse=True)\n            def funcsetup(request):\n                assert \"world\" in request.keywords\n                assert \"hello\" in  request.keywords\n\n            @pytest.mark.world\n            def test_function():\n                pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(passed=1)\n\n    def test_keyword_added_for_session(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n            def pytest_collection_modifyitems(session):\n                session.add_marker(\"mark1\")\n                session.add_marker(pytest.mark.mark2)\n                session.add_marker(pytest.mark.mark3)\n                pytest.raises(ValueError, lambda:\n                        session.add_marker(10))\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_some(request):\n                assert \"mark1\" in request.keywords\n                assert \"mark2\" in request.keywords\n                assert \"mark3\" in request.keywords\n                assert 10 not in request.keywords\n                marker = request.node.get_closest_marker(\"mark1\")\n                assert marker.name == \"mark1\"\n                assert marker.args == ()\n                assert marker.kwargs == {}\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-m\", \"mark1\")\n        reprec.assertoutcome(passed=1)\n\n    def assert_markers(self, items, **expected) -> None:\n        \"\"\"Assert that given items have expected marker names applied to them.\n        expected should be a dict of (item name -> seq of expected marker names).\n\n        Note: this could be moved to ``pytester`` if proven to be useful\n        to other modules.\n        \"\"\"\n        items = {x.name: x for x in items}\n        for name, expected_markers in expected.items():\n            markers = {m.name for m in items[name].iter_markers()}\n            assert markers == set(expected_markers)\n\n    @pytest.mark.filterwarnings(\"ignore\")\n    def test_mark_from_parameters(self, pytester: Pytester) -> None:\n        \"\"\"#1540\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            pytestmark = pytest.mark.skipif(True, reason='skip all')\n\n            # skipifs inside fixture params\n            params = [pytest.mark.skipif(False, reason='dont skip')('parameter')]\n\n\n            @pytest.fixture(params=params)\n            def parameter(request):\n                return request.param\n\n\n            def test_1(parameter):\n                assert True\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reprec.assertoutcome(skipped=1)\n\n    def test_reevaluate_dynamic_expr(self, pytester: Pytester) -> None:\n        \"\"\"#7360\"\"\"\n        py_file1 = pytester.makepyfile(\n            test_reevaluate_dynamic_expr1=\"\"\"\n            import pytest\n\n            skip = True\n\n            @pytest.mark.skipif(\"skip\")\n            def test_should_skip():\n                assert True\n        \"\"\"\n        )\n        py_file2 = pytester.makepyfile(\n            test_reevaluate_dynamic_expr2=\"\"\"\n            import pytest\n\n            skip = False\n\n            @pytest.mark.skipif(\"skip\")\n            def test_should_not_skip():\n                assert True\n        \"\"\"\n        )\n\n        file_name1 = os.path.basename(py_file1)\n        file_name2 = os.path.basename(py_file2)\n        reprec = pytester.inline_run(file_name1, file_name2)\n        reprec.assertoutcome(passed=1, skipped=1)\n\n\nclass TestKeywordSelection:\n    def test_select_simple(self, pytester: Pytester) -> None:\n        file_test = pytester.makepyfile(\n            \"\"\"\n            def test_one():\n                assert 0\n            class TestClass(object):\n                def test_method_one(self):\n                    assert 42 == 43\n        \"\"\"\n        )\n\n        def check(keyword, name):\n            reprec = pytester.inline_run(\"-s\", \"-k\", keyword, file_test)\n            _passed, _skipped, failed = reprec.listoutcomes()\n            assert len(failed) == 1\n            assert failed[0].nodeid.split(\"::\")[-1] == name\n            assert len(reprec.getcalls(\"pytest_deselected\")) == 1\n\n        for keyword in [\"test_one\", \"est_on\"]:\n            check(keyword, \"test_one\")\n        check(\"TestClass and test\", \"test_method_one\")\n\n    @pytest.mark.parametrize(\n        \"keyword\",\n        [\n            \"xxx\",\n            \"xxx and test_2\",\n            \"TestClass\",\n            \"xxx and not test_1\",\n            \"TestClass and test_2\",\n            \"xxx and TestClass and test_2\",\n        ],\n    )\n    def test_select_extra_keywords(self, pytester: Pytester, keyword) -> None:\n        p = pytester.makepyfile(\n            test_select=\"\"\"\n            def test_1():\n                pass\n            class TestClass(object):\n                def test_2(self):\n                    pass\n        \"\"\"\n        )\n        pytester.makepyfile(\n            conftest=\"\"\"\n            import pytest\n            @pytest.hookimpl(wrapper=True)\n            def pytest_pycollect_makeitem(name):\n                item = yield\n                if name == \"TestClass\":\n                    item.extra_keyword_matches.add(\"xxx\")\n                return item\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p.parent, \"-s\", \"-k\", keyword)\n        print(\"keyword\", repr(keyword))\n        passed, _skipped, _failed = reprec.listoutcomes()\n        assert len(passed) == 1\n        assert passed[0].nodeid.endswith(\"test_2\")\n        dlist = reprec.getcalls(\"pytest_deselected\")\n        assert len(dlist) == 1\n        assert dlist[0].items[0].name == \"test_1\"\n\n    def test_keyword_extra(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n           def test_one():\n               assert 0\n           test_one.mykeyword = True\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"-k\", \"mykeyword\", p)\n        _passed, _skipped, failed = reprec.countoutcomes()\n        assert failed == 1\n\n    @pytest.mark.xfail\n    def test_keyword_extra_dash(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n           def test_one():\n               assert 0\n           test_one.mykeyword = True\n        \"\"\"\n        )\n        # with argparse the argument to an option cannot\n        # start with '-'\n        reprec = pytester.inline_run(\"-k\", \"-mykeyword\", p)\n        passed, skipped, failed = reprec.countoutcomes()\n        assert passed + skipped + failed == 0\n\n    @pytest.mark.parametrize(\n        \"keyword\",\n        [\"__\", \"+\", \"..\"],\n    )\n    def test_no_magic_values(self, pytester: Pytester, keyword: str) -> None:\n        \"\"\"Make sure the tests do not match on magic values,\n        no double underscored values, like '__dict__' and '+'.\n        \"\"\"\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_one(): assert 1\n        \"\"\"\n        )\n\n        reprec = pytester.inline_run(\"-k\", keyword, p)\n        passed, skipped, failed = reprec.countoutcomes()\n        dlist = reprec.getcalls(\"pytest_deselected\")\n        assert passed + skipped + failed == 0\n        deselected_tests = dlist[0].items\n        assert len(deselected_tests) == 1\n\n    def test_no_match_directories_outside_the_suite(\n        self,\n        pytester: Pytester,\n        monkeypatch: pytest.MonkeyPatch,\n    ) -> None:\n        \"\"\"`-k` should not match against directories containing the test suite (#7040).\"\"\"\n        pytester.makefile(\n            **{\n                \"suite/pytest\": \"\"\"[pytest]\"\"\",\n            },\n            ext=\".ini\",\n        )\n        pytester.makepyfile(\n            **{\n                \"suite/ddd/tests/__init__.py\": \"\",\n                \"suite/ddd/tests/test_foo.py\": \"\"\"\n                def test_aaa(): pass\n                def test_ddd(): pass\n            \"\"\",\n            }\n        )\n        monkeypatch.chdir(pytester.path / \"suite\")\n\n        def get_collected_names(*args: str) -> list[str]:\n            _, rec = pytester.inline_genitems(*args)\n            calls = rec.getcalls(\"pytest_collection_finish\")\n            assert len(calls) == 1\n            return [x.name for x in calls[0].session.items]\n\n        # sanity check: collect both tests in normal runs\n        assert get_collected_names() == [\"test_aaa\", \"test_ddd\"]\n\n        # do not collect anything based on names outside the collection tree\n        assert get_collected_names(\"-k\", pytester._name) == []\n\n\nclass TestMarkDecorator:\n    @pytest.mark.parametrize(\n        \"lhs, rhs, expected\",\n        [\n            (pytest.mark.foo(), pytest.mark.foo(), True),\n            (pytest.mark.foo(), pytest.mark.bar(), False),\n            (pytest.mark.foo(), \"bar\", False),\n            (\"foo\", pytest.mark.bar(), False),\n        ],\n    )\n    def test__eq__(self, lhs, rhs, expected) -> None:\n        assert (lhs == rhs) == expected\n\n    def test_aliases(self) -> None:\n        md = pytest.mark.foo(1, \"2\", three=3)\n        assert md.name == \"foo\"\n        assert md.args == (1, \"2\")\n        assert md.kwargs == {\"three\": 3}\n\n\n@pytest.mark.parametrize(\"mark\", [None, \"\", \"skip\", \"xfail\"])\ndef test_parameterset_for_parametrize_marks(\n    pytester: Pytester, mark: str | None\n) -> None:\n    if mark is not None:\n        pytester.makeini(\n            f\"\"\"\n        [pytest]\n        {EMPTY_PARAMETERSET_OPTION}={mark}\n        \"\"\"\n        )\n\n    config = pytester.parseconfig()\n    from _pytest.mark import get_empty_parameterset_mark\n    from _pytest.mark import pytest_configure\n\n    pytest_configure(config)\n    result_mark = get_empty_parameterset_mark(config, [\"a\"], all)\n    if mark in (None, \"\"):\n        # normalize to the requested name\n        mark = \"skip\"\n    assert result_mark.name == mark\n    assert result_mark.kwargs[\"reason\"].startswith(\"got empty parameter set \")\n    if mark == \"xfail\":\n        assert result_mark.kwargs.get(\"run\") is False\n\n\ndef test_parameterset_for_fail_at_collect(pytester: Pytester) -> None:\n    pytester.makeini(\n        f\"\"\"\n    [pytest]\n    {EMPTY_PARAMETERSET_OPTION}=fail_at_collect\n    \"\"\"\n    )\n\n    config = pytester.parseconfig()\n    from _pytest.mark import get_empty_parameterset_mark\n    from _pytest.mark import pytest_configure\n\n    pytest_configure(config)\n\n    with pytest.raises(\n        Collector.CollectError,\n        match=r\"Empty parameter set in 'pytest_configure' at line \\d\\d+\",\n    ):\n        get_empty_parameterset_mark(config, [\"a\"], pytest_configure)\n\n    p1 = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.parametrize(\"empty\", [])\n        def test():\n            pass\n        \"\"\"\n    )\n    result = pytester.runpytest(str(p1))\n    result.stdout.fnmatch_lines(\n        [\n            \"collected 0 items / 1 error\",\n            \"* ERROR collecting test_parameterset_for_fail_at_collect.py *\",\n            \"Empty parameter set in 'test' at line 3\",\n            \"*= 1 error in *\",\n        ]\n    )\n    assert result.ret == ExitCode.INTERRUPTED\n\n\ndef test_paramset_empty_no_idfunc(\n    pytester: Pytester, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    \"\"\"An empty parameter set should not call the user provided id function (#13031).\"\"\"\n    p1 = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def idfunc(value):\n            raise ValueError()\n        @pytest.mark.parametrize(\"param\", [], ids=idfunc)\n        def test(param):\n            pass\n        \"\"\"\n    )\n    result = pytester.runpytest(p1, \"-v\", \"-rs\")\n    result.stdout.fnmatch_lines(\n        [\n            \"* collected 1 item\",\n            \"test_paramset_empty_no_idfunc* SKIPPED *\",\n            \"SKIPPED [1] test_paramset_empty_no_idfunc.py:5: got empty parameter set for (param)\",\n            \"*= 1 skipped in *\",\n        ]\n    )\n\n\ndef test_parameterset_for_parametrize_bad_markname(pytester: Pytester) -> None:\n    with pytest.raises(pytest.UsageError):\n        test_parameterset_for_parametrize_marks(pytester, \"bad\")\n\n\ndef test_mark_expressions_no_smear(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        class BaseTests(object):\n            def test_something(self):\n                pass\n\n        @pytest.mark.FOO\n        class TestFooClass(BaseTests):\n            pass\n\n        @pytest.mark.BAR\n        class TestBarClass(BaseTests):\n            pass\n    \"\"\"\n    )\n\n    reprec = pytester.inline_run(\"-m\", \"FOO\")\n    passed, skipped, failed = reprec.countoutcomes()\n    dlist = reprec.getcalls(\"pytest_deselected\")\n    assert passed == 1\n    assert skipped == failed == 0\n    deselected_tests = dlist[0].items\n    assert len(deselected_tests) == 1\n\n    # todo: fixed\n    # keywords smear - expected behaviour\n    # reprec_keywords = pytester.inline_run(\"-k\", \"FOO\")\n    # passed_k, skipped_k, failed_k = reprec_keywords.countoutcomes()\n    # assert passed_k == 2\n    # assert skipped_k == failed_k == 0\n\n\ndef test_addmarker_order(pytester) -> None:\n    session = mock.Mock()\n    session.own_markers = []\n    session.parent = None\n    session.nodeid = \"\"\n    session.path = pytester.path\n    node = Node.from_parent(session, name=\"Test\")\n    node.add_marker(\"foo\")\n    node.add_marker(\"bar\")\n    node.add_marker(\"baz\", append=False)\n    extracted = [x.name for x in node.iter_markers()]\n    assert extracted == [\"baz\", \"foo\", \"bar\"]\n\n\n@pytest.mark.filterwarnings(\"ignore\")\ndef test_markers_from_parametrize(pytester: Pytester) -> None:\n    \"\"\"#3605\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        first_custom_mark = pytest.mark.custom_marker\n        custom_mark = pytest.mark.custom_mark\n        @pytest.fixture(autouse=True)\n        def trigger(request):\n            custom_mark = list(request.node.iter_markers('custom_mark'))\n            print(\"Custom mark %s\" % custom_mark)\n\n        @custom_mark(\"custom mark non parametrized\")\n        def test_custom_mark_non_parametrized():\n            print(\"Hey from test\")\n\n        @pytest.mark.parametrize(\n            \"obj_type\",\n            [\n                first_custom_mark(\"first custom mark\")(\"template\"),\n                pytest.param( # Think this should be recommended way?\n                    \"disk\",\n                    marks=custom_mark('custom mark1')\n                ),\n                custom_mark(\"custom mark2\")(\"vm\"),  # Tried also this\n            ]\n        )\n        def test_custom_mark_parametrized(obj_type):\n            print(\"obj_type is:\", obj_type)\n    \"\"\"\n    )\n\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=4)\n\n\ndef test_pytest_param_id_requires_string() -> None:\n    with pytest.raises(TypeError) as excinfo:\n        pytest.param(id=True)  # type: ignore[arg-type]\n    (msg,) = excinfo.value.args\n    expected = (\n        \"Expected id to be a string or a `pytest.HIDDEN_PARAM` sentinel, \"\n        \"got <class 'bool'>: True\"\n    )\n    assert msg == expected\n\n\n@pytest.mark.parametrize(\"s\", (None, \"hello world\"))\ndef test_pytest_param_id_allows_none_or_string(s) -> None:\n    assert pytest.param(id=s)\n\n\n@pytest.mark.parametrize(\"expr\", (\"NOT internal_err\", \"NOT (internal_err)\", \"bogus=\"))\ndef test_marker_expr_eval_failure_handling(pytester: Pytester, expr) -> None:\n    foo = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.internal_err\n        def test_foo():\n            pass\n        \"\"\"\n    )\n    expected = f\"ERROR: Wrong expression passed to '-m': {expr}: *\"\n    result = pytester.runpytest(foo, \"-m\", expr)\n    result.stderr.fnmatch_lines([expected])\n    assert result.ret == ExitCode.USAGE_ERROR\n\n\ndef test_mark_mro() -> None:\n    xfail = pytest.mark.xfail\n\n    @xfail(\"a\")\n    class A:\n        pass\n\n    @xfail(\"b\")\n    class B:\n        pass\n\n    @xfail(\"c\")\n    class C(A, B):\n        pass\n\n    from _pytest.mark.structures import get_unpacked_marks\n\n    all_marks = get_unpacked_marks(C)\n\n    assert all_marks == [xfail(\"b\").mark, xfail(\"a\").mark, xfail(\"c\").mark]\n\n    assert get_unpacked_marks(C, consider_mro=False) == [xfail(\"c\").mark]\n\n\n# @pytest.mark.issue(\"https://github.com/pytest-dev/pytest/issues/10447\")\ndef test_mark_fixture_order_mro(pytester: Pytester):\n    \"\"\"This ensures we walk marks of the mro starting with the base classes\n    the action at a distance fixtures are taken as minimal example from a real project\n\n    \"\"\"\n    foo = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def add_attr1(request):\n            request.instance.attr1 = object()\n\n\n        @pytest.fixture\n        def add_attr2(request):\n            request.instance.attr2 = request.instance.attr1\n\n\n        @pytest.mark.usefixtures('add_attr1')\n        class Parent:\n            pass\n\n\n        @pytest.mark.usefixtures('add_attr2')\n        class TestThings(Parent):\n            def test_attrs(self):\n                assert self.attr1 == self.attr2\n        \"\"\"\n    )\n    result = pytester.runpytest(foo)\n    result.assert_outcomes(passed=1)\n\n\ndef test_mark_parametrize_over_staticmethod(pytester: Pytester) -> None:\n    \"\"\"Check that applying marks works as intended on classmethods and staticmethods.\n\n    Regression test for #12863.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        class TestClass:\n            @pytest.mark.parametrize(\"value\", [1, 2])\n            @classmethod\n            def test_classmethod_wrapper(cls, value: int):\n                assert value in [1, 2]\n\n            @classmethod\n            @pytest.mark.parametrize(\"value\", [1, 2])\n            def test_classmethod_wrapper_on_top(cls, value: int):\n                assert value in [1, 2]\n\n            @pytest.mark.parametrize(\"value\", [1, 2])\n            @staticmethod\n            def test_staticmethod_wrapper(value: int):\n                assert value in [1, 2]\n\n            @staticmethod\n            @pytest.mark.parametrize(\"value\", [1, 2])\n            def test_staticmethod_wrapper_on_top(value: int):\n                assert value in [1, 2]\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=8)\n\n\ndef test_fixture_disallow_on_marked_functions() -> None:\n    \"\"\"Test that applying @pytest.fixture to a marked function errors (#3364).\"\"\"\n    with pytest.raises(\n        pytest.fail.Exception,\n        match=r\"Marks cannot be applied to fixtures\",\n    ):\n\n        @pytest.fixture\n        @pytest.mark.parametrize(\"example\", [\"hello\"])\n        @pytest.mark.usefixtures(\"tmp_path\")\n        def foo():\n            raise NotImplementedError()\n\n\ndef test_fixture_disallow_marks_on_fixtures() -> None:\n    \"\"\"Test that applying a mark to a fixture errors (#3364).\"\"\"\n    with pytest.raises(\n        pytest.fail.Exception,\n        match=r\"Marks cannot be applied to fixtures\",\n    ):\n\n        @pytest.mark.parametrize(\"example\", [\"hello\"])\n        @pytest.mark.usefixtures(\"tmp_path\")\n        @pytest.fixture\n        def foo():\n            raise NotImplementedError()\n\n\ndef test_fixture_disallowed_between_marks() -> None:\n    \"\"\"Test that applying a mark to a fixture errors (#3364).\"\"\"\n    with pytest.raises(\n        pytest.fail.Exception,\n        match=r\"Marks cannot be applied to fixtures\",\n    ):\n\n        @pytest.mark.parametrize(\"example\", [\"hello\"])\n        @pytest.fixture\n        @pytest.mark.usefixtures(\"tmp_path\")\n        def foo():\n            raise NotImplementedError()\n"
  },
  {
    "path": "testing/test_mark_expression.py",
    "content": "from __future__ import annotations\n\nfrom _pytest.mark import MarkMatcher\nfrom _pytest.mark.expression import Expression\nfrom _pytest.mark.expression import ExpressionMatcher\nimport pytest\n\n\ndef evaluate(input: str, matcher: ExpressionMatcher) -> bool:\n    return Expression.compile(input).evaluate(matcher)\n\n\ndef test_empty_is_false() -> None:\n    assert not evaluate(\"\", lambda ident, /, **kwargs: False)\n    assert not evaluate(\"\", lambda ident, /, **kwargs: True)\n    assert not evaluate(\"   \", lambda ident, /, **kwargs: False)\n    assert not evaluate(\"\\t\", lambda ident, /, **kwargs: False)\n\n\n@pytest.mark.parametrize(\n    (\"expr\", \"expected\"),\n    (\n        (\"true\", True),\n        (\"false\", False),\n        (\"not true\", False),\n        (\"not false\", True),\n        (\"not not true\", True),\n        (\"not not false\", False),\n        (\"true and true\", True),\n        (\"true and false\", False),\n        (\"false and true\", False),\n        (\"true and true and true\", True),\n        (\"true and true and false\", False),\n        (\"true and true and not true\", False),\n        (\"false or false\", False),\n        (\"false or true\", True),\n        (\"true or true\", True),\n        (\"true or true or false\", True),\n        (\"true and true or false\", True),\n        (\"not true or true\", True),\n        (\"(not true) or true\", True),\n        (\"not (true or true)\", False),\n        (\"true and true or false and false\", True),\n        (\"true and (true or false) and false\", False),\n        (\"true and (true or (not (not false))) and false\", False),\n    ),\n)\ndef test_basic(expr: str, expected: bool) -> None:\n    def matcher(name: str, /, **kwargs: str | int | bool | None) -> bool:\n        return {\"true\": True, \"false\": False}[name]\n\n    assert evaluate(expr, matcher) is expected\n\n\n@pytest.mark.parametrize(\n    (\"expr\", \"expected\"),\n    (\n        (\"               true           \", True),\n        (\"               ((((((true))))))           \", True),\n        (\"     (         ((\\t  (((true)))))  \\t   \\t)\", True),\n        (\"(     true     and   (((false))))\", False),\n        (\"not not not not true\", True),\n        (\"not not not not not true\", False),\n    ),\n)\ndef test_syntax_oddities(expr: str, expected: bool) -> None:\n    def matcher(name: str, /, **kwargs: str | int | bool | None) -> bool:\n        return {\"true\": True, \"false\": False}[name]\n\n    assert evaluate(expr, matcher) is expected\n\n\ndef test_backslash_not_treated_specially() -> None:\n    r\"\"\"When generating nodeids, if the source name contains special characters\n    like a newline, they are escaped into two characters like \\n. Therefore, a\n    user will never need to insert a literal newline, only \\n (two chars). So\n    mark expressions themselves do not support escaping, instead they treat\n    backslashes as regular identifier characters.\"\"\"\n\n    def matcher(name: str, /, **kwargs: str | int | bool | None) -> bool:\n        return {r\"\\nfoo\\n\"}.__contains__(name)\n\n    assert evaluate(r\"\\nfoo\\n\", matcher)\n    assert not evaluate(r\"foo\", matcher)\n    with pytest.raises(SyntaxError):\n        evaluate(\"\\nfoo\\n\", matcher)\n\n\n@pytest.mark.parametrize(\n    (\"expr\", \"column\", \"message\"),\n    (\n        (\"(\", 2, \"expected not OR left parenthesis OR identifier; got end of input\"),\n        (\n            \" (\",\n            3,\n            \"expected not OR left parenthesis OR identifier; got end of input\",\n        ),\n        (\n            \")\",\n            1,\n            \"expected not OR left parenthesis OR identifier; got right parenthesis\",\n        ),\n        (\n            \") \",\n            1,\n            \"expected not OR left parenthesis OR identifier; got right parenthesis\",\n        ),\n        (\n            \"not\",\n            4,\n            \"expected not OR left parenthesis OR identifier; got end of input\",\n        ),\n        (\n            \"not not\",\n            8,\n            \"expected not OR left parenthesis OR identifier; got end of input\",\n        ),\n        (\n            \"(not)\",\n            5,\n            \"expected not OR left parenthesis OR identifier; got right parenthesis\",\n        ),\n        (\"and\", 1, \"expected not OR left parenthesis OR identifier; got and\"),\n        (\n            \"ident and\",\n            10,\n            \"expected not OR left parenthesis OR identifier; got end of input\",\n        ),\n        (\n            \"ident and or\",\n            11,\n            \"expected not OR left parenthesis OR identifier; got or\",\n        ),\n        (\"ident ident\", 7, \"expected end of input; got identifier\"),\n    ),\n)\ndef test_syntax_errors(expr: str, column: int, message: str) -> None:\n    with pytest.raises(SyntaxError) as excinfo:\n        evaluate(expr, lambda ident, /, **kwargs: True)\n    assert excinfo.value.offset == column\n    assert excinfo.value.msg == message\n\n\n@pytest.mark.parametrize(\n    \"ident\",\n    (\n        \".\",\n        \"...\",\n        \":::\",\n        \"a:::c\",\n        \"a+-b\",\n        r\"\\nhe\\\\l\\lo\\n\\t\\rbye\",\n        \"a/b\",\n        \"אבגד\",\n        \"aaאבגדcc\",\n        \"a[bcd]\",\n        \"1234\",\n        \"1234abcd\",\n        \"1234and\",\n        \"1234or\",\n        \"1234not\",\n        \"notandor\",\n        \"not_and_or\",\n        \"not[and]or\",\n        \"1234+5678\",\n        \"123.232\",\n        \"True\",\n        \"False\",\n        \"None\",\n        \"if\",\n        \"else\",\n        \"while\",\n    ),\n)\ndef test_valid_idents(ident: str) -> None:\n    def matcher(name: str, /, **kwargs: str | int | bool | None) -> bool:\n        return name == ident\n\n    assert evaluate(ident, matcher)\n\n\n@pytest.mark.parametrize(\n    \"ident\",\n    (\n        \"^\",\n        \"*\",\n        \"=\",\n        \"&\",\n        \"%\",\n        \"$\",\n        \"#\",\n        \"@\",\n        \"!\",\n        \"~\",\n        \"{\",\n        \"}\",\n        '\"',\n        \"'\",\n        \"|\",\n        \";\",\n        \"←\",\n    ),\n)\ndef test_invalid_idents(ident: str) -> None:\n    with pytest.raises(SyntaxError):\n        evaluate(ident, lambda ident, /, **kwargs: True)\n\n\n@pytest.mark.parametrize(\n    \"expr, expected_error_msg\",\n    (\n        (\"mark()\", \"expected identifier; got right parenthesis\"),\n        (\"mark(True=False)\", \"unexpected reserved python keyword `True`\"),\n        (\"mark(def=False)\", \"unexpected reserved python keyword `def`\"),\n        (\"mark(class=False)\", \"unexpected reserved python keyword `class`\"),\n        (\"mark(if=False)\", \"unexpected reserved python keyword `if`\"),\n        (\"mark(else=False)\", \"unexpected reserved python keyword `else`\"),\n        (\"mark(valid=False, def=1)\", \"unexpected reserved python keyword `def`\"),\n        (\"mark(1)\", \"not a valid python identifier 1\"),\n        (\"mark(var:=False\", \"not a valid python identifier var:\"),\n        (\"mark(1=2)\", \"not a valid python identifier 1\"),\n        (\"mark(/=2)\", \"not a valid python identifier /\"),\n        (\"mark(var==\", \"expected identifier; got =\"),\n        (\"mark(var)\", \"expected =; got right parenthesis\"),\n        (\"mark(var=none)\", 'unexpected character/s \"none\"'),\n        (\"mark(var=1.1)\", 'unexpected character/s \"1.1\"'),\n        (\"mark(var=')\", \"\"\"closing quote \"'\" is missing\"\"\"),\n        ('mark(var=\")', 'closing quote \"\"\" is missing'),\n        (\"\"\"mark(var=\"')\"\"\", 'closing quote \"\"\" is missing'),\n        (\"\"\"mark(var='\")\"\"\", \"\"\"closing quote \"'\" is missing\"\"\"),\n        (\n            r\"mark(var='\\hugo')\",\n            r'escaping with \"\\\\\" not supported in marker expression',\n        ),\n        (\"mark(empty_list=[])\", r'unexpected character/s \"\\[\\]\"'),\n        (\"'str'\", \"expected not OR left parenthesis OR identifier; got string literal\"),\n    ),\n)\ndef test_invalid_kwarg_name_or_value(\n    expr: str, expected_error_msg: str, mark_matcher: MarkMatcher\n) -> None:\n    with pytest.raises(SyntaxError, match=expected_error_msg):\n        assert evaluate(expr, mark_matcher)\n\n\n@pytest.fixture(scope=\"session\")\ndef mark_matcher() -> MarkMatcher:\n    markers = [\n        pytest.mark.number_mark(a=1, b=2, c=3, d=999_999).mark,\n        pytest.mark.builtin_matchers_mark(x=True, y=False, z=None).mark,\n        pytest.mark.str_mark(  # pylint: disable-next=non-ascii-name\n            m=\"M\", space=\"with space\", empty=\"\", aaאבגדcc=\"aaאבגדcc\", אבגד=\"אבגד\"\n        ).mark,\n    ]\n\n    return MarkMatcher.from_markers(markers)\n\n\n@pytest.mark.parametrize(\n    \"expr, expected\",\n    (\n        # happy cases\n        (\"number_mark(a=1)\", True),\n        (\"number_mark(b=2)\", True),\n        (\"number_mark(a=1,b=2)\", True),\n        (\"number_mark(a=1,     b=2)\", True),\n        (\"number_mark(d=999999)\", True),\n        (\"number_mark(a   =   1,b= 2,     c = 3)\", True),\n        # sad cases\n        (\"number_mark(a=6)\", False),\n        (\"number_mark(b=6)\", False),\n        (\"number_mark(a=1,b=6)\", False),\n        (\"number_mark(a=6,b=2)\", False),\n        (\"number_mark(a   =   1,b= 2,     c = 6)\", False),\n        (\"number_mark(a='1')\", False),\n    ),\n)\ndef test_keyword_expressions_with_numbers(\n    expr: str, expected: bool, mark_matcher: MarkMatcher\n) -> None:\n    assert evaluate(expr, mark_matcher) is expected\n\n\n@pytest.mark.parametrize(\n    \"expr, expected\",\n    (\n        (\"builtin_matchers_mark(x=True)\", True),\n        (\"builtin_matchers_mark(x=False)\", False),\n        (\"builtin_matchers_mark(y=True)\", False),\n        (\"builtin_matchers_mark(y=False)\", True),\n        (\"builtin_matchers_mark(z=None)\", True),\n        (\"builtin_matchers_mark(z=False)\", False),\n        (\"builtin_matchers_mark(z=True)\", False),\n        (\"builtin_matchers_mark(z=0)\", False),\n        (\"builtin_matchers_mark(z=1)\", False),\n    ),\n)\ndef test_builtin_matchers_keyword_expressions(\n    expr: str, expected: bool, mark_matcher: MarkMatcher\n) -> None:\n    assert evaluate(expr, mark_matcher) is expected\n\n\n@pytest.mark.parametrize(\n    \"expr, expected\",\n    (\n        (\"str_mark(m='M')\", True),\n        ('str_mark(m=\"M\")', True),\n        (\"str_mark(aaאבגדcc='aaאבגדcc')\", True),\n        (\"str_mark(אבגד='אבגד')\", True),\n        (\"str_mark(space='with space')\", True),\n        (\"str_mark(empty='')\", True),\n        ('str_mark(empty=\"\")', True),\n        (\"str_mark(m='wrong')\", False),\n        (\"str_mark(aaאבגדcc='wrong')\", False),\n        (\"str_mark(אבגד='wrong')\", False),\n        (\"str_mark(m='')\", False),\n        ('str_mark(m=\"\")', False),\n    ),\n)\ndef test_str_keyword_expressions(\n    expr: str, expected: bool, mark_matcher: MarkMatcher\n) -> None:\n    assert evaluate(expr, mark_matcher) is expected\n"
  },
  {
    "path": "testing/test_meta.py",
    "content": "\"\"\"Test importing of all internal packages and modules.\n\nThis ensures all internal packages can be imported without needing the pytest\nnamespace being set, which is critical for the initialization of xdist.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport pkgutil\nimport subprocess\nimport sys\n\nimport _pytest\nimport pytest\n\n\ndef _modules() -> list[str]:\n    pytest_pkg: str = _pytest.__path__  # type: ignore\n    return sorted(\n        n\n        for _, n, _ in pkgutil.walk_packages(pytest_pkg, prefix=_pytest.__name__ + \".\")\n    )\n\n\n@pytest.mark.slow\n@pytest.mark.parametrize(\"module\", _modules())\ndef test_no_warnings(module: str) -> None:\n    # fmt: off\n    subprocess.check_call((\n        sys.executable,\n        \"-W\", \"error\",\n        \"-c\", f\"__import__({module!r})\",\n    ))\n    # fmt: on\n"
  },
  {
    "path": "testing/test_monkeypatch.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nimport os\nfrom pathlib import Path\nimport re\nimport sys\nimport textwrap\nimport warnings\n\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\n@pytest.fixture\ndef mp() -> Generator[MonkeyPatch]:\n    cwd = os.getcwd()\n    sys_path = list(sys.path)\n    yield MonkeyPatch()\n    sys.path[:] = sys_path\n    os.chdir(cwd)\n\n\ndef test_setattr() -> None:\n    class A:\n        x = 1\n\n    monkeypatch = MonkeyPatch()\n    pytest.raises(AttributeError, monkeypatch.setattr, A, \"notexists\", 2)\n    monkeypatch.setattr(A, \"y\", 2, raising=False)\n    assert A.y == 2  # type: ignore\n    monkeypatch.undo()\n    assert not hasattr(A, \"y\")\n\n    monkeypatch = MonkeyPatch()\n    monkeypatch.setattr(A, \"x\", 2)\n    assert A.x == 2\n    monkeypatch.setattr(A, \"x\", 3)\n    assert A.x == 3\n    monkeypatch.undo()\n    assert A.x == 1\n\n    A.x = 5\n    monkeypatch.undo()  # double-undo makes no modification\n    assert A.x == 5\n\n    with pytest.raises(TypeError):\n        monkeypatch.setattr(A, \"y\")  # type: ignore[call-overload]\n\n\nclass TestSetattrWithImportPath:\n    def test_string_expression(self, monkeypatch: MonkeyPatch) -> None:\n        with monkeypatch.context() as mp:\n            mp.setattr(\"os.path.abspath\", lambda x: \"hello2\")\n            assert os.path.abspath(\"123\") == \"hello2\"\n\n    def test_string_expression_class(self, monkeypatch: MonkeyPatch) -> None:\n        with monkeypatch.context() as mp:\n            mp.setattr(\"_pytest.config.Config\", 42)\n            import _pytest\n\n            assert _pytest.config.Config == 42  # type: ignore\n\n    def test_unicode_string(self, monkeypatch: MonkeyPatch) -> None:\n        with monkeypatch.context() as mp:\n            mp.setattr(\"_pytest.config.Config\", 42)\n            import _pytest\n\n            assert _pytest.config.Config == 42  # type: ignore\n            mp.delattr(\"_pytest.config.Config\")\n\n    def test_wrong_target(self, monkeypatch: MonkeyPatch) -> None:\n        with pytest.raises(TypeError):\n            monkeypatch.setattr(None, None)  # type: ignore[call-overload]\n\n    def test_unknown_import(self, monkeypatch: MonkeyPatch) -> None:\n        with pytest.raises(ImportError):\n            monkeypatch.setattr(\"unkn123.classx\", None)\n\n    def test_unknown_attr(self, monkeypatch: MonkeyPatch) -> None:\n        with pytest.raises(AttributeError):\n            monkeypatch.setattr(\"os.path.qweqwe\", None)\n\n    def test_unknown_attr_non_raising(self, monkeypatch: MonkeyPatch) -> None:\n        # https://github.com/pytest-dev/pytest/issues/746\n        with monkeypatch.context() as mp:\n            mp.setattr(\"os.path.qweqwe\", 42, raising=False)\n            assert os.path.qweqwe == 42  # type: ignore\n\n    def test_delattr(self, monkeypatch: MonkeyPatch) -> None:\n        with monkeypatch.context() as mp:\n            mp.delattr(\"os.path.abspath\")\n            assert not hasattr(os.path, \"abspath\")\n            mp.undo()\n            assert os.path.abspath  # type:ignore[truthy-function]\n\n\ndef test_delattr() -> None:\n    class A:\n        x = 1\n\n    monkeypatch = MonkeyPatch()\n    monkeypatch.delattr(A, \"x\")\n    assert not hasattr(A, \"x\")\n    monkeypatch.undo()\n    assert A.x == 1\n\n    monkeypatch = MonkeyPatch()\n    monkeypatch.delattr(A, \"x\")\n    pytest.raises(AttributeError, monkeypatch.delattr, A, \"y\")\n    monkeypatch.delattr(A, \"y\", raising=False)\n    monkeypatch.setattr(A, \"x\", 5, raising=False)\n    assert A.x == 5\n    monkeypatch.undo()\n    assert A.x == 1\n\n\ndef test_setitem() -> None:\n    d = {\"x\": 1}\n    monkeypatch = MonkeyPatch()\n    monkeypatch.setitem(d, \"x\", 2)\n    monkeypatch.setitem(d, \"y\", 1700)\n    monkeypatch.setitem(d, \"y\", 1700)\n    assert d[\"x\"] == 2\n    assert d[\"y\"] == 1700\n    monkeypatch.setitem(d, \"x\", 3)\n    assert d[\"x\"] == 3\n    monkeypatch.undo()\n    assert d[\"x\"] == 1\n    assert \"y\" not in d\n    d[\"x\"] = 5\n    monkeypatch.undo()\n    assert d[\"x\"] == 5\n\n\ndef test_setitem_deleted_meanwhile() -> None:\n    d: dict[str, object] = {}\n    monkeypatch = MonkeyPatch()\n    monkeypatch.setitem(d, \"x\", 2)\n    del d[\"x\"]\n    monkeypatch.undo()\n    assert not d\n\n\n@pytest.mark.parametrize(\"before\", [True, False])\ndef test_setenv_deleted_meanwhile(before: bool) -> None:\n    key = \"qwpeoip123\"\n    if before:\n        os.environ[key] = \"world\"\n    monkeypatch = MonkeyPatch()\n    monkeypatch.setenv(key, \"hello\")\n    del os.environ[key]\n    monkeypatch.undo()\n    if before:\n        assert os.environ[key] == \"world\"\n        del os.environ[key]\n    else:\n        assert key not in os.environ\n\n\ndef test_delitem() -> None:\n    d: dict[str, object] = {\"x\": 1}\n    monkeypatch = MonkeyPatch()\n    monkeypatch.delitem(d, \"x\")\n    assert \"x\" not in d\n    monkeypatch.delitem(d, \"y\", raising=False)\n    pytest.raises(KeyError, monkeypatch.delitem, d, \"y\")\n    assert not d\n    monkeypatch.setitem(d, \"y\", 1700)\n    assert d[\"y\"] == 1700\n    d[\"hello\"] = \"world\"\n    monkeypatch.setitem(d, \"x\", 1500)\n    assert d[\"x\"] == 1500\n    monkeypatch.undo()\n    assert d == {\"hello\": \"world\", \"x\": 1}\n\n\ndef test_setenv() -> None:\n    monkeypatch = MonkeyPatch()\n    with pytest.warns(pytest.PytestWarning):\n        monkeypatch.setenv(\"XYZ123\", 2)  # type: ignore[arg-type]\n    import os\n\n    assert os.environ[\"XYZ123\"] == \"2\"\n    monkeypatch.undo()\n    assert \"XYZ123\" not in os.environ\n\n\ndef test_delenv() -> None:\n    name = \"xyz1234\"\n    assert name not in os.environ\n    monkeypatch = MonkeyPatch()\n    pytest.raises(KeyError, monkeypatch.delenv, name, raising=True)\n    monkeypatch.delenv(name, raising=False)\n    monkeypatch.undo()\n    os.environ[name] = \"1\"\n    try:\n        monkeypatch = MonkeyPatch()\n        monkeypatch.delenv(name)\n        assert name not in os.environ\n        monkeypatch.setenv(name, \"3\")\n        assert os.environ[name] == \"3\"\n        monkeypatch.undo()\n        assert os.environ[name] == \"1\"\n    finally:\n        if name in os.environ:\n            del os.environ[name]\n\n\nclass TestEnvironWarnings:\n    \"\"\"\n    os.environ keys and values should be native strings, otherwise it will cause problems with other modules (notably\n    subprocess). On Python 2 os.environ accepts anything without complaining, while Python 3 does the right thing\n    and raises an error.\n    \"\"\"\n\n    VAR_NAME = \"PYTEST_INTERNAL_MY_VAR\"\n\n    def test_setenv_non_str_warning(self, monkeypatch: MonkeyPatch) -> None:\n        value = 2\n        msg = (\n            \"Value of environment variable PYTEST_INTERNAL_MY_VAR type should be str, \"\n            \"but got 2 (type: int); converted to str implicitly\"\n        )\n        with pytest.warns(pytest.PytestWarning, match=re.escape(msg)):\n            monkeypatch.setenv(str(self.VAR_NAME), value)  # type: ignore[arg-type]\n\n\ndef test_setenv_prepend() -> None:\n    import os\n\n    monkeypatch = MonkeyPatch()\n    monkeypatch.setenv(\"XYZ123\", \"2\", prepend=\"-\")\n    monkeypatch.setenv(\"XYZ123\", \"3\", prepend=\"-\")\n    assert os.environ[\"XYZ123\"] == \"3-2\"\n    monkeypatch.undo()\n    assert \"XYZ123\" not in os.environ\n\n\ndef test_monkeypatch_plugin(pytester: Pytester) -> None:\n    reprec = pytester.inline_runsource(\n        \"\"\"\n        def test_method(monkeypatch):\n            assert monkeypatch.__class__.__name__ == \"MonkeyPatch\"\n    \"\"\"\n    )\n    res = reprec.countoutcomes()\n    assert tuple(res) == (1, 0, 0), res\n\n\ndef test_syspath_prepend(mp: MonkeyPatch) -> None:\n    old = list(sys.path)\n    mp.syspath_prepend(\"world\")\n    mp.syspath_prepend(\"hello\")\n    assert sys.path[0] == \"hello\"\n    assert sys.path[1] == \"world\"\n    mp.undo()\n    assert sys.path == old\n    mp.undo()\n    assert sys.path == old\n\n\ndef test_syspath_prepend_double_undo(mp: MonkeyPatch) -> None:\n    old_syspath = sys.path[:]\n    try:\n        mp.syspath_prepend(\"hello world\")\n        mp.undo()\n        sys.path.append(\"more hello world\")\n        mp.undo()\n        assert sys.path[-1] == \"more hello world\"\n    finally:\n        sys.path[:] = old_syspath\n\n\ndef test_chdir_with_path_local(mp: MonkeyPatch, tmp_path: Path) -> None:\n    mp.chdir(tmp_path)\n    assert os.getcwd() == str(tmp_path)\n\n\ndef test_chdir_with_str(mp: MonkeyPatch, tmp_path: Path) -> None:\n    mp.chdir(str(tmp_path))\n    assert os.getcwd() == str(tmp_path)\n\n\ndef test_chdir_undo(mp: MonkeyPatch, tmp_path: Path) -> None:\n    cwd = os.getcwd()\n    mp.chdir(tmp_path)\n    mp.undo()\n    assert os.getcwd() == cwd\n\n\ndef test_chdir_double_undo(mp: MonkeyPatch, tmp_path: Path) -> None:\n    mp.chdir(str(tmp_path))\n    mp.undo()\n    os.chdir(tmp_path)\n    mp.undo()\n    assert os.getcwd() == str(tmp_path)\n\n\ndef test_issue185_time_breaks(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import time\n        def test_m(monkeypatch):\n            def f():\n                raise Exception\n            monkeypatch.setattr(time, \"time\", f)\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        *1 passed*\n    \"\"\"\n    )\n\n\ndef test_importerror(pytester: Pytester) -> None:\n    p = pytester.mkpydir(\"package\")\n    p.joinpath(\"a.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        import doesnotexist\n\n        x = 1\n    \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    pytester.path.joinpath(\"test_importerror.py\").write_text(\n        textwrap.dedent(\n            \"\"\"\\\n        def test_importerror(monkeypatch):\n            monkeypatch.setattr('package.a.x', 2)\n    \"\"\"\n        ),\n        encoding=\"utf-8\",\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        *import error in package.a: No module named 'doesnotexist'*\n    \"\"\"\n    )\n\n\nclass Sample:\n    @staticmethod\n    def hello() -> bool:\n        return True\n\n\nclass SampleInherit(Sample):\n    pass\n\n\n@pytest.mark.parametrize(\n    \"Sample\",\n    [Sample, SampleInherit],\n    ids=[\"new\", \"new-inherit\"],\n)\ndef test_issue156_undo_staticmethod(Sample: type[Sample]) -> None:\n    monkeypatch = MonkeyPatch()\n\n    monkeypatch.setattr(Sample, \"hello\", None)\n    assert Sample.hello is None\n\n    monkeypatch.undo()  # type: ignore[unreachable]\n    assert Sample.hello()\n\n\ndef test_undo_class_descriptors_delattr() -> None:\n    class SampleParent:\n        @classmethod\n        def hello(_cls):\n            pass\n\n        @staticmethod\n        def world():\n            pass\n\n    class SampleChild(SampleParent):\n        pass\n\n    monkeypatch = MonkeyPatch()\n\n    original_hello = SampleChild.hello\n    original_world = SampleChild.world\n    monkeypatch.delattr(SampleParent, \"hello\")\n    monkeypatch.delattr(SampleParent, \"world\")\n    assert getattr(SampleParent, \"hello\", None) is None\n    assert getattr(SampleParent, \"world\", None) is None\n\n    monkeypatch.undo()\n    assert original_hello == SampleChild.hello\n    assert original_world == SampleChild.world\n\n\ndef test_issue1338_name_resolving() -> None:\n    pytest.importorskip(\"requests\")\n    monkeypatch = MonkeyPatch()\n    try:\n        monkeypatch.delattr(\"requests.sessions.Session.request\")\n    finally:\n        monkeypatch.undo()\n\n\ndef test_context() -> None:\n    monkeypatch = MonkeyPatch()\n\n    import functools\n    import inspect\n\n    with monkeypatch.context() as m:\n        m.setattr(functools, \"partial\", 3)\n        assert not inspect.isclass(functools.partial)\n    assert inspect.isclass(functools.partial)\n\n\ndef test_context_classmethod() -> None:\n    class A:\n        x = 1\n\n    with MonkeyPatch.context() as m:\n        m.setattr(A, \"x\", 2)\n        assert A.x == 2\n    assert A.x == 1\n\n\n@pytest.mark.filterwarnings(\n    r\"ignore:.*\\bpkg_resources\\b:DeprecationWarning\",\n    r\"ignore:.*\\bpkg_resources\\b:UserWarning\",\n)\ndef test_syspath_prepend_with_namespace_packages(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    # Needs to be in sys.modules.\n    pytest.importorskip(\"pkg_resources\")\n\n    for dirname in \"hello\", \"world\":\n        d = pytester.mkdir(dirname)\n        ns = d.joinpath(\"ns_pkg\")\n        ns.mkdir()\n        ns.joinpath(\"__init__.py\").write_text(\n            \"__import__('pkg_resources').declare_namespace(__name__)\", encoding=\"utf-8\"\n        )\n        lib = ns.joinpath(dirname)\n        lib.mkdir()\n        lib.joinpath(\"__init__.py\").write_text(\n            f\"def check(): return {dirname!r}\", encoding=\"utf-8\"\n        )\n\n    # First call should not warn - namespace package not registered yet.\n    monkeypatch.syspath_prepend(\"hello\")\n    # This registers ns_pkg as a namespace package.\n    import ns_pkg.hello\n\n    assert ns_pkg.hello.check() == \"hello\"\n\n    with pytest.raises(ImportError):\n        import ns_pkg.world\n\n    # Prepending should call fixup_namespace_packages.\n    # This call should warn - ns_pkg is now registered and \"world\" contains it\n    with pytest.warns(pytest.PytestRemovedIn10Warning, match=\"legacy namespace\"):\n        monkeypatch.syspath_prepend(\"world\")\n    import ns_pkg.world\n\n    assert ns_pkg.world.check() == \"world\"\n\n    # Should invalidate caches via importlib.invalidate_caches.\n    # Should not warn for path without namespace packages.\n    modules_tmpdir = pytester.mkdir(\"modules_tmpdir\")\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"error\")\n        monkeypatch.syspath_prepend(str(modules_tmpdir))\n\n    modules_tmpdir.joinpath(\"main_app.py\").write_text(\"app = True\", encoding=\"utf-8\")\n    from main_app import app  # noqa: F401\n"
  },
  {
    "path": "testing/test_nodes.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom pathlib import Path\nimport re\nimport warnings\n\nfrom _pytest import nodes\nfrom _pytest.outcomes import OutcomeException\nfrom _pytest.pytester import Pytester\nfrom _pytest.warning_types import PytestWarning\nimport pytest\n\n\ndef test_node_from_parent_disallowed_arguments() -> None:\n    with pytest.raises(TypeError, match=\"session is\"):\n        nodes.Node.from_parent(None, session=None)  # type: ignore[arg-type]\n    with pytest.raises(TypeError, match=\"config is\"):\n        nodes.Node.from_parent(None, config=None)  # type: ignore[arg-type]\n\n\ndef test_node_direct_construction_deprecated() -> None:\n    with pytest.raises(\n        OutcomeException,\n        match=(\n            r\"Direct construction of _pytest\\.nodes\\.Node has been deprecated, please \"\n            r\"use _pytest\\.nodes\\.Node\\.from_parent.\\nSee \"\n            r\"https://docs\\.pytest\\.org/en/stable/deprecations\\.html#node-construction-changed-to-node-from-parent\"\n            r\" for more details\\.\"\n        ),\n    ):\n        nodes.Node(None, session=None)  # type: ignore[arg-type]\n\n\ndef test_subclassing_both_item_and_collector_deprecated(\n    request, tmp_path: Path\n) -> None:\n    \"\"\"Verifies we warn on diamond inheritance from both Item and Collector.\"\"\"\n    # We do not expect any warnings messages to be issued during class definition.\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"error\")\n\n        class SoWrong(nodes.Item, nodes.File):\n            def __init__(self, parent: nodes.Collector, path: Path) -> None:\n                super().__init__(name=\"broken\", parent=parent, path=path)\n\n            def collect(self):\n                raise NotImplementedError()\n\n            def runtest(self):\n                raise NotImplementedError()\n\n    with pytest.warns(PytestWarning) as rec:\n        SoWrong.from_parent(request.session, path=tmp_path / \"broken.txt\")\n    messages = [str(x.message) for x in rec]\n    assert any(\n        re.search(\".*SoWrong.* not using a cooperative constructor.*\", x)\n        for x in messages\n    )\n    assert any(\n        re.search(\"(?m)SoWrong .* should not be a collector\", x) for x in messages\n    )\n\n\n@pytest.mark.parametrize(\n    \"warn_type, msg\", [(DeprecationWarning, \"deprecated\"), (PytestWarning, \"pytest\")]\n)\ndef test_node_warn_is_no_longer_only_pytest_warnings(\n    pytester: Pytester, warn_type: type[Warning], msg: str\n) -> None:\n    items = pytester.getitems(\n        \"\"\"\n        def test():\n            pass\n    \"\"\"\n    )\n    with pytest.warns(warn_type, match=msg):\n        items[0].warn(warn_type(msg))\n\n\ndef test_node_warning_enforces_warning_types(pytester: Pytester) -> None:\n    items = pytester.getitems(\n        \"\"\"\n        def test():\n            pass\n    \"\"\"\n    )\n    with pytest.raises(\n        ValueError, match=\"warning must be an instance of Warning or subclass\"\n    ):\n        items[0].warn(Exception(\"ok\"))  # type: ignore[arg-type]\n\n\nclass TestNormSep:\n    \"\"\"Tests for the norm_sep helper function.\"\"\"\n\n    def test_forward_slashes_unchanged(self) -> None:\n        \"\"\"Forward slashes pass through unchanged.\"\"\"\n        assert nodes.norm_sep(\"a/b/c\") == \"a/b/c\"\n\n    def test_backslashes_converted(self) -> None:\n        \"\"\"Backslashes are converted to forward slashes.\"\"\"\n        assert nodes.norm_sep(\"a\\\\b\\\\c\") == \"a/b/c\"\n\n    def test_mixed_separators(self) -> None:\n        \"\"\"Mixed separators are all normalized to forward slashes.\"\"\"\n        assert nodes.norm_sep(\"a\\\\b/c\\\\d\") == \"a/b/c/d\"\n\n    def test_pathlike_input(self, tmp_path: Path) -> None:\n        \"\"\"PathLike objects are converted to string with normalized separators.\"\"\"\n        # Create a path and verify it's normalized\n        result = nodes.norm_sep(tmp_path / \"subdir\" / \"file.py\")\n        assert \"\\\\\" not in result\n        assert \"subdir/file.py\" in result\n\n    def test_empty_string(self) -> None:\n        \"\"\"Empty string returns empty string.\"\"\"\n        assert nodes.norm_sep(\"\") == \"\"\n\n    def test_windows_absolute_path(self) -> None:\n        \"\"\"Windows absolute paths have backslashes converted.\"\"\"\n        assert nodes.norm_sep(\"C:\\\\Users\\\\test\\\\project\") == \"C:/Users/test/project\"\n\n\ndef test__check_initialpaths_for_relpath() -> None:\n    \"\"\"Ensure that it handles dirs, and does not always use dirname.\"\"\"\n    cwd = Path.cwd()\n\n    initial_paths = frozenset({cwd})\n\n    assert nodes._check_initialpaths_for_relpath(initial_paths, cwd) == \"\"\n\n    sub = cwd / \"file\"\n    assert nodes._check_initialpaths_for_relpath(initial_paths, sub) == \"file\"\n\n    outside = Path(\"/outside-this-does-not-exist\")\n    assert nodes._check_initialpaths_for_relpath(initial_paths, outside) is None\n\n\ndef test_failure_with_changed_cwd(pytester: Pytester) -> None:\n    \"\"\"\n    Test failure lines should use absolute paths if cwd has changed since\n    invocation, so the path is correct (#6428).\n    \"\"\"\n    p = pytester.makepyfile(\n        \"\"\"\n        import os\n        import pytest\n\n        @pytest.fixture\n        def private_dir():\n            out_dir = 'ddd'\n            os.mkdir(out_dir)\n            old_dir = os.getcwd()\n            os.chdir(out_dir)\n            yield out_dir\n            os.chdir(old_dir)\n\n        def test_show_wrong_path(private_dir):\n            assert False\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([str(p) + \":*: AssertionError\", \"*1 failed in *\"])\n"
  },
  {
    "path": "testing/test_parseopt.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport argparse\nimport locale\nimport os\nfrom pathlib import Path\nimport shlex\nimport subprocess\nimport sys\n\nfrom _pytest.config import argparsing as parseopt\nfrom _pytest.config.exceptions import UsageError\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\n@pytest.fixture\ndef parser() -> parseopt.Parser:\n    return parseopt.Parser(_ispytest=True)\n\n\nclass TestParser:\n    def test_no_help_by_default(self) -> None:\n        parser = parseopt.Parser(usage=\"xyz\", _ispytest=True)\n        pytest.raises(UsageError, lambda: parser.parse([\"-h\"]))\n\n    def test_custom_prog(self, parser: parseopt.Parser) -> None:\n        \"\"\"Custom prog can be set for `argparse.ArgumentParser`.\"\"\"\n        assert parser.optparser.prog == argparse.ArgumentParser().prog\n        parser.prog = \"custom-prog\"\n        assert parser.prog == \"custom-prog\"\n        assert parser.optparser.prog == \"custom-prog\"\n\n    def test_argument(self) -> None:\n        parser = argparse.ArgumentParser()\n\n        action = parser.add_argument(\"-a\")\n        argument = parseopt.Argument(action)\n        assert argument.names() == [\"-a\"]\n        assert argument.dest == \"a\"\n\n        action = parser.add_argument(\"-b\", \"--boop\")\n        argument = parseopt.Argument(action)\n        assert argument.names() == [\"-b\", \"--boop\"]\n        assert argument.dest == \"boop\"\n\n        action = parser.add_argument(\"-c\", \"--coop\", dest=\"abc\")\n        argument = parseopt.Argument(action)\n        assert argument.dest == \"abc\"\n        assert (\n            str(argument)\n            == \"Argument(opts: ['-c', '--coop'], dest: 'abc', default: None)\"\n        )\n\n    def test_argument_type(self) -> None:\n        parser = argparse.ArgumentParser()\n\n        action = parser.add_argument(\"-a\", dest=\"aa\", type=int)\n        argument = parseopt.Argument(action)\n        assert argument.type is int\n\n        action = parser.add_argument(\"-b\", dest=\"bb\", type=str)\n        argument = parseopt.Argument(action)\n        assert argument.type is str\n\n        action = parser.add_argument(\"-c\", dest=\"cc\", type=float)\n        argument = parseopt.Argument(action)\n        assert argument.type is float\n\n        action = parser.add_argument(\"-d\", dest=\"dd\", type=str, choices=[\"red\", \"blue\"])\n        argument = parseopt.Argument(action)\n        assert argument.type is str\n\n    def test_group_add_and_get(self, parser: parseopt.Parser) -> None:\n        group = parser.getgroup(\"hello\")\n        assert group.name == \"hello\"\n\n    def test_getgroup_simple(self, parser: parseopt.Parser) -> None:\n        group = parser.getgroup(\"hello\")\n        assert group.name == \"hello\"\n        group2 = parser.getgroup(\"hello\")\n        assert group2 is group\n\n    def test_group_ordering(self, parser: parseopt.Parser) -> None:\n        parser.getgroup(\"1\")\n        parser.getgroup(\"2\")\n        parser.getgroup(\"3\", after=\"1\")\n        groups = parser._groups\n        groups_names = [x.name for x in groups]\n        assert groups_names == [\"_anonymous\", \"1\", \"3\", \"2\"]\n\n    def test_group_addoption(self) -> None:\n        optparser = argparse.ArgumentParser()\n        arggroup = optparser.add_argument_group(\"hello\")\n        group = parseopt.OptionGroup(arggroup, \"hello\", None, _ispytest=True)\n        group.addoption(\"--option1\", action=\"store_true\")\n        assert len(group.options) == 1\n        assert isinstance(group.options[0], parseopt.Argument)\n\n    def test_group_addoption_conflict(self) -> None:\n        optparser = argparse.ArgumentParser()\n        arggroup = optparser.add_argument_group(\"hello again\")\n        group = parseopt.OptionGroup(arggroup, \"hello again\", None, _ispytest=True)\n        group.addoption(\"--option1\", \"--option-1\", action=\"store_true\")\n        with pytest.raises(ValueError) as err:\n            group.addoption(\"--option1\", \"--option-one\", action=\"store_true\")\n        assert str({\"--option1\"}) in str(err.value)\n\n    def test_group_shortopt_lowercase(self, parser: parseopt.Parser) -> None:\n        group = parser.getgroup(\"hello\")\n        with pytest.raises(ValueError):\n            group.addoption(\"-x\", action=\"store_true\")\n        assert len(group.options) == 0\n        group._addoption(\"-x\", action=\"store_true\")\n        assert len(group.options) == 1\n\n    def test_parser_addoption(self, parser: parseopt.Parser) -> None:\n        group = parser.getgroup(\"custom options\")\n        assert len(group.options) == 0\n        group.addoption(\"--option1\", action=\"store_true\")\n        assert len(group.options) == 1\n\n    def test_parse(self, parser: parseopt.Parser) -> None:\n        parser.addoption(\"--hello\", dest=\"hello\", action=\"store\")\n        args = parser.parse([\"--hello\", \"world\"])\n        assert args.hello == \"world\"\n        assert not getattr(args, parseopt.FILE_OR_DIR)\n\n    def test_parse2(self, parser: parseopt.Parser) -> None:\n        args = parser.parse([Path(\".\")])\n        assert getattr(args, parseopt.FILE_OR_DIR)[0] == \".\"\n\n    # Warning ignore because of:\n    # https://github.com/python/cpython/issues/85308\n    # Can be removed once Python<3.12 support is dropped.\n    @pytest.mark.filterwarnings(\"ignore:'encoding' argument not specified\")\n    def test_parse_from_file(self, parser: parseopt.Parser, tmp_path: Path) -> None:\n        tests = [\".\", \"some.py::Test::test_method[param0]\", \"other/test_file.py\"]\n        args_file = tmp_path / \"tests.txt\"\n        args_file.write_text(\"\\n\".join(tests), encoding=\"utf-8\")\n        args = parser.parse([f\"@{args_file.absolute()}\"])\n        assert getattr(args, parseopt.FILE_OR_DIR) == tests\n\n    def test_parse_known_args(self, parser: parseopt.Parser) -> None:\n        parser.parse_known_args([Path(\".\")])\n        parser.addoption(\"--hello\", action=\"store_true\")\n        ns = parser.parse_known_args([\"x\", \"--y\", \"--hello\", \"this\"])\n        assert ns.hello is True\n        assert ns.file_or_dir == [\"x\", \"this\"]\n\n    def test_parse_known_and_unknown_args(self, parser: parseopt.Parser) -> None:\n        parser.addoption(\"--hello\", action=\"store_true\")\n        ns, unknown = parser.parse_known_and_unknown_args(\n            [\"x\", \"--y\", \"--hello\", \"this\"]\n        )\n        assert ns.hello is True\n        assert ns.file_or_dir == [\"x\", \"this\"]\n        assert unknown == [\"--y\"]\n\n    def test_parse_will_set_default(self, parser: parseopt.Parser) -> None:\n        parser.addoption(\"--hello\", dest=\"hello\", default=\"x\", action=\"store\")\n        option = parser.parse([])\n        assert option.hello == \"x\"\n\n    def test_parse_set_options(self, parser: parseopt.Parser) -> None:\n        parser.addoption(\"--hello\", dest=\"hello\", action=\"store\")\n        parser.addoption(\"--world\", dest=\"world\", default=42)\n\n        option = argparse.Namespace()\n        parser.parse([\"--hello\", \"world\"], option)\n        assert option.hello == \"world\"\n        assert option.world == 42\n        assert getattr(option, parseopt.FILE_OR_DIR) == []\n\n    def test_parse_special_destination(self, parser: parseopt.Parser) -> None:\n        parser.addoption(\"--ultimate-answer\", type=int)\n        args = parser.parse([\"--ultimate-answer\", \"42\"])\n        assert args.ultimate_answer == 42\n\n    def test_parse_split_positional_arguments(self, parser: parseopt.Parser) -> None:\n        parser.addoption(\"-R\", action=\"store_true\")\n        parser.addoption(\"-S\", action=\"store_false\")\n        args = parser.parse([\"-R\", \"4\", \"2\", \"-S\"])\n        assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n        args = parser.parse([\"-R\", \"-S\", \"4\", \"2\", \"-R\"])\n        assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n        assert args.R is True\n        assert args.S is False\n        args = parser.parse([\"-R\", \"4\", \"-S\", \"2\"])\n        assert getattr(args, parseopt.FILE_OR_DIR) == [\"4\", \"2\"]\n        assert args.R is True\n        assert args.S is False\n\n    def test_drop_short_helper(self) -> None:\n        parser = argparse.ArgumentParser(\n            formatter_class=parseopt.DropShorterLongHelpFormatter, allow_abbrev=False\n        )\n        parser.add_argument(\n            \"-t\", \"--twoword\", \"--duo\", \"--two-word\", \"--two\", help=\"foo\"\n        )\n        # throws error on --deux only!\n        parser.add_argument(\n            \"-d\", \"--deuxmots\", \"--deux-mots\", action=\"store_true\", help=\"foo\"\n        )\n        parser.add_argument(\"-s\", action=\"store_true\", help=\"single short\")\n        parser.add_argument(\"--abc\", \"-a\", action=\"store_true\", help=\"bar\")\n        parser.add_argument(\"--klm\", \"-k\", \"--kl-m\", action=\"store_true\", help=\"bar\")\n        parser.add_argument(\n            \"-P\", \"--pq-r\", \"-p\", \"--pqr\", action=\"store_true\", help=\"bar\"\n        )\n        parser.add_argument(\n            \"--zwei-wort\", \"--zweiwort\", \"--zweiwort\", action=\"store_true\", help=\"bar\"\n        )\n        parser.add_argument(\n            \"-x\", \"--exit-on-first\", \"--exitfirst\", action=\"store_true\", help=\"spam\"\n        )\n        parser.add_argument(\"files_and_dirs\", nargs=\"*\")\n        args = parser.parse_args([\"-k\", \"--duo\", \"hallo\", \"--exitfirst\"])\n        assert args.twoword == \"hallo\"\n        assert args.klm is True\n        assert args.zwei_wort is False\n        assert args.exit_on_first is True\n        assert args.s is False\n        args = parser.parse_args([\"--deux-mots\"])\n        with pytest.raises(AttributeError):\n            assert args.deux_mots is True\n        assert args.deuxmots is True\n        args = parser.parse_args([\"file\", \"dir\"])\n        assert \"|\".join(args.files_and_dirs) == \"file|dir\"\n\n    def test_drop_short_0(self, parser: parseopt.Parser) -> None:\n        parser.addoption(\"--funcarg\", \"--func-arg\", action=\"store_true\")\n        parser.addoption(\"--abc-def\", \"--abc-def\", action=\"store_true\")\n        parser.addoption(\"--klm-hij\", action=\"store_true\")\n        with pytest.raises(UsageError):\n            parser.parse([\"--funcarg\", \"--k\"])\n\n    def test_drop_short_2(self, parser: parseopt.Parser) -> None:\n        parser.addoption(\"--func-arg\", \"--doit\", action=\"store_true\")\n        args = parser.parse([\"--doit\"])\n        assert args.func_arg is True\n\n    def test_drop_short_3(self, parser: parseopt.Parser) -> None:\n        parser.addoption(\"--func-arg\", \"--funcarg\", \"--doit\", action=\"store_true\")\n        args = parser.parse([\"abcd\"])\n        assert args.func_arg is False\n        assert args.file_or_dir == [\"abcd\"]\n\n    def test_drop_short_help0(self, parser: parseopt.Parser) -> None:\n        parser.addoption(\"--func-args\", \"--doit\", help=\"foo\", action=\"store_true\")\n        parser.parse([])\n        help = parser.optparser.format_help()\n        assert \"--func-args, --doit  foo\" in help\n\n    # testing would be more helpful with all help generated\n    def test_drop_short_help1(self, parser: parseopt.Parser) -> None:\n        group = parser.getgroup(\"general\")\n        group.addoption(\"--doit\", \"--func-args\", action=\"store_true\", help=\"foo\")\n        group._addoption(\n            \"-h\",\n            \"--help\",\n            action=\"store_true\",\n            dest=\"help\",\n            help=\"show help message and configuration info\",\n        )\n        parser.parse([\"-h\"])\n        help = parser.optparser.format_help()\n        assert \"-doit, --func-args  foo\" in help\n\n    def test_multiple_metavar_help(self, parser: parseopt.Parser) -> None:\n        \"\"\"\n        Help text for options with a metavar tuple should display help\n        in the form \"--preferences=value1 value2 value3\" (#2004).\n        \"\"\"\n        group = parser.getgroup(\"general\")\n        group.addoption(\n            \"--preferences\", metavar=(\"value1\", \"value2\", \"value3\"), nargs=3\n        )\n        group._addoption(\"-h\", \"--help\", action=\"store_true\", dest=\"help\")\n        parser.parse([\"-h\"])\n        help = parser.optparser.format_help()\n        assert \"--preferences=value1 value2 value3\" in help\n\n\ndef test_argcomplete(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n    if sys.version_info >= (3, 11):\n        # New in Python 3.11, ignores utf-8 mode\n        encoding = locale.getencoding()\n    else:\n        encoding = locale.getpreferredencoding(False)\n    try:\n        bash_version = subprocess.run(\n            [\"bash\", \"--version\"],\n            stdout=subprocess.PIPE,\n            stderr=subprocess.DEVNULL,\n            check=True,\n            text=True,\n            encoding=encoding,\n        ).stdout\n    except (OSError, subprocess.CalledProcessError):\n        pytest.skip(\"bash is not available\")\n    if \"GNU bash\" not in bash_version:\n        # See #7518.\n        pytest.skip(\"not a real bash\")\n\n    script = str(pytester.path.joinpath(\"test_argcomplete\"))\n\n    with open(str(script), \"w\", encoding=\"utf-8\") as fp:\n        # redirect output from argcomplete to stdin and stderr is not trivial\n        # http://stackoverflow.com/q/12589419/1307905\n        # so we use bash\n        fp.write(\n            f'COMP_WORDBREAKS=\"$COMP_WORDBREAKS\" {shlex.quote(sys.executable)} -m pytest 8>&1 9>&2'\n        )\n    # alternative would be extended Pytester.{run(),_run(),popen()} to be able\n    # to handle a keyword argument env that replaces os.environ in popen or\n    # extends the copy, advantage: could not forget to restore\n    monkeypatch.setenv(\"_ARGCOMPLETE\", \"1\")\n    monkeypatch.setenv(\"_ARGCOMPLETE_IFS\", \"\\x0b\")\n    monkeypatch.setenv(\"COMP_WORDBREAKS\", \" \\\\t\\\\n\\\"\\\\'><=;|&(:\")\n\n    arg = \"--fu\"\n    monkeypatch.setenv(\"COMP_LINE\", \"pytest \" + arg)\n    monkeypatch.setenv(\"COMP_POINT\", str(len(\"pytest \" + arg)))\n    result = pytester.run(\"bash\", str(script), arg)\n    if result.ret == 255:\n        # argcomplete not found\n        pytest.skip(\"argcomplete not available\")\n    elif not result.stdout.str():\n        pytest.skip(\n            f\"bash provided no output on stdout, argcomplete not available? (stderr={result.stderr.str()!r})\"\n        )\n    else:\n        result.stdout.fnmatch_lines([\"--funcargs\", \"--fulltrace\"])\n    os.mkdir(\"test_argcomplete.d\")\n    arg = \"test_argc\"\n    monkeypatch.setenv(\"COMP_LINE\", \"pytest \" + arg)\n    monkeypatch.setenv(\"COMP_POINT\", str(len(\"pytest \" + arg)))\n    result = pytester.run(\"bash\", str(script), arg)\n    result.stdout.fnmatch_lines([\"test_argcomplete\", \"test_argcomplete.d/\"])\n"
  },
  {
    "path": "testing/test_pastebin.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport email.message\nimport io\nfrom unittest import mock\n\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nclass TestPasteCapture:\n    @pytest.fixture\n    def pastebinlist(self, monkeypatch, request) -> list[str | bytes]:\n        pastebinlist: list[str | bytes] = []\n        plugin = request.config.pluginmanager.getplugin(\"pastebin\")\n        monkeypatch.setattr(plugin, \"create_new_paste\", pastebinlist.append)\n        return pastebinlist\n\n    def test_failed(self, pytester: Pytester, pastebinlist) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_pass() -> None:\n                pass\n            def test_fail():\n                assert 0\n            def test_skip():\n                pytest.skip(\"\")\n        \"\"\"\n        )\n        reprec = pytester.inline_run(testpath, \"--pastebin=failed\")\n        assert len(pastebinlist) == 1\n        s = pastebinlist[0]\n        assert s.find(\"def test_fail\") != -1\n        assert reprec.countoutcomes() == [1, 1, 1]\n\n    def test_all(self, pytester: Pytester, pastebinlist) -> None:\n        from _pytest.pytester import LineMatcher\n\n        testpath = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_pass():\n                pass\n            def test_fail():\n                assert 0\n            def test_skip():\n                pytest.skip(\"\")\n        \"\"\"\n        )\n        reprec = pytester.inline_run(testpath, \"--pastebin=all\", \"-v\")\n        assert reprec.countoutcomes() == [1, 1, 1]\n        assert len(pastebinlist) == 1\n        contents = pastebinlist[0].decode(\"utf-8\")\n        matcher = LineMatcher(contents.splitlines())\n        matcher.fnmatch_lines(\n            [\n                \"*test_pass PASSED*\",\n                \"*test_fail FAILED*\",\n                \"*test_skip SKIPPED*\",\n                \"*== 1 failed, 1 passed, 1 skipped in *\",\n            ]\n        )\n\n    def test_non_ascii_paste_text(self, pytester: Pytester, pastebinlist) -> None:\n        \"\"\"Make sure that text which contains non-ascii characters is pasted\n        correctly. See #1219.\n        \"\"\"\n        pytester.makepyfile(\n            test_unicode=\"\"\"\\\n            def test():\n                assert '☺' == 1\n            \"\"\"\n        )\n        result = pytester.runpytest(\"--pastebin=all\")\n        expected_msg = \"*assert '☺' == 1*\"\n        result.stdout.fnmatch_lines(\n            [\n                expected_msg,\n                \"*== 1 failed in *\",\n                \"*Sending information to Paste Service*\",\n            ]\n        )\n        assert len(pastebinlist) == 1\n\n\nclass TestPaste:\n    @pytest.fixture\n    def pastebin(self, request):\n        return request.config.pluginmanager.getplugin(\"pastebin\")\n\n    @pytest.fixture\n    def mocked_urlopen_invalid(self, monkeypatch: MonkeyPatch):\n        \"\"\"Monkeypatch the actual urlopen calls done by the internal plugin\n        function that connects to bpaste service, but return a url in an\n        unexpected format.\"\"\"\n        calls = []\n\n        def mocked(url, data):\n            calls.append((url, data))\n\n            class DummyFile:\n                def read(self):\n                    # part of html of a normal response\n                    return b'View <a href=\"/invalid/3c0c6750bd\">raw</a>.'\n\n            return DummyFile()\n\n        import urllib.request\n\n        monkeypatch.setattr(urllib.request, \"urlopen\", mocked)\n        return calls\n\n    @pytest.fixture\n    def mocked_urlopen(self, monkeypatch: MonkeyPatch):\n        \"\"\"Monkeypatch the actual urlopen calls done by the internal plugin\n        function that connects to bpaste service.\"\"\"\n        calls = []\n\n        def mocked(url, data):\n            calls.append((url, data))\n\n            class DummyFile:\n                def read(self):\n                    # part of html of a normal response\n                    return b'View <a href=\"/raw/3c0c6750bd\">raw</a>.'\n\n            return DummyFile()\n\n        import urllib.request\n\n        monkeypatch.setattr(urllib.request, \"urlopen\", mocked)\n        return calls\n\n    def test_pastebin_invalid_url(self, pastebin, mocked_urlopen_invalid) -> None:\n        result = pastebin.create_new_paste(b\"full-paste-contents\")\n        assert (\n            result\n            == \"bad response: invalid format ('View <a href=\\\"/invalid/3c0c6750bd\\\">raw</a>.')\"\n        )\n        assert len(mocked_urlopen_invalid) == 1\n\n    def test_pastebin_http_error(self, pastebin) -> None:\n        import urllib.error\n\n        with mock.patch(\n            \"urllib.request.urlopen\",\n            side_effect=urllib.error.HTTPError(\n                url=\"https://bpa.st\",\n                code=400,\n                msg=\"Bad request\",\n                hdrs=email.message.Message(),\n                fp=io.BytesIO(),\n            ),\n        ) as mock_urlopen:\n            result = pastebin.create_new_paste(b\"full-paste-contents\")\n        assert result == \"bad response: HTTP Error 400: Bad request\"\n        assert len(mock_urlopen.mock_calls) == 1\n\n    def test_pastebin_url_error(self, pastebin) -> None:\n        import urllib.error\n\n        with mock.patch(\n            \"urllib.request.urlopen\",\n            side_effect=urllib.error.URLError(\"the url was bad\"),\n        ) as mock_urlopen:\n            result = pastebin.create_new_paste(b\"full-paste-contents\")\n        assert result == \"bad response: <urlopen error the url was bad>\"\n        assert len(mock_urlopen.mock_calls) == 1\n\n    def test_create_new_paste(self, pastebin, mocked_urlopen) -> None:\n        result = pastebin.create_new_paste(b\"full-paste-contents\")\n        assert result == \"https://bpa.st/show/3c0c6750bd\"\n        assert len(mocked_urlopen) == 1\n        url, data = mocked_urlopen[0]\n        assert type(data) is bytes\n        lexer = \"text\"\n        assert url == \"https://bpa.st\"\n        assert f\"lexer={lexer}\" in data.decode()\n        assert \"code=full-paste-contents\" in data.decode()\n        assert \"expiry=1week\" in data.decode()\n\n    def test_create_new_paste_failure(self, pastebin, monkeypatch: MonkeyPatch) -> None:\n        import io\n        import urllib.request\n\n        def response(url, data):\n            stream = io.BytesIO(b\"something bad occurred\")\n            return stream\n\n        monkeypatch.setattr(urllib.request, \"urlopen\", response)\n        result = pastebin.create_new_paste(b\"full-paste-contents\")\n        assert result == \"bad response: invalid format ('something bad occurred')\"\n"
  },
  {
    "path": "testing/test_pathlib.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Generator\nfrom collections.abc import Iterator\nfrom collections.abc import Sequence\nimport errno\nimport importlib.abc\nimport importlib.machinery\nimport os.path\nfrom pathlib import Path\nimport pickle\nimport shutil\nimport sys\nfrom textwrap import dedent\nfrom types import ModuleType\nfrom typing import Any\nimport unittest.mock\n\nfrom _pytest.config import ExitCode\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pathlib import _import_module_using_spec\nfrom _pytest.pathlib import bestrelpath\nfrom _pytest.pathlib import commonpath\nfrom _pytest.pathlib import compute_module_name\nfrom _pytest.pathlib import CouldNotResolvePathError\nfrom _pytest.pathlib import ensure_deletable\nfrom _pytest.pathlib import fnmatch_ex\nfrom _pytest.pathlib import get_extended_length_path_str\nfrom _pytest.pathlib import get_lock_path\nfrom _pytest.pathlib import import_path\nfrom _pytest.pathlib import ImportMode\nfrom _pytest.pathlib import ImportPathMismatchError\nfrom _pytest.pathlib import insert_missing_modules\nfrom _pytest.pathlib import is_importable\nfrom _pytest.pathlib import maybe_delete_a_numbered_dir\nfrom _pytest.pathlib import module_name_from_path\nfrom _pytest.pathlib import resolve_package_path\nfrom _pytest.pathlib import resolve_pkg_root_and_module_name\nfrom _pytest.pathlib import safe_exists\nfrom _pytest.pathlib import scandir\nfrom _pytest.pathlib import spec_matches_module_path\nfrom _pytest.pathlib import symlink_or_skip\nfrom _pytest.pathlib import visit\nfrom _pytest.pytester import Pytester\nfrom _pytest.pytester import RunResult\nfrom _pytest.tmpdir import TempPathFactory\nimport pytest\n\n\n@pytest.fixture(autouse=True)\ndef autouse_pytester(pytester: Pytester) -> None:\n    \"\"\"\n    Fixture to make pytester() being autouse for all tests in this module.\n\n    pytester makes sure to restore sys.path to its previous state, and many tests in this module\n    import modules and change sys.path because of that, so common module names such as \"test\" or \"test.conftest\"\n    end up leaking to tests in other modules.\n\n    Note: we might consider extracting the sys.path restoration aspect into its own fixture, and apply it\n    to the entire test suite always.\n    \"\"\"\n\n\nclass TestFNMatcherPort:\n    \"\"\"Test our port of py.common.FNMatcher (fnmatch_ex).\"\"\"\n\n    if sys.platform == \"win32\":\n        drv1 = \"c:\"\n        drv2 = \"d:\"\n    else:\n        drv1 = \"/c\"\n        drv2 = \"/d\"\n\n    @pytest.mark.parametrize(\n        \"pattern, path\",\n        [\n            (\"*.py\", \"foo.py\"),\n            (\"*.py\", \"bar/foo.py\"),\n            (\"test_*.py\", \"foo/test_foo.py\"),\n            (\"tests/*.py\", \"tests/foo.py\"),\n            (f\"{drv1}/*.py\", f\"{drv1}/foo.py\"),\n            (f\"{drv1}/foo/*.py\", f\"{drv1}/foo/foo.py\"),\n            (\"tests/**/test*.py\", \"tests/foo/test_foo.py\"),\n            (\"tests/**/doc/test*.py\", \"tests/foo/bar/doc/test_foo.py\"),\n            (\"tests/**/doc/**/test*.py\", \"tests/foo/doc/bar/test_foo.py\"),\n        ],\n    )\n    def test_matching(self, pattern: str, path: str) -> None:\n        assert fnmatch_ex(pattern, path)\n\n    def test_matching_abspath(self) -> None:\n        abspath = os.path.abspath(os.path.join(\"tests/foo.py\"))\n        assert fnmatch_ex(\"tests/foo.py\", abspath)\n\n    @pytest.mark.parametrize(\n        \"pattern, path\",\n        [\n            (\"*.py\", \"foo.pyc\"),\n            (\"*.py\", \"foo/foo.pyc\"),\n            (\"tests/*.py\", \"foo/foo.py\"),\n            (f\"{drv1}/*.py\", f\"{drv2}/foo.py\"),\n            (f\"{drv1}/foo/*.py\", f\"{drv2}/foo/foo.py\"),\n            (\"tests/**/test*.py\", \"tests/foo.py\"),\n            (\"tests/**/test*.py\", \"foo/test_foo.py\"),\n            (\"tests/**/doc/test*.py\", \"tests/foo/bar/doc/foo.py\"),\n            (\"tests/**/doc/test*.py\", \"tests/foo/bar/test_foo.py\"),\n        ],\n    )\n    def test_not_matching(self, pattern: str, path: str) -> None:\n        assert not fnmatch_ex(pattern, path)\n\n\n@pytest.fixture(params=[True, False])\ndef ns_param(request: pytest.FixtureRequest) -> bool:\n    \"\"\"\n    Simple parametrized fixture for tests which call import_path() with consider_namespace_packages\n    using True and False.\n    \"\"\"\n    return bool(request.param)\n\n\nclass TestImportPath:\n    \"\"\"\n\n    Most of the tests here were copied from py lib's tests for \"py.local.path.pyimport\".\n\n    Having our own pyimport-like function is inline with removing py.path dependency in the future.\n    \"\"\"\n\n    @pytest.fixture(scope=\"session\")\n    def path1(self, tmp_path_factory: TempPathFactory) -> Generator[Path]:\n        path = tmp_path_factory.mktemp(\"path\")\n        self.setuptestfs(path)\n        yield path\n        assert path.joinpath(\"samplefile\").exists()\n\n    @pytest.fixture(autouse=True)\n    def preserve_sys(self):\n        with unittest.mock.patch.dict(sys.modules):\n            with unittest.mock.patch.object(sys, \"path\", list(sys.path)):\n                yield\n\n    def setuptestfs(self, path: Path) -> None:\n        # print \"setting up test fs for\", repr(path)\n        samplefile = path / \"samplefile\"\n        samplefile.write_text(\"samplefile\\n\", encoding=\"utf-8\")\n\n        execfile = path / \"execfile\"\n        execfile.write_text(\"x=42\", encoding=\"utf-8\")\n\n        execfilepy = path / \"execfile.py\"\n        execfilepy.write_text(\"x=42\", encoding=\"utf-8\")\n\n        d = {1: 2, \"hello\": \"world\", \"answer\": 42}\n        path.joinpath(\"samplepickle\").write_bytes(pickle.dumps(d, 1))\n\n        sampledir = path / \"sampledir\"\n        sampledir.mkdir()\n        sampledir.joinpath(\"otherfile\").touch()\n\n        otherdir = path / \"otherdir\"\n        otherdir.mkdir()\n        otherdir.joinpath(\"__init__.py\").touch()\n\n        module_a = otherdir / \"a.py\"\n        module_a.write_text(\"from .b import stuff as result\\n\", encoding=\"utf-8\")\n        module_b = otherdir / \"b.py\"\n        module_b.write_text('stuff=\"got it\"\\n', encoding=\"utf-8\")\n        module_c = otherdir / \"c.py\"\n        module_c.write_text(\n            dedent(\n                \"\"\"\n            import pluggy;\n            import otherdir.a\n            value = otherdir.a.result\n        \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        module_d = otherdir / \"d.py\"\n        module_d.write_text(\n            dedent(\n                \"\"\"\n            import pluggy;\n            from otherdir import a\n            value2 = a.result\n        \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n    def test_smoke_test(self, path1: Path, ns_param: bool) -> None:\n        obj = import_path(\n            path1 / \"execfile.py\", root=path1, consider_namespace_packages=ns_param\n        )\n        assert obj.x == 42\n        assert obj.__name__ == \"execfile\"\n\n    def test_import_path_missing_file(self, path1: Path, ns_param: bool) -> None:\n        with pytest.raises(ImportPathMismatchError):\n            import_path(\n                path1 / \"sampledir\", root=path1, consider_namespace_packages=ns_param\n            )\n\n    def test_renamed_dir_creates_mismatch(\n        self, tmp_path: Path, monkeypatch: MonkeyPatch, ns_param: bool\n    ) -> None:\n        tmp_path.joinpath(\"a\").mkdir()\n        p = tmp_path.joinpath(\"a\", \"test_x123.py\")\n        p.touch()\n        import_path(p, root=tmp_path, consider_namespace_packages=ns_param)\n        tmp_path.joinpath(\"a\").rename(tmp_path.joinpath(\"b\"))\n        with pytest.raises(ImportPathMismatchError):\n            import_path(\n                tmp_path.joinpath(\"b\", \"test_x123.py\"),\n                root=tmp_path,\n                consider_namespace_packages=ns_param,\n            )\n\n        # Errors can be ignored.\n        monkeypatch.setenv(\"PY_IGNORE_IMPORTMISMATCH\", \"1\")\n        import_path(\n            tmp_path.joinpath(\"b\", \"test_x123.py\"),\n            root=tmp_path,\n            consider_namespace_packages=ns_param,\n        )\n\n        # PY_IGNORE_IMPORTMISMATCH=0 does not ignore error.\n        monkeypatch.setenv(\"PY_IGNORE_IMPORTMISMATCH\", \"0\")\n        with pytest.raises(ImportPathMismatchError):\n            import_path(\n                tmp_path.joinpath(\"b\", \"test_x123.py\"),\n                root=tmp_path,\n                consider_namespace_packages=ns_param,\n            )\n\n    def test_messy_name(self, tmp_path: Path, ns_param: bool) -> None:\n        # https://bitbucket.org/hpk42/py-trunk/issue/129\n        path = tmp_path / \"foo__init__.py\"\n        path.touch()\n        module = import_path(path, root=tmp_path, consider_namespace_packages=ns_param)\n        assert module.__name__ == \"foo__init__\"\n\n    def test_dir(self, tmp_path: Path, ns_param: bool) -> None:\n        p = tmp_path / \"hello_123\"\n        p.mkdir()\n        p_init = p / \"__init__.py\"\n        p_init.touch()\n        m = import_path(p, root=tmp_path, consider_namespace_packages=ns_param)\n        assert m.__name__ == \"hello_123\"\n        m = import_path(p_init, root=tmp_path, consider_namespace_packages=ns_param)\n        assert m.__name__ == \"hello_123\"\n\n    def test_a(self, path1: Path, ns_param: bool) -> None:\n        otherdir = path1 / \"otherdir\"\n        mod = import_path(\n            otherdir / \"a.py\", root=path1, consider_namespace_packages=ns_param\n        )\n        assert mod.result == \"got it\"\n        assert mod.__name__ == \"otherdir.a\"\n\n    def test_b(self, path1: Path, ns_param: bool) -> None:\n        otherdir = path1 / \"otherdir\"\n        mod = import_path(\n            otherdir / \"b.py\", root=path1, consider_namespace_packages=ns_param\n        )\n        assert mod.stuff == \"got it\"\n        assert mod.__name__ == \"otherdir.b\"\n\n    def test_c(self, path1: Path, ns_param: bool) -> None:\n        otherdir = path1 / \"otherdir\"\n        mod = import_path(\n            otherdir / \"c.py\", root=path1, consider_namespace_packages=ns_param\n        )\n        assert mod.value == \"got it\"\n\n    def test_d(self, path1: Path, ns_param: bool) -> None:\n        otherdir = path1 / \"otherdir\"\n        mod = import_path(\n            otherdir / \"d.py\", root=path1, consider_namespace_packages=ns_param\n        )\n        assert mod.value2 == \"got it\"\n\n    def test_import_after(self, tmp_path: Path, ns_param: bool) -> None:\n        tmp_path.joinpath(\"xxxpackage\").mkdir()\n        tmp_path.joinpath(\"xxxpackage\", \"__init__.py\").touch()\n        mod1path = tmp_path.joinpath(\"xxxpackage\", \"module1.py\")\n        mod1path.touch()\n        mod1 = import_path(\n            mod1path, root=tmp_path, consider_namespace_packages=ns_param\n        )\n        assert mod1.__name__ == \"xxxpackage.module1\"\n        from xxxpackage import module1\n\n        assert module1 is mod1\n\n    def test_check_filepath_consistency(\n        self, monkeypatch: MonkeyPatch, tmp_path: Path, ns_param: bool\n    ) -> None:\n        name = \"pointsback123\"\n        p = tmp_path.joinpath(name + \".py\")\n        p.touch()\n        with monkeypatch.context() as mp:\n            for ending in (\".pyc\", \".pyo\"):\n                mod = ModuleType(name)\n                pseudopath = tmp_path.joinpath(name + ending)\n                pseudopath.touch()\n                mod.__file__ = str(pseudopath)\n                mp.setitem(sys.modules, name, mod)\n                newmod = import_path(\n                    p, root=tmp_path, consider_namespace_packages=ns_param\n                )\n                assert mod == newmod\n        mod = ModuleType(name)\n        pseudopath = tmp_path.joinpath(name + \"123.py\")\n        pseudopath.touch()\n        mod.__file__ = str(pseudopath)\n        monkeypatch.setitem(sys.modules, name, mod)\n        with pytest.raises(ImportPathMismatchError) as excinfo:\n            import_path(p, root=tmp_path, consider_namespace_packages=ns_param)\n        modname, modfile, orig = excinfo.value.args\n        assert modname == name\n        assert modfile == str(pseudopath)\n        assert orig == p\n        assert issubclass(ImportPathMismatchError, ImportError)\n\n    def test_ensuresyspath_append(self, tmp_path: Path, ns_param: bool) -> None:\n        root1 = tmp_path / \"root1\"\n        root1.mkdir()\n        file1 = root1 / \"x123.py\"\n        file1.touch()\n        assert str(root1) not in sys.path\n        import_path(\n            file1, mode=\"append\", root=tmp_path, consider_namespace_packages=ns_param\n        )\n        assert str(root1) == sys.path[-1]\n        assert str(root1) not in sys.path[:-1]\n\n    def test_invalid_path(self, tmp_path: Path, ns_param: bool) -> None:\n        with pytest.raises(ImportError):\n            import_path(\n                tmp_path / \"invalid.py\",\n                root=tmp_path,\n                consider_namespace_packages=ns_param,\n            )\n\n    @pytest.fixture\n    def simple_module(\n        self, tmp_path: Path, request: pytest.FixtureRequest\n    ) -> Iterator[Path]:\n        name = f\"mymod_{request.node.name}\"\n        fn = tmp_path / f\"_src/tests/{name}.py\"\n        fn.parent.mkdir(parents=True)\n        fn.write_text(\"def foo(x): return 40 + x\", encoding=\"utf-8\")\n        module_name = module_name_from_path(fn, root=tmp_path)\n        yield fn\n        sys.modules.pop(module_name, None)\n\n    def test_importmode_importlib(\n        self,\n        simple_module: Path,\n        tmp_path: Path,\n        request: pytest.FixtureRequest,\n        ns_param: bool,\n    ) -> None:\n        \"\"\"`importlib` mode does not change sys.path.\"\"\"\n        module = import_path(\n            simple_module,\n            mode=\"importlib\",\n            root=tmp_path,\n            consider_namespace_packages=ns_param,\n        )\n        assert module.foo(2) == 42\n        assert str(simple_module.parent) not in sys.path\n        assert module.__name__ in sys.modules\n        assert module.__name__ == f\"_src.tests.mymod_{request.node.name}\"\n        assert \"_src\" in sys.modules\n        assert \"_src.tests\" in sys.modules\n\n    def test_remembers_previous_imports(\n        self, simple_module: Path, tmp_path: Path, ns_param: bool\n    ) -> None:\n        \"\"\"`importlib` mode called remembers previous module (#10341, #10811).\"\"\"\n        module1 = import_path(\n            simple_module,\n            mode=\"importlib\",\n            root=tmp_path,\n            consider_namespace_packages=ns_param,\n        )\n        module2 = import_path(\n            simple_module,\n            mode=\"importlib\",\n            root=tmp_path,\n            consider_namespace_packages=ns_param,\n        )\n        assert module1 is module2\n\n    def test_no_meta_path_found(\n        self,\n        simple_module: Path,\n        monkeypatch: MonkeyPatch,\n        tmp_path: Path,\n        ns_param: bool,\n    ) -> None:\n        \"\"\"Even without any meta_path should still import module.\"\"\"\n        monkeypatch.setattr(sys, \"meta_path\", [])\n        module = import_path(\n            simple_module,\n            mode=\"importlib\",\n            root=tmp_path,\n            consider_namespace_packages=ns_param,\n        )\n        assert module.foo(2) == 42\n\n        # mode='importlib' fails if no spec is found to load the module\n        import importlib.util\n\n        # Force module to be re-imported.\n        del sys.modules[module.__name__]\n\n        monkeypatch.setattr(\n            importlib.util, \"spec_from_file_location\", lambda *args, **kwargs: None\n        )\n        with pytest.raises(ImportError):\n            import_path(\n                simple_module,\n                mode=\"importlib\",\n                root=tmp_path,\n                consider_namespace_packages=False,\n            )\n\n\ndef test_resolve_package_path(tmp_path: Path) -> None:\n    pkg = tmp_path / \"pkg1\"\n    pkg.mkdir()\n    (pkg / \"__init__.py\").touch()\n    (pkg / \"subdir\").mkdir()\n    (pkg / \"subdir/__init__.py\").touch()\n    assert resolve_package_path(pkg) == pkg\n    assert resolve_package_path(pkg / \"subdir/__init__.py\") == pkg\n\n\ndef test_package_unimportable(tmp_path: Path) -> None:\n    pkg = tmp_path / \"pkg1-1\"\n    pkg.mkdir()\n    pkg.joinpath(\"__init__.py\").touch()\n    subdir = pkg / \"subdir\"\n    subdir.mkdir()\n    (pkg / \"subdir/__init__.py\").touch()\n    assert resolve_package_path(subdir) == subdir\n    xyz = subdir / \"xyz.py\"\n    xyz.touch()\n    assert resolve_package_path(xyz) == subdir\n    assert not resolve_package_path(pkg)\n\n\ndef test_access_denied_during_cleanup(tmp_path: Path, monkeypatch: MonkeyPatch) -> None:\n    \"\"\"Ensure that deleting a numbered dir does not fail because of OSErrors (#4262).\"\"\"\n    path = tmp_path / \"temp-1\"\n    path.mkdir()\n\n    def renamed_failed(*args):\n        raise OSError(\"access denied\")\n\n    monkeypatch.setattr(Path, \"rename\", renamed_failed)\n\n    lock_path = get_lock_path(path)\n    maybe_delete_a_numbered_dir(path)\n    assert not lock_path.is_file()\n\n\ndef test_long_path_during_cleanup(tmp_path: Path) -> None:\n    \"\"\"Ensure that deleting long path works (particularly on Windows (#6775)).\"\"\"\n    path = (tmp_path / (\"a\" * 250)).resolve()\n    if sys.platform == \"win32\":\n        # make sure that the full path is > 260 characters without any\n        # component being over 260 characters\n        assert len(str(path)) > 260\n        extended_path = \"\\\\\\\\?\\\\\" + str(path)\n    else:\n        extended_path = str(path)\n    os.mkdir(extended_path)\n    assert os.path.isdir(extended_path)\n    maybe_delete_a_numbered_dir(path)\n    assert not os.path.isdir(extended_path)\n\n\ndef test_get_extended_length_path_str() -> None:\n    assert get_extended_length_path_str(r\"c:\\foo\") == r\"\\\\?\\c:\\foo\"\n    assert get_extended_length_path_str(r\"\\\\share\\foo\") == r\"\\\\?\\UNC\\share\\foo\"\n    assert get_extended_length_path_str(r\"\\\\?\\UNC\\share\\foo\") == r\"\\\\?\\UNC\\share\\foo\"\n    assert get_extended_length_path_str(r\"\\\\?\\c:\\foo\") == r\"\\\\?\\c:\\foo\"\n\n\ndef test_suppress_error_removing_lock(tmp_path: Path) -> None:\n    \"\"\"ensure_deletable should be resilient if lock file cannot be removed (#5456, #7491)\"\"\"\n    path = tmp_path / \"dir\"\n    path.mkdir()\n    lock = get_lock_path(path)\n    lock.touch()\n    mtime = lock.stat().st_mtime\n\n    with unittest.mock.patch.object(Path, \"unlink\", side_effect=OSError) as m:\n        assert not ensure_deletable(\n            path, consider_lock_dead_if_created_before=mtime + 30\n        )\n        assert m.call_count == 1\n    assert lock.is_file()\n\n    with unittest.mock.patch.object(Path, \"is_file\", side_effect=OSError) as m:\n        assert not ensure_deletable(\n            path, consider_lock_dead_if_created_before=mtime + 30\n        )\n        assert m.call_count == 1\n    assert lock.is_file()\n\n    # check now that we can remove the lock file in normal circumstances\n    assert ensure_deletable(path, consider_lock_dead_if_created_before=mtime + 30)\n    assert not lock.is_file()\n\n\ndef test_bestrelpath() -> None:\n    curdir = Path(\"/foo/bar/baz/path\")\n    assert bestrelpath(curdir, curdir) == \".\"\n    assert bestrelpath(curdir, curdir / \"hello\" / \"world\") == \"hello\" + os.sep + \"world\"\n    assert bestrelpath(curdir, curdir.parent / \"sister\") == \"..\" + os.sep + \"sister\"\n    assert bestrelpath(curdir, curdir.parent) == \"..\"\n    assert bestrelpath(curdir, Path(\"hello\")) == \"hello\"\n\n\ndef test_commonpath() -> None:\n    path = Path(\"/foo/bar/baz/path\")\n    subpath = path / \"sampledir\"\n    assert commonpath(path, subpath) == path\n    assert commonpath(subpath, path) == path\n    assert commonpath(Path(str(path) + \"suffix\"), path) == path.parent\n    assert commonpath(path, path.parent.parent) == path.parent.parent\n\n\ndef test_visit_ignores_errors(tmp_path: Path) -> None:\n    symlink_or_skip(\"recursive\", tmp_path / \"recursive\")\n    tmp_path.joinpath(\"foo\").write_bytes(b\"\")\n    tmp_path.joinpath(\"bar\").write_bytes(b\"\")\n\n    assert [\n        entry.name for entry in visit(str(tmp_path), recurse=lambda entry: False)\n    ] == [\"bar\", \"foo\"]\n\n\n@pytest.mark.skipif(not sys.platform.startswith(\"win\"), reason=\"Windows only\")\ndef test_samefile_false_negatives(tmp_path: Path, monkeypatch: MonkeyPatch) -> None:\n    \"\"\"\n    import_file() should not raise ImportPathMismatchError if the paths are exactly\n    equal on Windows. It seems directories mounted as UNC paths make os.path.samefile\n    return False, even when they are clearly equal.\n    \"\"\"\n    module_path = tmp_path.joinpath(\"my_module.py\")\n    module_path.write_text(\"def foo(): return 42\", encoding=\"utf-8\")\n    monkeypatch.syspath_prepend(tmp_path)\n\n    with monkeypatch.context() as mp:\n        # Forcibly make os.path.samefile() return False here to ensure we are comparing\n        # the paths too. Using a context to narrow the patch as much as possible given\n        # this is an important system function.\n        mp.setattr(os.path, \"samefile\", lambda x, y: False)\n        module = import_path(\n            module_path, root=tmp_path, consider_namespace_packages=False\n        )\n    assert getattr(module, \"foo\")() == 42\n\n\ndef test_scandir_with_non_existent_directory() -> None:\n    # Test with a directory that does not exist\n    non_existent_dir = \"path_to_non_existent_dir\"\n    result = scandir(non_existent_dir)\n    # Assert that the result is an empty list\n    assert result == []\n\n\ndef test_scandir_handles_os_error() -> None:\n    # Create a mock entry that will raise an OSError when is_file is called\n    mock_entry = unittest.mock.MagicMock()\n    mock_entry.is_file.side_effect = OSError(\"some permission error\")\n    # Mock os.scandir to return an iterator with our mock entry\n    with unittest.mock.patch(\"os.scandir\") as mock_scandir:\n        mock_scandir.return_value.__enter__.return_value = [mock_entry]\n        # Call the scandir function with a path\n        # We expect an OSError to be raised here\n        with pytest.raises(OSError, match=\"some permission error\"):\n            scandir(\"/fake/path\")\n        # Verify that the is_file method was called on the mock entry\n        mock_entry.is_file.assert_called_once()\n\n\nclass TestImportLibMode:\n    def test_importmode_importlib_with_dataclass(\n        self, tmp_path: Path, ns_param: bool\n    ) -> None:\n        \"\"\"Ensure that importlib mode works with a module containing dataclasses (#7856).\"\"\"\n        fn = tmp_path.joinpath(\"_src/tests/test_dataclass.py\")\n        fn.parent.mkdir(parents=True)\n        fn.write_text(\n            dedent(\n                \"\"\"\n                from dataclasses import dataclass\n\n                @dataclass\n                class Data:\n                    value: str\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        module = import_path(\n            fn, mode=\"importlib\", root=tmp_path, consider_namespace_packages=ns_param\n        )\n        Data: Any = getattr(module, \"Data\")\n        data = Data(value=\"foo\")\n        assert data.value == \"foo\"\n        assert data.__module__ == \"_src.tests.test_dataclass\"\n\n        # Ensure we do not import the same module again (#11475).\n        module2 = import_path(\n            fn, mode=\"importlib\", root=tmp_path, consider_namespace_packages=ns_param\n        )\n        assert module is module2\n\n    def test_importmode_importlib_with_pickle(\n        self, tmp_path: Path, ns_param: bool\n    ) -> None:\n        \"\"\"Ensure that importlib mode works with pickle (#7859).\"\"\"\n        fn = tmp_path.joinpath(\"_src/tests/test_pickle.py\")\n        fn.parent.mkdir(parents=True)\n        fn.write_text(\n            dedent(\n                \"\"\"\n                import pickle\n\n                def _action():\n                    return 42\n\n                def round_trip():\n                    s = pickle.dumps(_action)\n                    return pickle.loads(s)\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        module = import_path(\n            fn, mode=\"importlib\", root=tmp_path, consider_namespace_packages=ns_param\n        )\n        round_trip = getattr(module, \"round_trip\")\n        action = round_trip()\n        assert action() == 42\n\n        # Ensure we do not import the same module again (#11475).\n        module2 = import_path(\n            fn, mode=\"importlib\", root=tmp_path, consider_namespace_packages=ns_param\n        )\n        assert module is module2\n\n    def test_importmode_importlib_with_pickle_separate_modules(\n        self, tmp_path: Path, ns_param: bool\n    ) -> None:\n        \"\"\"\n        Ensure that importlib mode works can load pickles that look similar but are\n        defined in separate modules.\n        \"\"\"\n        fn1 = tmp_path.joinpath(\"_src/m1/tests/test.py\")\n        fn1.parent.mkdir(parents=True)\n        fn1.write_text(\n            dedent(\n                \"\"\"\n                import dataclasses\n                import pickle\n\n                @dataclasses.dataclass\n                class Data:\n                    x: int = 42\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        fn2 = tmp_path.joinpath(\"_src/m2/tests/test.py\")\n        fn2.parent.mkdir(parents=True)\n        fn2.write_text(\n            dedent(\n                \"\"\"\n                import dataclasses\n                import pickle\n\n                @dataclasses.dataclass\n                class Data:\n                    x: str = \"\"\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        import pickle\n\n        def round_trip(obj):\n            s = pickle.dumps(obj)\n            return pickle.loads(s)\n\n        module = import_path(\n            fn1, mode=\"importlib\", root=tmp_path, consider_namespace_packages=ns_param\n        )\n        Data1 = getattr(module, \"Data\")\n\n        module = import_path(\n            fn2, mode=\"importlib\", root=tmp_path, consider_namespace_packages=ns_param\n        )\n        Data2 = getattr(module, \"Data\")\n\n        assert round_trip(Data1(20)) == Data1(20)\n        assert round_trip(Data2(\"hello\")) == Data2(\"hello\")\n        assert Data1.__module__ == \"_src.m1.tests.test\"\n        assert Data2.__module__ == \"_src.m2.tests.test\"\n\n    def test_module_name_from_path(self, tmp_path: Path) -> None:\n        result = module_name_from_path(tmp_path / \"src/tests/test_foo.py\", tmp_path)\n        assert result == \"src.tests.test_foo\"\n\n        # Path is not relative to root dir: use the full path to obtain the module name.\n        result = module_name_from_path(Path(\"/home/foo/test_foo.py\"), Path(\"/bar\"))\n        assert result == \"home.foo.test_foo\"\n\n        # Importing __init__.py files should return the package as module name.\n        result = module_name_from_path(tmp_path / \"src/app/__init__.py\", tmp_path)\n        assert result == \"src.app\"\n\n        # Unless __init__.py file is at the root, in which case we cannot have an empty module name.\n        result = module_name_from_path(tmp_path / \"__init__.py\", tmp_path)\n        assert result == \"__init__\"\n\n        # Modules which start with \".\" are considered relative and will not be imported\n        # unless part of a package, so we replace it with a \"_\" when generating the fake module name.\n        result = module_name_from_path(tmp_path / \".env/tests/test_foo.py\", tmp_path)\n        assert result == \"_env.tests.test_foo\"\n\n        # We want to avoid generating extra intermediate modules if some directory just happens\n        # to contain a \".\" in the name.\n        result = module_name_from_path(\n            tmp_path / \".env.310/tests/test_foo.py\", tmp_path\n        )\n        assert result == \"_env_310.tests.test_foo\"\n\n    def test_resolve_pkg_root_and_module_name(\n        self, tmp_path: Path, monkeypatch: MonkeyPatch, pytester: Pytester\n    ) -> None:\n        # Create a directory structure first without __init__.py files.\n        (tmp_path / \"src/app/core\").mkdir(parents=True)\n        models_py = tmp_path / \"src/app/core/models.py\"\n        models_py.touch()\n\n        with pytest.raises(CouldNotResolvePathError):\n            _ = resolve_pkg_root_and_module_name(models_py)\n\n        # Create the __init__.py files, it should now resolve to a proper module name.\n        (tmp_path / \"src/app/__init__.py\").touch()\n        (tmp_path / \"src/app/core/__init__.py\").touch()\n        assert resolve_pkg_root_and_module_name(\n            models_py, consider_namespace_packages=True\n        ) == (\n            tmp_path / \"src\",\n            \"app.core.models\",\n        )\n\n        # If we add tmp_path to sys.path, src becomes a namespace package.\n        monkeypatch.syspath_prepend(tmp_path)\n        validate_namespace_package(pytester, [tmp_path], [\"src.app.core.models\"])\n\n        assert resolve_pkg_root_and_module_name(\n            models_py, consider_namespace_packages=True\n        ) == (\n            tmp_path,\n            \"src.app.core.models\",\n        )\n        assert resolve_pkg_root_and_module_name(\n            models_py, consider_namespace_packages=False\n        ) == (\n            tmp_path / \"src\",\n            \"app.core.models\",\n        )\n\n    def test_insert_missing_modules(\n        self, monkeypatch: MonkeyPatch, tmp_path: Path\n    ) -> None:\n        monkeypatch.chdir(tmp_path)\n        # Use 'xxx' and 'xxy' as parent names as they are unlikely to exist and\n        # don't end up being imported.\n        modules = {\"xxx.tests.foo\": ModuleType(\"xxx.tests.foo\")}\n        insert_missing_modules(modules, \"xxx.tests.foo\")\n        assert sorted(modules) == [\"xxx\", \"xxx.tests\", \"xxx.tests.foo\"]\n\n        mod = ModuleType(\"mod\", doc=\"My Module\")\n        modules = {\"xxy\": mod}\n        insert_missing_modules(modules, \"xxy\")\n        assert modules == {\"xxy\": mod}\n\n        modules = {}\n        insert_missing_modules(modules, \"\")\n        assert modules == {}\n\n    @pytest.mark.parametrize(\"b_is_package\", [True, False])\n    @pytest.mark.parametrize(\"insert_modules\", [True, False])\n    def test_import_module_using_spec(\n        self, b_is_package, insert_modules, tmp_path: Path\n    ):\n        \"\"\"\n        Verify that `_import_module_using_spec` can obtain a spec based on the path, thereby enabling the import.\n        When importing, not only the target module is imported, but also the parent modules are recursively imported.\n        \"\"\"\n        file_path = tmp_path / \"a/b/c/demo.py\"\n        file_path.parent.mkdir(parents=True)\n        file_path.write_text(\"my_name='demo'\", encoding=\"utf-8\")\n\n        if b_is_package:\n            (tmp_path / \"a/b/__init__.py\").write_text(\n                \"my_name='b.__init__'\", encoding=\"utf-8\"\n            )\n\n        mod = _import_module_using_spec(\n            \"a.b.c.demo\",\n            file_path,\n            file_path.parent,\n            insert_modules=insert_modules,\n        )\n\n        # target module is imported\n        assert mod is not None\n        assert spec_matches_module_path(mod.__spec__, file_path) is True\n\n        mod_demo = sys.modules[\"a.b.c.demo\"]\n        assert \"demo.py\" in str(mod_demo)\n        assert mod_demo.my_name == \"demo\"  # Imported and available for use\n\n        # parent modules are recursively imported.\n        mod_a = sys.modules[\"a\"]\n        mod_b = sys.modules[\"a.b\"]\n        mod_c = sys.modules[\"a.b.c\"]\n\n        assert mod_a.b is mod_b\n        assert mod_a.b.c is mod_c\n        assert mod_a.b.c.demo is mod_demo\n\n        assert \"namespace\" in str(mod_a).lower()\n        assert \"namespace\" in str(mod_c).lower()\n\n        # Compatibility package and namespace package.\n        if b_is_package:\n            assert \"namespace\" not in str(mod_b).lower()\n            assert \"__init__.py\" in str(mod_b).lower()  # Imported __init__.py\n            assert mod_b.my_name == \"b.__init__\"  # Imported and available for use\n\n        else:\n            assert \"namespace\" in str(mod_b).lower()\n            with pytest.raises(AttributeError):  # Not imported __init__.py\n                assert mod_b.my_name\n\n    def test_parent_contains_child_module_attribute(\n        self, monkeypatch: MonkeyPatch, tmp_path: Path\n    ):\n        monkeypatch.chdir(tmp_path)\n        # Use 'xxx' and 'xxy' as parent names as they are unlikely to exist and\n        # don't end up being imported.\n        modules = {\"xxx.tests.foo\": ModuleType(\"xxx.tests.foo\")}\n        insert_missing_modules(modules, \"xxx.tests.foo\")\n        assert sorted(modules) == [\"xxx\", \"xxx.tests\", \"xxx.tests.foo\"]\n        assert modules[\"xxx\"].tests is modules[\"xxx.tests\"]\n        assert modules[\"xxx.tests\"].foo is modules[\"xxx.tests.foo\"]\n\n    def test_importlib_package(\n        self, monkeypatch: MonkeyPatch, tmp_path: Path, ns_param: bool\n    ):\n        \"\"\"\n        Importing a package using --importmode=importlib should not import the\n        package's __init__.py file more than once (#11306).\n        \"\"\"\n        monkeypatch.chdir(tmp_path)\n        monkeypatch.syspath_prepend(tmp_path)\n\n        package_name = \"importlib_import_package\"\n        tmp_path.joinpath(package_name).mkdir()\n        init = tmp_path.joinpath(f\"{package_name}/__init__.py\")\n        init.write_text(\n            dedent(\n                \"\"\"\n                from .singleton import Singleton\n\n                instance = Singleton()\n                \"\"\"\n            ),\n            encoding=\"ascii\",\n        )\n        singleton = tmp_path.joinpath(f\"{package_name}/singleton.py\")\n        singleton.write_text(\n            dedent(\n                \"\"\"\n                class Singleton:\n                    INSTANCES = []\n\n                    def __init__(self) -> None:\n                        self.INSTANCES.append(self)\n                        if len(self.INSTANCES) > 1:\n                            raise RuntimeError(\"Already initialized\")\n                \"\"\"\n            ),\n            encoding=\"ascii\",\n        )\n\n        mod = import_path(\n            init,\n            root=tmp_path,\n            mode=ImportMode.importlib,\n            consider_namespace_packages=ns_param,\n        )\n        assert len(mod.instance.INSTANCES) == 1\n        # Ensure we do not import the same module again (#11475).\n        mod2 = import_path(\n            init,\n            root=tmp_path,\n            mode=ImportMode.importlib,\n            consider_namespace_packages=ns_param,\n        )\n        assert mod is mod2\n\n    def test_importlib_root_is_package(self, pytester: Pytester) -> None:\n        \"\"\"\n        Regression for importing a `__init__`.py file that is at the root\n        (#11417).\n        \"\"\"\n        pytester.makepyfile(__init__=\"\")\n        pytester.makepyfile(\n            \"\"\"\n            def test_my_test():\n                assert True\n            \"\"\"\n        )\n\n        result = pytester.runpytest(\"--import-mode=importlib\")\n        result.stdout.fnmatch_lines(\"* 1 passed *\")\n\n    @pytest.mark.parametrize(\"name\", [\"code\", \"time\", \"math\"])\n    def test_importlib_same_name_as_stl(\n        self, pytester, ns_param: bool, tmp_path: Path, name: str\n    ):\n        \"\"\"Import a namespace package with the same name as the standard library (#13026).\"\"\"\n        file_path = pytester.path / f\"{name}/foo/test_demo.py\"\n        file_path.parent.mkdir(parents=True)\n        file_path.write_text(\n            dedent(\n                \"\"\"\n            def test_demo():\n                pass\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        # unit test\n        importlib.import_module(name)  # import standard library\n\n        import_path(  # import user files\n            file_path,\n            mode=ImportMode.importlib,\n            root=pytester.path,\n            consider_namespace_packages=ns_param,\n        )\n\n        # E2E test\n        result = pytester.runpytest(\"--import-mode=importlib\")\n        result.stdout.fnmatch_lines(\"* 1 passed *\")\n\n    def create_installed_doctests_and_tests_dir(\n        self, path: Path, monkeypatch: MonkeyPatch\n    ) -> tuple[Path, Path, Path]:\n        \"\"\"\n        Create a directory structure where the application code is installed in a virtual environment,\n        and the tests are in an outside \".tests\" directory.\n\n        Return the paths to the core module (installed in the virtualenv), and the test modules.\n        \"\"\"\n        app = path / \"src/app\"\n        app.mkdir(parents=True)\n        (app / \"__init__.py\").touch()\n        core_py = app / \"core.py\"\n        core_py.write_text(\n            dedent(\n                \"\"\"\n                def foo():\n                    '''\n                    >>> 1 + 1\n                    2\n                    '''\n                \"\"\"\n            ),\n            encoding=\"ascii\",\n        )\n\n        # Install it into a site-packages directory, and add it to sys.path, mimicking what\n        # happens when installing into a virtualenv.\n        site_packages = path / \".env/lib/site-packages\"\n        site_packages.mkdir(parents=True)\n        shutil.copytree(app, site_packages / \"app\")\n        assert (site_packages / \"app/core.py\").is_file()\n\n        monkeypatch.syspath_prepend(site_packages)\n\n        # Create the tests files, outside 'src' and the virtualenv.\n        # We use the same test name on purpose, but in different directories, to ensure\n        # this works as advertised.\n        conftest_path1 = path / \".tests/a/conftest.py\"\n        conftest_path1.parent.mkdir(parents=True)\n        conftest_path1.write_text(\n            dedent(\n                \"\"\"\n                import pytest\n                @pytest.fixture\n                def a_fix(): return \"a\"\n                \"\"\"\n            ),\n            encoding=\"ascii\",\n        )\n        test_path1 = path / \".tests/a/test_core.py\"\n        test_path1.write_text(\n            dedent(\n                \"\"\"\n                import app.core\n                def test(a_fix):\n                    assert a_fix == \"a\"\n                \"\"\",\n            ),\n            encoding=\"ascii\",\n        )\n\n        conftest_path2 = path / \".tests/b/conftest.py\"\n        conftest_path2.parent.mkdir(parents=True)\n        conftest_path2.write_text(\n            dedent(\n                \"\"\"\n                import pytest\n                @pytest.fixture\n                def b_fix(): return \"b\"\n                \"\"\"\n            ),\n            encoding=\"ascii\",\n        )\n\n        test_path2 = path / \".tests/b/test_core.py\"\n        test_path2.write_text(\n            dedent(\n                \"\"\"\n                import app.core\n                def test(b_fix):\n                    assert b_fix == \"b\"\n                \"\"\",\n            ),\n            encoding=\"ascii\",\n        )\n        return (site_packages / \"app/core.py\"), test_path1, test_path2\n\n    def test_import_using_normal_mechanism_first(\n        self, monkeypatch: MonkeyPatch, pytester: Pytester, ns_param: bool\n    ) -> None:\n        \"\"\"\n        Test import_path imports from the canonical location when possible first, only\n        falling back to its normal flow when the module being imported is not reachable via sys.path (#11475).\n        \"\"\"\n        core_py, test_path1, test_path2 = self.create_installed_doctests_and_tests_dir(\n            pytester.path, monkeypatch\n        )\n\n        # core_py is reached from sys.path, so should be imported normally.\n        mod = import_path(\n            core_py,\n            mode=\"importlib\",\n            root=pytester.path,\n            consider_namespace_packages=ns_param,\n        )\n        assert mod.__name__ == \"app.core\"\n        assert mod.__file__ and Path(mod.__file__) == core_py\n\n        # Ensure we do not import the same module again (#11475).\n        mod2 = import_path(\n            core_py,\n            mode=\"importlib\",\n            root=pytester.path,\n            consider_namespace_packages=ns_param,\n        )\n        assert mod is mod2\n\n        # tests are not reachable from sys.path, so they are imported as a standalone modules.\n        # Instead of '.tests.a.test_core', we import as \"_tests.a.test_core\" because\n        # importlib considers module names starting with '.' to be local imports.\n        mod = import_path(\n            test_path1,\n            mode=\"importlib\",\n            root=pytester.path,\n            consider_namespace_packages=ns_param,\n        )\n        assert mod.__name__ == \"_tests.a.test_core\"\n\n        # Ensure we do not import the same module again (#11475).\n        mod2 = import_path(\n            test_path1,\n            mode=\"importlib\",\n            root=pytester.path,\n            consider_namespace_packages=ns_param,\n        )\n        assert mod is mod2\n\n        mod = import_path(\n            test_path2,\n            mode=\"importlib\",\n            root=pytester.path,\n            consider_namespace_packages=ns_param,\n        )\n        assert mod.__name__ == \"_tests.b.test_core\"\n\n        # Ensure we do not import the same module again (#11475).\n        mod2 = import_path(\n            test_path2,\n            mode=\"importlib\",\n            root=pytester.path,\n            consider_namespace_packages=ns_param,\n        )\n        assert mod is mod2\n\n    def test_import_using_normal_mechanism_first_integration(\n        self, monkeypatch: MonkeyPatch, pytester: Pytester, ns_param: bool\n    ) -> None:\n        \"\"\"\n        Same test as above, but verify the behavior calling pytest.\n\n        We should not make this call in the same test as above, as the modules have already\n        been imported by separate import_path() calls.\n        \"\"\"\n        core_py, test_path1, test_path2 = self.create_installed_doctests_and_tests_dir(\n            pytester.path, monkeypatch\n        )\n        result = pytester.runpytest(\n            \"--import-mode=importlib\",\n            \"-o\",\n            f\"consider_namespace_packages={ns_param}\",\n            \"--doctest-modules\",\n            \"--pyargs\",\n            \"app\",\n            \"./.tests\",\n        )\n        result.stdout.fnmatch_lines(\n            [\n                f\"{core_py.relative_to(pytester.path)} . *\",\n                f\"{test_path1.relative_to(pytester.path)} . *\",\n                f\"{test_path2.relative_to(pytester.path)} . *\",\n                \"* 3 passed*\",\n            ]\n        )\n\n    def test_import_path_imports_correct_file(\n        self, pytester: Pytester, ns_param: bool\n    ) -> None:\n        \"\"\"\n        Import the module by the given path, even if other module with the same name\n        is reachable from sys.path.\n        \"\"\"\n        pytester.syspathinsert()\n        # Create a 'x.py' module reachable from sys.path that raises AssertionError\n        # if imported.\n        x_at_root = pytester.path / \"x.py\"\n        x_at_root.write_text(\"raise AssertionError('x at root')\", encoding=\"ascii\")\n\n        # Create another x.py module, but in some subdirectories to ensure it is not\n        # accessible from sys.path.\n        x_in_sub_dir = pytester.path / \"a/b/x.py\"\n        x_in_sub_dir.parent.mkdir(parents=True)\n        x_in_sub_dir.write_text(\"X = 'a/b/x'\", encoding=\"ascii\")\n\n        # Import our x.py module from the subdirectories.\n        # The 'x.py' module from sys.path was not imported for sure because\n        # otherwise we would get an AssertionError.\n        mod = import_path(\n            x_in_sub_dir,\n            mode=ImportMode.importlib,\n            root=pytester.path,\n            consider_namespace_packages=ns_param,\n        )\n        assert mod.__file__ and Path(mod.__file__) == x_in_sub_dir\n        assert mod.X == \"a/b/x\"\n\n        mod2 = import_path(\n            x_in_sub_dir,\n            mode=ImportMode.importlib,\n            root=pytester.path,\n            consider_namespace_packages=ns_param,\n        )\n        assert mod is mod2\n\n        # Attempt to import root 'x.py'.\n        with pytest.raises(AssertionError, match=\"x at root\"):\n            _ = import_path(\n                x_at_root,\n                mode=ImportMode.importlib,\n                root=pytester.path,\n                consider_namespace_packages=ns_param,\n            )\n\n\ndef test_safe_exists(tmp_path: Path) -> None:\n    d = tmp_path.joinpath(\"some_dir\")\n    d.mkdir()\n    assert safe_exists(d) is True\n\n    f = tmp_path.joinpath(\"some_file\")\n    f.touch()\n    assert safe_exists(f) is True\n\n    # Use unittest.mock() as a context manager to have a very narrow\n    # patch lifetime.\n    p = tmp_path.joinpath(\"some long filename\" * 100)\n    with unittest.mock.patch.object(\n        Path,\n        \"exists\",\n        autospec=True,\n        side_effect=OSError(errno.ENAMETOOLONG, \"name too long\"),\n    ):\n        assert safe_exists(p) is False\n\n    with unittest.mock.patch.object(\n        Path,\n        \"exists\",\n        autospec=True,\n        side_effect=ValueError(\"name too long\"),\n    ):\n        assert safe_exists(p) is False\n\n\ndef test_import_sets_module_as_attribute(pytester: Pytester) -> None:\n    \"\"\"Unittest test for #12194.\"\"\"\n    pytester.path.joinpath(\"foo/bar/baz\").mkdir(parents=True)\n    pytester.path.joinpath(\"foo/__init__.py\").touch()\n    pytester.path.joinpath(\"foo/bar/__init__.py\").touch()\n    pytester.path.joinpath(\"foo/bar/baz/__init__.py\").touch()\n    pytester.syspathinsert()\n\n    # Import foo.bar.baz and ensure parent modules also ended up imported.\n    baz = import_path(\n        pytester.path.joinpath(\"foo/bar/baz/__init__.py\"),\n        mode=ImportMode.importlib,\n        root=pytester.path,\n        consider_namespace_packages=False,\n    )\n    assert baz.__name__ == \"foo.bar.baz\"\n    foo = sys.modules[\"foo\"]\n    assert foo.__name__ == \"foo\"\n    bar = sys.modules[\"foo.bar\"]\n    assert bar.__name__ == \"foo.bar\"\n\n    # Check parent modules have an attribute pointing to their children.\n    assert bar.baz is baz\n    assert foo.bar is bar\n\n    # Ensure we returned the \"foo.bar\" module cached in sys.modules.\n    bar_2 = import_path(\n        pytester.path.joinpath(\"foo/bar/__init__.py\"),\n        mode=ImportMode.importlib,\n        root=pytester.path,\n        consider_namespace_packages=False,\n    )\n    assert bar_2 is bar\n\n\ndef test_import_sets_module_as_attribute_without_init_files(pytester: Pytester) -> None:\n    \"\"\"Similar to test_import_sets_module_as_attribute, but without __init__.py files.\"\"\"\n    pytester.path.joinpath(\"foo/bar\").mkdir(parents=True)\n    pytester.path.joinpath(\"foo/bar/baz.py\").touch()\n    pytester.syspathinsert()\n\n    # Import foo.bar.baz and ensure parent modules also ended up imported.\n    baz = import_path(\n        pytester.path.joinpath(\"foo/bar/baz.py\"),\n        mode=ImportMode.importlib,\n        root=pytester.path,\n        consider_namespace_packages=False,\n    )\n    assert baz.__name__ == \"foo.bar.baz\"\n    foo = sys.modules[\"foo\"]\n    assert foo.__name__ == \"foo\"\n    bar = sys.modules[\"foo.bar\"]\n    assert bar.__name__ == \"foo.bar\"\n\n    # Check parent modules have an attribute pointing to their children.\n    assert bar.baz is baz\n    assert foo.bar is bar\n\n    # Ensure we returned the \"foo.bar.baz\" module cached in sys.modules.\n    baz_2 = import_path(\n        pytester.path.joinpath(\"foo/bar/baz.py\"),\n        mode=ImportMode.importlib,\n        root=pytester.path,\n        consider_namespace_packages=False,\n    )\n    assert baz_2 is baz\n\n\ndef test_import_sets_module_as_attribute_regression(pytester: Pytester) -> None:\n    \"\"\"Regression test for #12194.\"\"\"\n    pytester.path.joinpath(\"foo/bar/baz\").mkdir(parents=True)\n    pytester.path.joinpath(\"foo/__init__.py\").touch()\n    pytester.path.joinpath(\"foo/bar/__init__.py\").touch()\n    pytester.path.joinpath(\"foo/bar/baz/__init__.py\").touch()\n    f = pytester.makepyfile(\n        \"\"\"\n        import foo\n        from foo.bar import baz\n        foo.bar.baz\n\n        def test_foo() -> None:\n            pass\n        \"\"\"\n    )\n\n    pytester.syspathinsert()\n    result = pytester.runpython(f)\n    assert result.ret == 0\n\n    result = pytester.runpytest(\"--import-mode=importlib\", \"--doctest-modules\")\n    assert result.ret == 0\n\n\ndef test_import_submodule_not_namespace(pytester: Pytester) -> None:\n    \"\"\"\n    Regression test for importing a submodule 'foo.bar' while there is a 'bar' directory\n    reachable from sys.path -- ensuring the top-level module does not end up imported as a namespace\n    package.\n\n    #12194\n    https://github.com/pytest-dev/pytest/pull/12208#issuecomment-2056458432\n    \"\"\"\n    pytester.syspathinsert()\n    # Create package 'foo' with a submodule 'bar'.\n    pytester.path.joinpath(\"foo\").mkdir()\n    foo_path = pytester.path.joinpath(\"foo/__init__.py\")\n    foo_path.touch()\n    bar_path = pytester.path.joinpath(\"foo/bar.py\")\n    bar_path.touch()\n    # Create top-level directory in `sys.path` with the same name as that submodule.\n    pytester.path.joinpath(\"bar\").mkdir()\n\n    # Import `foo`, then `foo.bar`, and check they were imported from the correct location.\n    foo = import_path(\n        foo_path,\n        mode=ImportMode.importlib,\n        root=pytester.path,\n        consider_namespace_packages=False,\n    )\n    bar = import_path(\n        bar_path,\n        mode=ImportMode.importlib,\n        root=pytester.path,\n        consider_namespace_packages=False,\n    )\n    assert foo.__name__ == \"foo\"\n    assert bar.__name__ == \"foo.bar\"\n    assert foo.__file__ is not None\n    assert bar.__file__ is not None\n    assert Path(foo.__file__) == foo_path\n    assert Path(bar.__file__) == bar_path\n\n\nclass TestNamespacePackages:\n    \"\"\"Test import_path support when importing from properly namespace packages.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_imports_tracking(self, monkeypatch: MonkeyPatch) -> None:\n        monkeypatch.setattr(sys, \"pytest_namespace_packages_test\", [], raising=False)\n\n    def setup_directories(\n        self, tmp_path: Path, monkeypatch: MonkeyPatch | None, pytester: Pytester\n    ) -> tuple[Path, Path]:\n        # Use a code to guard against modules being imported more than once.\n        # This is a safeguard in case future changes break this invariant.\n        code = dedent(\n            \"\"\"\n            import sys\n            imported = getattr(sys, \"pytest_namespace_packages_test\", [])\n            assert __name__ not in imported, f\"{__name__} already imported\"\n            imported.append(__name__)\n            sys.pytest_namespace_packages_test = imported\n            \"\"\"\n        )\n\n        # Set up a namespace package \"com.company\", containing\n        # two subpackages, \"app\" and \"calc\".\n        (tmp_path / \"src/dist1/com/company/app/core\").mkdir(parents=True)\n        (tmp_path / \"src/dist1/com/company/app/__init__.py\").write_text(\n            code, encoding=\"UTF-8\"\n        )\n        (tmp_path / \"src/dist1/com/company/app/core/__init__.py\").write_text(\n            code, encoding=\"UTF-8\"\n        )\n        models_py = tmp_path / \"src/dist1/com/company/app/core/models.py\"\n        models_py.touch()\n\n        (tmp_path / \"src/dist2/com/company/calc/algo\").mkdir(parents=True)\n        (tmp_path / \"src/dist2/com/company/calc/__init__.py\").write_text(\n            code, encoding=\"UTF-8\"\n        )\n        (tmp_path / \"src/dist2/com/company/calc/algo/__init__.py\").write_text(\n            code, encoding=\"UTF-8\"\n        )\n        algorithms_py = tmp_path / \"src/dist2/com/company/calc/algo/algorithms.py\"\n        algorithms_py.write_text(code, encoding=\"UTF-8\")\n\n        r = validate_namespace_package(\n            pytester,\n            [tmp_path / \"src/dist1\", tmp_path / \"src/dist2\"],\n            [\"com.company.app.core.models\", \"com.company.calc.algo.algorithms\"],\n        )\n        assert r.ret == 0\n        if monkeypatch is not None:\n            monkeypatch.syspath_prepend(tmp_path / \"src/dist1\")\n            monkeypatch.syspath_prepend(tmp_path / \"src/dist2\")\n        return models_py, algorithms_py\n\n    @pytest.mark.parametrize(\"import_mode\", [\"prepend\", \"append\", \"importlib\"])\n    def test_resolve_pkg_root_and_module_name_ns_multiple_levels(\n        self,\n        tmp_path: Path,\n        monkeypatch: MonkeyPatch,\n        pytester: Pytester,\n        import_mode: str,\n    ) -> None:\n        models_py, algorithms_py = self.setup_directories(\n            tmp_path, monkeypatch, pytester\n        )\n\n        pkg_root, module_name = resolve_pkg_root_and_module_name(\n            models_py, consider_namespace_packages=True\n        )\n        assert (pkg_root, module_name) == (\n            tmp_path / \"src/dist1\",\n            \"com.company.app.core.models\",\n        )\n\n        mod = import_path(\n            models_py, mode=import_mode, root=tmp_path, consider_namespace_packages=True\n        )\n        assert mod.__name__ == \"com.company.app.core.models\"\n        assert mod.__file__ == str(models_py)\n\n        # Ensure we do not import the same module again (#11475).\n        mod2 = import_path(\n            models_py, mode=import_mode, root=tmp_path, consider_namespace_packages=True\n        )\n        assert mod is mod2\n\n        pkg_root, module_name = resolve_pkg_root_and_module_name(\n            algorithms_py, consider_namespace_packages=True\n        )\n        assert (pkg_root, module_name) == (\n            tmp_path / \"src/dist2\",\n            \"com.company.calc.algo.algorithms\",\n        )\n\n        mod = import_path(\n            algorithms_py,\n            mode=import_mode,\n            root=tmp_path,\n            consider_namespace_packages=True,\n        )\n        assert mod.__name__ == \"com.company.calc.algo.algorithms\"\n        assert mod.__file__ == str(algorithms_py)\n\n        # Ensure we do not import the same module again (#11475).\n        mod2 = import_path(\n            algorithms_py,\n            mode=import_mode,\n            root=tmp_path,\n            consider_namespace_packages=True,\n        )\n        assert mod is mod2\n\n    def test_ns_multiple_levels_import_rewrite_assertions(\n        self,\n        tmp_path: Path,\n        monkeypatch: MonkeyPatch,\n        pytester: Pytester,\n    ) -> None:\n        \"\"\"Check assert rewriting with `--import-mode=importlib` (#12659).\"\"\"\n        self.setup_directories(tmp_path, monkeypatch, pytester)\n        code = dedent(\"\"\"\n        def test():\n            assert \"four lights\" == \"five lights\"\n        \"\"\")\n\n        # A case is in a subdirectory with an `__init__.py` file.\n        test_py = tmp_path / \"src/dist2/com/company/calc/algo/test_demo.py\"\n        test_py.write_text(code, encoding=\"UTF-8\")\n\n        pkg_root, module_name = resolve_pkg_root_and_module_name(\n            test_py, consider_namespace_packages=True\n        )\n        assert (pkg_root, module_name) == (\n            tmp_path / \"src/dist2\",\n            \"com.company.calc.algo.test_demo\",\n        )\n\n        result = pytester.runpytest(\"--import-mode=importlib\", test_py)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"E       AssertionError: assert 'four lights' == 'five lights'\",\n                \"E         *\",\n                \"E         - five lights*\",\n                \"E         + four lights\",\n            ]\n        )\n\n    def test_ns_multiple_levels_import_error(\n        self,\n        tmp_path: Path,\n        pytester: Pytester,\n    ) -> None:\n        # Trigger condition 1: ns and file with the same name\n        file = pytester.path / \"cow/moo/moo.py\"\n        file.parent.mkdir(parents=True)\n        file.write_text(\"data=123\", encoding=\"utf-8\")\n\n        # Trigger condition 2: tests are located in ns\n        tests = pytester.path / \"cow/moo/test_moo.py\"\n\n        tests.write_text(\n            dedent(\n                \"\"\"\n            from cow.moo.moo import data\n\n            def test_moo():\n                print(data)\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        result = pytester.runpytest(\"--import-mode=importlib\")\n        assert result.ret == ExitCode.OK\n\n    @pytest.mark.parametrize(\"import_mode\", [\"prepend\", \"append\", \"importlib\"])\n    def test_incorrect_namespace_package(\n        self,\n        tmp_path: Path,\n        monkeypatch: MonkeyPatch,\n        pytester: Pytester,\n        import_mode: str,\n    ) -> None:\n        models_py, algorithms_py = self.setup_directories(\n            tmp_path, monkeypatch, pytester\n        )\n        # Namespace packages must not have an __init__.py at its top-level\n        # directory; if it does, it is no longer a namespace package, and we fall back\n        # to importing just the part of the package containing the __init__.py files.\n        (tmp_path / \"src/dist1/com/__init__.py\").touch()\n\n        # Because of the __init__ file, 'com' is no longer a namespace package:\n        # 'com.company.app' is importable as a normal module.\n        # 'com.company.calc' is no longer importable because 'com' is not a namespace package anymore.\n        r = validate_namespace_package(\n            pytester,\n            [tmp_path / \"src/dist1\", tmp_path / \"src/dist2\"],\n            [\"com.company.app.core.models\", \"com.company.calc.algo.algorithms\"],\n        )\n        assert r.ret == 1\n        r.stderr.fnmatch_lines(\"*No module named 'com.company.calc*\")\n\n        pkg_root, module_name = resolve_pkg_root_and_module_name(\n            models_py, consider_namespace_packages=True\n        )\n        assert (pkg_root, module_name) == (\n            tmp_path / \"src/dist1\",\n            \"com.company.app.core.models\",\n        )\n\n        # dist2/com/company will contain a normal Python package.\n        pkg_root, module_name = resolve_pkg_root_and_module_name(\n            algorithms_py, consider_namespace_packages=True\n        )\n        assert (pkg_root, module_name) == (\n            tmp_path / \"src/dist2/com/company\",\n            \"calc.algo.algorithms\",\n        )\n\n    def test_detect_meta_path(\n        self,\n        tmp_path: Path,\n        monkeypatch: MonkeyPatch,\n        pytester: Pytester,\n    ) -> None:\n        \"\"\"\n        resolve_pkg_root_and_module_name() considers sys.meta_path when importing namespace packages.\n\n        Regression test for #12112.\n        \"\"\"\n\n        class CustomImporter(importlib.abc.MetaPathFinder):\n            \"\"\"\n            Imports the module name \"com\" as a namespace package.\n\n            This ensures our namespace detection considers sys.meta_path, which is important\n            to support all possible ways a module can be imported (for example editable installs).\n            \"\"\"\n\n            def find_spec(\n                self, name: str, path: Any = None, target: Any = None\n            ) -> importlib.machinery.ModuleSpec | None:\n                if name == \"com\":\n                    spec = importlib.machinery.ModuleSpec(\"com\", loader=None)\n                    spec.submodule_search_locations = [str(com_root_2), str(com_root_1)]\n                    return spec\n                return None\n\n        # Setup directories without configuring sys.path.\n        models_py, _algorithms_py = self.setup_directories(\n            tmp_path, monkeypatch=None, pytester=pytester\n        )\n        com_root_1 = tmp_path / \"src/dist1/com\"\n        com_root_2 = tmp_path / \"src/dist2/com\"\n\n        # Because the namespace package is not setup correctly, we cannot resolve it as a namespace package.\n        pkg_root, module_name = resolve_pkg_root_and_module_name(\n            models_py, consider_namespace_packages=True\n        )\n        assert (pkg_root, module_name) == (\n            tmp_path / \"src/dist1/com/company\",\n            \"app.core.models\",\n        )\n\n        # Insert our custom importer, which will recognize the \"com\" directory as a namespace package.\n        new_meta_path = [CustomImporter(), *sys.meta_path]\n        monkeypatch.setattr(sys, \"meta_path\", new_meta_path)\n\n        # Now we should be able to resolve the path as namespace package.\n        pkg_root, module_name = resolve_pkg_root_and_module_name(\n            models_py, consider_namespace_packages=True\n        )\n        assert (pkg_root, module_name) == (\n            tmp_path / \"src/dist1\",\n            \"com.company.app.core.models\",\n        )\n\n    @pytest.mark.parametrize(\"insert\", [True, False])\n    def test_full_ns_packages_without_init_files(\n        self, pytester: Pytester, tmp_path: Path, monkeypatch: MonkeyPatch, insert: bool\n    ) -> None:\n        (tmp_path / \"src/dist1/ns/b/app/bar/test\").mkdir(parents=True)\n        (tmp_path / \"src/dist1/ns/b/app/bar/m.py\").touch()\n\n        if insert:\n            # The presence of this __init__.py is not a problem, ns.b.app is still part of the namespace package.\n            (tmp_path / \"src/dist1/ns/b/app/__init__.py\").touch()\n\n        (tmp_path / \"src/dist2/ns/a/core/foo/test\").mkdir(parents=True)\n        (tmp_path / \"src/dist2/ns/a/core/foo/m.py\").touch()\n\n        # Validate the namespace package by importing it in a Python subprocess.\n        r = validate_namespace_package(\n            pytester,\n            [tmp_path / \"src/dist1\", tmp_path / \"src/dist2\"],\n            [\"ns.b.app.bar.m\", \"ns.a.core.foo.m\"],\n        )\n        assert r.ret == 0\n        monkeypatch.syspath_prepend(tmp_path / \"src/dist1\")\n        monkeypatch.syspath_prepend(tmp_path / \"src/dist2\")\n\n        assert resolve_pkg_root_and_module_name(\n            tmp_path / \"src/dist1/ns/b/app/bar/m.py\", consider_namespace_packages=True\n        ) == (tmp_path / \"src/dist1\", \"ns.b.app.bar.m\")\n        assert resolve_pkg_root_and_module_name(\n            tmp_path / \"src/dist2/ns/a/core/foo/m.py\", consider_namespace_packages=True\n        ) == (tmp_path / \"src/dist2\", \"ns.a.core.foo.m\")\n\n\ndef test_ns_import_same_name_directory_12592(\n    tmp_path: Path, pytester: Pytester\n) -> None:\n    \"\"\"Regression for `--import-mode=importlib` with directory parent and child with same name (#12592).\"\"\"\n    y_dir = tmp_path / \"x/y/y\"\n    y_dir.mkdir(parents=True)\n    test_y = tmp_path / \"x/y/test_y.py\"\n    test_y.write_text(\"def test(): pass\", encoding=\"UTF-8\")\n\n    result = pytester.runpytest(\"--import-mode=importlib\", test_y)\n    assert result.ret == ExitCode.OK\n\n\ndef test_is_importable(pytester: Pytester) -> None:\n    pytester.syspathinsert()\n\n    path = pytester.path / \"bar/foo.py\"\n    path.parent.mkdir()\n    path.touch()\n    assert is_importable(\"bar.foo\", path) is True\n\n    # Ensure that the module that can be imported points to the path we expect.\n    path = pytester.path / \"some/other/path/bar/foo.py\"\n    path.mkdir(parents=True, exist_ok=True)\n    assert is_importable(\"bar.foo\", path) is False\n\n    # Paths containing \".\" cannot be imported.\n    path = pytester.path / \"bar.x/__init__.py\"\n    path.parent.mkdir()\n    path.touch()\n    assert is_importable(\"bar.x\", path) is False\n\n    # Pass starting with \".\" denote relative imports and cannot be checked using is_importable.\n    path = pytester.path / \".bar.x/__init__.py\"\n    path.parent.mkdir()\n    path.touch()\n    assert is_importable(\".bar.x\", path) is False\n\n\ndef test_compute_module_name(tmp_path: Path) -> None:\n    assert compute_module_name(tmp_path, tmp_path) is None\n    assert compute_module_name(Path(), Path()) is None\n\n    assert compute_module_name(tmp_path, tmp_path / \"mod.py\") == \"mod\"\n    assert compute_module_name(tmp_path, tmp_path / \"src/app/bar\") == \"src.app.bar\"\n    assert compute_module_name(tmp_path, tmp_path / \"src/app/bar.py\") == \"src.app.bar\"\n    assert (\n        compute_module_name(tmp_path, tmp_path / \"src/app/bar/__init__.py\")\n        == \"src.app.bar\"\n    )\n\n\ndef validate_namespace_package(\n    pytester: Pytester, paths: Sequence[Path], modules: Sequence[str]\n) -> RunResult:\n    \"\"\"\n    Validate that a Python namespace package is set up correctly.\n\n    In a sub interpreter, add 'paths' to sys.path and attempt to import the given modules.\n\n    In this module many tests configure a set of files as a namespace package, this function\n    is used as sanity check that our files are configured correctly from the point of view of Python.\n    \"\"\"\n    lines = [\n        \"import sys\",\n        # Configure sys.path.\n        *[f\"sys.path.append(r{str(x)!r})\" for x in paths],\n        # Imports.\n        *[f\"import {x}\" for x in modules],\n    ]\n    return pytester.runpython_c(\"\\n\".join(lines))\n"
  },
  {
    "path": "testing/test_pluginmanager.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport os\nimport shutil\nimport sys\nimport types\n\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.config.exceptions import UsageError\nfrom _pytest.main import Session\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pathlib import import_path\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\n@pytest.fixture\ndef pytestpm() -> PytestPluginManager:\n    return PytestPluginManager()\n\n\nclass TestPytestPluginInteractions:\n    def test_addhooks_conftestplugin(\n        self, pytester: Pytester, _config_for_test: Config\n    ) -> None:\n        pytester.makepyfile(\n            newhooks=\"\"\"\n            def pytest_myhook(xyz):\n                \"new hook\"\n        \"\"\"\n        )\n        conf = pytester.makeconftest(\n            \"\"\"\n            import newhooks\n            def pytest_addhooks(pluginmanager):\n                pluginmanager.add_hookspecs(newhooks)\n            def pytest_myhook(xyz):\n                return xyz + 1\n        \"\"\"\n        )\n        config = _config_for_test\n        pm = config.pluginmanager\n        pm.hook.pytest_addhooks.call_historic(\n            kwargs=dict(pluginmanager=config.pluginmanager)\n        )\n        config.pluginmanager._importconftest(\n            conf,\n            importmode=\"prepend\",\n            rootpath=pytester.path,\n            consider_namespace_packages=False,\n        )\n        # print(config.pluginmanager.get_plugins())\n        res = config.hook.pytest_myhook(xyz=10)\n        assert res == [11]\n\n    def test_addhooks_nohooks(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import sys\n            def pytest_addhooks(pluginmanager):\n                pluginmanager.add_hookspecs(sys)\n        \"\"\"\n        )\n        res = pytester.runpytest()\n        assert res.ret != 0\n        res.stderr.fnmatch_lines([\"*did not find*sys*\"])\n\n    def test_do_option_postinitialize(self, pytester: Pytester) -> None:\n        config = pytester.parseconfigure()\n        assert not hasattr(config.option, \"test123\")\n        p = pytester.makepyfile(\n            \"\"\"\n            def pytest_addoption(parser):\n                parser.addoption('--test123', action=\"store_true\",\n                    default=True)\n        \"\"\"\n        )\n        config.pluginmanager._importconftest(\n            p,\n            importmode=\"prepend\",\n            rootpath=pytester.path,\n            consider_namespace_packages=False,\n        )\n        assert config.option.test123\n\n    def test_configure(self, pytester: Pytester) -> None:\n        config = pytester.parseconfig()\n        values = []\n\n        class A:\n            def pytest_configure(self):\n                values.append(self)\n\n        config.pluginmanager.register(A())\n        assert len(values) == 0\n        config._do_configure()\n        assert len(values) == 1\n        config.pluginmanager.register(A())  # leads to a configured() plugin\n        assert len(values) == 2\n        assert values[0] != values[1]\n\n        config._ensure_unconfigure()\n        config.pluginmanager.register(A())\n        assert len(values) == 2\n\n    @pytest.mark.skipif(\n        not sys.platform.startswith(\"win\"),\n        reason=\"requires a case-insensitive file system\",\n    )\n    def test_conftestpath_case_sensitivity(self, pytester: Pytester) -> None:\n        \"\"\"Unit test for issue #9765.\"\"\"\n        config = pytester.parseconfig()\n        pytester.makepyfile(**{\"tests/conftest.py\": \"\"})\n\n        conftest = pytester.path.joinpath(\"tests/conftest.py\")\n        conftest_upper_case = pytester.path.joinpath(\"TESTS/conftest.py\")\n\n        mod = config.pluginmanager._importconftest(\n            conftest,\n            importmode=\"prepend\",\n            rootpath=pytester.path,\n            consider_namespace_packages=False,\n        )\n        plugin = config.pluginmanager.get_plugin(str(conftest))\n        assert plugin is mod\n\n        mod_uppercase = config.pluginmanager._importconftest(\n            conftest_upper_case,\n            importmode=\"prepend\",\n            rootpath=pytester.path,\n            consider_namespace_packages=False,\n        )\n        plugin_uppercase = config.pluginmanager.get_plugin(str(conftest_upper_case))\n        assert plugin_uppercase is mod_uppercase\n\n        # No str(conftestpath) normalization so conftest should be imported\n        # twice and modules should be different objects\n        assert mod is not mod_uppercase\n\n    def test_hook_tracing(self, _config_for_test: Config) -> None:\n        pytestpm = _config_for_test.pluginmanager  # fully initialized with plugins\n        saveindent = []\n\n        class api1:\n            def pytest_plugin_registered(self):\n                saveindent.append(pytestpm.trace.root.indent)\n\n        class api2:\n            def pytest_plugin_registered(self):\n                saveindent.append(pytestpm.trace.root.indent)\n                raise ValueError()\n\n        values: list[str] = []\n        pytestpm.trace.root.setwriter(values.append)\n        undo = pytestpm.enable_tracing()\n        try:\n            indent = pytestpm.trace.root.indent\n            p = api1()\n            pytestpm.register(p)\n            assert pytestpm.trace.root.indent == indent\n            assert len(values) >= 2\n            assert \"pytest_plugin_registered\" in values[0]\n            assert \"finish\" in values[1]\n\n            values[:] = []\n            with pytest.raises(ValueError):\n                pytestpm.register(api2())\n            assert pytestpm.trace.root.indent == indent\n            assert saveindent[0] > indent\n        finally:\n            undo()\n\n    def test_hook_proxy(self, pytester: Pytester) -> None:\n        \"\"\"Test the gethookproxy function(#2016)\"\"\"\n        config = pytester.parseconfig()\n        session = Session.from_config(config)\n        pytester.makepyfile(**{\"tests/conftest.py\": \"\", \"tests/subdir/conftest.py\": \"\"})\n\n        conftest1 = pytester.path.joinpath(\"tests/conftest.py\")\n        conftest2 = pytester.path.joinpath(\"tests/subdir/conftest.py\")\n\n        config.pluginmanager._importconftest(\n            conftest1,\n            importmode=\"prepend\",\n            rootpath=pytester.path,\n            consider_namespace_packages=False,\n        )\n        ihook_a = session.gethookproxy(pytester.path / \"tests\")\n        assert ihook_a is not None\n        config.pluginmanager._importconftest(\n            conftest2,\n            importmode=\"prepend\",\n            rootpath=pytester.path,\n            consider_namespace_packages=False,\n        )\n        ihook_b = session.gethookproxy(pytester.path / \"tests\")\n        assert ihook_a is not ihook_b\n\n    def test_hook_with_addoption(self, pytester: Pytester) -> None:\n        \"\"\"Test that hooks can be used in a call to pytest_addoption\"\"\"\n        pytester.makepyfile(\n            newhooks=\"\"\"\n            import pytest\n            @pytest.hookspec(firstresult=True)\n            def pytest_default_value():\n                pass\n        \"\"\"\n        )\n        pytester.makepyfile(\n            myplugin=\"\"\"\n            import newhooks\n            def pytest_addhooks(pluginmanager):\n                pluginmanager.add_hookspecs(newhooks)\n            def pytest_addoption(parser, pluginmanager):\n                default_value = pluginmanager.hook.pytest_default_value()\n                parser.addoption(\"--config\", help=\"Config, defaults to %(default)s\", default=default_value)\n        \"\"\"\n        )\n        pytester.makeconftest(\n            \"\"\"\n            pytest_plugins=(\"myplugin\",)\n            def pytest_default_value():\n                return \"default_value\"\n        \"\"\"\n        )\n        res = pytester.runpytest(\"--help\")\n        res.stdout.fnmatch_lines([\"*--config=CONFIG*default_value*\"])\n\n\ndef test_default_markers(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--markers\")\n    result.stdout.fnmatch_lines([\"*tryfirst*first*\", \"*trylast*last*\"])\n\n\ndef test_importplugin_error_message(\n    pytester: Pytester, pytestpm: PytestPluginManager\n) -> None:\n    \"\"\"Don't hide import errors when importing plugins and provide\n    an easy to debug message.\n\n    See #375 and #1998.\n    \"\"\"\n    pytester.syspathinsert(pytester.path)\n    pytester.makepyfile(\n        qwe=\"\"\"\\\n        def test_traceback():\n            raise ImportError('Not possible to import: ☺')\n        test_traceback()\n        \"\"\"\n    )\n    with pytest.raises(ImportError) as excinfo:\n        pytestpm.import_plugin(\"qwe\")\n\n    assert str(excinfo.value).endswith(\n        'Error importing plugin \"qwe\": Not possible to import: ☺'\n    )\n    assert \"in test_traceback\" in str(excinfo.traceback[-1])\n\n\nclass TestPytestPluginManager:\n    def test_register_imported_modules(self) -> None:\n        pm = PytestPluginManager()\n        mod = types.ModuleType(\"x.y.pytest_hello\")\n        pm.register(mod)\n        assert pm.is_registered(mod)\n        values = pm.get_plugins()\n        assert mod in values\n        pytest.raises(ValueError, pm.register, mod)\n        pytest.raises(ValueError, lambda: pm.register(mod))\n        # assert not pm.is_registered(mod2)\n        assert pm.get_plugins() == values\n\n    def test_canonical_import(self, monkeypatch):\n        mod = types.ModuleType(\"pytest_xyz\")\n        monkeypatch.setitem(sys.modules, \"pytest_xyz\", mod)\n        pm = PytestPluginManager()\n        pm.import_plugin(\"pytest_xyz\")\n        assert pm.get_plugin(\"pytest_xyz\") == mod\n        assert pm.is_registered(mod)\n\n    def test_consider_module(\n        self, pytester: Pytester, pytestpm: PytestPluginManager\n    ) -> None:\n        pytester.syspathinsert()\n        pytester.makepyfile(pytest_p1=\"#\")\n        pytester.makepyfile(pytest_p2=\"#\")\n        mod = types.ModuleType(\"temp\")\n        mod.__dict__[\"pytest_plugins\"] = [\"pytest_p1\", \"pytest_p2\"]\n        pytestpm.consider_module(mod)\n        p1 = pytestpm.get_plugin(\"pytest_p1\")\n        assert p1 is not None\n        assert p1.__name__ == \"pytest_p1\"\n        p2 = pytestpm.get_plugin(\"pytest_p2\")\n        assert p2 is not None\n        assert p2.__name__ == \"pytest_p2\"\n\n    def test_consider_module_import_module(\n        self, pytester: Pytester, _config_for_test: Config\n    ) -> None:\n        pytestpm = _config_for_test.pluginmanager\n        mod = types.ModuleType(\"x\")\n        mod.__dict__[\"pytest_plugins\"] = \"pytest_a\"\n        aplugin = pytester.makepyfile(pytest_a=\"#\")\n        reprec = pytester.make_hook_recorder(pytestpm)\n        pytester.syspathinsert(aplugin.parent)\n        pytestpm.consider_module(mod)\n        call = reprec.getcall(pytestpm.hook.pytest_plugin_registered.name)\n        assert call.plugin.__name__ == \"pytest_a\"\n\n        # check that it is not registered twice\n        pytestpm.consider_module(mod)\n        values = reprec.getcalls(\"pytest_plugin_registered\")\n        assert len(values) == 1\n\n    def test_consider_env_fails_to_import(\n        self, monkeypatch: MonkeyPatch, pytestpm: PytestPluginManager\n    ) -> None:\n        monkeypatch.setenv(\"PYTEST_PLUGINS\", \"nonexisting\", prepend=\",\")\n        with pytest.raises(ImportError):\n            pytestpm.consider_env()\n\n    @pytest.mark.filterwarnings(\"always\")\n    def test_plugin_skip(self, pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n        p = pytester.makepyfile(\n            skipping1=\"\"\"\n            import pytest\n            pytest.skip(\"hello\", allow_module_level=True)\n        \"\"\"\n        )\n        shutil.copy(p, p.with_name(\"skipping2.py\"))\n        monkeypatch.setenv(\"PYTEST_PLUGINS\", \"skipping2\")\n        result = pytester.runpytest(\"-p\", \"skipping1\", syspathinsert=True)\n        assert result.ret == ExitCode.NO_TESTS_COLLECTED\n        result.stdout.fnmatch_lines(\n            [\"*skipped plugin*skipping1*hello*\", \"*skipped plugin*skipping2*hello*\"]\n        )\n\n    def test_consider_env_plugin_instantiation(\n        self,\n        pytester: Pytester,\n        monkeypatch: MonkeyPatch,\n        pytestpm: PytestPluginManager,\n    ) -> None:\n        pytester.syspathinsert()\n        pytester.makepyfile(xy123=\"#\")\n        monkeypatch.setitem(os.environ, \"PYTEST_PLUGINS\", \"xy123\")\n        l1 = len(pytestpm.get_plugins())\n        pytestpm.consider_env()\n        l2 = len(pytestpm.get_plugins())\n        assert l2 == l1 + 1\n        assert pytestpm.get_plugin(\"xy123\")\n        pytestpm.consider_env()\n        l3 = len(pytestpm.get_plugins())\n        assert l2 == l3\n\n    def test_pluginmanager_ENV_startup(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        pytester.makepyfile(pytest_x500=\"#\")\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_hello(pytestconfig):\n                plugin = pytestconfig.pluginmanager.get_plugin('pytest_x500')\n                assert plugin is not None\n        \"\"\"\n        )\n        monkeypatch.setenv(\"PYTEST_PLUGINS\", \"pytest_x500\", prepend=\",\")\n        result = pytester.runpytest(p, syspathinsert=True)\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_import_plugin_importname(\n        self, pytester: Pytester, pytestpm: PytestPluginManager\n    ) -> None:\n        pytest.raises(ImportError, pytestpm.import_plugin, \"qweqwex.y\")\n        pytest.raises(ImportError, pytestpm.import_plugin, \"pytest_qweqwx.y\")\n\n        pytester.syspathinsert()\n        pluginname = \"pytest_hello\"\n        pytester.makepyfile(**{pluginname: \"\"})\n        pytestpm.import_plugin(\"pytest_hello\")\n        len1 = len(pytestpm.get_plugins())\n        pytestpm.import_plugin(\"pytest_hello\")\n        len2 = len(pytestpm.get_plugins())\n        assert len1 == len2\n        plugin1 = pytestpm.get_plugin(\"pytest_hello\")\n        assert plugin1 is not None\n        assert plugin1.__name__.endswith(\"pytest_hello\")\n        plugin2 = pytestpm.get_plugin(\"pytest_hello\")\n        assert plugin2 is plugin1\n\n    def test_import_plugin_dotted_name(\n        self, pytester: Pytester, pytestpm: PytestPluginManager\n    ) -> None:\n        pytest.raises(ImportError, pytestpm.import_plugin, \"qweqwex.y\")\n        pytest.raises(ImportError, pytestpm.import_plugin, \"pytest_qweqwex.y\")\n\n        pytester.syspathinsert()\n        pytester.mkpydir(\"pkg\").joinpath(\"plug.py\").write_text(\"x=3\", encoding=\"utf-8\")\n        pluginname = \"pkg.plug\"\n        pytestpm.import_plugin(pluginname)\n        mod = pytestpm.get_plugin(\"pkg.plug\")\n        assert mod is not None\n        assert mod.x == 3\n\n    def test_consider_conftest_deps(\n        self,\n        pytester: Pytester,\n        pytestpm: PytestPluginManager,\n    ) -> None:\n        mod = import_path(\n            pytester.makepyfile(\"pytest_plugins='xyz'\"),\n            root=pytester.path,\n            consider_namespace_packages=False,\n        )\n        with pytest.raises(ImportError):\n            pytestpm.consider_conftest(mod, registration_name=\"unused\")\n\n\nclass TestPytestPluginManagerBootstrapping:\n    def test_preparse_args(self, pytestpm: PytestPluginManager) -> None:\n        pytest.raises(\n            ImportError, lambda: pytestpm.consider_preparse([\"xyz\", \"-p\", \"hello123\"])\n        )\n\n        # Handles -p without space (#3532).\n        with pytest.raises(ImportError) as excinfo:\n            pytestpm.consider_preparse([\"-phello123\"])\n        assert '\"hello123\"' in excinfo.value.args[0]\n        pytestpm.consider_preparse([\"-pno:hello123\"])\n\n        # Handles -p without following arg (when used without argparse).\n        pytestpm.consider_preparse([\"-p\"])\n\n        with pytest.raises(UsageError, match=r\"^plugin main cannot be disabled$\"):\n            pytestpm.consider_preparse([\"-p\", \"no:main\"])\n\n    def test_plugin_prevent_register(self, pytestpm: PytestPluginManager) -> None:\n        pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\"])\n        l1 = pytestpm.get_plugins()\n        pytestpm.register(42, name=\"abc\")\n        l2 = pytestpm.get_plugins()\n        assert len(l2) == len(l1)\n        assert 42 not in l2\n\n    def test_plugin_prevent_register_unregistered_already_registered(\n        self, pytestpm: PytestPluginManager\n    ) -> None:\n        pytestpm.register(42, name=\"abc\")\n        l1 = pytestpm.get_plugins()\n        assert 42 in l1\n        pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\"])\n        l2 = pytestpm.get_plugins()\n        assert 42 not in l2\n\n    def test_plugin_prevent_register_stepwise_on_cacheprovider_unregister(\n        self, pytestpm: PytestPluginManager\n    ) -> None:\n        \"\"\"From PR #4304: The only way to unregister a module is documented at\n        the end of https://docs.pytest.org/en/stable/how-to/plugins.html.\n\n        When unregister cacheprovider, then unregister stepwise too.\n        \"\"\"\n        pytestpm.register(42, name=\"cacheprovider\")\n        pytestpm.register(43, name=\"stepwise\")\n        l1 = pytestpm.get_plugins()\n        assert 42 in l1\n        assert 43 in l1\n        pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:cacheprovider\"])\n        l2 = pytestpm.get_plugins()\n        assert 42 not in l2\n        assert 43 not in l2\n\n    def test_blocked_plugin_can_be_used(self, pytestpm: PytestPluginManager) -> None:\n        pytestpm.consider_preparse([\"xyz\", \"-p\", \"no:abc\", \"-p\", \"abc\"])\n\n        assert pytestpm.has_plugin(\"abc\")\n        assert not pytestpm.is_blocked(\"abc\")\n        assert not pytestpm.is_blocked(\"pytest_abc\")\n"
  },
  {
    "path": "testing/test_pytester.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport os\nimport subprocess\nimport sys\nfrom types import ModuleType\n\nfrom _pytest.config import ExitCode\nfrom _pytest.config import PytestPluginManager\nfrom _pytest.monkeypatch import MonkeyPatch\nimport _pytest.pytester as pytester_mod\nfrom _pytest.pytester import HookRecorder\nfrom _pytest.pytester import LineMatcher\nfrom _pytest.pytester import Pytester\nfrom _pytest.pytester import SysModulesSnapshot\nfrom _pytest.pytester import SysPathsSnapshot\nimport _pytest.timing\nimport pytest\n\n\ndef test_make_hook_recorder(pytester: Pytester) -> None:\n    item = pytester.getitem(\"def test_func(): pass\")\n    recorder = pytester.make_hook_recorder(item.config.pluginmanager)\n    assert not recorder.getfailures()\n\n    # (The silly condition is to fool mypy that the code below this is reachable)\n    if 1 + 1 == 2:\n        pytest.xfail(\"internal reportrecorder tests need refactoring\")\n\n    class rep:\n        excinfo = None\n        passed = False\n        failed = True\n        skipped = False\n        when = \"call\"\n\n    recorder.hook.pytest_runtest_logreport(report=rep)  # type: ignore[attr-defined]\n    failures = recorder.getfailures()\n    assert failures == [rep]  # type: ignore[comparison-overlap]\n    failures = recorder.getfailures()\n    assert failures == [rep]  # type: ignore[comparison-overlap]\n\n    class rep2:\n        excinfo = None\n        passed = False\n        failed = False\n        skipped = True\n        when = \"call\"\n\n    rep2.passed = False\n    rep2.skipped = True\n    recorder.hook.pytest_runtest_logreport(report=rep2)  # type: ignore[attr-defined]\n\n    modcol = pytester.getmodulecol(\"\")\n    rep3 = modcol.config.hook.pytest_make_collect_report(collector=modcol)\n    rep3.passed = False\n    rep3.failed = True\n    rep3.skipped = False\n    recorder.hook.pytest_collectreport(report=rep3)  # type: ignore[attr-defined]\n\n    passed, skipped, failed = recorder.listoutcomes()\n    assert not passed and skipped and failed\n\n    numpassed, numskipped, numfailed = recorder.countoutcomes()\n    assert numpassed == 0\n    assert numskipped == 1\n    assert numfailed == 1\n    assert len(recorder.getfailedcollections()) == 1\n\n    recorder.unregister()  # type: ignore[attr-defined]\n    recorder.clear()\n    recorder.hook.pytest_runtest_logreport(report=rep3)  # type: ignore[attr-defined]\n    pytest.raises(ValueError, recorder.getfailures)\n\n\ndef test_parseconfig(pytester: Pytester) -> None:\n    config1 = pytester.parseconfig()\n    config2 = pytester.parseconfig()\n    assert config2 is not config1\n\n\ndef test_pytester_runs_with_plugin(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        pytest_plugins = \"pytester\"\n        def test_hello(pytester):\n            assert 1\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=1)\n\n\ndef test_pytester_with_doctest(pytester: Pytester) -> None:\n    \"\"\"Check that pytester can be used within doctests.\n\n    It used to use `request.function`, which is `None` with doctests.\"\"\"\n    pytester.makepyfile(\n        **{\n            \"sub/t-doctest.py\": \"\"\"\n        '''\n        >>> import os\n        >>> pytester = getfixture(\"pytester\")\n        >>> str(pytester.makepyfile(\"content\")).replace(os.sep, '/')\n        '.../basetemp/sub.t-doctest0/sub.py'\n        '''\n    \"\"\",\n            \"sub/__init__.py\": \"\",\n        }\n    )\n    result = pytester.runpytest(\n        \"-p\", \"pytester\", \"--doctest-modules\", \"sub/t-doctest.py\"\n    )\n    assert result.ret == 0\n\n\ndef test_runresult_assertion_on_xfail(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        pytest_plugins = \"pytester\"\n\n        @pytest.mark.xfail\n        def test_potato():\n            assert False\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(xfailed=1)\n    assert result.ret == 0\n\n\ndef test_runresult_assertion_on_xpassed(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        pytest_plugins = \"pytester\"\n\n        @pytest.mark.xfail\n        def test_potato():\n            assert True\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(xpassed=1)\n    assert result.ret == 0\n\n\ndef test_xpassed_with_strict_is_considered_a_failure(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        pytest_plugins = \"pytester\"\n\n        @pytest.mark.xfail(strict=True)\n        def test_potato():\n            assert True\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(failed=1)\n    assert result.ret != 0\n\n\ndef make_holder():\n    class apiclass:\n        def pytest_xyz(self, arg):\n            \"\"\"X\"\"\"\n\n        def pytest_xyz_noarg(self):\n            \"\"\"X\"\"\"\n\n    apimod = type(os)(\"api\")\n\n    def pytest_xyz(arg):\n        \"\"\"X\"\"\"\n\n    def pytest_xyz_noarg():\n        \"\"\"X\"\"\"\n\n    apimod.pytest_xyz = pytest_xyz  # type: ignore\n    apimod.pytest_xyz_noarg = pytest_xyz_noarg  # type: ignore\n    return apiclass, apimod\n\n\n@pytest.mark.parametrize(\"holder\", make_holder())\ndef test_hookrecorder_basic(holder) -> None:\n    pm = PytestPluginManager()\n    pm.add_hookspecs(holder)\n    rec = HookRecorder(pm, _ispytest=True)\n    pm.hook.pytest_xyz(arg=123)\n    call = rec.popcall(\"pytest_xyz\")\n    assert call.arg == 123\n    assert call._name == \"pytest_xyz\"\n    pytest.raises(pytest.fail.Exception, rec.popcall, \"abc\")\n    pm.hook.pytest_xyz_noarg()\n    call = rec.popcall(\"pytest_xyz_noarg\")\n    assert call._name == \"pytest_xyz_noarg\"\n\n\ndef test_makepyfile_unicode(pytester: Pytester) -> None:\n    pytester.makepyfile(chr(0xFFFD))\n\n\ndef test_makepyfile_utf8(pytester: Pytester) -> None:\n    \"\"\"Ensure makepyfile accepts utf-8 bytes as input (#2738)\"\"\"\n    utf8_contents = \"\"\"\n        def setup_function(function):\n            mixed_encoding = 'São Paulo'\n    \"\"\".encode()\n    p = pytester.makepyfile(utf8_contents)\n    assert \"mixed_encoding = 'São Paulo'\".encode() in p.read_bytes()\n\n\nclass TestInlineRunModulesCleanup:\n    def test_inline_run_test_module_not_cleaned_up(self, pytester: Pytester) -> None:\n        test_mod = pytester.makepyfile(\"def test_foo(): assert True\")\n        result = pytester.inline_run(str(test_mod))\n        assert result.ret == ExitCode.OK\n        # rewrite module, now test should fail if module was re-imported\n        test_mod.write_text(\"def test_foo(): assert False\", encoding=\"utf-8\")\n        result2 = pytester.inline_run(str(test_mod))\n        assert result2.ret == ExitCode.TESTS_FAILED\n\n    def spy_factory(self):\n        class SysModulesSnapshotSpy:\n            instances: list[SysModulesSnapshotSpy] = []\n\n            def __init__(self, preserve=None) -> None:\n                SysModulesSnapshotSpy.instances.append(self)\n                self._spy_restore_count = 0\n                self._spy_preserve = preserve\n                self.__snapshot = SysModulesSnapshot(preserve=preserve)\n\n            def restore(self):\n                self._spy_restore_count += 1\n                return self.__snapshot.restore()\n\n        return SysModulesSnapshotSpy\n\n    def test_inline_run_taking_and_restoring_a_sys_modules_snapshot(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        spy_factory = self.spy_factory()\n        monkeypatch.setattr(pytester_mod, \"SysModulesSnapshot\", spy_factory)\n        pytester.syspathinsert()\n        original = dict(sys.modules)\n        pytester.makepyfile(import1=\"# you son of a silly person\")\n        pytester.makepyfile(import2=\"# my hovercraft is full of eels\")\n        test_mod = pytester.makepyfile(\n            \"\"\"\n            import import1\n            def test_foo(): import import2\"\"\"\n        )\n        pytester.inline_run(str(test_mod))\n        assert len(spy_factory.instances) == 1\n        spy = spy_factory.instances[0]\n        assert spy._spy_restore_count == 1\n        assert sys.modules == original\n        assert all(sys.modules[x] is original[x] for x in sys.modules)\n\n    def test_inline_run_sys_modules_snapshot_restore_preserving_modules(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        spy_factory = self.spy_factory()\n        monkeypatch.setattr(pytester_mod, \"SysModulesSnapshot\", spy_factory)\n        test_mod = pytester.makepyfile(\"def test_foo(): pass\")\n        pytester.inline_run(str(test_mod))\n        spy = spy_factory.instances[0]\n        assert not spy._spy_preserve(\"black_knight\")\n        assert spy._spy_preserve(\"zope\")\n        assert spy._spy_preserve(\"zope.interface\")\n        assert spy._spy_preserve(\"zopelicious\")\n\n    def test_external_test_module_imports_not_cleaned_up(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.syspathinsert()\n        pytester.makepyfile(imported=\"data = 'you son of a silly person'\")\n        import imported\n\n        test_mod = pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                import imported\n                imported.data = 42\"\"\"\n        )\n        pytester.inline_run(str(test_mod))\n        assert imported.data == 42\n\n\ndef test_assert_outcomes_after_pytest_error(pytester: Pytester) -> None:\n    pytester.makepyfile(\"def test_foo(): assert True\")\n\n    result = pytester.runpytest(\"--unexpected-argument\")\n    with pytest.raises(ValueError, match=\"Pytest terminal summary report not found\"):\n        result.assert_outcomes(passed=0)\n\n\nclass TestSysModulesSnapshot:\n    key = \"my-test-module\"\n\n    def test_remove_added(self) -> None:\n        original = dict(sys.modules)\n        assert self.key not in sys.modules\n        snapshot = SysModulesSnapshot()\n        sys.modules[self.key] = ModuleType(\"something\")\n        assert self.key in sys.modules\n        snapshot.restore()\n        assert sys.modules == original\n\n    def test_add_removed(self, monkeypatch: MonkeyPatch) -> None:\n        assert self.key not in sys.modules\n        monkeypatch.setitem(sys.modules, self.key, ModuleType(\"something\"))\n        assert self.key in sys.modules\n        original = dict(sys.modules)\n        snapshot = SysModulesSnapshot()\n        del sys.modules[self.key]\n        assert self.key not in sys.modules\n        snapshot.restore()\n        assert sys.modules == original\n\n    def test_restore_reloaded(self, monkeypatch: MonkeyPatch) -> None:\n        assert self.key not in sys.modules\n        monkeypatch.setitem(sys.modules, self.key, ModuleType(\"something\"))\n        assert self.key in sys.modules\n        original = dict(sys.modules)\n        snapshot = SysModulesSnapshot()\n        sys.modules[self.key] = ModuleType(\"something else\")\n        snapshot.restore()\n        assert sys.modules == original\n\n    def test_preserve_modules(self, monkeypatch: MonkeyPatch) -> None:\n        key = [self.key + str(i) for i in range(3)]\n        assert not any(k in sys.modules for k in key)\n        for i, k in enumerate(key):\n            mod = ModuleType(\"something\" + str(i))\n            monkeypatch.setitem(sys.modules, k, mod)\n        original = dict(sys.modules)\n\n        def preserve(name):\n            return name in (key[0], key[1], \"some-other-key\")\n\n        snapshot = SysModulesSnapshot(preserve=preserve)\n        sys.modules[key[0]] = original[key[0]] = ModuleType(\"something else0\")\n        sys.modules[key[1]] = original[key[1]] = ModuleType(\"something else1\")\n        sys.modules[key[2]] = ModuleType(\"something else2\")\n        snapshot.restore()\n        assert sys.modules == original\n\n    def test_preserve_container(self, monkeypatch: MonkeyPatch) -> None:\n        original = dict(sys.modules)\n        assert self.key not in original\n        replacement = dict(sys.modules)\n        replacement[self.key] = ModuleType(\"life of brian\")\n        snapshot = SysModulesSnapshot()\n        monkeypatch.setattr(sys, \"modules\", replacement)\n        snapshot.restore()\n        assert sys.modules is replacement\n        assert sys.modules == original\n\n\n@pytest.mark.parametrize(\"path_type\", (\"path\", \"meta_path\"))\nclass TestSysPathsSnapshot:\n    other_path = {\"path\": \"meta_path\", \"meta_path\": \"path\"}\n\n    @staticmethod\n    def path(n: int) -> str:\n        return \"my-dirty-little-secret-\" + str(n)\n\n    def test_restore(self, monkeypatch: MonkeyPatch, path_type) -> None:\n        other_path_type = self.other_path[path_type]\n        for i in range(10):\n            assert self.path(i) not in getattr(sys, path_type)\n        sys_path = [self.path(i) for i in range(6)]\n        monkeypatch.setattr(sys, path_type, sys_path)\n        original = list(sys_path)\n        original_other = list(getattr(sys, other_path_type))\n        snapshot = SysPathsSnapshot()\n        transformation = {\"source\": (0, 1, 2, 3, 4, 5), \"target\": (6, 2, 9, 7, 5, 8)}\n        assert sys_path == [self.path(x) for x in transformation[\"source\"]]\n        sys_path[1] = self.path(6)\n        sys_path[3] = self.path(7)\n        sys_path.append(self.path(8))\n        del sys_path[4]\n        sys_path[3:3] = [self.path(9)]\n        del sys_path[0]\n        assert sys_path == [self.path(x) for x in transformation[\"target\"]]\n        snapshot.restore()\n        assert getattr(sys, path_type) is sys_path\n        assert getattr(sys, path_type) == original\n        assert getattr(sys, other_path_type) == original_other\n\n    def test_preserve_container(self, monkeypatch: MonkeyPatch, path_type) -> None:\n        other_path_type = self.other_path[path_type]\n        original_data = list(getattr(sys, path_type))\n        original_other = getattr(sys, other_path_type)\n        original_other_data = list(original_other)\n        new: list[object] = []\n        snapshot = SysPathsSnapshot()\n        monkeypatch.setattr(sys, path_type, new)\n        snapshot.restore()\n        assert getattr(sys, path_type) is new\n        assert getattr(sys, path_type) == original_data\n        assert getattr(sys, other_path_type) is original_other\n        assert getattr(sys, other_path_type) == original_other_data\n\n\ndef test_pytester_subprocess(pytester: Pytester) -> None:\n    testfile = pytester.makepyfile(\"def test_one(): pass\")\n    assert pytester.runpytest_subprocess(testfile).ret == 0\n\n\ndef test_pytester_subprocess_via_runpytest_arg(pytester: Pytester) -> None:\n    testfile = pytester.makepyfile(\n        \"\"\"\n        def test_pytester_subprocess(pytester):\n            import os\n            testfile = pytester.makepyfile(\n                \\\"\"\"\n                import os\n                def test_one():\n                    assert {} != os.getpid()\n                \\\"\"\".format(os.getpid())\n            )\n            assert pytester.runpytest(testfile).ret == 0\n        \"\"\"\n    )\n    result = pytester.runpytest_inprocess(\n        \"-p\", \"pytester\", \"--runpytest\", \"subprocess\", testfile\n    )\n    assert result.ret == 0\n\n\ndef test_unicode_args(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"-k\", \"אבג\")\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_pytester_run_no_timeout(pytester: Pytester) -> None:\n    testfile = pytester.makepyfile(\"def test_no_timeout(): pass\")\n    assert pytester.runpytest_subprocess(testfile).ret == ExitCode.OK\n\n\ndef test_pytester_run_with_timeout(pytester: Pytester) -> None:\n    testfile = pytester.makepyfile(\"def test_no_timeout(): pass\")\n\n    timeout = 120\n\n    instant = _pytest.timing.Instant()\n    result = pytester.runpytest_subprocess(testfile, timeout=timeout)\n    duration = instant.elapsed()\n\n    assert result.ret == ExitCode.OK\n    assert duration.seconds < timeout\n\n\ndef test_pytester_run_timeout_expires(pytester: Pytester) -> None:\n    testfile = pytester.makepyfile(\n        \"\"\"\n        import time\n\n        def test_timeout():\n            time.sleep(10)\"\"\"\n    )\n    with pytest.raises(pytester.TimeoutExpired):\n        pytester.runpytest_subprocess(testfile, timeout=1)\n\n\ndef test_linematcher_with_nonlist() -> None:\n    \"\"\"Test LineMatcher with regard to passing in a set (accidentally).\"\"\"\n    from _pytest._code.source import Source\n\n    lm = LineMatcher([])\n    with pytest.raises(TypeError, match=\"invalid type for lines2: set\"):\n        lm.fnmatch_lines(set())  # type: ignore[arg-type]\n    with pytest.raises(TypeError, match=\"invalid type for lines2: dict\"):\n        lm.fnmatch_lines({})  # type: ignore[arg-type]\n    with pytest.raises(TypeError, match=\"invalid type for lines2: set\"):\n        lm.re_match_lines(set())  # type: ignore[arg-type]\n    with pytest.raises(TypeError, match=\"invalid type for lines2: dict\"):\n        lm.re_match_lines({})  # type: ignore[arg-type]\n    with pytest.raises(TypeError, match=\"invalid type for lines2: Source\"):\n        lm.fnmatch_lines(Source())  # type: ignore[arg-type]\n    lm.fnmatch_lines([])\n    lm.fnmatch_lines(())\n    lm.fnmatch_lines(\"\")\n    assert lm._getlines({}) == {}  # type: ignore[arg-type,comparison-overlap]\n    assert lm._getlines(set()) == set()  # type: ignore[arg-type,comparison-overlap]\n    assert lm._getlines(Source()) == []\n    assert lm._getlines(Source(\"pass\\npass\")) == [\"pass\", \"pass\"]\n\n\ndef test_linematcher_match_failure() -> None:\n    lm = LineMatcher([\"foo\", \"foo\", \"bar\"])\n    with pytest.raises(pytest.fail.Exception) as e:\n        lm.fnmatch_lines([\"foo\", \"f*\", \"baz\"])\n    assert e.value.msg is not None\n    assert e.value.msg.splitlines() == [\n        \"exact match: 'foo'\",\n        \"fnmatch: 'f*'\",\n        \"   with: 'foo'\",\n        \"nomatch: 'baz'\",\n        \"    and: 'bar'\",\n        \"remains unmatched: 'baz'\",\n    ]\n\n    lm = LineMatcher([\"foo\", \"foo\", \"bar\"])\n    with pytest.raises(pytest.fail.Exception) as e:\n        lm.re_match_lines([\"foo\", \"^f.*\", \"baz\"])\n    assert e.value.msg is not None\n    assert e.value.msg.splitlines() == [\n        \"exact match: 'foo'\",\n        \"re.match: '^f.*'\",\n        \"    with: 'foo'\",\n        \" nomatch: 'baz'\",\n        \"     and: 'bar'\",\n        \"remains unmatched: 'baz'\",\n    ]\n\n\ndef test_linematcher_consecutive() -> None:\n    lm = LineMatcher([\"1\", \"\", \"2\"])\n    with pytest.raises(pytest.fail.Exception) as excinfo:\n        lm.fnmatch_lines([\"1\", \"2\"], consecutive=True)\n    assert str(excinfo.value).splitlines() == [\n        \"exact match: '1'\",\n        \"no consecutive match: '2'\",\n        \"   with: ''\",\n    ]\n\n    lm.re_match_lines([\"1\", r\"\\d?\", \"2\"], consecutive=True)\n    with pytest.raises(pytest.fail.Exception) as excinfo:\n        lm.re_match_lines([\"1\", r\"\\d\", \"2\"], consecutive=True)\n    assert str(excinfo.value).splitlines() == [\n        \"exact match: '1'\",\n        r\"no consecutive match: '\\\\d'\",\n        \"    with: ''\",\n    ]\n\n\n@pytest.mark.parametrize(\"function\", [\"no_fnmatch_line\", \"no_re_match_line\"])\ndef test_linematcher_no_matching(function: str) -> None:\n    if function == \"no_fnmatch_line\":\n        good_pattern = \"*.py OK*\"\n        bad_pattern = \"*X.py OK*\"\n    else:\n        assert function == \"no_re_match_line\"\n        good_pattern = r\".*py OK\"\n        bad_pattern = r\".*Xpy OK\"\n\n    lm = LineMatcher(\n        [\n            \"cachedir: .pytest_cache\",\n            \"collecting ... collected 1 item\",\n            \"\",\n            \"show_fixtures_per_test.py OK\",\n            \"=== elapsed 1s ===\",\n        ]\n    )\n\n    # check the function twice to ensure we don't accumulate the internal buffer\n    for i in range(2):\n        with pytest.raises(pytest.fail.Exception) as e:\n            func = getattr(lm, function)\n            func(good_pattern)\n        obtained = str(e.value).splitlines()\n        if function == \"no_fnmatch_line\":\n            assert obtained == [\n                f\"nomatch: '{good_pattern}'\",\n                \"    and: 'cachedir: .pytest_cache'\",\n                \"    and: 'collecting ... collected 1 item'\",\n                \"    and: ''\",\n                f\"fnmatch: '{good_pattern}'\",\n                \"   with: 'show_fixtures_per_test.py OK'\",\n            ]\n        else:\n            assert obtained == [\n                f\" nomatch: '{good_pattern}'\",\n                \"     and: 'cachedir: .pytest_cache'\",\n                \"     and: 'collecting ... collected 1 item'\",\n                \"     and: ''\",\n                f\"re.match: '{good_pattern}'\",\n                \"    with: 'show_fixtures_per_test.py OK'\",\n            ]\n\n    func = getattr(lm, function)\n    func(bad_pattern)  # bad pattern does not match any line: passes\n\n\ndef test_linematcher_no_matching_after_match() -> None:\n    lm = LineMatcher([\"1\", \"2\", \"3\"])\n    lm.fnmatch_lines([\"1\", \"3\"])\n    with pytest.raises(pytest.fail.Exception) as e:\n        lm.no_fnmatch_line(\"*\")\n    assert str(e.value).splitlines() == [\"fnmatch: '*'\", \"   with: '1'\"]\n\n\ndef test_linematcher_string_api() -> None:\n    lm = LineMatcher([\"foo\", \"bar\"])\n    assert str(lm) == \"foo\\nbar\"\n\n\ndef test_pytest_addopts_before_pytester(request, monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setenv(\"PYTEST_ADDOPTS\", \"--orig-unused\")\n    _: Pytester = request.getfixturevalue(\"pytester\")\n    assert \"PYTEST_ADDOPTS\" not in os.environ\n\n\ndef test_run_stdin(pytester: Pytester) -> None:\n    with pytest.raises(pytester.TimeoutExpired):\n        pytester.run(\n            sys.executable,\n            \"-c\",\n            \"import sys, time; time.sleep(1); print(sys.stdin.read())\",\n            stdin=subprocess.PIPE,\n            timeout=0.1,\n        )\n\n    with pytest.raises(pytester.TimeoutExpired):\n        result = pytester.run(\n            sys.executable,\n            \"-c\",\n            \"import sys, time; time.sleep(1); print(sys.stdin.read())\",\n            stdin=b\"input\\n2ndline\",\n            timeout=0.1,\n        )\n\n    result = pytester.run(\n        sys.executable,\n        \"-c\",\n        \"import sys; print(sys.stdin.read())\",\n        stdin=b\"input\\n2ndline\",\n    )\n    assert result.stdout.lines == [\"input\", \"2ndline\"]\n    assert result.stderr.str() == \"\"\n    assert result.ret == 0\n\n\ndef test_popen_stdin_pipe(pytester: Pytester) -> None:\n    proc = pytester.popen(\n        [sys.executable, \"-c\", \"import sys; print(sys.stdin.read())\"],\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n        stdin=subprocess.PIPE,\n    )\n    stdin = b\"input\\n2ndline\"\n    stdout, stderr = proc.communicate(input=stdin)\n    assert stdout.decode(\"utf8\").splitlines() == [\"input\", \"2ndline\"]\n    assert stderr == b\"\"\n    assert proc.returncode == 0\n\n\ndef test_popen_stdin_bytes(pytester: Pytester) -> None:\n    proc = pytester.popen(\n        [sys.executable, \"-c\", \"import sys; print(sys.stdin.read())\"],\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n        stdin=b\"input\\n2ndline\",\n    )\n    stdout, stderr = proc.communicate()\n    assert stdout.decode(\"utf8\").splitlines() == [\"input\", \"2ndline\"]\n    assert stderr == b\"\"\n    assert proc.returncode == 0\n\n\ndef test_popen_default_stdin_stderr_and_stdin_None(pytester: Pytester) -> None:\n    # stdout, stderr default to pipes,\n    # stdin can be None to not close the pipe, avoiding\n    # \"ValueError: flush of closed file\" with `communicate()`.\n    #\n    # Wraps the test to make it not hang when run with \"-s\".\n    p1 = pytester.makepyfile(\n        '''\n        import sys\n\n        def test_inner(pytester):\n            p1 = pytester.makepyfile(\n                \"\"\"\n                import sys\n                print(sys.stdin.read())  # empty\n                print('stdout')\n                sys.stderr.write('stderr')\n                \"\"\"\n            )\n            proc = pytester.popen([sys.executable, str(p1)], stdin=None)\n            stdout, stderr = proc.communicate(b\"ignored\")\n            assert stdout.splitlines() == [b\"\", b\"stdout\"]\n            assert stderr.splitlines() == [b\"stderr\"]\n            assert proc.returncode == 0\n        '''\n    )\n    result = pytester.runpytest(\"-p\", \"pytester\", str(p1))\n    assert result.ret == 0\n\n\ndef test_spawn_uses_tmphome(pytester: Pytester) -> None:\n    tmphome = str(pytester.path)\n    assert os.environ.get(\"HOME\") == tmphome\n\n    pytester._monkeypatch.setenv(\"CUSTOMENV\", \"42\")\n\n    p1 = pytester.makepyfile(\n        f\"\"\"\n        import os\n\n        def test():\n            assert os.environ[\"HOME\"] == {tmphome!r}\n            assert os.environ[\"CUSTOMENV\"] == \"42\"\n        \"\"\"\n    )\n    child = pytester.spawn_pytest(str(p1))\n    out = child.read()\n    assert child.wait() == 0, out.decode(\"utf8\")\n\n\ndef test_run_result_repr() -> None:\n    outlines = [\"some\", \"normal\", \"output\"]\n    errlines = [\"some\", \"nasty\", \"errors\", \"happened\"]\n\n    # known exit code\n    r = pytester_mod.RunResult(1, outlines, errlines, duration=0.5)\n    assert repr(r) == (\n        f\"<RunResult ret={pytest.ExitCode.TESTS_FAILED!s} len(stdout.lines)=3\"\n        \" len(stderr.lines)=4 duration=0.50s>\"\n    )\n\n    # unknown exit code: just the number\n    r = pytester_mod.RunResult(99, outlines, errlines, duration=0.5)\n    assert (\n        repr(r) == \"<RunResult ret=99 len(stdout.lines)=3\"\n        \" len(stderr.lines)=4 duration=0.50s>\"\n    )\n\n\ndef test_pytester_outcomes_with_multiple_errors(pytester: Pytester) -> None:\n    p1 = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def bad_fixture():\n            raise Exception(\"bad\")\n\n        def test_error1(bad_fixture):\n            pass\n\n        def test_error2(bad_fixture):\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest(str(p1))\n    result.assert_outcomes(errors=2)\n\n    assert result.parseoutcomes() == {\"errors\": 2}\n\n\ndef test_parse_summary_line_always_plural() -> None:\n    \"\"\"Parsing summaries always returns plural nouns (#6505)\"\"\"\n    lines = [\n        \"some output 1\",\n        \"some output 2\",\n        \"======= 1 failed, 1 passed, 1 warning, 1 error in 0.13s ====\",\n        \"done.\",\n    ]\n    assert pytester_mod.RunResult.parse_summary_nouns(lines) == {\n        \"errors\": 1,\n        \"failed\": 1,\n        \"passed\": 1,\n        \"warnings\": 1,\n    }\n\n    lines = [\n        \"some output 1\",\n        \"some output 2\",\n        \"======= 1 failed, 1 passed, 2 warnings, 2 errors in 0.13s ====\",\n        \"done.\",\n    ]\n    assert pytester_mod.RunResult.parse_summary_nouns(lines) == {\n        \"errors\": 2,\n        \"failed\": 1,\n        \"passed\": 1,\n        \"warnings\": 2,\n    }\n\n\ndef test_makefile_joins_absolute_path(pytester: Pytester) -> None:\n    absfile = pytester.path / \"absfile\"\n    p1 = pytester.makepyfile(**{str(absfile): \"\"})\n    assert str(p1) == str(pytester.path / \"absfile.py\")\n\n\ndef test_pytester_makefile_dot_prefixes_extension_with_warning(\n    pytester: Pytester,\n) -> None:\n    with pytest.raises(\n        ValueError,\n        match=r\"pytester\\.makefile expects a file extension, try \\.foo\\.bar instead of foo\\.bar\",\n    ):\n        pytester.makefile(\"foo.bar\", \"\")\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_pytester_assert_outcomes_warnings(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import warnings\n\n        def test_with_warning():\n            warnings.warn(UserWarning(\"some custom warning\"))\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(passed=1, warnings=1)\n    # If warnings is not passed, it is not checked at all.\n    result.assert_outcomes(passed=1)\n\n\ndef test_pytester_outcomes_deselected(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_one():\n            pass\n\n        def test_two():\n            pass\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-k\", \"test_one\")\n    result.assert_outcomes(passed=1, deselected=1)\n    # If deselected is not passed, it is not checked at all.\n    result.assert_outcomes(passed=1)\n\n\ndef test_pytester_subprocess_with_string_plugins(pytester: Pytester) -> None:\n    \"\"\"Test that pytester.runpytest_subprocess is OK with named (string)\n    `.plugins`.\"\"\"\n    pytester.plugins = [\"pytester\"]\n\n    result = pytester.runpytest_subprocess()\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_pytester_subprocess_with_non_string_plugins(pytester: Pytester) -> None:\n    \"\"\"Test that pytester.runpytest_subprocess fails with a proper error given\n    non-string `.plugins`.\"\"\"\n\n    class MyPlugin:\n        pass\n\n    pytester.plugins = [MyPlugin()]\n\n    with pytest.raises(ValueError, match=\"plugins as objects is not supported\"):\n        pytester.runpytest_subprocess()\n"
  },
  {
    "path": "testing/test_python_path.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport sys\nfrom textwrap import dedent\n\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\n@pytest.fixture()\ndef file_structure(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_foo=\"\"\"\n        from foo import foo\n\n        def test_foo():\n            assert foo() == 1\n        \"\"\"\n    )\n\n    pytester.makepyfile(\n        test_bar=\"\"\"\n        from bar import bar\n\n        def test_bar():\n            assert bar() == 2\n        \"\"\"\n    )\n\n    foo_py = pytester.mkdir(\"sub\") / \"foo.py\"\n    content = dedent(\n        \"\"\"\n        def foo():\n            return 1\n        \"\"\"\n    )\n    foo_py.write_text(content, encoding=\"utf-8\")\n\n    bar_py = pytester.mkdir(\"sub2\") / \"bar.py\"\n    content = dedent(\n        \"\"\"\n        def bar():\n            return 2\n        \"\"\"\n    )\n    bar_py.write_text(content, encoding=\"utf-8\")\n\n\ndef test_one_dir(pytester: Pytester, file_structure) -> None:\n    pytester.makefile(\".ini\", pytest=\"[pytest]\\npythonpath=sub\\n\")\n    result = pytester.runpytest(\"test_foo.py\")\n    assert result.ret == 0\n    result.assert_outcomes(passed=1)\n\n\ndef test_two_dirs(pytester: Pytester, file_structure) -> None:\n    pytester.makefile(\".ini\", pytest=\"[pytest]\\npythonpath=sub sub2\\n\")\n    result = pytester.runpytest(\"test_foo.py\", \"test_bar.py\")\n    assert result.ret == 0\n    result.assert_outcomes(passed=2)\n\n\ndef test_local_plugin(pytester: Pytester, file_structure) -> None:\n    \"\"\"`pythonpath` kicks early enough to load plugins via -p (#11118).\"\"\"\n    localplugin_py = pytester.path / \"sub\" / \"localplugin.py\"\n    content = dedent(\n        \"\"\"\n        def pytest_load_initial_conftests():\n            print(\"local plugin load\")\n\n        def pytest_unconfigure():\n            print(\"local plugin unconfig\")\n        \"\"\"\n    )\n    localplugin_py.write_text(content, encoding=\"utf-8\")\n\n    pytester.makeini(\"[pytest]\\npythonpath=sub\\n\")\n    result = pytester.runpytest(\"-plocalplugin\", \"-s\", \"test_foo.py\")\n    result.stdout.fnmatch_lines([\"local plugin load\", \"local plugin unconfig\"])\n    assert result.ret == 0\n    result.assert_outcomes(passed=1)\n\n\ndef test_module_not_found(pytester: Pytester, file_structure) -> None:\n    \"\"\"Without the pythonpath setting, the module should not be found.\"\"\"\n    pytester.makefile(\".ini\", pytest=\"[pytest]\\n\")\n    result = pytester.runpytest(\"test_foo.py\")\n    assert result.ret == pytest.ExitCode.INTERRUPTED\n    result.assert_outcomes(errors=1)\n    expected_error = \"E   ModuleNotFoundError: No module named 'foo'\"\n    result.stdout.fnmatch_lines([expected_error])\n\n\ndef test_no_config_file(pytester: Pytester, file_structure) -> None:\n    \"\"\"If no configuration file, test should error.\"\"\"\n    result = pytester.runpytest(\"test_foo.py\")\n    assert result.ret == pytest.ExitCode.INTERRUPTED\n    result.assert_outcomes(errors=1)\n    expected_error = \"E   ModuleNotFoundError: No module named 'foo'\"\n    result.stdout.fnmatch_lines([expected_error])\n\n\ndef test_clean_up(pytester: Pytester) -> None:\n    \"\"\"Test that the plugin cleans up after itself.\"\"\"\n    # This is tough to test behaviorally because the cleanup really runs last.\n    # So the test make several implementation assumptions:\n    # - Cleanup is done in pytest_unconfigure().\n    # - Not a hook wrapper.\n    # So we can add a hook wrapper ourselves to test what it does.\n    pytester.makefile(\".ini\", pytest=\"[pytest]\\npythonpath=I_SHALL_BE_REMOVED\\n\")\n    pytester.makepyfile(test_foo=\"\"\"def test_foo(): pass\"\"\")\n\n    before: list[str] | None = None\n    after: list[str] | None = None\n\n    class Plugin:\n        @pytest.hookimpl(tryfirst=True)\n        def pytest_unconfigure(self) -> None:\n            nonlocal before\n            before = sys.path.copy()\n\n    result = pytester.runpytest_inprocess(plugins=[Plugin()])\n    after = sys.path.copy()\n    assert result.ret == 0\n\n    assert before is not None\n    assert after is not None\n    assert any(\"I_SHALL_BE_REMOVED\" in entry for entry in before)\n    assert not any(\"I_SHALL_BE_REMOVED\" in entry for entry in after)\n"
  },
  {
    "path": "testing/test_recwarn.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport sys\nimport warnings\n\nimport pytest\nfrom pytest import ExitCode\nfrom pytest import Pytester\nfrom pytest import WarningsRecorder\n\n\ndef test_recwarn_stacklevel(recwarn: WarningsRecorder) -> None:\n    warnings.warn(\"hello\")\n    warn = recwarn.pop()\n    assert warn.filename == __file__\n\n\ndef test_recwarn_functional(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import warnings\n        def test_method(recwarn):\n            warnings.warn(\"hello\")\n            warn = recwarn.pop()\n            assert isinstance(warn.message, UserWarning)\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(passed=1)\n\n\n@pytest.mark.filterwarnings(\"\")\ndef test_recwarn_captures_deprecation_warning(recwarn: WarningsRecorder) -> None:\n    \"\"\"\n    Check that recwarn can capture DeprecationWarning by default\n    without custom filterwarnings (see #8666).\n    \"\"\"\n    warnings.warn(DeprecationWarning(\"some deprecation\"))\n    assert len(recwarn) == 1\n    assert recwarn.pop(DeprecationWarning)\n\n\nclass TestSubclassWarningPop:\n    class ParentWarning(Warning):\n        pass\n\n    class ChildWarning(ParentWarning):\n        pass\n\n    class ChildOfChildWarning(ChildWarning):\n        pass\n\n    @staticmethod\n    def raise_warnings_from_list(_warnings: list[type[Warning]]):\n        for warn in _warnings:\n            warnings.warn(f\"Warning {warn().__repr__()}\", warn)\n\n    def test_pop_finds_exact_match(self):\n        with pytest.warns((self.ParentWarning, self.ChildWarning)) as record:\n            self.raise_warnings_from_list(\n                [self.ChildWarning, self.ParentWarning, self.ChildOfChildWarning]\n            )\n\n        assert len(record) == 3\n        _warn = record.pop(self.ParentWarning)\n        assert _warn.category is self.ParentWarning\n\n    def test_pop_raises_if_no_match(self):\n        with pytest.raises(AssertionError):\n            with pytest.warns(self.ParentWarning) as record:\n                self.raise_warnings_from_list([self.ParentWarning])\n            record.pop(self.ChildOfChildWarning)\n\n    def test_pop_finds_best_inexact_match(self):\n        with pytest.warns(self.ParentWarning) as record:\n            self.raise_warnings_from_list(\n                [self.ChildOfChildWarning, self.ChildWarning, self.ChildOfChildWarning]\n            )\n\n        _warn = record.pop(self.ParentWarning)\n        assert _warn.category is self.ChildWarning\n\n\nclass TestWarningsRecorderChecker:\n    def test_recording(self) -> None:\n        rec = WarningsRecorder(_ispytest=True)\n        with rec:\n            assert not rec.list\n            warnings.warn_explicit(\"hello\", UserWarning, \"xyz\", 13)\n            assert len(rec.list) == 1\n            warnings.warn(DeprecationWarning(\"hello\"))\n            assert len(rec.list) == 2\n            warn = rec.pop()\n            assert str(warn.message) == \"hello\"\n            values = rec.list\n            rec.clear()\n            assert len(rec.list) == 0\n            assert values is rec.list\n            pytest.raises(AssertionError, rec.pop)\n\n    def test_warn_stacklevel(self) -> None:\n        \"\"\"#4243\"\"\"\n        rec = WarningsRecorder(_ispytest=True)\n        with rec:\n            warnings.warn(\"test\", DeprecationWarning, 2)\n\n    def test_typechecking(self) -> None:\n        from _pytest.recwarn import WarningsChecker\n\n        with pytest.raises(TypeError):\n            WarningsChecker(5, _ispytest=True)  # type: ignore[arg-type]\n        with pytest.raises(TypeError):\n            WarningsChecker((\"hi\", RuntimeWarning), _ispytest=True)  # type: ignore[arg-type]\n        with pytest.raises(TypeError):\n            WarningsChecker([DeprecationWarning, RuntimeWarning], _ispytest=True)  # type: ignore[arg-type]\n\n    def test_invalid_enter_exit(self) -> None:\n        # wrap this test in WarningsRecorder to ensure warning state gets reset\n        with WarningsRecorder(_ispytest=True):\n            with pytest.raises(RuntimeError):\n                rec = WarningsRecorder(_ispytest=True)\n                rec.__exit__(None, None, None)  # can't exit before entering\n\n            with pytest.raises(RuntimeError):\n                rec = WarningsRecorder(_ispytest=True)\n                with rec:\n                    with rec:\n                        pass  # can't enter twice\n\n\nclass TestDeprecatedCall:\n    \"\"\"test pytest.deprecated_call()\"\"\"\n\n    def dep(self, i: int, j: int | None = None) -> int:\n        if i == 0:\n            warnings.warn(\"is deprecated\", DeprecationWarning, stacklevel=1)\n        return 42\n\n    def dep_explicit(self, i: int) -> None:\n        if i == 0:\n            warnings.warn_explicit(\n                \"dep_explicit\", category=DeprecationWarning, filename=\"hello\", lineno=3\n            )\n\n    def test_deprecated_call_raises(self) -> None:\n        with pytest.raises(pytest.fail.Exception, match=\"No warnings of type\"):\n            pytest.deprecated_call(self.dep, 3, 5)\n\n    def test_deprecated_call(self) -> None:\n        pytest.deprecated_call(self.dep, 0, 5)\n\n    def test_deprecated_call_ret(self) -> None:\n        ret = pytest.deprecated_call(self.dep, 0)\n        assert ret == 42\n\n    def test_deprecated_call_preserves(self) -> None:\n        # Type ignored because `onceregistry` and `filters` are not\n        # documented API.\n        onceregistry = warnings.onceregistry.copy()  # type: ignore\n        filters = warnings.filters[:]\n        warn = warnings.warn\n        warn_explicit = warnings.warn_explicit\n        self.test_deprecated_call_raises()\n        self.test_deprecated_call()\n        assert onceregistry == warnings.onceregistry  # type: ignore\n        assert filters == warnings.filters\n        assert warn is warnings.warn\n        assert warn_explicit is warnings.warn_explicit\n\n    def test_deprecated_explicit_call_raises(self) -> None:\n        with pytest.raises(pytest.fail.Exception):\n            pytest.deprecated_call(self.dep_explicit, 3)\n\n    def test_deprecated_explicit_call(self) -> None:\n        pytest.deprecated_call(self.dep_explicit, 0)\n        pytest.deprecated_call(self.dep_explicit, 0)\n\n    @pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n    def test_deprecated_call_no_warning(self, mode) -> None:\n        \"\"\"Ensure deprecated_call() raises the expected failure when its block/function does\n        not raise a deprecation warning.\n        \"\"\"\n\n        def f():\n            pass\n\n        msg = \"No warnings of type (.*DeprecationWarning.*, .*PendingDeprecationWarning.*)\"\n        with pytest.raises(pytest.fail.Exception, match=msg):\n            if mode == \"call\":\n                pytest.deprecated_call(f)\n            else:\n                with pytest.deprecated_call():\n                    f()\n\n    @pytest.mark.parametrize(\n        \"warning_type\", [PendingDeprecationWarning, DeprecationWarning, FutureWarning]\n    )\n    @pytest.mark.parametrize(\"mode\", [\"context_manager\", \"call\"])\n    @pytest.mark.parametrize(\"call_f_first\", [True, False])\n    @pytest.mark.filterwarnings(\"ignore\")\n    def test_deprecated_call_modes(self, warning_type, mode, call_f_first) -> None:\n        \"\"\"Ensure deprecated_call() captures a deprecation warning as expected inside its\n        block/function.\n        \"\"\"\n\n        def f():\n            warnings.warn(warning_type(\"hi\"))\n            return 10\n\n        # ensure deprecated_call() can capture the warning even if it has already been triggered\n        if call_f_first:\n            assert f() == 10\n        if mode == \"call\":\n            assert pytest.deprecated_call(f) == 10\n        else:\n            with pytest.deprecated_call():\n                assert f() == 10\n\n    def test_deprecated_call_specificity(self) -> None:\n        other_warnings = [\n            Warning,\n            UserWarning,\n            SyntaxWarning,\n            RuntimeWarning,\n            ImportWarning,\n            UnicodeWarning,\n        ]\n        for warning in other_warnings:\n\n            def f():\n                warnings.warn(warning(\"hi\"))  # noqa: B023\n\n            with pytest.warns(warning):\n                with pytest.raises(pytest.fail.Exception):\n                    pytest.deprecated_call(f)\n                with pytest.raises(pytest.fail.Exception):\n                    with pytest.deprecated_call():\n                        f()\n\n    def test_deprecated_call_supports_match(self) -> None:\n        with pytest.deprecated_call(match=r\"must be \\d+$\"):\n            warnings.warn(\"value must be 42\", DeprecationWarning)\n\n        with pytest.deprecated_call():\n            with pytest.raises(pytest.fail.Exception, match=\"DID NOT WARN\"):\n                with pytest.deprecated_call(match=r\"must be \\d+$\"):\n                    warnings.warn(\"this is not here\", DeprecationWarning)\n\n\nclass TestWarns:\n    def test_check_callable(self) -> None:\n        source = \"warnings.warn('w1', RuntimeWarning)\"\n        with pytest.raises(TypeError, match=r\".* must be callable\"):\n            pytest.warns(RuntimeWarning, source)  # type: ignore\n\n    def test_several_messages(self) -> None:\n        # different messages, b/c Python suppresses multiple identical warnings\n        pytest.warns(RuntimeWarning, lambda: warnings.warn(\"w1\", RuntimeWarning))\n        with pytest.warns(RuntimeWarning):\n            with pytest.raises(pytest.fail.Exception):\n                pytest.warns(UserWarning, lambda: warnings.warn(\"w2\", RuntimeWarning))\n        pytest.warns(RuntimeWarning, lambda: warnings.warn(\"w3\", RuntimeWarning))\n\n    def test_function(self) -> None:\n        pytest.warns(\n            SyntaxWarning, lambda msg: warnings.warn(msg, SyntaxWarning), \"syntax\"\n        )\n\n    def test_warning_tuple(self) -> None:\n        pytest.warns(\n            (RuntimeWarning, SyntaxWarning), lambda: warnings.warn(\"w1\", RuntimeWarning)\n        )\n        pytest.warns(\n            (RuntimeWarning, SyntaxWarning), lambda: warnings.warn(\"w2\", SyntaxWarning)\n        )\n        with pytest.warns():\n            pytest.raises(\n                pytest.fail.Exception,\n                lambda: pytest.warns(\n                    (RuntimeWarning, SyntaxWarning),\n                    lambda: warnings.warn(\"w3\", UserWarning),\n                ),\n            )\n\n    def test_as_contextmanager(self) -> None:\n        with pytest.warns(RuntimeWarning):\n            warnings.warn(\"runtime\", RuntimeWarning)\n\n        with pytest.warns(UserWarning):\n            warnings.warn(\"user\", UserWarning)\n\n        with pytest.warns():\n            with pytest.raises(pytest.fail.Exception) as excinfo:\n                with pytest.warns(RuntimeWarning):\n                    warnings.warn(\"user\", UserWarning)\n        excinfo.match(\n            r\"DID NOT WARN. No warnings of type \\(.+RuntimeWarning.+,\\) were emitted.\\n\"\n            r\" Emitted warnings: \\[UserWarning\\('user',?\\)\\].\"\n        )\n\n        with pytest.warns():\n            with pytest.raises(pytest.fail.Exception) as excinfo:\n                with pytest.warns(UserWarning):\n                    warnings.warn(\"runtime\", RuntimeWarning)\n        excinfo.match(\n            r\"DID NOT WARN. No warnings of type \\(.+UserWarning.+,\\) were emitted.\\n\"\n            r\" Emitted warnings: \\[RuntimeWarning\\('runtime',?\\)].\"\n        )\n\n        with pytest.raises(pytest.fail.Exception) as excinfo:\n            with pytest.warns(UserWarning):\n                pass\n        excinfo.match(\n            r\"DID NOT WARN. No warnings of type \\(.+UserWarning.+,\\) were emitted.\\n\"\n            r\" Emitted warnings: \\[\\].\"\n        )\n\n        warning_classes = (UserWarning, FutureWarning)\n        with pytest.warns():\n            with pytest.raises(pytest.fail.Exception) as excinfo:\n                with pytest.warns(warning_classes) as warninfo:\n                    warnings.warn(\"runtime\", RuntimeWarning)\n                    warnings.warn(\"import\", ImportWarning)\n\n        messages = [each.message for each in warninfo]\n        expected_str = (\n            f\"DID NOT WARN. No warnings of type {warning_classes} were emitted.\\n\"\n            f\" Emitted warnings: {messages}.\"\n        )\n\n        assert str(excinfo.value) == expected_str\n\n    def test_record(self) -> None:\n        with pytest.warns(UserWarning) as record:\n            warnings.warn(\"user\", UserWarning)\n\n        assert len(record) == 1\n        assert str(record[0].message) == \"user\"\n\n    def test_record_only(self) -> None:\n        with pytest.warns() as record:\n            warnings.warn(\"user\", UserWarning)\n            warnings.warn(\"runtime\", RuntimeWarning)\n\n        assert len(record) == 2\n        assert str(record[0].message) == \"user\"\n        assert str(record[1].message) == \"runtime\"\n\n    def test_record_only_none_type_error(self) -> None:\n        with pytest.raises(TypeError):\n            pytest.warns(None)  # type: ignore[call-overload]\n\n    def test_record_by_subclass(self) -> None:\n        with pytest.warns(Warning) as record:\n            warnings.warn(\"user\", UserWarning)\n            warnings.warn(\"runtime\", RuntimeWarning)\n\n        assert len(record) == 2\n        assert str(record[0].message) == \"user\"\n        assert str(record[1].message) == \"runtime\"\n\n        class MyUserWarning(UserWarning):\n            pass\n\n        class MyRuntimeWarning(RuntimeWarning):\n            pass\n\n        with pytest.warns((UserWarning, RuntimeWarning)) as record:\n            warnings.warn(\"user\", MyUserWarning)\n            warnings.warn(\"runtime\", MyRuntimeWarning)\n\n        assert len(record) == 2\n        assert str(record[0].message) == \"user\"\n        assert str(record[1].message) == \"runtime\"\n\n    def test_double_test(self, pytester: Pytester) -> None:\n        \"\"\"If a test is run again, the warning should still be raised\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            import warnings\n\n            @pytest.mark.parametrize('run', [1, 2])\n            def test(run):\n                with pytest.warns(RuntimeWarning):\n                    warnings.warn(\"runtime\", RuntimeWarning)\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*2 passed in*\"])\n\n    def test_match_regex(self) -> None:\n        with pytest.warns(UserWarning, match=r\"must be \\d+$\"):\n            warnings.warn(\"value must be 42\", UserWarning)\n\n        with pytest.warns():\n            with pytest.raises(pytest.fail.Exception):\n                with pytest.warns(UserWarning, match=r\"must be \\d+$\"):\n                    warnings.warn(\"this is not here\", UserWarning)\n\n        with pytest.warns():\n            with pytest.raises(pytest.fail.Exception):\n                with pytest.warns(FutureWarning, match=r\"must be \\d+$\"):\n                    warnings.warn(\"value must be 42\", UserWarning)\n\n    def test_one_from_multiple_warns(self) -> None:\n        with pytest.warns():\n            with pytest.raises(pytest.fail.Exception, match=\"DID NOT WARN\"):\n                with pytest.warns(UserWarning, match=r\"aaa\"):\n                    with pytest.warns(UserWarning, match=r\"aaa\"):\n                        warnings.warn(\"cccccccccc\", UserWarning)\n                        warnings.warn(\"bbbbbbbbbb\", UserWarning)\n                        warnings.warn(\"aaaaaaaaaa\", UserWarning)\n\n    def test_none_of_multiple_warns(self) -> None:\n        with pytest.warns():\n            with pytest.raises(pytest.fail.Exception, match=\"DID NOT WARN\"):\n                with pytest.warns(UserWarning, match=r\"aaa\"):\n                    warnings.warn(\"bbbbbbbbbb\", UserWarning)\n                    warnings.warn(\"cccccccccc\", UserWarning)\n\n    @pytest.mark.filterwarnings(\"ignore\")\n    def test_can_capture_previously_warned(self) -> None:\n        def f() -> int:\n            warnings.warn(UserWarning(\"ohai\"))\n            return 10\n\n        assert f() == 10\n        assert pytest.warns(UserWarning, f) == 10\n        assert pytest.warns(UserWarning, f) == 10\n        assert pytest.warns(UserWarning, f) != \"10\"  # type: ignore[comparison-overlap]\n\n    def test_warns_context_manager_with_kwargs(self) -> None:\n        with pytest.raises(TypeError) as excinfo:\n            with pytest.warns(UserWarning, foo=\"bar\"):  # type: ignore\n                pass\n        assert \"Unexpected keyword arguments\" in str(excinfo.value)\n\n    def test_re_emit_single(self) -> None:\n        with pytest.warns(DeprecationWarning):\n            with pytest.warns(UserWarning):\n                warnings.warn(\"user warning\", UserWarning)\n                warnings.warn(\"some deprecation warning\", DeprecationWarning)\n\n    def test_re_emit_multiple(self) -> None:\n        with pytest.warns(UserWarning):\n            warnings.warn(\"first warning\", UserWarning)\n            warnings.warn(\"second warning\", UserWarning)\n\n    def test_re_emit_match_single(self) -> None:\n        with pytest.warns(DeprecationWarning):\n            with pytest.warns(UserWarning, match=\"user warning\"):\n                warnings.warn(\"user warning\", UserWarning)\n                warnings.warn(\"some deprecation warning\", DeprecationWarning)\n\n    def test_re_emit_match_multiple(self) -> None:\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"error\")  # if anything is re-emitted\n            with pytest.warns(UserWarning, match=\"user warning\"):\n                warnings.warn(\"first user warning\", UserWarning)\n                warnings.warn(\"second user warning\", UserWarning)\n\n    def test_re_emit_non_match_single(self) -> None:\n        with pytest.warns(UserWarning, match=\"v2 warning\"):\n            with pytest.warns(UserWarning, match=\"v1 warning\"):\n                warnings.warn(\"v1 warning\", UserWarning)\n                warnings.warn(\"non-matching v2 warning\", UserWarning)\n\n    def test_catch_warning_within_raise(self) -> None:\n        # warns-in-raises works since https://github.com/pytest-dev/pytest/pull/11129\n        with pytest.raises(ValueError, match=\"some exception\"):\n            with pytest.warns(FutureWarning, match=\"some warning\"):\n                warnings.warn(\"some warning\", category=FutureWarning)\n                raise ValueError(\"some exception\")\n        # and raises-in-warns has always worked but we'll check for symmetry.\n        with pytest.warns(FutureWarning, match=\"some warning\"):\n            with pytest.raises(ValueError, match=\"some exception\"):\n                warnings.warn(\"some warning\", category=FutureWarning)\n                raise ValueError(\"some exception\")\n\n    def test_skip_within_warns(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #11907.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def test_it():\n                with pytest.warns(Warning):\n                    pytest.skip(\"this is OK\")\n            \"\"\",\n        )\n\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.OK\n        result.assert_outcomes(skipped=1)\n\n    def test_fail_within_warns(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #11907.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def test_it():\n                with pytest.warns(Warning):\n                    pytest.fail(\"BOOM\")\n            \"\"\",\n        )\n\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.TESTS_FAILED\n        result.assert_outcomes(failed=1)\n        assert \"DID NOT WARN\" not in str(result.stdout)\n\n    def test_exit_within_warns(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #11907.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def test_it():\n                with pytest.warns(Warning):\n                    pytest.exit()\n            \"\"\",\n        )\n\n        result = pytester.runpytest()\n        assert result.ret == ExitCode.INTERRUPTED\n        result.assert_outcomes()\n\n    def test_keyboard_interrupt_within_warns(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #11907.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            def test_it():\n                with pytest.warns(Warning):\n                    raise KeyboardInterrupt()\n            \"\"\",\n        )\n\n        result = pytester.runpytest_subprocess()\n        assert result.ret == ExitCode.INTERRUPTED\n        result.assert_outcomes()\n\n\ndef test_raise_type_error_on_invalid_warning() -> None:\n    \"\"\"Check pytest.warns validates warning messages are strings (#10865) or\n    Warning instances (#11959).\"\"\"\n    with pytest.raises(TypeError, match=\"Warning must be str or Warning\"):\n        with pytest.warns(UserWarning):\n            warnings.warn(1)  # type: ignore\n\n\n@pytest.mark.parametrize(\n    \"message\",\n    [\n        pytest.param(\"Warning\", id=\"str\"),\n        pytest.param(UserWarning(), id=\"UserWarning\"),\n        pytest.param(Warning(), id=\"Warning\"),\n    ],\n)\ndef test_no_raise_type_error_on_valid_warning(message: str | Warning) -> None:\n    \"\"\"Check pytest.warns validates warning messages are strings (#10865) or\n    Warning instances (#11959).\"\"\"\n    with pytest.warns(Warning):\n        warnings.warn(message)\n\n\n@pytest.mark.skipif(\n    hasattr(sys, \"pypy_version_info\"),\n    reason=\"Not for pypy\",\n)\ndef test_raise_type_error_on_invalid_warning_message_cpython() -> None:\n    # Check that we get the same behavior with the stdlib, at least if filtering\n    # (see https://github.com/python/cpython/issues/103577 for details)\n    with pytest.raises(TypeError):\n        with warnings.catch_warnings():\n            warnings.filterwarnings(\"ignore\", \"test\")\n            warnings.warn(1)  # type: ignore\n\n\ndef test_multiple_arg_custom_warning() -> None:\n    \"\"\"Test for issue #11906.\"\"\"\n\n    class CustomWarning(UserWarning):\n        def __init__(self, a, b):\n            pass\n\n    with pytest.warns(CustomWarning):\n        with pytest.raises(pytest.fail.Exception, match=\"DID NOT WARN\"):\n            with pytest.warns(CustomWarning, match=\"not gonna match\"):\n                a, b = 1, 2\n                warnings.warn(CustomWarning(a, b))\n"
  },
  {
    "path": "testing/test_reports.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\n\nfrom _pytest._code.code import ExceptionChainRepr\nfrom _pytest._code.code import ExceptionRepr\nfrom _pytest.config import Config\nfrom _pytest.pytester import Pytester\nfrom _pytest.python_api import approx\nfrom _pytest.reports import CollectReport\nfrom _pytest.reports import TestReport\nimport pytest\n\n\nclass TestReportSerialization:\n    def test_xdist_longrepr_to_str_issue_241(self, pytester: Pytester) -> None:\n        \"\"\"Regarding issue pytest-xdist#241.\n\n        This test came originally from test_remote.py in xdist (ca03269).\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def test_a(): assert False\n            def test_b(): pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reports = reprec.getreports(\"pytest_runtest_logreport\")\n        assert len(reports) == 6\n        test_a_call = reports[1]\n        assert test_a_call.when == \"call\"\n        assert test_a_call.outcome == \"failed\"\n        assert test_a_call._to_json()[\"longrepr\"][\"reprtraceback\"][\"style\"] == \"long\"\n        test_b_call = reports[4]\n        assert test_b_call.when == \"call\"\n        assert test_b_call.outcome == \"passed\"\n        assert test_b_call._to_json()[\"longrepr\"] is None\n\n    def test_xdist_report_longrepr_reprcrash_130(self, pytester: Pytester) -> None:\n        \"\"\"Regarding issue pytest-xdist#130\n\n        This test came originally from test_remote.py in xdist (ca03269).\n        \"\"\"\n        reprec = pytester.inline_runsource(\n            \"\"\"\n                    def test_fail():\n                        assert False, 'Expected Message'\n                \"\"\"\n        )\n        reports = reprec.getreports(\"pytest_runtest_logreport\")\n        assert len(reports) == 3\n        rep = reports[1]\n        added_section = (\"Failure Metadata\", \"metadata metadata\", \"*\")\n        assert isinstance(rep.longrepr, ExceptionRepr)\n        rep.longrepr.sections.append(added_section)\n        d = rep._to_json()\n        a = TestReport._from_json(d)\n        assert isinstance(a.longrepr, ExceptionRepr)\n        # Check assembled == rep\n        assert a.__dict__.keys() == rep.__dict__.keys()\n        for key in rep.__dict__.keys():\n            if key != \"longrepr\":\n                assert getattr(a, key) == getattr(rep, key)\n        assert rep.longrepr.reprcrash is not None\n        assert a.longrepr.reprcrash is not None\n        assert rep.longrepr.reprcrash.lineno == a.longrepr.reprcrash.lineno\n        assert rep.longrepr.reprcrash.message == a.longrepr.reprcrash.message\n        assert rep.longrepr.reprcrash.path == a.longrepr.reprcrash.path\n        assert rep.longrepr.reprtraceback.entrysep == a.longrepr.reprtraceback.entrysep\n        assert (\n            rep.longrepr.reprtraceback.extraline == a.longrepr.reprtraceback.extraline\n        )\n        assert rep.longrepr.reprtraceback.style == a.longrepr.reprtraceback.style\n        assert rep.longrepr.sections == a.longrepr.sections\n        # Missing section attribute PR171\n        assert added_section in a.longrepr.sections\n\n    def test_reprentries_serialization_170(self, pytester: Pytester) -> None:\n        \"\"\"Regarding issue pytest-xdist#170\n\n        This test came originally from test_remote.py in xdist (ca03269).\n        \"\"\"\n        from _pytest._code.code import ReprEntry\n\n        reprec = pytester.inline_runsource(\n            \"\"\"\n                            def test_repr_entry():\n                                x = 0\n                                assert x\n                        \"\"\",\n            \"--showlocals\",\n        )\n        reports = reprec.getreports(\"pytest_runtest_logreport\")\n        assert len(reports) == 3\n        rep = reports[1]\n        assert isinstance(rep.longrepr, ExceptionRepr)\n        d = rep._to_json()\n        a = TestReport._from_json(d)\n        assert isinstance(a.longrepr, ExceptionRepr)\n\n        rep_entries = rep.longrepr.reprtraceback.reprentries\n        a_entries = a.longrepr.reprtraceback.reprentries\n        for a_entry, rep_entry in zip(a_entries, rep_entries, strict=True):\n            assert isinstance(rep_entry, ReprEntry)\n            assert rep_entry.reprfileloc is not None\n            assert rep_entry.reprfuncargs is not None\n            assert rep_entry.reprlocals is not None\n\n            assert isinstance(a_entry, ReprEntry)\n            assert a_entry.reprfileloc is not None\n            assert a_entry.reprfuncargs is not None\n            assert a_entry.reprlocals is not None\n\n            assert rep_entry.lines == a_entry.lines\n            assert rep_entry.reprfileloc.lineno == a_entry.reprfileloc.lineno\n            assert rep_entry.reprfileloc.message == a_entry.reprfileloc.message\n            assert rep_entry.reprfileloc.path == a_entry.reprfileloc.path\n            assert rep_entry.reprfuncargs.args == a_entry.reprfuncargs.args\n            assert rep_entry.reprlocals.lines == a_entry.reprlocals.lines\n            assert rep_entry.style == a_entry.style\n\n    def test_reprentries_serialization_196(self, pytester: Pytester) -> None:\n        \"\"\"Regarding issue pytest-xdist#196\n\n        This test came originally from test_remote.py in xdist (ca03269).\n        \"\"\"\n        from _pytest._code.code import ReprEntryNative\n\n        reprec = pytester.inline_runsource(\n            \"\"\"\n                            def test_repr_entry_native():\n                                x = 0\n                                assert x\n                        \"\"\",\n            \"--tb=native\",\n        )\n        reports = reprec.getreports(\"pytest_runtest_logreport\")\n        assert len(reports) == 3\n        rep = reports[1]\n        assert isinstance(rep.longrepr, ExceptionRepr)\n        d = rep._to_json()\n        a = TestReport._from_json(d)\n        assert isinstance(a.longrepr, ExceptionRepr)\n\n        rep_entries = rep.longrepr.reprtraceback.reprentries\n        a_entries = a.longrepr.reprtraceback.reprentries\n        for rep_entry, a_entry in zip(rep_entries, a_entries, strict=True):\n            assert isinstance(rep_entry, ReprEntryNative)\n            assert rep_entry.lines == a_entry.lines\n\n    def test_itemreport_outcomes(self, pytester: Pytester) -> None:\n        # This test came originally from test_remote.py in xdist (ca03269).\n        reprec = pytester.inline_runsource(\n            \"\"\"\n            import pytest\n            def test_pass(): pass\n            def test_fail(): 0/0\n            @pytest.mark.skipif(\"True\")\n            def test_skip(): pass\n            def test_skip_imperative():\n                pytest.skip(\"hello\")\n            @pytest.mark.xfail(\"True\")\n            def test_xfail(): 0/0\n            def test_xfail_imperative():\n                pytest.xfail(\"hello\")\n        \"\"\"\n        )\n        reports = reprec.getreports(\"pytest_runtest_logreport\")\n        assert len(reports) == 17  # with setup/teardown \"passed\" reports\n        for rep in reports:\n            d = rep._to_json()\n            newrep = TestReport._from_json(d)\n            assert newrep.passed == rep.passed\n            assert newrep.failed == rep.failed\n            assert newrep.skipped == rep.skipped\n            if newrep.skipped and not hasattr(newrep, \"wasxfail\"):\n                assert isinstance(newrep.longrepr, tuple)\n                assert len(newrep.longrepr) == 3\n            assert newrep.outcome == rep.outcome\n            assert newrep.when == rep.when\n            assert newrep.keywords == rep.keywords\n            if rep.failed:\n                assert newrep.longreprtext == rep.longreprtext\n\n    def test_collectreport_passed(self, pytester: Pytester) -> None:\n        \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n        reprec = pytester.inline_runsource(\"def test_func(): pass\")\n        reports = reprec.getreports(\"pytest_collectreport\")\n        for rep in reports:\n            d = rep._to_json()\n            newrep = CollectReport._from_json(d)\n            assert newrep.passed == rep.passed\n            assert newrep.failed == rep.failed\n            assert newrep.skipped == rep.skipped\n\n    def test_collectreport_fail(self, pytester: Pytester) -> None:\n        \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n        reprec = pytester.inline_runsource(\"qwe abc\")\n        reports = reprec.getreports(\"pytest_collectreport\")\n        assert reports\n        for rep in reports:\n            d = rep._to_json()\n            newrep = CollectReport._from_json(d)\n            assert newrep.passed == rep.passed\n            assert newrep.failed == rep.failed\n            assert newrep.skipped == rep.skipped\n            if rep.failed:\n                assert newrep.longrepr == str(rep.longrepr)\n\n    def test_extended_report_deserialization(self, pytester: Pytester) -> None:\n        \"\"\"This test came originally from test_remote.py in xdist (ca03269).\"\"\"\n        reprec = pytester.inline_runsource(\"qwe abc\")\n        reports = reprec.getreports(\"pytest_collectreport\")\n        assert reports\n        for rep in reports:\n            rep.extra = True  # type: ignore[attr-defined]\n            d = rep._to_json()\n            newrep = CollectReport._from_json(d)\n            assert newrep.extra\n            assert newrep.passed == rep.passed\n            assert newrep.failed == rep.failed\n            assert newrep.skipped == rep.skipped\n            if rep.failed:\n                assert newrep.longrepr == str(rep.longrepr)\n\n    def test_paths_support(self, pytester: Pytester) -> None:\n        \"\"\"Report attributes which are path-like should become strings.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def test_a():\n                assert False\n        \"\"\"\n        )\n\n        class MyPathLike:\n            def __init__(self, path: str) -> None:\n                self.path = path\n\n            def __fspath__(self) -> str:\n                return self.path\n\n        reprec = pytester.inline_run()\n        reports = reprec.getreports(\"pytest_runtest_logreport\")\n        assert len(reports) == 3\n        test_a_call = reports[1]\n        test_a_call.path1 = MyPathLike(str(pytester.path))  # type: ignore[attr-defined]\n        test_a_call.path2 = pytester.path  # type: ignore[attr-defined]\n        data = test_a_call._to_json()\n        assert data[\"path1\"] == str(pytester.path)\n        assert data[\"path2\"] == str(pytester.path)\n\n    def test_deserialization_failure(self, pytester: Pytester) -> None:\n        \"\"\"Check handling of failure during deserialization of report types.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def test_a():\n                assert False\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reports = reprec.getreports(\"pytest_runtest_logreport\")\n        assert len(reports) == 3\n        test_a_call = reports[1]\n        data = test_a_call._to_json()\n        entry = data[\"longrepr\"][\"reprtraceback\"][\"reprentries\"][0]\n        assert entry[\"type\"] == \"ReprEntry\"\n\n        entry[\"type\"] = \"Unknown\"\n        with pytest.raises(\n            RuntimeError, match=\"INTERNALERROR: Unknown entry type returned: Unknown\"\n        ):\n            TestReport._from_json(data)\n\n    @pytest.mark.parametrize(\"report_class\", [TestReport, CollectReport])\n    def test_chained_exceptions(\n        self, pytester: Pytester, tw_mock, report_class\n    ) -> None:\n        \"\"\"Check serialization/deserialization of report objects containing chained exceptions (#5786)\"\"\"\n        pytester.makepyfile(\n            f\"\"\"\n            def foo():\n                raise ValueError('value error')\n            def test_a():\n                try:\n                    foo()\n                except ValueError as e:\n                    raise RuntimeError('runtime error') from e\n            if {report_class is CollectReport}:\n                test_a()\n        \"\"\"\n        )\n\n        reprec = pytester.inline_run()\n        if report_class is TestReport:\n            reports: Sequence[TestReport] | Sequence[CollectReport] = reprec.getreports(\n                \"pytest_runtest_logreport\"\n            )\n            # we have 3 reports: setup/call/teardown\n            assert len(reports) == 3\n            # get the call report\n            report = reports[1]\n        else:\n            assert report_class is CollectReport\n            # three collection reports: session, test file, directory\n            reports = reprec.getreports(\"pytest_collectreport\")\n            assert len(reports) == 3\n            report = reports[1]\n\n        def check_longrepr(longrepr: ExceptionChainRepr) -> None:\n            \"\"\"Check the attributes of the given longrepr object according to the test file.\n\n            We can get away with testing both CollectReport and TestReport with this function because\n            the longrepr objects are very similar.\n            \"\"\"\n            assert isinstance(longrepr, ExceptionChainRepr)\n            assert longrepr.sections == [(\"title\", \"contents\", \"=\")]\n            assert len(longrepr.chain) == 2\n            entry1, entry2 = longrepr.chain\n            tb1, _fileloc1, desc1 = entry1\n            tb2, _fileloc2, desc2 = entry2\n\n            assert \"ValueError('value error')\" in str(tb1)\n            assert \"RuntimeError('runtime error')\" in str(tb2)\n\n            assert (\n                desc1\n                == \"The above exception was the direct cause of the following exception:\"\n            )\n            assert desc2 is None\n\n        assert report.failed\n        assert len(report.sections) == 0\n        assert isinstance(report.longrepr, ExceptionChainRepr)\n        report.longrepr.addsection(\"title\", \"contents\", \"=\")\n        check_longrepr(report.longrepr)\n\n        data = report._to_json()\n        loaded_report = report_class._from_json(data)\n\n        assert loaded_report.failed\n        check_longrepr(loaded_report.longrepr)\n\n        # make sure we don't blow up on ``toterminal`` call; we don't test the actual output because it is very\n        # brittle and hard to maintain, but we can assume it is correct because ``toterminal`` is already tested\n        # elsewhere and we do check the contents of the longrepr object after loading it.\n        loaded_report.longrepr.toterminal(tw_mock)\n\n    def test_chained_exceptions_no_reprcrash(self, pytester: Pytester, tw_mock) -> None:\n        \"\"\"Regression test for tracebacks without a reprcrash (#5971)\n\n        This happens notably on exceptions raised by multiprocess.pool: the exception transfer\n        from subprocess to main process creates an artificial exception, which ExceptionInfo\n        can't obtain the ReprFileLocation from.\n        \"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            from concurrent.futures import ProcessPoolExecutor\n\n            def func():\n                raise ValueError('value error')\n\n            def test_a():\n                with ProcessPoolExecutor() as p:\n                    p.submit(func).result()\n        \"\"\"\n        )\n\n        pytester.syspathinsert()\n        reprec = pytester.inline_run()\n\n        reports = reprec.getreports(\"pytest_runtest_logreport\")\n\n        def check_longrepr(longrepr: object) -> None:\n            assert isinstance(longrepr, ExceptionChainRepr)\n            assert len(longrepr.chain) == 2\n            entry1, entry2 = longrepr.chain\n            tb1, fileloc1, _desc1 = entry1\n            tb2, fileloc2, _desc2 = entry2\n\n            assert \"RemoteTraceback\" in str(tb1)\n            assert \"ValueError: value error\" in str(tb2)\n\n            assert fileloc1 is None\n            assert fileloc2 is not None\n            assert fileloc2.message == \"ValueError: value error\"\n\n        # 3 reports: setup/call/teardown: get the call report\n        assert len(reports) == 3\n        report = reports[1]\n\n        assert report.failed\n        check_longrepr(report.longrepr)\n\n        data = report._to_json()\n        loaded_report = TestReport._from_json(data)\n\n        assert loaded_report.failed\n        check_longrepr(loaded_report.longrepr)\n\n        # for same reasons as previous test, ensure we don't blow up here\n        assert loaded_report.longrepr is not None\n        assert isinstance(loaded_report.longrepr, ExceptionChainRepr)\n        loaded_report.longrepr.toterminal(tw_mock)\n\n    def test_report_prevent_ConftestImportFailure_hiding_exception(\n        self, pytester: Pytester\n    ) -> None:\n        sub_dir = pytester.path.joinpath(\"ns\")\n        sub_dir.mkdir()\n        sub_dir.joinpath(\"conftest.py\").write_text(\"import unknown\", encoding=\"utf-8\")\n\n        result = pytester.runpytest_subprocess(\".\")\n        result.stdout.fnmatch_lines([\"E   *Error: No module named 'unknown'\"])\n        result.stdout.no_fnmatch_line(\"ERROR  - *ConftestImportFailure*\")\n\n    def test_report_timestamps_match_duration(self, pytester: Pytester, mock_timing):\n        reprec = pytester.inline_runsource(\n            \"\"\"\n            import pytest\n            from _pytest import timing\n            @pytest.fixture\n            def fixture_():\n                timing.sleep(5)\n                yield\n                timing.sleep(5)\n            def test_1(fixture_): timing.sleep(10)\n        \"\"\"\n        )\n        reports = reprec.getreports(\"pytest_runtest_logreport\")\n        assert len(reports) == 3\n        for report in reports:\n            data = report._to_json()\n            loaded_report = TestReport._from_json(data)\n            assert loaded_report.stop - loaded_report.start == approx(report.duration)\n\n    @pytest.mark.parametrize(\n        \"first_skip_reason, second_skip_reason, skip_reason_output\",\n        [(\"A\", \"B\", \"(A; B)\"), (\"A\", \"A\", \"(A)\")],\n    )\n    def test_exception_group_with_only_skips(\n        self,\n        pytester: Pytester,\n        first_skip_reason: str,\n        second_skip_reason: str,\n        skip_reason_output: str,\n    ):\n        \"\"\"\n        Test that when an ExceptionGroup with only Skipped exceptions is raised in teardown,\n        it is reported as a single skipped test, not as an error.\n        This is a regression test for issue #13537.\n        \"\"\"\n        pytester.makepyfile(\n            test_it=f\"\"\"\n            import pytest\n            @pytest.fixture\n            def fixA():\n                yield\n                pytest.skip(reason=\"{first_skip_reason}\")\n            @pytest.fixture\n            def fixB():\n                yield\n                pytest.skip(reason=\"{second_skip_reason}\")\n            def test_skip(fixA, fixB):\n                assert True\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-v\")\n        result.assert_outcomes(passed=1, skipped=1)\n        out = result.stdout.str()\n        assert skip_reason_output in out\n        assert \"ERROR at teardown\" not in out\n\n    @pytest.mark.parametrize(\n        \"use_item_location, skip_file_location\",\n        [(True, \"test_it.py\"), (False, \"runner.py\")],\n    )\n    def test_exception_group_skips_use_item_location(\n        self, pytester: Pytester, use_item_location: bool, skip_file_location: str\n    ):\n        \"\"\"\n        Regression for #13537:\n        If any skip inside an ExceptionGroup has _use_item_location=True,\n        the report location should point to the test item, not the fixture teardown.\n        \"\"\"\n        pytester.makepyfile(\n            test_it=f\"\"\"\n            import pytest\n            @pytest.fixture\n            def fix_item1():\n                yield\n                exc = pytest.skip.Exception(\"A\")\n                exc._use_item_location = True\n                raise exc\n            @pytest.fixture\n            def fix_item2():\n                yield\n                exc = pytest.skip.Exception(\"B\")\n                exc._use_item_location = {use_item_location}\n                raise exc\n            def test_both(fix_item1, fix_item2):\n                assert True\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-rs\")\n        result.assert_outcomes(passed=1, skipped=1)\n\n        out = result.stdout.str()\n        # Both reasons should appear\n        assert \"A\" and \"B\" in out\n        # Crucially, the skip should be attributed to the test item, not teardown\n        assert skip_file_location in out\n\n\nclass TestHooks:\n    \"\"\"Test that the hooks are working correctly for plugins\"\"\"\n\n    def test_test_report(self, pytester: Pytester, pytestconfig: Config) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_a(): assert False\n            def test_b(): pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reports = reprec.getreports(\"pytest_runtest_logreport\")\n        assert len(reports) == 6\n        for rep in reports:\n            data = pytestconfig.hook.pytest_report_to_serializable(\n                config=pytestconfig, report=rep\n            )\n            assert data[\"$report_type\"] == \"TestReport\"\n            new_rep = pytestconfig.hook.pytest_report_from_serializable(\n                config=pytestconfig, data=data\n            )\n            assert new_rep.nodeid == rep.nodeid\n            assert new_rep.when == rep.when\n            assert new_rep.outcome == rep.outcome\n\n    def test_collect_report(self, pytester: Pytester, pytestconfig: Config) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_a(): assert False\n            def test_b(): pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reports = reprec.getreports(\"pytest_collectreport\")\n        assert len(reports) == 3\n        for rep in reports:\n            data = pytestconfig.hook.pytest_report_to_serializable(\n                config=pytestconfig, report=rep\n            )\n            assert data[\"$report_type\"] == \"CollectReport\"\n            new_rep = pytestconfig.hook.pytest_report_from_serializable(\n                config=pytestconfig, data=data\n            )\n            assert new_rep.nodeid == rep.nodeid\n            assert new_rep.when == \"collect\"\n            assert new_rep.outcome == rep.outcome\n\n    @pytest.mark.parametrize(\n        \"hook_name\", [\"pytest_runtest_logreport\", \"pytest_collectreport\"]\n    )\n    def test_invalid_report_types(\n        self, pytester: Pytester, pytestconfig: Config, hook_name: str\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_a(): pass\n            \"\"\"\n        )\n        reprec = pytester.inline_run()\n        reports = reprec.getreports(hook_name)\n        assert reports\n        rep = reports[0]\n        data = pytestconfig.hook.pytest_report_to_serializable(\n            config=pytestconfig, report=rep\n        )\n        data[\"$report_type\"] = \"Unknown\"\n        with pytest.raises(AssertionError):\n            _ = pytestconfig.hook.pytest_report_from_serializable(\n                config=pytestconfig, data=data\n            )\n"
  },
  {
    "path": "testing/test_runner.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom functools import partial\nimport inspect\nimport os\nfrom pathlib import Path\nimport sys\nimport types\n\nfrom _pytest import outcomes\nfrom _pytest import reports\nfrom _pytest import runner\nfrom _pytest._code import ExceptionInfo\nfrom _pytest._code.code import ExceptionChainRepr\nfrom _pytest.config import ExitCode\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.outcomes import OutcomeException\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import ExceptionGroup\n\n\nclass TestSetupState:\n    def test_setup(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\"def test_func(): pass\")\n        ss = item.session._setupstate\n        values = [1]\n        ss.setup(item)\n        ss.addfinalizer(values.pop, item)\n        assert values\n        ss.teardown_exact(None)\n        assert not values\n\n    def test_teardown_exact_stack_empty(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\"def test_func(): pass\")\n        ss = item.session._setupstate\n        ss.setup(item)\n        ss.teardown_exact(None)\n        ss.teardown_exact(None)\n        ss.teardown_exact(None)\n\n    def test_setup_fails_and_failure_is_cached(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            def setup_module(mod):\n                raise ValueError(42)\n            def test_func(): pass\n        \"\"\"\n        )\n        ss = item.session._setupstate\n        with pytest.raises(ValueError):\n            ss.setup(item)\n        with pytest.raises(ValueError):\n            ss.setup(item)\n\n    def test_teardown_multiple_one_fails(self, pytester: Pytester) -> None:\n        r = []\n\n        def fin1():\n            r.append(\"fin1\")\n\n        def fin2():\n            raise Exception(\"oops\")\n\n        def fin3():\n            r.append(\"fin3\")\n\n        item = pytester.getitem(\"def test_func(): pass\")\n        ss = item.session._setupstate\n        ss.setup(item)\n        ss.addfinalizer(fin1, item)\n        ss.addfinalizer(fin2, item)\n        ss.addfinalizer(fin3, item)\n        with pytest.raises(Exception) as err:\n            ss.teardown_exact(None)\n        assert err.value.args == (\"oops\",)\n        assert r == [\"fin3\", \"fin1\"]\n\n    def test_teardown_multiple_fail(self, pytester: Pytester) -> None:\n        def fin1():\n            raise Exception(\"oops1\")\n\n        def fin2():\n            raise Exception(\"oops2\")\n\n        item = pytester.getitem(\"def test_func(): pass\")\n        ss = item.session._setupstate\n        ss.setup(item)\n        ss.addfinalizer(fin1, item)\n        ss.addfinalizer(fin2, item)\n        with pytest.raises(ExceptionGroup) as err:\n            ss.teardown_exact(None)\n\n        # Note that finalizers are run LIFO, but because FIFO is more intuitive for\n        # users we reverse the order of messages, and see the error from fin1 first.\n        err1, err2 = err.value.exceptions\n        assert err1.args == (\"oops1\",)\n        assert err2.args == (\"oops2\",)\n\n    def test_teardown_multiple_scopes_one_fails(self, pytester: Pytester) -> None:\n        module_teardown = []\n\n        def fin_func():\n            raise Exception(\"oops1\")\n\n        def fin_module():\n            module_teardown.append(\"fin_module\")\n\n        item = pytester.getitem(\"def test_func(): pass\")\n        mod = item.listchain()[-2]\n        ss = item.session._setupstate\n        ss.setup(item)\n        ss.addfinalizer(fin_module, mod)\n        ss.addfinalizer(fin_func, item)\n        with pytest.raises(Exception, match=\"oops1\"):\n            ss.teardown_exact(None)\n        assert module_teardown == [\"fin_module\"]\n\n    def test_teardown_multiple_scopes_several_fail(self, pytester) -> None:\n        def raiser(exc):\n            raise exc\n\n        item = pytester.getitem(\"def test_func(): pass\")\n        mod = item.listchain()[-2]\n        ss = item.session._setupstate\n        ss.setup(item)\n        ss.addfinalizer(partial(raiser, KeyError(\"from module scope\")), mod)\n        ss.addfinalizer(partial(raiser, TypeError(\"from function scope 1\")), item)\n        ss.addfinalizer(partial(raiser, ValueError(\"from function scope 2\")), item)\n\n        with pytest.raises(ExceptionGroup, match=\"errors during test teardown\") as e:\n            ss.teardown_exact(None)\n        mod, func = e.value.exceptions\n        assert isinstance(mod, KeyError)\n        assert isinstance(func.exceptions[0], TypeError)\n        assert isinstance(func.exceptions[1], ValueError)\n\n    def test_cached_exception_doesnt_get_longer(self, pytester: Pytester) -> None:\n        \"\"\"Regression test for #12204 (the \"BTW\" case).\"\"\"\n        pytester.makepyfile(test=\"\")\n        # If the collector.setup() raises, all collected items error with this\n        # exception.\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            class MyItem(pytest.Item):\n                def runtest(self) -> None: pass\n\n            class MyBadCollector(pytest.Collector):\n                def collect(self):\n                    return [\n                        MyItem.from_parent(self, name=\"one\"),\n                        MyItem.from_parent(self, name=\"two\"),\n                        MyItem.from_parent(self, name=\"three\"),\n                    ]\n\n                def setup(self):\n                    1 / 0\n\n            def pytest_collect_file(file_path, parent):\n                if file_path.name == \"test.py\":\n                    return MyBadCollector.from_parent(parent, name='bad')\n            \"\"\"\n        )\n\n        result = pytester.runpytest_inprocess(\"--tb=native\")\n        assert result.ret == ExitCode.TESTS_FAILED\n        failures = result.reprec.getfailures()  # type: ignore[attr-defined]\n        assert len(failures) == 3\n        lines1 = failures[1].longrepr.reprtraceback.reprentries[0].lines\n        lines2 = failures[2].longrepr.reprtraceback.reprentries[0].lines\n        assert len(lines1) == len(lines2)\n\n\nclass BaseFunctionalTests:\n    def test_passfunction(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            def test_func():\n                pass\n        \"\"\"\n        )\n        rep = reports[1]\n        assert rep.passed\n        assert not rep.failed\n        assert rep.outcome == \"passed\"\n        assert not rep.longrepr\n\n    def test_failfunction(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            def test_func():\n                assert 0\n        \"\"\"\n        )\n        rep = reports[1]\n        assert not rep.passed\n        assert not rep.skipped\n        assert rep.failed\n        assert rep.when == \"call\"\n        assert rep.outcome == \"failed\"\n        # assert isinstance(rep.longrepr, ReprExceptionInfo)\n\n    def test_skipfunction(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            import pytest\n            def test_func():\n                pytest.skip(\"hello\")\n        \"\"\"\n        )\n        rep = reports[1]\n        assert not rep.failed\n        assert not rep.passed\n        assert rep.skipped\n        assert rep.outcome == \"skipped\"\n        # assert rep.skipped.when == \"call\"\n        # assert rep.skipped.when == \"call\"\n        # assert rep.skipped == \"%sreason == \"hello\"\n        # assert rep.skipped.location.lineno == 3\n        # assert rep.skipped.location.path\n        # assert not rep.skipped.failurerepr\n\n    def test_skip_in_setup_function(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            import pytest\n            def setup_function(func):\n                pytest.skip(\"hello\")\n            def test_func():\n                pass\n        \"\"\"\n        )\n        print(reports)\n        rep = reports[0]\n        assert not rep.failed\n        assert not rep.passed\n        assert rep.skipped\n        # assert rep.skipped.reason == \"hello\"\n        # assert rep.skipped.location.lineno == 3\n        # assert rep.skipped.location.lineno == 3\n        assert len(reports) == 2\n        assert reports[1].passed  # teardown\n\n    def test_failure_in_setup_function(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            import pytest\n            def setup_function(func):\n                raise ValueError(42)\n            def test_func():\n                pass\n        \"\"\"\n        )\n        rep = reports[0]\n        assert not rep.skipped\n        assert not rep.passed\n        assert rep.failed\n        assert rep.when == \"setup\"\n        assert len(reports) == 2\n\n    def test_failure_in_teardown_function(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            import pytest\n            def teardown_function(func):\n                raise ValueError(42)\n            def test_func():\n                pass\n        \"\"\"\n        )\n        print(reports)\n        assert len(reports) == 3\n        rep = reports[2]\n        assert not rep.skipped\n        assert not rep.passed\n        assert rep.failed\n        assert rep.when == \"teardown\"\n        # assert rep.longrepr.reprcrash.lineno == 3\n        # assert rep.longrepr.reprtraceback.reprentries\n\n    def test_custom_failure_repr(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            conftest=\"\"\"\n            import pytest\n            class Function(pytest.Function):\n                def repr_failure(self, excinfo):\n                    return \"hello\"\n        \"\"\"\n        )\n        reports = pytester.runitem(\n            \"\"\"\n            import pytest\n            def test_func():\n                assert 0\n        \"\"\"\n        )\n        rep = reports[1]\n        assert not rep.skipped\n        assert not rep.passed\n        assert rep.failed\n        # assert rep.outcome.when == \"call\"\n        # assert rep.failed.where.lineno == 3\n        # assert rep.failed.where.path.basename == \"test_func.py\"\n        # assert rep.failed.failurerepr == \"hello\"\n\n    def test_teardown_final_returncode(self, pytester: Pytester) -> None:\n        rec = pytester.inline_runsource(\n            \"\"\"\n            def test_func():\n                pass\n            def teardown_function(func):\n                raise ValueError(42)\n        \"\"\"\n        )\n        assert rec.ret == 1\n\n    def test_logstart_logfinish_hooks(self, pytester: Pytester) -> None:\n        rec = pytester.inline_runsource(\n            \"\"\"\n            import pytest\n            def test_func():\n                pass\n        \"\"\"\n        )\n        reps = rec.getcalls(\"pytest_runtest_logstart pytest_runtest_logfinish\")\n        assert [x._name for x in reps] == [\n            \"pytest_runtest_logstart\",\n            \"pytest_runtest_logfinish\",\n        ]\n        for rep in reps:\n            assert rep.nodeid == \"test_logstart_logfinish_hooks.py::test_func\"\n            assert rep.location == (\"test_logstart_logfinish_hooks.py\", 1, \"test_func\")\n\n    def test_exact_teardown_issue90(self, pytester: Pytester) -> None:\n        rec = pytester.inline_runsource(\n            \"\"\"\n            import pytest\n\n            class TestClass(object):\n                def test_method(self):\n                    pass\n                def teardown_class(cls):\n                    raise Exception()\n\n            def test_func():\n                import sys\n                # on python2 exc_info is kept till a function exits\n                # so we would end up calling test functions while\n                # sys.exc_info would return the indexerror\n                # from guessing the lastitem\n                excinfo = sys.exc_info()\n                import traceback\n                assert excinfo[0] is None, \\\n                       traceback.format_exception(*excinfo)\n            def teardown_function(func):\n                raise ValueError(42)\n        \"\"\"\n        )\n        reps = rec.getreports(\"pytest_runtest_logreport\")\n        print(reps)\n        for i in range(2):\n            assert reps[i].nodeid.endswith(\"test_method\")\n            assert reps[i].passed\n        assert reps[2].when == \"teardown\"\n        assert reps[2].failed\n        assert len(reps) == 6\n        for i in range(3, 5):\n            assert reps[i].nodeid.endswith(\"test_func\")\n            assert reps[i].passed\n        assert reps[5].when == \"teardown\"\n        assert reps[5].nodeid.endswith(\"test_func\")\n        assert reps[5].failed\n\n    def test_exact_teardown_issue1206(self, pytester: Pytester) -> None:\n        \"\"\"Issue shadowing error with wrong number of arguments on teardown_method.\"\"\"\n        rec = pytester.inline_runsource(\n            \"\"\"\n            import pytest\n\n            class TestClass(object):\n                def teardown_method(self, x, y, z):\n                    pass\n\n                def test_method(self):\n                    assert True\n        \"\"\"\n        )\n        reps = rec.getreports(\"pytest_runtest_logreport\")\n        print(reps)\n        assert len(reps) == 3\n        #\n        assert reps[0].nodeid.endswith(\"test_method\")\n        assert reps[0].passed\n        assert reps[0].when == \"setup\"\n        #\n        assert reps[1].nodeid.endswith(\"test_method\")\n        assert reps[1].passed\n        assert reps[1].when == \"call\"\n        #\n        assert reps[2].nodeid.endswith(\"test_method\")\n        assert reps[2].failed\n        assert reps[2].when == \"teardown\"\n        longrepr = reps[2].longrepr\n        assert isinstance(longrepr, ExceptionChainRepr)\n        assert longrepr.reprcrash\n        assert longrepr.reprcrash.message in (\n            \"TypeError: teardown_method() missing 2 required positional arguments: 'y' and 'z'\",\n            # Python >= 3.10\n            \"TypeError: TestClass.teardown_method() missing 2 required positional arguments: 'y' and 'z'\",\n        )\n\n    def test_failure_in_setup_function_ignores_custom_repr(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            conftest=\"\"\"\n            import pytest\n            class Function(pytest.Function):\n                def repr_failure(self, excinfo):\n                    assert 0\n        \"\"\"\n        )\n        reports = pytester.runitem(\n            \"\"\"\n            def setup_function(func):\n                raise ValueError(42)\n            def test_func():\n                pass\n        \"\"\"\n        )\n        assert len(reports) == 2\n        rep = reports[0]\n        print(rep)\n        assert not rep.skipped\n        assert not rep.passed\n        assert rep.failed\n        # assert rep.outcome.when == \"setup\"\n        # assert rep.outcome.where.lineno == 3\n        # assert rep.outcome.where.path.basename == \"test_func.py\"\n        # assert isinstance(rep.failed.failurerepr, PythonFailureRepr)\n\n    def test_systemexit_does_not_bail_out(self, pytester: Pytester) -> None:\n        try:\n            reports = pytester.runitem(\n                \"\"\"\n                def test_func():\n                    raise SystemExit(42)\n            \"\"\"\n            )\n        except SystemExit:\n            assert False, \"runner did not catch SystemExit\"\n        rep = reports[1]\n        assert rep.failed\n        assert rep.when == \"call\"\n\n    def test_exit_propagates(self, pytester: Pytester) -> None:\n        try:\n            pytester.runitem(\n                \"\"\"\n                import pytest\n                def test_func():\n                    raise pytest.exit.Exception()\n            \"\"\"\n            )\n        except pytest.exit.Exception:\n            pass\n        else:\n            assert False, \"did not raise\"\n\n\nclass TestExecutionNonForked(BaseFunctionalTests):\n    def getrunner(self):\n        def f(item):\n            return runner.runtestprotocol(item, log=False)\n\n        return f\n\n    def test_keyboardinterrupt_propagates(self, pytester: Pytester) -> None:\n        try:\n            pytester.runitem(\n                \"\"\"\n                def test_func():\n                    raise KeyboardInterrupt(\"fake\")\n            \"\"\"\n            )\n        except KeyboardInterrupt:\n            pass\n        else:\n            assert False, \"did not raise\"\n\n\nclass TestSessionReports:\n    def test_collect_result(self, pytester: Pytester) -> None:\n        col = pytester.getmodulecol(\n            \"\"\"\n            def test_func1():\n                pass\n            class TestClass(object):\n                pass\n        \"\"\"\n        )\n        rep = runner.collect_one_node(col)\n        assert not rep.failed\n        assert not rep.skipped\n        assert rep.passed\n        locinfo = rep.location\n        assert locinfo is not None\n        assert locinfo[0] == col.path.name\n        assert not locinfo[1]\n        assert locinfo[2] == col.path.name\n        res = rep.result\n        assert len(res) == 2\n        assert res[0].name == \"test_func1\"\n        assert res[1].name == \"TestClass\"\n\n\nreporttypes: list[type[reports.BaseReport]] = [\n    reports.BaseReport,\n    reports.TestReport,\n    reports.CollectReport,\n]\n\n\n@pytest.mark.parametrize(\n    \"reporttype\", reporttypes, ids=[x.__name__ for x in reporttypes]\n)\ndef test_report_extra_parameters(reporttype: type[reports.BaseReport]) -> None:\n    args = list(inspect.signature(reporttype.__init__).parameters.keys())[1:]\n    basekw: dict[str, list[object]] = {arg: [] for arg in args}\n    report = reporttype(newthing=1, **basekw)\n    assert report.newthing == 1\n\n\ndef test_callinfo() -> None:\n    ci = runner.CallInfo.from_call(lambda: 0, \"collect\")\n    assert ci.when == \"collect\"\n    assert ci.result == 0\n    assert \"result\" in repr(ci)\n    assert repr(ci) == \"<CallInfo when='collect' result: 0>\"\n    assert str(ci) == \"<CallInfo when='collect' result: 0>\"\n\n    ci2 = runner.CallInfo.from_call(lambda: 0 / 0, \"collect\")\n    assert ci2.when == \"collect\"\n    assert not hasattr(ci2, \"result\")\n    assert repr(ci2) == f\"<CallInfo when='collect' excinfo={ci2.excinfo!r}>\"\n    assert str(ci2) == repr(ci2)\n    assert ci2.excinfo\n\n    # Newlines are escaped.\n    def raise_assertion():\n        assert 0, \"assert_msg\"\n\n    ci3 = runner.CallInfo.from_call(raise_assertion, \"call\")\n    assert repr(ci3) == f\"<CallInfo when='call' excinfo={ci3.excinfo!r}>\"\n    assert \"\\n\" not in repr(ci3)\n\n\n# design question: do we want general hooks in python files?\n# then something like the following functional tests makes sense\n\n\n@pytest.mark.xfail\ndef test_runtest_in_module_ordering(pytester: Pytester) -> None:\n    p1 = pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def pytest_runtest_setup(item): # runs after class-level!\n            item.function.mylist.append(\"module\")\n        class TestClass(object):\n            def pytest_runtest_setup(self, item):\n                assert not hasattr(item.function, 'mylist')\n                item.function.mylist = ['class']\n            @pytest.fixture\n            def mylist(self, request):\n                return request.function.mylist\n            @pytest.hookimpl(wrapper=True)\n            def pytest_runtest_call(self, item):\n                try:\n                    yield\n                except ValueError:\n                    pass\n            def test_hello1(self, mylist):\n                assert mylist == ['class', 'module'], mylist\n                raise ValueError()\n            def test_hello2(self, mylist):\n                assert mylist == ['class', 'module'], mylist\n        def pytest_runtest_teardown(item):\n            del item.function.mylist\n    \"\"\"\n    )\n    result = pytester.runpytest(p1)\n    result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_outcomeexception_exceptionattributes() -> None:\n    outcome = outcomes.OutcomeException(\"test\")\n    assert outcome.args[0] == outcome.msg\n\n\ndef test_outcomeexception_passes_except_Exception() -> None:\n    with pytest.raises(outcomes.OutcomeException):\n        try:\n            raise outcomes.OutcomeException(\"test\")\n        except Exception as e:\n            raise NotImplementedError from e\n\n\ndef test_pytest_exit() -> None:\n    with pytest.raises(pytest.exit.Exception) as excinfo:\n        pytest.exit(\"hello\")\n    assert excinfo.errisinstance(pytest.exit.Exception)\n\n\ndef test_pytest_fail() -> None:\n    with pytest.raises(pytest.fail.Exception) as excinfo:\n        pytest.fail(\"hello\")\n    s = excinfo.exconly(tryshort=True)\n    assert s.startswith(\"Failed\")\n\n\ndef test_pytest_exit_msg(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n    import pytest\n\n    def pytest_configure(config):\n        pytest.exit('oh noes')\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stderr.fnmatch_lines([\"Exit: oh noes\"])\n\n\ndef _strip_resource_warnings(lines):\n    # Assert no output on stderr, except for unreliable ResourceWarnings.\n    # (https://github.com/pytest-dev/pytest/issues/5088)\n    return [\n        x\n        for x in lines\n        if not x.startswith((\"Exception ignored in:\", \"ResourceWarning\"))\n    ]\n\n\ndef test_pytest_exit_returncode(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\\\n        import pytest\n        def test_foo():\n            pytest.exit(\"some exit msg\", 99)\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*! *Exit: some exit msg !*\"])\n\n    assert _strip_resource_warnings(result.stderr.lines) == []\n    assert result.ret == 99\n\n    # It prints to stderr also in case of exit during pytest_sessionstart.\n    pytester.makeconftest(\n        \"\"\"\\\n        import pytest\n\n        def pytest_sessionstart():\n            pytest.exit(\"during_sessionstart\", 98)\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*! *Exit: during_sessionstart !*\"])\n    assert _strip_resource_warnings(result.stderr.lines) == [\n        \"Exit: during_sessionstart\"\n    ]\n    assert result.ret == 98\n\n\ndef test_pytest_fail_notrace_runtest(pytester: Pytester) -> None:\n    \"\"\"Test pytest.fail(..., pytrace=False) does not show tracebacks during test run.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def test_hello():\n            pytest.fail(\"hello\", pytrace=False)\n        def teardown_function(function):\n            pytest.fail(\"world\", pytrace=False)\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"world\", \"hello\"])\n    result.stdout.no_fnmatch_line(\"*def teardown_function*\")\n\n\ndef test_pytest_fail_notrace_collection(pytester: Pytester) -> None:\n    \"\"\"Test pytest.fail(..., pytrace=False) does not show tracebacks during collection.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def some_internal_function():\n            pytest.fail(\"hello\", pytrace=False)\n        some_internal_function()\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"hello\"])\n    result.stdout.no_fnmatch_line(\"*def some_internal_function()*\")\n\n\ndef test_pytest_fail_notrace_non_ascii(pytester: Pytester) -> None:\n    \"\"\"Fix pytest.fail with pytrace=False with non-ascii characters (#1178).\n\n    This tests with native and unicode strings containing non-ascii chars.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\\\n        import pytest\n\n        def test_hello():\n            pytest.fail('oh oh: ☺', pytrace=False)\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*test_hello*\", \"oh oh: ☺\"])\n    result.stdout.no_fnmatch_line(\"*def test_hello*\")\n\n\ndef test_pytest_no_tests_collected_exit_status(pytester: Pytester) -> None:\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*collected 0 items*\"])\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n    pytester.makepyfile(\n        test_foo=\"\"\"\n        def test_foo():\n            assert 1\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*collected 1 item*\"])\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n    assert result.ret == ExitCode.OK\n\n    result = pytester.runpytest(\"-k nonmatch\")\n    result.stdout.fnmatch_lines([\"*collected 1 item*\"])\n    result.stdout.fnmatch_lines([\"*1 deselected*\"])\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_exception_printing_skip() -> None:\n    assert pytest.skip.Exception == pytest.skip.Exception\n    try:\n        pytest.skip(\"hello\")\n    except pytest.skip.Exception:\n        excinfo = ExceptionInfo.from_current()\n        s = excinfo.exconly(tryshort=True)\n        assert s.startswith(\"Skipped\")\n\n\ndef test_importorskip(monkeypatch) -> None:\n    importorskip = pytest.importorskip\n\n    def f():\n        importorskip(\"asdlkj\")\n\n    try:\n        sysmod = importorskip(\"sys\")\n        assert sysmod is sys\n        # path = pytest.importorskip(\"os.path\")\n        # assert path == os.path\n        excinfo = pytest.raises(pytest.skip.Exception, f)\n        assert excinfo is not None\n        excrepr = excinfo.getrepr()\n        assert excrepr is not None\n        assert excrepr.reprcrash is not None\n        path = Path(excrepr.reprcrash.path)\n        # check that importorskip reports the actual call\n        # in this test the test_runner.py file\n        assert path.stem == \"test_runner\"\n        pytest.raises(SyntaxError, pytest.importorskip, \"x y z\")\n        pytest.raises(SyntaxError, pytest.importorskip, \"x=y\")\n        mod = types.ModuleType(\"hello123\")\n        mod.__version__ = \"1.3\"  # type: ignore\n        monkeypatch.setitem(sys.modules, \"hello123\", mod)\n        with pytest.raises(pytest.skip.Exception):\n            pytest.importorskip(\"hello123\", minversion=\"1.3.1\")\n        mod2 = pytest.importorskip(\"hello123\", minversion=\"1.3\")\n        assert mod2 == mod\n    except pytest.skip.Exception:  # pragma: no cover\n        assert False, f\"spurious skip: {ExceptionInfo.from_current()}\"\n\n\ndef test_importorskip_imports_last_module_part() -> None:\n    ospath = pytest.importorskip(\"os.path\")\n    assert os.path == ospath\n\n\nclass TestImportOrSkipExcType:\n    \"\"\"Tests for importorskip's exc_type behavior.\"\"\"\n\n    def test_module_not_found_skips_by_default(self) -> None:\n        with pytest.raises(pytest.skip.Exception):\n            pytest.importorskip(\n                \"TestImportOrSkipExcType_test_module_not_found_skips_without_warning\"\n            )\n\n    def test_import_error_is_propagated_by_default(self, pytester: Pytester) -> None:\n        fn = pytester.makepyfile(\"raise ImportError('some specific problem')\")\n        pytester.syspathinsert()\n\n        with pytest.raises(ImportError, match=\"some specific problem\"):\n            pytest.importorskip(fn.stem)\n\n    def test_import_error_can_be_captured_explicitly(self, pytester: Pytester) -> None:\n        fn = pytester.makepyfile(\"raise ImportError('some specific problem')\")\n        pytester.syspathinsert()\n\n        with pytest.raises(pytest.skip.Exception):\n            pytest.importorskip(fn.stem, exc_type=ImportError)\n\n    def test_import_error_integration(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_foo():\n                pytest.importorskip(\"warning_integration_module\")\n            \"\"\"\n        )\n        pytester.makepyfile(\n            warning_integration_module=\"\"\"\n                raise ImportError(\"required library foobar not compiled properly\")\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\"*ImportError: required library foobar not compiled properly*\"]\n        )\n        result.assert_outcomes(failed=1)\n\n\ndef test_importorskip_dev_module(monkeypatch) -> None:\n    try:\n        mod = types.ModuleType(\"mockmodule\")\n        mod.__version__ = \"0.13.0.dev-43290\"  # type: ignore\n        monkeypatch.setitem(sys.modules, \"mockmodule\", mod)\n        mod2 = pytest.importorskip(\"mockmodule\", minversion=\"0.12.0\")\n        assert mod2 == mod\n        with pytest.raises(pytest.skip.Exception):\n            pytest.importorskip(\"mockmodule1\", minversion=\"0.14.0\")\n    except pytest.skip.Exception:  # pragma: no cover\n        assert False, f\"spurious skip: {ExceptionInfo.from_current()}\"\n\n\ndef test_importorskip_module_level(pytester: Pytester) -> None:\n    \"\"\"`importorskip` must be able to skip entire modules when used at module level.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        foobarbaz = pytest.importorskip(\"foobarbaz\")\n\n        def test_foo():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*collected 0 items / 1 skipped*\"])\n\n\ndef test_importorskip_custom_reason(pytester: Pytester) -> None:\n    \"\"\"Make sure custom reasons are used.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        foobarbaz = pytest.importorskip(\"foobarbaz2\", reason=\"just because\")\n\n        def test_foo():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-ra\")\n    result.stdout.fnmatch_lines([\"*just because*\"])\n    result.stdout.fnmatch_lines([\"*collected 0 items / 1 skipped*\"])\n\n\ndef test_pytest_cmdline_main(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def test_hello():\n            assert 1\n        if __name__ == '__main__':\n           pytest.cmdline.main([__file__])\n    \"\"\"\n    )\n    import subprocess\n\n    popen = subprocess.Popen([sys.executable, str(p)], stdout=subprocess.PIPE)\n    popen.communicate()\n    ret = popen.wait()\n    assert ret == 0\n\n\ndef test_unicode_in_longrepr(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\\\n        import pytest\n        @pytest.hookimpl(wrapper=True)\n        def pytest_runtest_makereport():\n            rep = yield\n            if rep.when == \"call\":\n                rep.longrepr = 'ä'\n            return rep\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        def test_out():\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 1\n    assert \"UnicodeEncodeError\" not in result.stderr.str()\n\n\ndef test_failure_in_setup(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def setup_module():\n            0/0\n        def test_func():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--tb=line\")\n    result.stdout.no_fnmatch_line(\"*def setup_module*\")\n\n\ndef test_makereport_getsource(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_foo():\n            if False: pass\n            else: assert False\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.no_fnmatch_line(\"*INTERNALERROR*\")\n    result.stdout.fnmatch_lines([\"*else: assert False*\"])\n\n\ndef test_makereport_getsource_dynamic_code(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    \"\"\"Test that exception in dynamically generated code doesn't break getting the source line.\"\"\"\n    import inspect\n\n    original_findsource = inspect.findsource\n\n    def findsource(obj):\n        # Can be triggered by dynamically created functions\n        if obj.__name__ == \"foo\":\n            raise IndexError()\n        return original_findsource(obj)\n\n    monkeypatch.setattr(inspect, \"findsource\", findsource)\n\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def foo(missing):\n            pass\n\n        def test_fix(foo):\n            assert False\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-vv\")\n    result.stdout.no_fnmatch_line(\"*INTERNALERROR*\")\n    result.stdout.fnmatch_lines([\"*test_fix*\", \"*fixture*'missing'*not found*\"])\n\n\ndef test_store_except_info_on_error() -> None:\n    \"\"\"Test that upon test failure, the exception info is stored on\n    sys.last_traceback and friends.\"\"\"\n\n    # Simulate item that might raise a specific exception, depending on `raise_error` class var\n    class ItemMightRaise:\n        nodeid = \"item_that_raises\"\n        raise_error = True\n\n        def runtest(self):\n            if self.raise_error:\n                raise IndexError(\"TEST\")\n\n    try:\n        runner.pytest_runtest_call(ItemMightRaise())  # type: ignore[arg-type]\n    except IndexError:\n        pass\n    # Check that exception info is stored on sys\n    assert sys.last_type is IndexError\n    assert isinstance(sys.last_value, IndexError)\n    if sys.version_info >= (3, 12, 0):\n        assert isinstance(sys.last_exc, IndexError)  # type:ignore[attr-defined]\n\n    assert sys.last_value.args[0] == \"TEST\"\n    assert sys.last_traceback\n\n    # The next run should clear the exception info stored by the previous run\n    ItemMightRaise.raise_error = False\n    runner.pytest_runtest_call(ItemMightRaise())  # type: ignore[arg-type]\n    assert not hasattr(sys, \"last_type\")\n    assert not hasattr(sys, \"last_value\")\n    if sys.version_info >= (3, 12, 0):\n        assert not hasattr(sys, \"last_exc\")\n    assert not hasattr(sys, \"last_traceback\")\n\n\ndef test_current_test_env_var(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n    pytest_current_test_vars: list[tuple[str, str]] = []\n    monkeypatch.setattr(\n        sys, \"pytest_current_test_vars\", pytest_current_test_vars, raising=False\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import sys\n        import os\n\n        @pytest.fixture\n        def fix():\n            sys.pytest_current_test_vars.append(('setup', os.environ['PYTEST_CURRENT_TEST']))\n            yield\n            sys.pytest_current_test_vars.append(('teardown', os.environ['PYTEST_CURRENT_TEST']))\n\n        def test(fix):\n            sys.pytest_current_test_vars.append(('call', os.environ['PYTEST_CURRENT_TEST']))\n    \"\"\"\n    )\n    result = pytester.runpytest_inprocess()\n    assert result.ret == 0\n    test_id = \"test_current_test_env_var.py::test\"\n    assert pytest_current_test_vars == [\n        (\"setup\", test_id + \" (setup)\"),\n        (\"call\", test_id + \" (call)\"),\n        (\"teardown\", test_id + \" (teardown)\"),\n    ]\n    assert \"PYTEST_CURRENT_TEST\" not in os.environ\n\n\nclass TestReportContents:\n    \"\"\"Test user-level API of ``TestReport`` objects.\"\"\"\n\n    def getrunner(self):\n        return lambda item: runner.runtestprotocol(item, log=False)\n\n    def test_longreprtext_pass(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            def test_func():\n                pass\n        \"\"\"\n        )\n        rep = reports[1]\n        assert rep.longreprtext == \"\"\n\n    def test_longreprtext_skip(self, pytester: Pytester) -> None:\n        \"\"\"TestReport.longreprtext can handle non-str ``longrepr`` attributes (#7559)\"\"\"\n        reports = pytester.runitem(\n            \"\"\"\n            import pytest\n            def test_func():\n                pytest.skip()\n            \"\"\"\n        )\n        _, call_rep, _ = reports\n        assert isinstance(call_rep.longrepr, tuple)\n        assert \"Skipped\" in call_rep.longreprtext\n\n    def test_longreprtext_collect_skip(self, pytester: Pytester) -> None:\n        \"\"\"CollectReport.longreprtext can handle non-str ``longrepr`` attributes (#7559)\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            pytest.skip(allow_module_level=True)\n            \"\"\"\n        )\n        rec = pytester.inline_run()\n        calls = rec.getcalls(\"pytest_collectreport\")\n        _, call, _ = calls\n        assert isinstance(call.report.longrepr, tuple)\n        assert \"Skipped\" in call.report.longreprtext\n\n    def test_longreprtext_failure(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            def test_func():\n                x = 1\n                assert x == 4\n        \"\"\"\n        )\n        rep = reports[1]\n        assert \"assert 1 == 4\" in rep.longreprtext\n\n    def test_captured_text(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            import pytest\n            import sys\n\n            @pytest.fixture\n            def fix():\n                sys.stdout.write('setup: stdout\\\\n')\n                sys.stderr.write('setup: stderr\\\\n')\n                yield\n                sys.stdout.write('teardown: stdout\\\\n')\n                sys.stderr.write('teardown: stderr\\\\n')\n                assert 0\n\n            def test_func(fix):\n                sys.stdout.write('call: stdout\\\\n')\n                sys.stderr.write('call: stderr\\\\n')\n                assert 0\n        \"\"\"\n        )\n        setup, call, teardown = reports\n        assert setup.capstdout == \"setup: stdout\\n\"\n        assert call.capstdout == \"setup: stdout\\ncall: stdout\\n\"\n        assert teardown.capstdout == \"setup: stdout\\ncall: stdout\\nteardown: stdout\\n\"\n\n        assert setup.capstderr == \"setup: stderr\\n\"\n        assert call.capstderr == \"setup: stderr\\ncall: stderr\\n\"\n        assert teardown.capstderr == \"setup: stderr\\ncall: stderr\\nteardown: stderr\\n\"\n\n    def test_no_captured_text(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            def test_func():\n                pass\n        \"\"\"\n        )\n        rep = reports[1]\n        assert rep.capstdout == \"\"\n        assert rep.capstderr == \"\"\n\n    def test_longrepr_type(self, pytester: Pytester) -> None:\n        reports = pytester.runitem(\n            \"\"\"\n            import pytest\n            def test_func():\n                pytest.fail(pytrace=False)\n        \"\"\"\n        )\n        rep = reports[1]\n        assert isinstance(rep.longrepr, ExceptionChainRepr)\n\n\ndef test_outcome_exception_bad_msg() -> None:\n    \"\"\"Check that OutcomeExceptions validate their input to prevent confusing errors (#5578)\"\"\"\n\n    def func() -> None:\n        raise NotImplementedError()\n\n    expected = (\n        \"OutcomeException expected string as 'msg' parameter, got 'function' instead.\\n\"\n        \"Perhaps you meant to use a mark?\"\n    )\n    with pytest.raises(TypeError) as excinfo:\n        OutcomeException(func)  # type: ignore\n    assert str(excinfo.value) == expected\n\n\ndef test_pytest_version_env_var(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n    monkeypatch.setenv(\"PYTEST_VERSION\", \"old version\")\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import os\n\n\n        def test():\n            assert os.environ.get(\"PYTEST_VERSION\") == pytest.__version__\n    \"\"\"\n    )\n    result = pytester.runpytest_inprocess()\n    assert result.ret == ExitCode.OK\n    assert os.environ[\"PYTEST_VERSION\"] == \"old version\"\n\n\ndef test_teardown_session_failed(pytester: Pytester) -> None:\n    \"\"\"Test that higher-scoped fixture teardowns run in the context of the last\n    item after the test session bails early due to --maxfail.\n\n    Regression test for #11706.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture(scope=\"module\")\n        def baz():\n            yield\n            pytest.fail(\"This is a failing teardown\")\n\n        def test_foo(baz):\n            pytest.fail(\"This is a failing test\")\n\n        def test_bar(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--maxfail=1\")\n    result.assert_outcomes(failed=1, errors=1)\n\n\ndef test_teardown_session_stopped(pytester: Pytester) -> None:\n    \"\"\"Test that higher-scoped fixture teardowns run in the context of the last\n    item after the test session bails early due to --stepwise.\n\n    Regression test for #11706.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture(scope=\"module\")\n        def baz():\n            yield\n            pytest.fail(\"This is a failing teardown\")\n\n        def test_foo(baz):\n            pytest.fail(\"This is a failing test\")\n\n        def test_bar(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--stepwise\")\n    result.assert_outcomes(failed=1, errors=1)\n"
  },
  {
    "path": "testing/test_runner_xunit.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Test correct setup/teardowns at module, class, and instance level.\"\"\"\n\nfrom __future__ import annotations\n\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\ndef test_module_and_function_setup(pytester: Pytester) -> None:\n    reprec = pytester.inline_runsource(\n        \"\"\"\n        modlevel = []\n        def setup_module(module):\n            assert not modlevel\n            module.modlevel.append(42)\n\n        def teardown_module(module):\n            modlevel.pop()\n\n        def setup_function(function):\n            function.answer = 17\n\n        def teardown_function(function):\n            del function.answer\n\n        def test_modlevel():\n            assert modlevel[0] == 42\n            assert test_modlevel.answer == 17\n\n        class TestFromClass(object):\n            def test_module(self):\n                assert modlevel[0] == 42\n                assert not hasattr(test_modlevel, 'answer')\n    \"\"\"\n    )\n    rep = reprec.matchreport(\"test_modlevel\")\n    assert rep.passed\n    rep = reprec.matchreport(\"test_module\")\n    assert rep.passed\n\n\ndef test_module_setup_failure_no_teardown(pytester: Pytester) -> None:\n    reprec = pytester.inline_runsource(\n        \"\"\"\n        values = []\n        def setup_module(module):\n            values.append(1)\n            0/0\n\n        def test_nothing():\n            pass\n\n        def teardown_module(module):\n            values.append(2)\n    \"\"\"\n    )\n    reprec.assertoutcome(failed=1)\n    calls = reprec.getcalls(\"pytest_runtest_setup\")\n    assert calls[0].item.module.values == [1]\n\n\ndef test_setup_function_failure_no_teardown(pytester: Pytester) -> None:\n    reprec = pytester.inline_runsource(\n        \"\"\"\n        modlevel = []\n        def setup_function(function):\n            modlevel.append(1)\n            0/0\n\n        def teardown_function(module):\n            modlevel.append(2)\n\n        def test_func():\n            pass\n    \"\"\"\n    )\n    calls = reprec.getcalls(\"pytest_runtest_setup\")\n    assert calls[0].item.module.modlevel == [1]\n\n\ndef test_class_setup(pytester: Pytester) -> None:\n    reprec = pytester.inline_runsource(\n        \"\"\"\n        class TestSimpleClassSetup(object):\n            clslevel = []\n            def setup_class(cls):\n                cls.clslevel.append(23)\n\n            def teardown_class(cls):\n                cls.clslevel.pop()\n\n            def test_classlevel(self):\n                assert self.clslevel[0] == 23\n\n        class TestInheritedClassSetupStillWorks(TestSimpleClassSetup):\n            def test_classlevel_anothertime(self):\n                assert self.clslevel == [23]\n\n        def test_cleanup():\n            assert not TestSimpleClassSetup.clslevel\n            assert not TestInheritedClassSetupStillWorks.clslevel\n    \"\"\"\n    )\n    reprec.assertoutcome(passed=1 + 2 + 1)\n\n\ndef test_class_setup_failure_no_teardown(pytester: Pytester) -> None:\n    reprec = pytester.inline_runsource(\n        \"\"\"\n        class TestSimpleClassSetup(object):\n            clslevel = []\n            def setup_class(cls):\n                0/0\n\n            def teardown_class(cls):\n                cls.clslevel.append(1)\n\n            def test_classlevel(self):\n                pass\n\n        def test_cleanup():\n            assert not TestSimpleClassSetup.clslevel\n    \"\"\"\n    )\n    reprec.assertoutcome(failed=1, passed=1)\n\n\ndef test_method_setup(pytester: Pytester) -> None:\n    reprec = pytester.inline_runsource(\n        \"\"\"\n        class TestSetupMethod(object):\n            def setup_method(self, meth):\n                self.methsetup = meth\n            def teardown_method(self, meth):\n                del self.methsetup\n\n            def test_some(self):\n                assert self.methsetup == self.test_some\n\n            def test_other(self):\n                assert self.methsetup == self.test_other\n    \"\"\"\n    )\n    reprec.assertoutcome(passed=2)\n\n\ndef test_method_setup_failure_no_teardown(pytester: Pytester) -> None:\n    reprec = pytester.inline_runsource(\n        \"\"\"\n        class TestMethodSetup(object):\n            clslevel = []\n            def setup_method(self, method):\n                self.clslevel.append(1)\n                0/0\n\n            def teardown_method(self, method):\n                self.clslevel.append(2)\n\n            def test_method(self):\n                pass\n\n        def test_cleanup():\n            assert TestMethodSetup.clslevel == [1]\n    \"\"\"\n    )\n    reprec.assertoutcome(failed=1, passed=1)\n\n\ndef test_method_setup_uses_fresh_instances(pytester: Pytester) -> None:\n    reprec = pytester.inline_runsource(\n        \"\"\"\n        class TestSelfState1(object):\n            memory = []\n            def test_hello(self):\n                self.memory.append(self)\n\n            def test_afterhello(self):\n                assert self != self.memory[0]\n    \"\"\"\n    )\n    reprec.assertoutcome(passed=2, failed=0)\n\n\ndef test_setup_that_skips_calledagain(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def setup_module(mod):\n            pytest.skip(\"x\")\n        def test_function1():\n            pass\n        def test_function2():\n            pass\n    \"\"\"\n    )\n    reprec = pytester.inline_run(p)\n    reprec.assertoutcome(skipped=2)\n\n\ndef test_setup_fails_again_on_all_tests(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def setup_module(mod):\n            raise ValueError(42)\n        def test_function1():\n            pass\n        def test_function2():\n            pass\n    \"\"\"\n    )\n    reprec = pytester.inline_run(p)\n    reprec.assertoutcome(failed=2)\n\n\ndef test_setup_funcarg_setup_when_outer_scope_fails(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def setup_module(mod):\n            raise ValueError(42)\n        @pytest.fixture\n        def hello(request):\n            raise ValueError(\"xyz43\")\n        def test_function1(hello):\n            pass\n        def test_function2(hello):\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest(p)\n    result.stdout.fnmatch_lines(\n        [\n            \"*function1*\",\n            \"*ValueError*42*\",\n            \"*function2*\",\n            \"*ValueError*42*\",\n            \"*2 errors*\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*xyz43*\")\n\n\n@pytest.mark.parametrize(\"arg\", [\"\", \"arg\"])\ndef test_setup_teardown_function_level_with_optional_argument(\n    pytester: Pytester,\n    monkeypatch,\n    arg: str,\n) -> None:\n    \"\"\"Parameter to setup/teardown xunit-style functions parameter is now optional (#1728).\"\"\"\n    import sys\n\n    trace_setups_teardowns: list[str] = []\n    monkeypatch.setattr(\n        sys, \"trace_setups_teardowns\", trace_setups_teardowns, raising=False\n    )\n    p = pytester.makepyfile(\n        f\"\"\"\n        import pytest\n        import sys\n\n        trace = sys.trace_setups_teardowns.append\n\n        def setup_module({arg}): trace('setup_module')\n        def teardown_module({arg}): trace('teardown_module')\n\n        def setup_function({arg}): trace('setup_function')\n        def teardown_function({arg}): trace('teardown_function')\n\n        def test_function_1(): pass\n        def test_function_2(): pass\n\n        class Test(object):\n            def setup_method(self, {arg}): trace('setup_method')\n            def teardown_method(self, {arg}): trace('teardown_method')\n\n            def test_method_1(self): pass\n            def test_method_2(self): pass\n    \"\"\"\n    )\n    result = pytester.inline_run(p)\n    result.assertoutcome(passed=4)\n\n    expected = [\n        \"setup_module\",\n        \"setup_function\",\n        \"teardown_function\",\n        \"setup_function\",\n        \"teardown_function\",\n        \"setup_method\",\n        \"teardown_method\",\n        \"setup_method\",\n        \"teardown_method\",\n        \"teardown_module\",\n    ]\n    assert trace_setups_teardowns == expected\n"
  },
  {
    "path": "testing/test_scope.py",
    "content": "from __future__ import annotations\n\nimport re\n\nfrom _pytest.scope import Scope\nimport pytest\n\n\ndef test_ordering() -> None:\n    assert Scope.Session > Scope.Package\n    assert Scope.Package > Scope.Module\n    assert Scope.Module > Scope.Class\n    assert Scope.Class > Scope.Function\n\n\ndef test_next_lower() -> None:\n    assert Scope.Session.next_lower() is Scope.Package\n    assert Scope.Package.next_lower() is Scope.Module\n    assert Scope.Module.next_lower() is Scope.Class\n    assert Scope.Class.next_lower() is Scope.Function\n\n    with pytest.raises(ValueError, match=\"Function is the lower-most scope\"):\n        Scope.Function.next_lower()\n\n\ndef test_next_higher() -> None:\n    assert Scope.Function.next_higher() is Scope.Class\n    assert Scope.Class.next_higher() is Scope.Module\n    assert Scope.Module.next_higher() is Scope.Package\n    assert Scope.Package.next_higher() is Scope.Session\n\n    with pytest.raises(ValueError, match=\"Session is the upper-most scope\"):\n        Scope.Session.next_higher()\n\n\ndef test_from_user() -> None:\n    assert Scope.from_user(\"module\", \"for parametrize\", \"some::id\") is Scope.Module\n\n    expected_msg = \"for parametrize from some::id got an unexpected scope value 'foo'\"\n    with pytest.raises(pytest.fail.Exception, match=re.escape(expected_msg)):\n        Scope.from_user(\"foo\", \"for parametrize\", \"some::id\")  # type:ignore[arg-type]\n"
  },
  {
    "path": "testing/test_session.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom _pytest.config import ExitCode\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nclass SessionTests:\n    def test_basic_testitem_events(self, pytester: Pytester) -> None:\n        tfile = pytester.makepyfile(\n            \"\"\"\n            def test_one():\n                pass\n            def test_one_one():\n                assert 0\n            def test_other():\n                raise ValueError(23)\n            class TestClass(object):\n                def test_two(self, someargs):\n                    pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(tfile)\n        passed, skipped, failed = reprec.listoutcomes()\n        assert len(skipped) == 0\n        assert len(passed) == 1\n        assert len(failed) == 3\n\n        def end(x):\n            return x.nodeid.split(\"::\")[-1]\n\n        assert end(failed[0]) == \"test_one_one\"\n        assert end(failed[1]) == \"test_other\"\n        itemstarted = reprec.getcalls(\"pytest_itemcollected\")\n        assert len(itemstarted) == 4\n        # XXX check for failing funcarg setup\n        # colreports = reprec.getcalls(\"pytest_collectreport\")\n        # assert len(colreports) == 4\n        # assert colreports[1].report.failed\n\n    def test_nested_import_error(self, pytester: Pytester) -> None:\n        tfile = pytester.makepyfile(\n            \"\"\"\n            import import_fails\n            def test_this():\n                assert import_fails.a == 1\n        \"\"\",\n            import_fails=\"\"\"\n            import does_not_work\n            a = 1\n        \"\"\",\n        )\n        reprec = pytester.inline_run(tfile)\n        values = reprec.getfailedcollections()\n        assert len(values) == 1\n        out = str(values[0].longrepr)\n        assert out.find(\"does_not_work\") != -1\n\n    def test_raises_output(self, pytester: Pytester) -> None:\n        reprec = pytester.inline_runsource(\n            \"\"\"\n            import pytest\n            def test_raises_doesnt():\n                pytest.raises(ValueError, int, \"3\")\n        \"\"\"\n        )\n        _passed, _skipped, failed = reprec.listoutcomes()\n        assert len(failed) == 1\n        out = failed[0].longrepr.reprcrash.message  # type: ignore[union-attr]\n        assert \"DID NOT RAISE\" in out\n\n    def test_syntax_error_module(self, pytester: Pytester) -> None:\n        reprec = pytester.inline_runsource(\"this is really not python\")\n        values = reprec.getfailedcollections()\n        assert len(values) == 1\n        out = str(values[0].longrepr)\n        assert out.find(\"not python\") != -1\n\n    def test_exit_first_problem(self, pytester: Pytester) -> None:\n        reprec = pytester.inline_runsource(\n            \"\"\"\n            def test_one(): assert 0\n            def test_two(): assert 0\n        \"\"\",\n            \"--exitfirst\",\n        )\n        passed, skipped, failed = reprec.countoutcomes()\n        assert failed == 1\n        assert passed == skipped == 0\n\n    def test_maxfail(self, pytester: Pytester) -> None:\n        reprec = pytester.inline_runsource(\n            \"\"\"\n            def test_one(): assert 0\n            def test_two(): assert 0\n            def test_three(): assert 0\n        \"\"\",\n            \"--maxfail=2\",\n        )\n        passed, skipped, failed = reprec.countoutcomes()\n        assert failed == 2\n        assert passed == skipped == 0\n\n    def test_broken_repr(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            class reprexc(BaseException):\n                def __str__(self):\n                    return \"Ha Ha fooled you, I'm a broken repr().\"\n\n            class BrokenRepr1(object):\n                foo=0\n                def __repr__(self):\n                    raise reprexc\n\n            class TestBrokenClass(object):\n                def test_explicit_bad_repr(self):\n                    t = BrokenRepr1()\n                    with pytest.raises(BaseException, match=\"broken repr\"):\n                        repr(t)\n\n                def test_implicit_bad_repr1(self):\n                    t = BrokenRepr1()\n                    assert t.foo == 1\n\n        \"\"\"\n        )\n        reprec = pytester.inline_run(p)\n        passed, skipped, failed = reprec.listoutcomes()\n        assert (len(passed), len(skipped), len(failed)) == (1, 0, 1)\n        out = failed[0].longrepr.reprcrash.message  # type: ignore[union-attr]\n        assert out.find(\"<[reprexc() raised in repr()] BrokenRepr1\") != -1\n\n    def test_broken_repr_with_showlocals_verbose(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            class ObjWithErrorInRepr:\n                def __repr__(self):\n                    raise NotImplementedError\n\n            def test_repr_error():\n                x = ObjWithErrorInRepr()\n                assert x == \"value\"\n        \"\"\"\n        )\n        reprec = pytester.inline_run(\"--showlocals\", \"-vv\", p)\n        passed, skipped, failed = reprec.listoutcomes()\n        assert (len(passed), len(skipped), len(failed)) == (0, 0, 1)\n        entries = failed[0].longrepr.reprtraceback.reprentries  # type: ignore[union-attr]\n        assert len(entries) == 1\n        repr_locals = entries[0].reprlocals\n        assert repr_locals.lines\n        assert len(repr_locals.lines) == 1\n        assert repr_locals.lines[0].startswith(\n            \"x          = <[NotImplementedError() raised in repr()] ObjWithErrorInRepr\"\n        )\n\n    def test_skip_file_by_conftest(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            conftest=\"\"\"\n            import pytest\n            def pytest_collect_file():\n                pytest.skip(\"intentional\")\n        \"\"\",\n            test_file=\"\"\"\n            def test_one(): pass\n        \"\"\",\n        )\n        try:\n            reprec = pytester.inline_run(pytester.path)\n        except pytest.skip.Exception:  # pragma: no cover\n            pytest.fail(\"wrong skipped caught\")\n        reports = reprec.getreports(\"pytest_collectreport\")\n        # Session, Dir\n        assert len(reports) == 2\n        assert reports[1].skipped\n\n\nclass TestNewSession(SessionTests):\n    def test_order_of_execution(self, pytester: Pytester) -> None:\n        reprec = pytester.inline_runsource(\n            \"\"\"\n            values = []\n            def test_1():\n                values.append(1)\n            def test_2():\n                values.append(2)\n            def test_3():\n                assert values == [1,2]\n            class Testmygroup(object):\n                reslist = values\n                def test_1(self):\n                    self.reslist.append(1)\n                def test_2(self):\n                    self.reslist.append(2)\n                def test_3(self):\n                    self.reslist.append(3)\n                def test_4(self):\n                    assert self.reslist == [1,2,1,2,3]\n        \"\"\"\n        )\n        passed, skipped, failed = reprec.countoutcomes()\n        assert failed == skipped == 0\n        assert passed == 7\n\n    def test_collect_only_with_various_situations(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            test_one=\"\"\"\n                def test_one():\n                    raise ValueError()\n\n                class TestX(object):\n                    def test_method_one(self):\n                        pass\n\n                class TestY(TestX):\n                    pass\n            \"\"\",\n            test_three=\"xxxdsadsadsadsa\",\n            __init__=\"\",\n        )\n        reprec = pytester.inline_run(\"--collect-only\", p.parent)\n\n        itemstarted = reprec.getcalls(\"pytest_itemcollected\")\n        assert len(itemstarted) == 3\n        assert not reprec.getreports(\"pytest_runtest_logreport\")\n        started = reprec.getcalls(\"pytest_collectstart\")\n        finished = reprec.getreports(\"pytest_collectreport\")\n        assert len(started) == len(finished)\n        assert len(started) == 6\n        colfail = [x for x in finished if x.failed]\n        assert len(colfail) == 1\n\n    def test_minus_x_import_error(self, pytester: Pytester) -> None:\n        pytester.makepyfile(__init__=\"\")\n        pytester.makepyfile(test_one=\"xxxx\", test_two=\"yyyy\")\n        reprec = pytester.inline_run(\"-x\", pytester.path)\n        finished = reprec.getreports(\"pytest_collectreport\")\n        colfail = [x for x in finished if x.failed]\n        assert len(colfail) == 1\n\n    def test_minus_x_overridden_by_maxfail(self, pytester: Pytester) -> None:\n        pytester.makepyfile(__init__=\"\")\n        pytester.makepyfile(test_one=\"xxxx\", test_two=\"yyyy\", test_third=\"zzz\")\n        reprec = pytester.inline_run(\"-x\", \"--maxfail=2\", pytester.path)\n        finished = reprec.getreports(\"pytest_collectreport\")\n        colfail = [x for x in finished if x.failed]\n        assert len(colfail) == 2\n\n\ndef test_plugin_specify(pytester: Pytester) -> None:\n    with pytest.raises(ImportError):\n        pytester.parseconfig(\"-p\", \"nqweotexistent\")\n    # pytest.raises(ImportError,\n    #    \"config.do_configure(config)\"\n    # )\n\n\ndef test_plugin_already_exists(pytester: Pytester) -> None:\n    config = pytester.parseconfig(\"-p\", \"terminal\")\n    assert config.option.plugins == [\"terminal\"]\n    config._do_configure()\n    config._ensure_unconfigure()\n\n\ndef test_exclude(pytester: Pytester) -> None:\n    hellodir = pytester.mkdir(\"hello\")\n    hellodir.joinpath(\"test_hello.py\").write_text(\"x y syntaxerror\", encoding=\"utf-8\")\n    hello2dir = pytester.mkdir(\"hello2\")\n    hello2dir.joinpath(\"test_hello2.py\").write_text(\"x y syntaxerror\", encoding=\"utf-8\")\n    pytester.makepyfile(test_ok=\"def test_pass(): pass\")\n    result = pytester.runpytest(\"--ignore=hello\", \"--ignore=hello2\")\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_exclude_glob(pytester: Pytester) -> None:\n    hellodir = pytester.mkdir(\"hello\")\n    hellodir.joinpath(\"test_hello.py\").write_text(\"x y syntaxerror\", encoding=\"utf-8\")\n    hello2dir = pytester.mkdir(\"hello2\")\n    hello2dir.joinpath(\"test_hello2.py\").write_text(\"x y syntaxerror\", encoding=\"utf-8\")\n    hello3dir = pytester.mkdir(\"hallo3\")\n    hello3dir.joinpath(\"test_hello3.py\").write_text(\"x y syntaxerror\", encoding=\"utf-8\")\n    subdir = pytester.mkdir(\"sub\")\n    subdir.joinpath(\"test_hello4.py\").write_text(\"x y syntaxerror\", encoding=\"utf-8\")\n    pytester.makepyfile(test_ok=\"def test_pass(): pass\")\n    result = pytester.runpytest(\"--ignore-glob=*h[ea]llo*\")\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_deselect(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_a=\"\"\"\n        import pytest\n\n        def test_a1(): pass\n\n        @pytest.mark.parametrize('b', range(3))\n        def test_a2(b): pass\n\n        class TestClass:\n            def test_c1(self): pass\n\n            def test_c2(self): pass\n    \"\"\"\n    )\n    result = pytester.runpytest(\n        \"-v\",\n        \"--deselect=test_a.py::test_a2[1]\",\n        \"--deselect=test_a.py::test_a2[2]\",\n        \"--deselect=test_a.py::TestClass::test_c1\",\n    )\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*3 passed, 3 deselected*\"])\n    for line in result.stdout.lines:\n        assert not line.startswith((\"test_a.py::test_a2[1]\", \"test_a.py::test_a2[2]\"))\n\n\ndef test_sessionfinish_with_start(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        import os\n        values = []\n        def pytest_sessionstart():\n            values.append(os.getcwd())\n            os.chdir(\"..\")\n\n        def pytest_sessionfinish():\n            assert values[0] == os.getcwd()\n\n    \"\"\"\n    )\n    res = pytester.runpytest(\"--collect-only\")\n    assert res.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_collection_args_do_not_duplicate_modules(pytester: Pytester) -> None:\n    \"\"\"Test that when multiple collection args are specified on the command line\n    for the same module, only a single Module collector is created.\n\n    Regression test for #723, #3358.\n    \"\"\"\n    pytester.makepyfile(\n        **{\n            \"d/test_it\": \"\"\"\n                def test_1(): pass\n                def test_2(): pass\n                \"\"\"\n        }\n    )\n\n    result = pytester.runpytest(\n        \"--collect-only\",\n        \"d/test_it.py::test_1\",\n        \"d/test_it.py::test_2\",\n    )\n    result.stdout.fnmatch_lines(\n        [\n            \"  <Dir d>\",\n            \"    <Module test_it.py>\",\n            \"      <Function test_1>\",\n            \"      <Function test_2>\",\n        ],\n        consecutive=True,\n    )\n\n    # Different, but related case.\n    result = pytester.runpytest(\n        \"--collect-only\",\n        \"--keep-duplicates\",\n        \"d\",\n        \"d\",\n    )\n    result.stdout.fnmatch_lines(\n        [\n            \"  <Dir d>\",\n            \"    <Module test_it.py>\",\n            \"      <Function test_1>\",\n            \"      <Function test_2>\",\n            \"      <Function test_1>\",\n            \"      <Function test_2>\",\n        ],\n        consecutive=True,\n    )\n\n\n@pytest.mark.parametrize(\"path\", [\"root\", \"{relative}/root\", \"{environment}/root\"])\ndef test_rootdir_option_arg(\n    pytester: Pytester, monkeypatch: MonkeyPatch, path: str\n) -> None:\n    monkeypatch.setenv(\"PY_ROOTDIR_PATH\", str(pytester.path))\n    path = path.format(relative=str(pytester.path), environment=\"$PY_ROOTDIR_PATH\")\n\n    rootdir = pytester.path / \"root\" / \"tests\"\n    rootdir.mkdir(parents=True)\n    pytester.makepyfile(\n        \"\"\"\n        import os\n        def test_one():\n            assert 1\n    \"\"\"\n    )\n\n    result = pytester.runpytest(f\"--rootdir={path}\")\n    result.stdout.fnmatch_lines(\n        [\n            f\"*rootdir: {pytester.path}/root\",\n            \"root/test_rootdir_option_arg.py *\",\n            \"*1 passed*\",\n        ]\n    )\n\n\ndef test_rootdir_wrong_option_arg(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--rootdir=wrong_dir\")\n    result.stderr.fnmatch_lines(\n        [\"*Directory *wrong_dir* not found. Check your '--rootdir' option.*\"]\n    )\n\n\ndef test_shouldfail_is_sticky(pytester: Pytester) -> None:\n    \"\"\"Test that session.shouldfail cannot be reset to False after being set.\n\n    Issue #11706.\n    \"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_sessionfinish(session):\n            assert session.shouldfail\n            session.shouldfail = False\n            assert session.shouldfail\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def test_foo():\n            pytest.fail(\"This is a failing test\")\n\n        def test_bar(): pass\n        \"\"\"\n    )\n\n    result = pytester.runpytest(\"--maxfail=1\", \"-Wall\")\n\n    result.assert_outcomes(failed=1, warnings=1)\n    result.stdout.fnmatch_lines(\"*session.shouldfail cannot be unset*\")\n\n\ndef test_shouldstop_is_sticky(pytester: Pytester) -> None:\n    \"\"\"Test that session.shouldstop cannot be reset to False after being set.\n\n    Issue #11706.\n    \"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_sessionfinish(session):\n            assert session.shouldstop\n            session.shouldstop = False\n            assert session.shouldstop\n        \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def test_foo():\n            pytest.fail(\"This is a failing test\")\n\n        def test_bar(): pass\n        \"\"\"\n    )\n\n    result = pytester.runpytest(\"--stepwise\", \"-Wall\")\n\n    result.assert_outcomes(failed=1, warnings=1)\n    result.stdout.fnmatch_lines(\"*session.shouldstop cannot be unset*\")\n"
  },
  {
    "path": "testing/test_setuponly.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport sys\n\nfrom _pytest.config import ExitCode\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\n@pytest.fixture(params=[\"--setup-only\", \"--setup-plan\", \"--setup-show\"], scope=\"module\")\ndef mode(request):\n    return request.param\n\n\ndef test_show_only_active_fixtures(\n    pytester: Pytester, mode, dummy_yaml_custom_test\n) -> None:\n    pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture\n        def _arg0():\n            \"\"\"hidden arg0 fixture\"\"\"\n        @pytest.fixture\n        def arg1():\n            \"\"\"arg1 docstring\"\"\"\n        def test_arg1(arg1):\n            pass\n    '''\n    )\n\n    result = pytester.runpytest(mode)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\"*SETUP    F arg1*\", \"*test_arg1 (fixtures used: arg1)*\", \"*TEARDOWN F arg1*\"]\n    )\n    result.stdout.no_fnmatch_line(\"*_arg0*\")\n\n\ndef test_show_different_scopes(pytester: Pytester, mode) -> None:\n    p = pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture\n        def arg_function():\n            \"\"\"function scoped fixture\"\"\"\n        @pytest.fixture(scope='session')\n        def arg_session():\n            \"\"\"session scoped fixture\"\"\"\n        def test_arg1(arg_session, arg_function):\n            pass\n    '''\n    )\n\n    result = pytester.runpytest(mode, p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"SETUP    S arg_session*\",\n            \"*SETUP    F arg_function*\",\n            \"*test_arg1 (fixtures used: arg_function, arg_session)*\",\n            \"*TEARDOWN F arg_function*\",\n            \"TEARDOWN S arg_session*\",\n        ]\n    )\n\n\ndef test_show_nested_fixtures(pytester: Pytester, mode) -> None:\n    pytester.makeconftest(\n        '''\n        import pytest\n        @pytest.fixture(scope='session')\n        def arg_same():\n            \"\"\"session scoped fixture\"\"\"\n        '''\n    )\n    p = pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture(scope='function')\n        def arg_same(arg_same):\n            \"\"\"function scoped fixture\"\"\"\n        def test_arg1(arg_same):\n            pass\n    '''\n    )\n\n    result = pytester.runpytest(mode, p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"SETUP    S arg_same*\",\n            \"*SETUP    F arg_same (fixtures used: arg_same)*\",\n            \"*test_arg1 (fixtures used: arg_same)*\",\n            \"*TEARDOWN F arg_same*\",\n            \"TEARDOWN S arg_same*\",\n        ]\n    )\n\n\ndef test_show_fixtures_with_autouse(pytester: Pytester, mode) -> None:\n    p = pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture\n        def arg_function():\n            \"\"\"function scoped fixture\"\"\"\n        @pytest.fixture(scope='session', autouse=True)\n        def arg_session():\n            \"\"\"session scoped fixture\"\"\"\n        def test_arg1(arg_function):\n            pass\n    '''\n    )\n\n    result = pytester.runpytest(mode, p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"SETUP    S arg_session*\",\n            \"*SETUP    F arg_function*\",\n            \"*test_arg1 (fixtures used: arg_function, arg_session)*\",\n        ]\n    )\n\n\ndef test_show_fixtures_with_parameters(pytester: Pytester, mode) -> None:\n    pytester.makeconftest(\n        '''\n        import pytest\n        @pytest.fixture(scope='session', params=['foo', 'bar'])\n        def arg_same():\n            \"\"\"session scoped fixture\"\"\"\n        '''\n    )\n    p = pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture(scope='function')\n        def arg_other(arg_same):\n            \"\"\"function scoped fixture\"\"\"\n        def test_arg1(arg_other):\n            pass\n    '''\n    )\n\n    result = pytester.runpytest(mode, p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"SETUP    S arg_same?'foo'?\",\n            \"TEARDOWN S arg_same?'foo'?\",\n            \"SETUP    S arg_same?'bar'?\",\n            \"TEARDOWN S arg_same?'bar'?\",\n        ]\n    )\n\n\ndef test_show_fixtures_with_parameter_ids(pytester: Pytester, mode) -> None:\n    pytester.makeconftest(\n        '''\n        import pytest\n        @pytest.fixture(\n            scope='session', params=['foo', 'bar'], ids=['spam', 'ham'])\n        def arg_same():\n            \"\"\"session scoped fixture\"\"\"\n        '''\n    )\n    p = pytester.makepyfile(\n        '''\n        import pytest\n        @pytest.fixture(scope='function')\n        def arg_other(arg_same):\n            \"\"\"function scoped fixture\"\"\"\n        def test_arg1(arg_other):\n            pass\n    '''\n    )\n\n    result = pytester.runpytest(mode, p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\"SETUP    S arg_same?'spam'?\", \"SETUP    S arg_same?'ham'?\"]\n    )\n\n\ndef test_show_fixtures_with_parameter_ids_function(pytester: Pytester, mode) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.fixture(params=['foo', 'bar'], ids=lambda p: p.upper())\n        def foobar():\n            pass\n        def test_foobar(foobar):\n            pass\n    \"\"\"\n    )\n\n    result = pytester.runpytest(mode, p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\"*SETUP    F foobar?'FOO'?\", \"*SETUP    F foobar?'BAR'?\"]\n    )\n\n\ndef test_dynamic_fixture_request(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.fixture()\n        def dynamically_requested_fixture():\n            pass\n        @pytest.fixture()\n        def dependent_fixture(request):\n            request.getfixturevalue('dynamically_requested_fixture')\n        def test_dyn(dependent_fixture):\n            pass\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"--setup-only\", p)\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\n            \"*SETUP    F dynamically_requested_fixture\",\n            \"*TEARDOWN F dynamically_requested_fixture\",\n        ]\n    )\n\n\ndef test_capturing(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest, sys\n        @pytest.fixture()\n        def one():\n            sys.stdout.write('this should be captured')\n            sys.stderr.write('this should also be captured')\n        @pytest.fixture()\n        def two(one):\n            assert 0\n        def test_capturing(two):\n            pass\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"--setup-only\", p)\n    result.stdout.fnmatch_lines(\n        [\"this should be captured\", \"this should also be captured\"]\n    )\n\n\ndef test_show_fixtures_and_execute_test(pytester: Pytester) -> None:\n    \"\"\"Verify that setups are shown and tests are executed.\"\"\"\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.fixture\n        def arg():\n            assert True\n        def test_arg(arg):\n            assert False\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"--setup-show\", p)\n    assert result.ret == 1\n\n    result.stdout.fnmatch_lines(\n        [\"*SETUP    F arg*\", \"*test_arg (fixtures used: arg)F*\", \"*TEARDOWN F arg*\"]\n    )\n\n\ndef test_setup_show_with_KeyboardInterrupt_in_test(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.fixture\n        def arg():\n            pass\n        def test_arg(arg):\n            raise KeyboardInterrupt()\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--setup-show\", p, no_reraise_ctrlc=True)\n    result.stdout.fnmatch_lines(\n        [\n            \"*SETUP    F arg*\",\n            \"*test_arg (fixtures used: arg)*\",\n            \"*TEARDOWN F arg*\",\n            \"*! KeyboardInterrupt !*\",\n            \"*= no tests ran in *\",\n        ]\n    )\n    assert result.ret == ExitCode.INTERRUPTED\n\n\ndef test_show_fixture_action_with_bytes(pytester: Pytester) -> None:\n    # Issue 7126, BytesWarning when using --setup-show with bytes parameter\n    test_file = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.parametrize('data', [b'Hello World'])\n        def test_data(data):\n            pass\n        \"\"\"\n    )\n    result = pytester.run(\n        sys.executable, \"-bb\", \"-m\", \"pytest\", \"--setup-show\", str(test_file)\n    )\n    assert result.ret == 0\n"
  },
  {
    "path": "testing/test_setupplan.py",
    "content": "from __future__ import annotations\n\nfrom _pytest.pytester import Pytester\n\n\ndef test_show_fixtures_and_test(\n    pytester: Pytester, dummy_yaml_custom_test: None\n) -> None:\n    \"\"\"Verify that fixtures are not executed.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.fixture\n        def arg():\n            assert False\n        def test_arg(arg):\n            assert False\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"--setup-plan\")\n    assert result.ret == 0\n\n    result.stdout.fnmatch_lines(\n        [\"*SETUP    F arg*\", \"*test_arg (fixtures used: arg)\", \"*TEARDOWN F arg*\"]\n    )\n\n\ndef test_show_multi_test_fixture_setup_and_teardown_correctly_simple(\n    pytester: Pytester,\n) -> None:\n    \"\"\"Verify that when a fixture lives for longer than a single test, --setup-plan\n    correctly displays the SETUP/TEARDOWN indicators the right number of times.\n\n    As reported in https://github.com/pytest-dev/pytest/issues/2049\n    --setup-plan was showing SETUP/TEARDOWN on every test, even when the fixture\n    should persist through multiple tests.\n\n    (Note that this bug never affected actual test execution, which used the\n    correct fixture lifetimes. It was purely a display bug for --setup-plan, and\n    did not affect the related --setup-show or --setup-only.)\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.fixture(scope = 'class')\n        def fix():\n            return object()\n        class TestClass:\n            def test_one(self, fix):\n                assert False\n            def test_two(self, fix):\n                assert False\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"--setup-plan\")\n    assert result.ret == 0\n\n    setup_fragment = \"SETUP    C fix\"\n    setup_count = 0\n\n    teardown_fragment = \"TEARDOWN C fix\"\n    teardown_count = 0\n\n    for line in result.stdout.lines:\n        if setup_fragment in line:\n            setup_count += 1\n        if teardown_fragment in line:\n            teardown_count += 1\n\n    # before the fix this tests, there would have been a setup/teardown\n    # message for each test, so the counts would each have been 2\n    assert setup_count == 1\n    assert teardown_count == 1\n\n\ndef test_show_multi_test_fixture_setup_and_teardown_same_as_setup_show(\n    pytester: Pytester,\n) -> None:\n    \"\"\"Verify that SETUP/TEARDOWN messages match what comes out of --setup-show.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.fixture(scope = 'session')\n        def sess():\n            return True\n        @pytest.fixture(scope = 'module')\n        def mod():\n            return True\n        @pytest.fixture(scope = 'class')\n        def cls():\n            return True\n        @pytest.fixture(scope = 'function')\n        def func():\n            return True\n        def test_outside(sess, mod, cls, func):\n            assert True\n        class TestCls:\n            def test_one(self, sess, mod, cls, func):\n                assert True\n            def test_two(self, sess, mod, cls, func):\n                assert True\n    \"\"\"\n    )\n\n    plan_result = pytester.runpytest(\"--setup-plan\")\n    show_result = pytester.runpytest(\"--setup-show\")\n\n    # the number and text of these lines should be identical\n    plan_lines = [\n        line\n        for line in plan_result.stdout.lines\n        if \"SETUP\" in line or \"TEARDOWN\" in line\n    ]\n    show_lines = [\n        line\n        for line in show_result.stdout.lines\n        if \"SETUP\" in line or \"TEARDOWN\" in line\n    ]\n\n    assert plan_lines == show_lines\n"
  },
  {
    "path": "testing/test_skipping.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport textwrap\n\nfrom _pytest.pytester import Pytester\nfrom _pytest.runner import runtestprotocol\nfrom _pytest.skipping import evaluate_skip_marks\nfrom _pytest.skipping import evaluate_xfail_marks\nfrom _pytest.skipping import pytest_runtest_setup\nimport pytest\n\n\nclass TestEvaluation:\n    def test_no_marker(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\"def test_func(): pass\")\n        skipped = evaluate_skip_marks(item)\n        assert not skipped\n\n    def test_marked_xfail_no_args(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail\n            def test_func():\n                pass\n        \"\"\"\n        )\n        xfailed = evaluate_xfail_marks(item)\n        assert xfailed\n        assert xfailed.reason == \"\"\n        assert xfailed.run\n\n    def test_marked_skipif_no_args(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.skipif\n            def test_func():\n                pass\n        \"\"\"\n        )\n        skipped = evaluate_skip_marks(item)\n        assert skipped\n        assert skipped.reason == \"\"\n\n    def test_marked_one_arg(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.skipif(\"hasattr(os, 'sep')\")\n            def test_func():\n                pass\n        \"\"\"\n        )\n        skipped = evaluate_skip_marks(item)\n        assert skipped\n        assert skipped.reason == \"condition: hasattr(os, 'sep')\"\n\n    def test_marked_one_arg_with_reason(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.skipif(\"hasattr(os, 'sep')\", attr=2, reason=\"hello world\")\n            def test_func():\n                pass\n        \"\"\"\n        )\n        skipped = evaluate_skip_marks(item)\n        assert skipped\n        assert skipped.reason == \"hello world\"\n\n    def test_marked_one_arg_twice(self, pytester: Pytester) -> None:\n        lines = [\n            \"\"\"@pytest.mark.skipif(\"not hasattr(os, 'murks')\")\"\"\",\n            \"\"\"@pytest.mark.skipif(condition=\"hasattr(os, 'murks')\")\"\"\",\n        ]\n        for i in range(2):\n            item = pytester.getitem(\n                f\"\"\"\n                import pytest\n                {lines[i]}\n                {lines[(i + 1) % 2]}\n                def test_func():\n                    pass\n            \"\"\"\n            )\n            skipped = evaluate_skip_marks(item)\n            assert skipped\n            assert skipped.reason == \"condition: not hasattr(os, 'murks')\"\n\n    def test_marked_one_arg_twice2(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.skipif(\"hasattr(os, 'murks')\")\n            @pytest.mark.skipif(\"not hasattr(os, 'murks')\")\n            def test_func():\n                pass\n        \"\"\"\n        )\n        skipped = evaluate_skip_marks(item)\n        assert skipped\n        assert skipped.reason == \"condition: not hasattr(os, 'murks')\"\n\n    def test_marked_skipif_with_boolean_without_reason(\n        self, pytester: Pytester\n    ) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.skipif(False)\n            def test_func():\n                pass\n        \"\"\"\n        )\n        with pytest.raises(pytest.fail.Exception) as excinfo:\n            evaluate_skip_marks(item)\n        assert excinfo.value.msg is not None\n        assert (\n            \"\"\"Error evaluating 'skipif': you need to specify reason=STRING when using booleans as conditions.\"\"\"\n            in excinfo.value.msg\n        )\n\n    def test_marked_skipif_with_invalid_boolean(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n\n            class InvalidBool:\n                def __bool__(self):\n                    raise TypeError(\"INVALID\")\n\n            @pytest.mark.skipif(InvalidBool(), reason=\"xxx\")\n            def test_func():\n                pass\n        \"\"\"\n        )\n        with pytest.raises(pytest.fail.Exception) as excinfo:\n            evaluate_skip_marks(item)\n        assert excinfo.value.msg is not None\n        assert \"Error evaluating 'skipif' condition as a boolean\" in excinfo.value.msg\n        assert \"INVALID\" in excinfo.value.msg\n\n    def test_skipif_class(self, pytester: Pytester) -> None:\n        (item,) = pytester.getitems(\n            \"\"\"\n            import pytest\n            class TestClass(object):\n                pytestmark = pytest.mark.skipif(\"config._hackxyz\")\n                def test_func(self):\n                    pass\n        \"\"\"\n        )\n        item.config._hackxyz = 3  # type: ignore[attr-defined]\n        skipped = evaluate_skip_marks(item)\n        assert skipped\n        assert skipped.reason == \"condition: config._hackxyz\"\n\n    def test_skipif_markeval_namespace(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            def pytest_markeval_namespace():\n                return {\"color\": \"green\"}\n            \"\"\"\n        )\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.skipif(\"color == 'green'\")\n            def test_1():\n                assert True\n\n            @pytest.mark.skipif(\"color == 'red'\")\n            def test_2():\n                assert True\n        \"\"\"\n        )\n        res = pytester.runpytest(p)\n        assert res.ret == 0\n        res.stdout.fnmatch_lines([\"*1 skipped*\"])\n        res.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    def test_skipif_markeval_namespace_multiple(self, pytester: Pytester) -> None:\n        \"\"\"Keys defined by ``pytest_markeval_namespace()`` in nested plugins override top-level ones.\"\"\"\n        root = pytester.mkdir(\"root\")\n        root.joinpath(\"__init__.py\").touch()\n        root.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            import pytest\n\n            def pytest_markeval_namespace():\n                return {\"arg\": \"root\"}\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        root.joinpath(\"test_root.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            import pytest\n\n            @pytest.mark.skipif(\"arg == 'root'\")\n            def test_root():\n                assert False\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        foo = root.joinpath(\"foo\")\n        foo.mkdir()\n        foo.joinpath(\"__init__.py\").touch()\n        foo.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            import pytest\n\n            def pytest_markeval_namespace():\n                return {\"arg\": \"foo\"}\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        foo.joinpath(\"test_foo.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            import pytest\n\n            @pytest.mark.skipif(\"arg == 'foo'\")\n            def test_foo():\n                assert False\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        bar = root.joinpath(\"bar\")\n        bar.mkdir()\n        bar.joinpath(\"__init__.py\").touch()\n        bar.joinpath(\"conftest.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            import pytest\n\n            def pytest_markeval_namespace():\n                return {\"arg\": \"bar\"}\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        bar.joinpath(\"test_bar.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n            import pytest\n\n            @pytest.mark.skipif(\"arg == 'bar'\")\n            def test_bar():\n                assert False\n            \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        reprec = pytester.inline_run(\"-vs\", \"--capture=no\")\n        reprec.assertoutcome(skipped=3)\n\n    def test_skipif_markeval_namespace_ValueError(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            def pytest_markeval_namespace():\n                return True\n            \"\"\"\n        )\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.skipif(\"color == 'green'\")\n            def test_1():\n                assert True\n        \"\"\"\n        )\n        res = pytester.runpytest(p)\n        assert res.ret == 1\n        res.stdout.fnmatch_lines(\n            [\n                \"*ValueError: pytest_markeval_namespace() needs to return a dict, got True*\"\n            ]\n        )\n\n\nclass TestXFail:\n    @pytest.mark.parametrize(\"strict\", [True, False])\n    def test_xfail_simple(self, pytester: Pytester, strict: bool) -> None:\n        item = pytester.getitem(\n            f\"\"\"\n            import pytest\n            @pytest.mark.xfail(strict={strict})\n            def test_func():\n                assert 0\n        \"\"\"\n        )\n        reports = runtestprotocol(item, log=False)\n        assert len(reports) == 3\n        callreport = reports[1]\n        assert callreport.skipped\n        assert callreport.wasxfail == \"\"\n\n    def test_xfail_xpassed(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail(reason=\"this is an xfail\")\n            def test_func():\n                assert 1\n        \"\"\"\n        )\n        reports = runtestprotocol(item, log=False)\n        assert len(reports) == 3\n        callreport = reports[1]\n        assert callreport.passed\n        assert callreport.wasxfail == \"this is an xfail\"\n\n    def test_xfail_using_platform(self, pytester: Pytester) -> None:\n        \"\"\"Verify that platform can be used with xfail statements.\"\"\"\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail(\"platform.platform() == platform.platform()\")\n            def test_func():\n                assert 0\n        \"\"\"\n        )\n        reports = runtestprotocol(item, log=False)\n        assert len(reports) == 3\n        callreport = reports[1]\n        assert callreport.wasxfail\n\n    def test_xfail_xpassed_strict(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail(strict=True, reason=\"nope\")\n            def test_func():\n                assert 1\n        \"\"\"\n        )\n        reports = runtestprotocol(item, log=False)\n        assert len(reports) == 3\n        callreport = reports[1]\n        assert callreport.failed\n        assert str(callreport.longrepr) == \"[XPASS(strict)] nope\"\n        assert not hasattr(callreport, \"wasxfail\")\n\n    def test_xfail_run_anyway(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail\n            def test_func():\n                assert 0\n            def test_func2():\n                pytest.xfail(\"hello\")\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--runxfail\")\n        result.stdout.fnmatch_lines(\n            [\"*def test_func():*\", \"*assert 0*\", \"*1 failed*1 pass*\"]\n        )\n\n    @pytest.mark.parametrize(\n        \"test_input,expected\",\n        [\n            (\n                [\"-rs\"],\n                [\"SKIPPED [1] test_sample.py:2: unconditional skip\", \"*1 skipped*\"],\n            ),\n            (\n                [\"-rs\", \"--runxfail\"],\n                [\"SKIPPED [1] test_sample.py:2: unconditional skip\", \"*1 skipped*\"],\n            ),\n        ],\n    )\n    def test_xfail_run_with_skip_mark(\n        self, pytester: Pytester, test_input, expected\n    ) -> None:\n        pytester.makepyfile(\n            test_sample=\"\"\"\n            import pytest\n            @pytest.mark.skip\n            def test_skip_location() -> None:\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(*test_input)\n        result.stdout.fnmatch_lines(expected)\n\n    def test_xfail_evalfalse_but_fails(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail('False')\n            def test_func():\n                assert 0\n        \"\"\"\n        )\n        reports = runtestprotocol(item, log=False)\n        callreport = reports[1]\n        assert callreport.failed\n        assert not hasattr(callreport, \"wasxfail\")\n        assert \"xfail\" in callreport.keywords\n\n    def test_xfail_not_report_default(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            test_one=\"\"\"\n            import pytest\n            @pytest.mark.xfail\n            def test_this():\n                assert 0\n        \"\"\"\n        )\n        pytester.runpytest(p, \"-v\")\n        # result.stdout.fnmatch_lines([\n        #    \"*HINT*use*-r*\"\n        # ])\n\n    def test_xfail_not_run_xfail_reporting(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            test_one=\"\"\"\n            import pytest\n            @pytest.mark.xfail(run=False, reason=\"noway\")\n            def test_this():\n                assert 0\n            @pytest.mark.xfail(\"True\", run=False)\n            def test_this_true():\n                assert 0\n            @pytest.mark.xfail(\"False\", run=False, reason=\"huh\")\n            def test_this_false():\n                assert 1\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-rx\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_one*test_this - *NOTRUN* noway\",\n                \"*test_one*test_this_true - *NOTRUN* condition: True\",\n                \"*1 passed*\",\n            ]\n        )\n\n    def test_xfail_not_run_no_setup_run(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            test_one=\"\"\"\n            import pytest\n            @pytest.mark.xfail(run=False, reason=\"hello\")\n            def test_this():\n                assert 0\n            def setup_module(mod):\n                raise ValueError(42)\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-rx\")\n        result.stdout.fnmatch_lines([\"*test_one*test_this*NOTRUN*hello\", \"*1 xfailed*\"])\n\n    def test_xfail_xpass(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            test_one=\"\"\"\n            import pytest\n            @pytest.mark.xfail\n            def test_that():\n                assert 1\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-rX\")\n        result.stdout.fnmatch_lines([\"*XPASS*test_that*\", \"*1 xpassed*\"])\n        assert result.ret == 0\n\n    def test_xfail_imperative(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_this():\n                pytest.xfail(\"hello\")\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n        result = pytester.runpytest(p, \"-rx\")\n        result.stdout.fnmatch_lines([\"*XFAIL*test_this*hello*\"])\n        result = pytester.runpytest(p, \"--runxfail\")\n        result.stdout.fnmatch_lines([\"*1 pass*\"])\n\n    def test_xfail_imperative_in_setup_function(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def setup_function(function):\n                pytest.xfail(\"hello\")\n\n            def test_this():\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n        result = pytester.runpytest(p, \"-rx\")\n        result.stdout.fnmatch_lines([\"*XFAIL*test_this*hello*\"])\n        result = pytester.runpytest(p, \"--runxfail\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *def test_this*\n            *1 fail*\n        \"\"\"\n        )\n\n    def xtest_dynamic_xfail_set_during_setup(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def setup_function(function):\n                pytest.mark.xfail(function)\n            def test_this():\n                assert 0\n            def test_that():\n                assert 1\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-rxX\")\n        result.stdout.fnmatch_lines([\"*XFAIL*test_this*\", \"*XPASS*test_that*\"])\n\n    def test_dynamic_xfail_no_run(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def arg(request):\n                request.applymarker(pytest.mark.xfail(run=False))\n            def test_this(arg):\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-rxX\")\n        result.stdout.fnmatch_lines([\"*XFAIL*test_this*NOTRUN*\"])\n\n    def test_dynamic_xfail_set_during_funcarg_setup(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.fixture\n            def arg(request):\n                request.applymarker(pytest.mark.xfail)\n            def test_this2(arg):\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines([\"*1 xfailed*\"])\n\n    def test_dynamic_xfail_set_during_runtest_failed(self, pytester: Pytester) -> None:\n        # Issue #7486.\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_this(request):\n                request.node.add_marker(pytest.mark.xfail(reason=\"xfail\"))\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.assert_outcomes(xfailed=1)\n\n    def test_dynamic_xfail_set_during_runtest_passed_strict(\n        self, pytester: Pytester\n    ) -> None:\n        # Issue #7486.\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_this(request):\n                request.node.add_marker(pytest.mark.xfail(reason=\"xfail\", strict=True))\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.assert_outcomes(failed=1)\n\n    @pytest.mark.parametrize(\n        \"expected, actual, matchline\",\n        [\n            (\"TypeError\", \"TypeError\", \"*1 xfailed*\"),\n            (\"(AttributeError, TypeError)\", \"TypeError\", \"*1 xfailed*\"),\n            (\"TypeError\", \"IndexError\", \"*1 failed*\"),\n            (\"(AttributeError, TypeError)\", \"IndexError\", \"*1 failed*\"),\n        ],\n    )\n    def test_xfail_raises(\n        self, expected, actual, matchline, pytester: Pytester\n    ) -> None:\n        p = pytester.makepyfile(\n            f\"\"\"\n            import pytest\n            @pytest.mark.xfail(raises={expected})\n            def test_raises():\n                raise {actual}()\n        \"\"\"\n        )\n        result = pytester.runpytest(p)\n        result.stdout.fnmatch_lines([matchline])\n\n    def test_strict_sanity(self, pytester: Pytester) -> None:\n        \"\"\"Sanity check for xfail(strict=True): a failing test should behave\n        exactly like a normal xfail.\"\"\"\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail(reason='unsupported feature', strict=True)\n            def test_foo():\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-rxX\")\n        result.stdout.fnmatch_lines([\"*XFAIL*unsupported feature*\"])\n        assert result.ret == 0\n\n    @pytest.mark.parametrize(\"strict\", [True, False])\n    def test_strict_xfail(self, pytester: Pytester, strict: bool) -> None:\n        p = pytester.makepyfile(\n            f\"\"\"\n            import pytest\n\n            @pytest.mark.xfail(reason='unsupported feature', strict={strict})\n            def test_foo():\n                with open('foo_executed', 'w', encoding='utf-8'):\n                    pass  # make sure test executes\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-rxX\")\n        if strict:\n            result.stdout.fnmatch_lines(\n                [\"*test_foo*\", \"*XPASS(strict)*unsupported feature*\"]\n            )\n        else:\n            result.stdout.fnmatch_lines(\n                [\n                    \"*test_strict_xfail*\",\n                    \"XPASS test_strict_xfail.py::test_foo - unsupported feature\",\n                ]\n            )\n        assert result.ret == (1 if strict else 0)\n        assert pytester.path.joinpath(\"foo_executed\").exists()\n\n    @pytest.mark.parametrize(\"strict\", [True, False])\n    def test_strict_xfail_condition(self, pytester: Pytester, strict: bool) -> None:\n        p = pytester.makepyfile(\n            f\"\"\"\n            import pytest\n\n            @pytest.mark.xfail(False, reason='unsupported feature', strict={strict})\n            def test_foo():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-rxX\")\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n        assert result.ret == 0\n\n    @pytest.mark.parametrize(\"strict\", [True, False])\n    def test_xfail_condition_keyword(self, pytester: Pytester, strict: bool) -> None:\n        p = pytester.makepyfile(\n            f\"\"\"\n            import pytest\n\n            @pytest.mark.xfail(condition=False, reason='unsupported feature', strict={strict})\n            def test_foo():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-rxX\")\n        result.stdout.fnmatch_lines([\"*1 passed*\"])\n        assert result.ret == 0\n\n    @pytest.mark.parametrize(\"strict_val\", [\"true\", \"false\"])\n    @pytest.mark.parametrize(\"option_name\", [\"strict_xfail\", \"strict\"])\n    def test_strict_xfail_default_from_file(\n        self, pytester: Pytester, strict_val: str, option_name: str\n    ) -> None:\n        pytester.makeini(\n            f\"\"\"\n            [pytest]\n            {option_name} = {strict_val}\n        \"\"\"\n        )\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail(reason='unsupported feature')\n            def test_foo():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-rxX\")\n        strict = strict_val == \"true\"\n        result.stdout.fnmatch_lines([\"*1 failed*\" if strict else \"*1 xpassed*\"])\n        assert result.ret == (1 if strict else 0)\n\n    def test_xfail_markeval_namespace(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            def pytest_markeval_namespace():\n                return {\"color\": \"green\"}\n            \"\"\"\n        )\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.xfail(\"color == 'green'\")\n            def test_1():\n                assert False\n\n            @pytest.mark.xfail(\"color == 'red'\")\n            def test_2():\n                assert False\n        \"\"\"\n        )\n        res = pytester.runpytest(p)\n        assert res.ret == 1\n        res.stdout.fnmatch_lines([\"*1 failed*\"])\n        res.stdout.fnmatch_lines([\"*1 xfailed*\"])\n\n\nclass TestXFailwithSetupTeardown:\n    def test_failing_setup_issue9(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def setup_function(func):\n                assert 0\n\n            @pytest.mark.xfail\n            def test_func():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 xfail*\"])\n\n    def test_failing_teardown_issue9(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def teardown_function(func):\n                assert 0\n\n            @pytest.mark.xfail\n            def test_func():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"*1 xfail*\"])\n\n\nclass TestSkip:\n    def test_skip_class(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skip\n            class TestSomething(object):\n                def test_foo(self):\n                    pass\n                def test_bar(self):\n                    pass\n\n            def test_baz():\n                pass\n        \"\"\"\n        )\n        rec = pytester.inline_run()\n        rec.assertoutcome(skipped=2, passed=1)\n\n    def test_skips_on_false_string(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skip('False')\n            def test_foo():\n                pass\n        \"\"\"\n        )\n        rec = pytester.inline_run()\n        rec.assertoutcome(skipped=1)\n\n    def test_arg_as_reason(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skip('testing stuff')\n            def test_bar():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-rs\")\n        result.stdout.fnmatch_lines([\"*testing stuff*\", \"*1 skipped*\"])\n\n    def test_skip_no_reason(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skip\n            def test_foo():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-rs\")\n        result.stdout.fnmatch_lines([\"*unconditional skip*\", \"*1 skipped*\"])\n\n    def test_skip_with_reason(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skip(reason=\"for lolz\")\n            def test_bar():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-rs\")\n        result.stdout.fnmatch_lines([\"*for lolz*\", \"*1 skipped*\"])\n\n    def test_only_skips_marked_test(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skip\n            def test_foo():\n                pass\n            @pytest.mark.skip(reason=\"nothing in particular\")\n            def test_bar():\n                pass\n            def test_baz():\n                assert True\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-rs\")\n        result.stdout.fnmatch_lines([\"*nothing in particular*\", \"*1 passed*2 skipped*\"])\n\n    def test_strict_and_skip(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skip\n            def test_hello():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-rs\", \"--strict-markers\")\n        result.stdout.fnmatch_lines([\"*unconditional skip*\", \"*1 skipped*\"])\n\n    def test_wrong_skip_usage(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skip(False, reason=\"I thought this was skipif\")\n            def test_hello():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*TypeError: *__init__() got multiple values for argument 'reason'\"\n                \" - maybe you meant pytest.mark.skipif?\"\n            ]\n        )\n\n\nclass TestSkipif:\n    def test_skipif_conditional(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.skipif(\"hasattr(os, 'sep')\")\n            def test_func():\n                pass\n        \"\"\"\n        )\n        x = pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))\n        assert x.value.msg == \"condition: hasattr(os, 'sep')\"\n\n    @pytest.mark.parametrize(\n        \"params\", [\"\\\"hasattr(sys, 'platform')\\\"\", 'True, reason=\"invalid platform\"']\n    )\n    def test_skipif_reporting(self, pytester: Pytester, params) -> None:\n        p = pytester.makepyfile(\n            test_foo=f\"\"\"\n            import pytest\n            @pytest.mark.skipif({params})\n            def test_that():\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(p, \"-s\", \"-rs\")\n        result.stdout.fnmatch_lines([\"*SKIP*1*test_foo.py*platform*\", \"*1 skipped*\"])\n        assert result.ret == 0\n\n    def test_skipif_using_platform(self, pytester: Pytester) -> None:\n        item = pytester.getitem(\n            \"\"\"\n            import pytest\n            @pytest.mark.skipif(\"platform.platform() == platform.platform()\")\n            def test_func():\n                pass\n        \"\"\"\n        )\n        pytest.raises(pytest.skip.Exception, lambda: pytest_runtest_setup(item))\n\n    @pytest.mark.parametrize(\n        \"marker, msg1, msg2\",\n        [(\"skipif\", \"SKIP\", \"skipped\"), (\"xfail\", \"XPASS\", \"xpassed\")],\n    )\n    def test_skipif_reporting_multiple(\n        self, pytester: Pytester, marker, msg1, msg2\n    ) -> None:\n        pytester.makepyfile(\n            test_foo=f\"\"\"\n            import pytest\n            @pytest.mark.{marker}(False, reason='first_condition')\n            @pytest.mark.{marker}(True, reason='second_condition')\n            def test_foobar():\n                assert 1\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\", \"-rsxX\")\n        result.stdout.fnmatch_lines(\n            [f\"*{msg1}*test_foo.py*second_condition*\", f\"*1 {msg2}*\"]\n        )\n        assert result.ret == 0\n\n\ndef test_skip_not_report_default(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        test_one=\"\"\"\n        import pytest\n        def test_this():\n            pytest.skip(\"hello\")\n    \"\"\"\n    )\n    result = pytester.runpytest(p, \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            # \"*HINT*use*-r*\",\n            \"*1 skipped*\"\n        ]\n    )\n\n\ndef test_skipif_class(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        class TestClass(object):\n            pytestmark = pytest.mark.skipif(\"True\")\n            def test_that(self):\n                assert 0\n            def test_though(self):\n                assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest(p)\n    result.stdout.fnmatch_lines([\"*2 skipped*\"])\n\n\ndef test_skipped_reasons_functional(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_one=\"\"\"\n            import pytest\n            from helpers import doskip\n\n            def setup_function(func):  # LINE 4\n                doskip(\"setup function\")\n\n            def test_func():\n                pass\n\n            class TestClass:\n                def test_method(self):\n                    doskip(\"test method\")\n\n                @pytest.mark.skip(\"via_decorator\")  # LINE 14\n                def test_deco(self):\n                    assert 0\n        \"\"\",\n        helpers=\"\"\"\n            import pytest, sys\n            def doskip(reason):\n                assert sys._getframe().f_lineno == 3\n                pytest.skip(reason)  # LINE 4\n        \"\"\",\n    )\n    result = pytester.runpytest(\"-rs\")\n    result.stdout.fnmatch_lines_random(\n        [\n            \"SKIPPED [[]1[]] test_one.py:7: setup function\",\n            \"SKIPPED [[]1[]] helpers.py:4: test method\",\n            \"SKIPPED [[]1[]] test_one.py:14: via_decorator\",\n        ]\n    )\n    assert result.ret == 0\n\n\ndef test_skipped_folding(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_one=\"\"\"\n            import pytest\n            pytestmark = pytest.mark.skip(\"Folding\")\n            def setup_function(func):\n                pass\n            def test_func():\n                pass\n            class TestClass(object):\n                def test_method(self):\n                    pass\n       \"\"\"\n    )\n    result = pytester.runpytest(\"-rs\")\n    result.stdout.fnmatch_lines([\"*SKIP*2*test_one.py: Folding\"])\n    assert result.ret == 0\n\n\ndef test_reportchars(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def test_1():\n            assert 0\n        @pytest.mark.xfail\n        def test_2():\n            assert 0\n        @pytest.mark.xfail\n        def test_3():\n            pass\n        def test_4():\n            pytest.skip(\"four\")\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-rfxXs\")\n    result.stdout.fnmatch_lines(\n        [\"FAIL*test_1*\", \"XFAIL*test_2*\", \"XPASS*test_3*\", \"SKIP*four*\"]\n    )\n\n\ndef test_reportchars_error(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        conftest=\"\"\"\n        def pytest_runtest_teardown():\n            assert 0\n        \"\"\",\n        test_simple=\"\"\"\n        def test_foo():\n            pass\n        \"\"\",\n    )\n    result = pytester.runpytest(\"-rE\")\n    result.stdout.fnmatch_lines([\"ERROR*test_foo*\"])\n\n\ndef test_reportchars_all(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def test_1():\n            assert 0\n        @pytest.mark.xfail\n        def test_2():\n            assert 0\n        @pytest.mark.xfail\n        def test_3():\n            pass\n        def test_4():\n            pytest.skip(\"four\")\n        @pytest.fixture\n        def fail():\n            assert 0\n        def test_5(fail):\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-ra\")\n    result.stdout.fnmatch_lines(\n        [\n            \"SKIP*four*\",\n            \"XFAIL*test_2*\",\n            \"XPASS*test_3*\",\n            \"ERROR*test_5*\",\n            \"FAIL*test_1*\",\n        ]\n    )\n\n\ndef test_reportchars_all_error(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        conftest=\"\"\"\n        def pytest_runtest_teardown():\n            assert 0\n        \"\"\",\n        test_simple=\"\"\"\n        def test_foo():\n            pass\n        \"\"\",\n    )\n    result = pytester.runpytest(\"-ra\")\n    result.stdout.fnmatch_lines([\"ERROR*test_foo*\"])\n\n\ndef test_errors_in_xfail_skip_expressions(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.skipif(\"asd\")\n        def test_nameerror():\n            pass\n        @pytest.mark.xfail(\"syntax error\")\n        def test_syntax():\n            pass\n\n        def test_func():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n\n    expected = [\n        \"*ERROR*test_nameerror*\",\n        \"*asd*\",\n        \"\",\n        \"During handling of the above exception, another exception occurred:\",\n    ]\n\n    expected += [\n        \"*evaluating*skipif*condition*\",\n        \"*asd*\",\n        \"*ERROR*test_syntax*\",\n        \"*evaluating*xfail*condition*\",\n        \"    syntax error\",\n        \"            ^\",\n        \"SyntaxError: invalid syntax\",\n        \"*1 pass*2 errors*\",\n    ]\n    result.stdout.fnmatch_lines(expected)\n\n\ndef test_xfail_skipif_with_globals(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        x = 3\n        @pytest.mark.skipif(\"x == 3\")\n        def test_skip1():\n            pass\n        @pytest.mark.xfail(\"x == 3\")\n        def test_boolean():\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-rsx\")\n    result.stdout.fnmatch_lines([\"*SKIP*x == 3*\", \"*XFAIL*test_boolean*x == 3*\"])\n\n\ndef test_default_markers(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--markers\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*skipif(condition, ..., [*], reason=...)*skip*\",\n            \"*xfail(condition, ..., [*], reason=..., run=True, raises=None, strict=strict_xfail)*expected failure*\",\n        ]\n    )\n\n\ndef test_xfail_test_setup_exception(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n            def pytest_runtest_setup():\n                0 / 0\n        \"\"\"\n    )\n    p = pytester.makepyfile(\n        \"\"\"\n            import pytest\n            @pytest.mark.xfail\n            def test_func():\n                assert 0\n        \"\"\"\n    )\n    result = pytester.runpytest(p)\n    assert result.ret == 0\n    assert \"xfailed\" in result.stdout.str()\n    result.stdout.no_fnmatch_line(\"*xpassed*\")\n\n\ndef test_imperativeskip_on_xfail_test(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.xfail\n        def test_that_fails():\n            assert 0\n\n        @pytest.mark.skipif(\"True\")\n        def test_hello():\n            pass\n    \"\"\"\n    )\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n        def pytest_runtest_setup(item):\n            pytest.skip(\"abc\")\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-rsxX\")\n    result.stdout.fnmatch_lines_random(\n        \"\"\"\n        *SKIP*abc*\n        *SKIP*condition: True*\n        *2 skipped*\n    \"\"\"\n    )\n\n\nclass TestBooleanCondition:\n    def test_skipif(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skipif(True, reason=\"True123\")\n            def test_func1():\n                pass\n            @pytest.mark.skipif(False, reason=\"True123\")\n            def test_func2():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *1 passed*1 skipped*\n        \"\"\"\n        )\n\n    def test_skipif_noreason(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.skipif(True)\n            def test_func():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-rs\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *1 error*\n        \"\"\"\n        )\n\n    def test_xfail(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.xfail(True, reason=\"True123\")\n            def test_func():\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-rxs\")\n        result.stdout.fnmatch_lines(\n            \"\"\"\n            *XFAIL*True123*\n            *1 xfail*\n        \"\"\"\n        )\n\n\ndef test_xfail_item(pytester: Pytester) -> None:\n    # Ensure pytest.xfail works with non-Python Item\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n\n        class MyItem(pytest.Item):\n            nodeid = 'foo'\n            def runtest(self):\n                pytest.xfail(\"Expected Failure\")\n\n        def pytest_collect_file(file_path, parent):\n            return MyItem.from_parent(name=\"foo\", parent=parent)\n    \"\"\"\n    )\n    result = pytester.inline_run()\n    _passed, skipped, failed = result.listoutcomes()\n    assert not failed\n    xfailed = [r for r in skipped if hasattr(r, \"wasxfail\")]\n    assert xfailed\n\n\ndef test_module_level_skip_error(pytester: Pytester) -> None:\n    \"\"\"Verify that using pytest.skip at module level causes a collection error.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        pytest.skip(\"skip_module_level\")\n\n        def test_func():\n            assert True\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\"*Using pytest.skip outside of a test will skip the entire module*\"]\n    )\n\n\ndef test_module_level_skip_with_allow_module_level(pytester: Pytester) -> None:\n    \"\"\"Verify that using pytest.skip(allow_module_level=True) is allowed.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        pytest.skip(\"skip_module_level\", allow_module_level=True)\n\n        def test_func():\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-rxs\")\n    result.stdout.fnmatch_lines([\"*SKIP*skip_module_level\"])\n\n\ndef test_invalid_skip_keyword_parameter(pytester: Pytester) -> None:\n    \"\"\"Verify that using pytest.skip() with unknown parameter raises an error.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        pytest.skip(\"skip_module_level\", unknown=1)\n\n        def test_func():\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*TypeError:*['unknown']*\"])\n\n\ndef test_mark_xfail_item(pytester: Pytester) -> None:\n    # Ensure pytest.mark.xfail works with non-Python Item\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n\n        class MyItem(pytest.Item):\n            nodeid = 'foo'\n            def setup(self):\n                marker = pytest.mark.xfail(\"1 == 2\", reason=\"Expected failure - false\")\n                self.add_marker(marker)\n                marker = pytest.mark.xfail(True, reason=\"Expected failure - true\")\n                self.add_marker(marker)\n            def runtest(self):\n                assert False\n\n        def pytest_collect_file(file_path, parent):\n            return MyItem.from_parent(name=\"foo\", parent=parent)\n    \"\"\"\n    )\n    result = pytester.inline_run()\n    _passed, skipped, failed = result.listoutcomes()\n    assert not failed\n    xfailed = [r for r in skipped if hasattr(r, \"wasxfail\")]\n    assert xfailed\n\n\ndef test_summary_list_after_errors(pytester: Pytester) -> None:\n    \"\"\"Ensure the list of errors/fails/xfails/skips appears after tracebacks in terminal reporting.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def test_fail():\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-ra\")\n    result.stdout.fnmatch_lines(\n        [\n            \"=* FAILURES *=\",\n            \"*= short test summary info =*\",\n            \"FAILED test_summary_list_after_errors.py::test_fail - assert 0\",\n        ]\n    )\n\n\ndef test_importorskip() -> None:\n    with pytest.raises(\n        pytest.skip.Exception,\n        match=r\"^could not import 'doesnotexist': No module named .*\",\n    ):\n        pytest.importorskip(\"doesnotexist\")\n\n\ndef test_relpath_rootdir(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        **{\n            \"tests/test_1.py\": \"\"\"\n        import pytest\n        @pytest.mark.skip()\n        def test_pass():\n            pass\n            \"\"\",\n        }\n    )\n    result = pytester.runpytest(\"-rs\", \"tests/test_1.py\", \"--rootdir=tests\")\n    result.stdout.fnmatch_lines(\n        [\"SKIPPED [[]1[]] tests/test_1.py:2: unconditional skip\"]\n    )\n\n\ndef test_skip_from_fixture(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        **{\n            \"tests/test_1.py\": \"\"\"\n        import pytest\n        def test_pass(arg):\n            pass\n        @pytest.fixture\n        def arg():\n            condition = True\n            if condition:\n                pytest.skip(\"Fixture conditional skip\")\n            \"\"\",\n        }\n    )\n    result = pytester.runpytest(\"-rs\", \"tests/test_1.py\", \"--rootdir=tests\")\n    result.stdout.fnmatch_lines(\n        [\"SKIPPED [[]1[]] tests/test_1.py:2: Fixture conditional skip\"]\n    )\n\n\ndef test_skip_using_reason_works_ok(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def test_skipping_reason():\n            pytest.skip(reason=\"skippedreason\")\n        \"\"\"\n    )\n    result = pytester.runpytest(p)\n    result.stdout.no_fnmatch_line(\"*PytestDeprecationWarning*\")\n    result.assert_outcomes(skipped=1)\n\n\ndef test_fail_using_reason_works_ok(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def test_failing_reason():\n            pytest.fail(reason=\"failedreason\")\n        \"\"\"\n    )\n    result = pytester.runpytest(p)\n    result.stdout.no_fnmatch_line(\"*PytestDeprecationWarning*\")\n    result.assert_outcomes(failed=1)\n\n\ndef test_exit_with_reason_works_ok(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def test_exit_reason_only():\n            pytest.exit(reason=\"foo\")\n        \"\"\"\n    )\n    result = pytester.runpytest(p)\n    result.stdout.fnmatch_lines(\"*_pytest.outcomes.Exit: foo*\")\n"
  },
  {
    "path": "testing/test_stash.py",
    "content": "from __future__ import annotations\n\nfrom _pytest.stash import Stash\nfrom _pytest.stash import StashKey\nimport pytest\n\n\ndef test_stash() -> None:\n    stash = Stash()\n\n    assert len(stash) == 0\n    assert not stash\n\n    key1 = StashKey[str]()\n    key2 = StashKey[int]()\n\n    # Basic functionality - single key.\n    assert key1 not in stash\n    stash[key1] = \"hello\"\n    assert key1 in stash\n    assert stash[key1] == \"hello\"\n    assert stash.get(key1, None) == \"hello\"\n    stash[key1] = \"world\"\n    assert stash[key1] == \"world\"\n    # Has correct type (no mypy error).\n    stash[key1] + \"string\"\n    assert len(stash) == 1\n    assert stash\n\n    # No interaction with another key.\n    assert key2 not in stash\n    assert stash.get(key2, None) is None\n    with pytest.raises(KeyError):\n        stash[key2]\n    with pytest.raises(KeyError):\n        del stash[key2]\n    stash[key2] = 1\n    assert stash[key2] == 1\n    # Has correct type (no mypy error).\n    stash[key2] + 20\n    del stash[key1]\n    with pytest.raises(KeyError):\n        del stash[key1]\n    with pytest.raises(KeyError):\n        stash[key1]\n\n    # setdefault\n    stash[key1] = \"existing\"\n    assert stash.setdefault(key1, \"default\") == \"existing\"\n    assert stash[key1] == \"existing\"\n    key_setdefault = StashKey[bytes]()\n    assert stash.setdefault(key_setdefault, b\"default\") == b\"default\"\n    assert stash[key_setdefault] == b\"default\"\n    assert len(stash) == 3\n    assert stash\n\n    # Can't accidentally add attributes to stash object itself.\n    with pytest.raises(AttributeError):\n        stash.foo = \"nope\"  # type: ignore[attr-defined]\n\n    # No interaction with another stash.\n    stash2 = Stash()\n    key3 = StashKey[int]()\n    assert key2 not in stash2\n    stash2[key2] = 100\n    stash2[key3] = 200\n    assert stash2[key2] + stash2[key3] == 300\n    assert stash[key2] == 1\n    assert key3 not in stash\n"
  },
  {
    "path": "testing/test_stepwise.py",
    "content": "# mypy: disallow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nimport json\nfrom pathlib import Path\n\nfrom _pytest.cacheprovider import Cache\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nfrom _pytest.stepwise import STEPWISE_CACHE_DIR\nimport pytest\n\n\n@pytest.fixture\ndef stepwise_pytester(pytester: Pytester) -> Pytester:\n    # Rather than having to modify our testfile between tests, we introduce\n    # a flag for whether or not the second test should fail.\n    pytester.makeconftest(\n        \"\"\"\ndef pytest_addoption(parser):\n    group = parser.getgroup('general')\n    group.addoption('--fail', action='store_true', dest='fail')\n    group.addoption('--fail-last', action='store_true', dest='fail_last')\n\"\"\"\n    )\n\n    # Create a simple test suite.\n    pytester.makepyfile(\n        test_a=\"\"\"\ndef test_success_before_fail():\n    assert 1\n\ndef test_fail_on_flag(request):\n    assert not request.config.getvalue('fail')\n\ndef test_success_after_fail():\n    assert 1\n\ndef test_fail_last_on_flag(request):\n    assert not request.config.getvalue('fail_last')\n\ndef test_success_after_last_fail():\n    assert 1\n\"\"\"\n    )\n\n    pytester.makepyfile(\n        test_b=\"\"\"\ndef test_success():\n    assert 1\n\"\"\"\n    )\n\n    # customize cache directory so we don't use the tox's cache directory, which makes tests in this module flaky\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        cache_dir = .cache\n    \"\"\"\n    )\n\n    return pytester\n\n\n@pytest.fixture\ndef error_pytester(pytester: Pytester) -> Pytester:\n    pytester.makepyfile(\n        test_a=\"\"\"\ndef test_error(nonexisting_fixture):\n    assert 1\n\ndef test_success_after_fail():\n    assert 1\n\"\"\"\n    )\n\n    return pytester\n\n\n@pytest.fixture\ndef broken_pytester(pytester: Pytester) -> Pytester:\n    pytester.makepyfile(\n        working_testfile=\"def test_proper(): assert 1\", broken_testfile=\"foobar\"\n    )\n    return pytester\n\n\ndef _strip_resource_warnings(lines: Sequence[str]) -> Sequence[str]:\n    # Strip unreliable ResourceWarnings, so no-output assertions on stderr can work.\n    # (https://github.com/pytest-dev/pytest/issues/5088)\n    return [\n        x\n        for x in lines\n        if not x.startswith((\"Exception ignored in:\", \"ResourceWarning\"))\n    ]\n\n\ndef test_run_without_stepwise(stepwise_pytester: Pytester) -> None:\n    result = stepwise_pytester.runpytest(\"-v\", \"--strict-markers\", \"--fail\")\n    result.stdout.fnmatch_lines([\"*test_success_before_fail PASSED*\"])\n    result.stdout.fnmatch_lines([\"*test_fail_on_flag FAILED*\"])\n    result.stdout.fnmatch_lines([\"*test_success_after_fail PASSED*\"])\n\n\ndef test_stepwise_output_summary(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.parametrize(\"expected\", [True, True, True, True, False])\n        def test_data(expected):\n            assert expected\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\", \"--stepwise\")\n    result.stdout.fnmatch_lines([\"stepwise: no previously failed tests, not skipping.\"])\n    result = pytester.runpytest(\"-v\", \"--stepwise\")\n    result.stdout.fnmatch_lines(\n        [\n            \"stepwise: skipping 4 already passed items (cache from * ago, use --sw-reset to discard).\",\n            \"*1 failed, 4 deselected*\",\n        ]\n    )\n\n\ndef test_fail_and_continue_with_stepwise(stepwise_pytester: Pytester) -> None:\n    # Run the tests with a failing second test.\n    result = stepwise_pytester.runpytest(\n        \"-v\", \"--strict-markers\", \"--stepwise\", \"--fail\"\n    )\n    assert _strip_resource_warnings(result.stderr.lines) == []\n\n    stdout = result.stdout.str()\n    # Make sure we stop after first failing test.\n    assert \"test_success_before_fail PASSED\" in stdout\n    assert \"test_fail_on_flag FAILED\" in stdout\n    assert \"test_success_after_fail\" not in stdout\n\n    # \"Fix\" the test that failed in the last run and run it again.\n    result = stepwise_pytester.runpytest(\"-v\", \"--strict-markers\", \"--stepwise\")\n    assert _strip_resource_warnings(result.stderr.lines) == []\n\n    stdout = result.stdout.str()\n    # Make sure the latest failing test runs and then continues.\n    assert \"test_success_before_fail\" not in stdout\n    assert \"test_fail_on_flag PASSED\" in stdout\n    assert \"test_success_after_fail PASSED\" in stdout\n\n\n@pytest.mark.parametrize(\"stepwise_skip\", [\"--stepwise-skip\", \"--sw-skip\"])\ndef test_run_with_skip_option(stepwise_pytester: Pytester, stepwise_skip: str) -> None:\n    result = stepwise_pytester.runpytest(\n        \"-v\",\n        \"--strict-markers\",\n        \"--stepwise\",\n        stepwise_skip,\n        \"--fail\",\n        \"--fail-last\",\n    )\n    assert _strip_resource_warnings(result.stderr.lines) == []\n\n    stdout = result.stdout.str()\n    # Make sure first fail is ignore and second fail stops the test run.\n    assert \"test_fail_on_flag FAILED\" in stdout\n    assert \"test_success_after_fail PASSED\" in stdout\n    assert \"test_fail_last_on_flag FAILED\" in stdout\n    assert \"test_success_after_last_fail\" not in stdout\n\n\ndef test_fail_on_errors(error_pytester: Pytester) -> None:\n    result = error_pytester.runpytest(\"-v\", \"--strict-markers\", \"--stepwise\")\n\n    assert _strip_resource_warnings(result.stderr.lines) == []\n    stdout = result.stdout.str()\n\n    assert \"test_error ERROR\" in stdout\n    assert \"test_success_after_fail\" not in stdout\n\n\ndef test_change_testfile(stepwise_pytester: Pytester) -> None:\n    result = stepwise_pytester.runpytest(\n        \"-v\", \"--strict-markers\", \"--stepwise\", \"--fail\", \"test_a.py\"\n    )\n    assert _strip_resource_warnings(result.stderr.lines) == []\n\n    stdout = result.stdout.str()\n    assert \"test_fail_on_flag FAILED\" in stdout\n\n    # Make sure the second test run starts from the beginning, since the\n    # test to continue from does not exist in testfile_b.\n    result = stepwise_pytester.runpytest(\n        \"-v\", \"--strict-markers\", \"--stepwise\", \"test_b.py\"\n    )\n    assert _strip_resource_warnings(result.stderr.lines) == []\n\n    stdout = result.stdout.str()\n    assert \"test_success PASSED\" in stdout\n\n\n@pytest.mark.parametrize(\"broken_first\", [True, False])\ndef test_stop_on_collection_errors(\n    broken_pytester: Pytester, broken_first: bool\n) -> None:\n    \"\"\"Stop during collection errors. Broken test first or broken test last\n    actually surfaced a bug (#5444), so we test both situations.\"\"\"\n    files = [\"working_testfile.py\", \"broken_testfile.py\"]\n    if broken_first:\n        files.reverse()\n    result = broken_pytester.runpytest(\"-v\", \"--strict-markers\", \"--stepwise\", *files)\n    result.stdout.fnmatch_lines(\"*error during collection*\")\n\n\ndef test_xfail_handling(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n    \"\"\"Ensure normal xfail is ignored, and strict xfail interrupts the session in sw mode\n\n    (#5547)\n    \"\"\"\n    monkeypatch.setattr(\"sys.dont_write_bytecode\", True)\n\n    contents = \"\"\"\n        import pytest\n        def test_a(): pass\n\n        @pytest.mark.xfail(strict={strict})\n        def test_b(): assert {assert_value}\n\n        def test_c(): pass\n        def test_d(): pass\n    \"\"\"\n    pytester.makepyfile(contents.format(assert_value=\"0\", strict=\"False\"))\n    result = pytester.runpytest(\"--sw\", \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*::test_a PASSED *\",\n            \"*::test_b XFAIL *\",\n            \"*::test_c PASSED *\",\n            \"*::test_d PASSED *\",\n            \"* 3 passed, 1 xfailed in *\",\n        ]\n    )\n\n    pytester.makepyfile(contents.format(assert_value=\"1\", strict=\"True\"))\n    result = pytester.runpytest(\"--sw\", \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*::test_a PASSED *\",\n            \"*::test_b FAILED *\",\n            \"* Interrupted*\",\n            \"* 1 failed, 1 passed in *\",\n        ]\n    )\n\n    pytester.makepyfile(contents.format(assert_value=\"0\", strict=\"True\"))\n    result = pytester.runpytest(\"--sw\", \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*::test_b XFAIL *\",\n            \"*::test_c PASSED *\",\n            \"*::test_d PASSED *\",\n            \"* 2 passed, 1 deselected, 1 xfailed in *\",\n        ]\n    )\n\n\ndef test_stepwise_skip_is_independent(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_one():\n            assert False\n\n        def test_two():\n            assert False\n\n        def test_three():\n            assert False\n\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--tb\", \"no\", \"--stepwise-skip\")\n    result.assert_outcomes(failed=2)\n    result.stdout.fnmatch_lines(\n        [\n            \"FAILED test_stepwise_skip_is_independent.py::test_one - assert False\",\n            \"FAILED test_stepwise_skip_is_independent.py::test_two - assert False\",\n            \"*Interrupted: Test failed, continuing from this test next run.*\",\n        ]\n    )\n\n\ndef test_sw_skip_help(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"-h\")\n    result.stdout.fnmatch_lines(\"*Implicitly enables --stepwise.\")\n\n\ndef test_stepwise_xdist_dont_store_lastfailed(pytester: Pytester) -> None:\n    pytester.makefile(\n        ext=\".ini\",\n        pytest=f\"[pytest]\\ncache_dir = {pytester.path}\\n\",\n    )\n\n    pytester.makepyfile(\n        conftest=\"\"\"\nimport pytest\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_configure(config) -> None:\n    config.workerinput = True\n\"\"\"\n    )\n    pytester.makepyfile(\n        test_one=\"\"\"\ndef test_one():\n    assert False\n\"\"\"\n    )\n    result = pytester.runpytest(\"--stepwise\")\n    assert result.ret == pytest.ExitCode.INTERRUPTED\n\n    stepwise_cache_file = (\n        pytester.path / Cache._CACHE_PREFIX_VALUES / STEPWISE_CACHE_DIR\n    )\n    assert not Path(stepwise_cache_file).exists()\n\n\ndef test_disabled_stepwise_xdist_dont_clear_cache(pytester: Pytester) -> None:\n    pytester.makefile(\n        ext=\".ini\",\n        pytest=f\"[pytest]\\ncache_dir = {pytester.path}\\n\",\n    )\n\n    stepwise_cache_file = (\n        pytester.path / Cache._CACHE_PREFIX_VALUES / STEPWISE_CACHE_DIR\n    )\n    stepwise_cache_dir = stepwise_cache_file.parent\n    stepwise_cache_dir.mkdir(exist_ok=True, parents=True)\n\n    stepwise_cache_file_relative = f\"{Cache._CACHE_PREFIX_VALUES}/{STEPWISE_CACHE_DIR}\"\n\n    expected_value = '\"test_one.py::test_one\"'\n    content = {f\"{stepwise_cache_file_relative}\": expected_value}\n\n    pytester.makefile(ext=\"\", **content)\n\n    pytester.makepyfile(\n        conftest=\"\"\"\nimport pytest\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_configure(config) -> None:\n    config.workerinput = True\n\"\"\"\n    )\n    pytester.makepyfile(\n        test_one=\"\"\"\ndef test_one():\n    assert True\n\"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n\n    assert Path(stepwise_cache_file).exists()\n    with stepwise_cache_file.open(encoding=\"utf-8\") as file_handle:\n        observed_value = file_handle.readlines()\n    assert [expected_value] == observed_value\n\n\ndef test_do_not_reset_cache_if_disabled(pytester: Pytester) -> None:\n    \"\"\"\n    If pytest is run without --stepwise, do not clear the stepwise cache.\n\n    Keeping the cache around is important for this workflow:\n\n    1. Run tests with --stepwise\n    2. Stop at the failing test, and iterate over it changing the code and running it in isolation\n    (in the IDE for example).\n    3. Run tests with --stepwise again - at this point we expect to start from the failing test, which should now pass,\n       and continue with the next tests.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        def test_1(): pass\n        def test_2(): assert False\n        def test_3(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--stepwise\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*::test_2 - assert False*\",\n            \"*failed, continuing from this test next run*\",\n            \"=* 1 failed, 1 passed in *\",\n        ]\n    )\n\n    # Run a specific test without passing `--stepwise`.\n    result = pytester.runpytest(\"-k\", \"test_1\")\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    # Running with `--stepwise` should continue from the last failing test.\n    result = pytester.runpytest(\"--stepwise\")\n    result.stdout.fnmatch_lines(\n        [\n            \"stepwise: skipping 1 already passed items (cache from *, use --sw-reset to discard).\",\n            \"*::test_2 - assert False*\",\n            \"*failed, continuing from this test next run*\",\n            \"=* 1 failed, 1 deselected in *\",\n        ]\n    )\n\n\ndef test_reset(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_1(): pass\n        def test_2(): assert False\n        def test_3(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--stepwise\", \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"stepwise: no previously failed tests, not skipping.\",\n            \"*::test_1 *PASSED*\",\n            \"*::test_2 *FAILED*\",\n            \"*failed, continuing from this test next run*\",\n            \"* 1 failed, 1 passed in *\",\n        ]\n    )\n\n    result = pytester.runpytest(\"--stepwise\", \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"stepwise: skipping 1 already passed items (cache from *, use --sw-reset to discard).\",\n            \"*::test_2 *FAILED*\",\n            \"*failed, continuing from this test next run*\",\n            \"* 1 failed, 1 deselected in *\",\n        ]\n    )\n\n    # Running with --stepwise-reset restarts the stepwise workflow.\n    result = pytester.runpytest(\"-v\", \"--stepwise-reset\")\n    result.stdout.fnmatch_lines(\n        [\n            \"stepwise: resetting state, not skipping.\",\n            \"*::test_1 *PASSED*\",\n            \"*::test_2 *FAILED*\",\n            \"*failed, continuing from this test next run*\",\n            \"* 1 failed, 1 passed in *\",\n        ]\n    )\n\n\ndef test_change_test_count(pytester: Pytester) -> None:\n    # Run initially with 3 tests.\n    pytester.makepyfile(\n        \"\"\"\n        def test_1(): pass\n        def test_2(): assert False\n        def test_3(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--stepwise\", \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"stepwise: no previously failed tests, not skipping.\",\n            \"*::test_1 *PASSED*\",\n            \"*::test_2 *FAILED*\",\n            \"*failed, continuing from this test next run*\",\n            \"* 1 failed, 1 passed in *\",\n        ]\n    )\n\n    # Change the number of tests, which invalidates the test cache.\n    pytester.makepyfile(\n        \"\"\"\n        def test_1(): pass\n        def test_2(): assert False\n        def test_3(): pass\n        def test_4(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--stepwise\", \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"stepwise: test count changed, not skipping (now 4 tests, previously 3).\",\n            \"*::test_1 *PASSED*\",\n            \"*::test_2 *FAILED*\",\n            \"*failed, continuing from this test next run*\",\n            \"* 1 failed, 1 passed in *\",\n        ]\n    )\n\n    # Fix the failing test and run again.\n    pytester.makepyfile(\n        \"\"\"\n        def test_1(): pass\n        def test_2(): pass\n        def test_3(): pass\n        def test_4(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--stepwise\", \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"stepwise: skipping 1 already passed items (cache from *, use --sw-reset to discard).\",\n            \"*::test_2 *PASSED*\",\n            \"*::test_3 *PASSED*\",\n            \"*::test_4 *PASSED*\",\n            \"* 3 passed, 1 deselected in *\",\n        ]\n    )\n\n\ndef test_cache_error(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_1(): pass\n        \"\"\"\n    )\n    # Run stepwise normally to generate the cache information.\n    result = pytester.runpytest(\"--stepwise\", \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"stepwise: no previously failed tests, not skipping.\",\n            \"*::test_1 *PASSED*\",\n            \"* 1 passed in *\",\n        ]\n    )\n\n    # Corrupt the cache.\n    cache_file = pytester.path / f\".pytest_cache/v/{STEPWISE_CACHE_DIR}\"\n    assert cache_file.is_file()\n    cache_file.write_text(json.dumps({\"invalid\": True}), encoding=\"UTF-8\")\n\n    # Check we run as if the cache did not exist, but also show an error message.\n    result = pytester.runpytest(\"--stepwise\", \"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"stepwise: error reading cache, discarding (KeyError: *\",\n            \"stepwise: no previously failed tests, not skipping.\",\n            \"*::test_1 *PASSED*\",\n            \"* 1 passed in *\",\n        ]\n    )\n"
  },
  {
    "path": "testing/test_subtests.py",
    "content": "from __future__ import annotations\n\nfrom enum import Enum\nimport json\nimport sys\nfrom typing import Literal\n\nfrom _pytest._io.saferepr import saferepr\nfrom _pytest.subtests import SubtestContext\nfrom _pytest.subtests import SubtestReport\nimport pytest\n\n\nIS_PY311 = sys.version_info[:2] >= (3, 11)\n\n\ndef test_failures(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> None:\n    monkeypatch.setenv(\"COLUMNS\", \"120\")\n    pytester.makepyfile(\n        \"\"\"\n        def test_foo(subtests):\n            with subtests.test(\"foo subtest\"):\n                assert False, \"foo subtest failure\"\n\n        def test_bar(subtests):\n            with subtests.test(\"bar subtest\"):\n                assert False, \"bar subtest failure\"\n            assert False, \"test_bar also failed\"\n\n        def test_zaz(subtests):\n            with subtests.test(\"zaz subtest\"):\n                pass\n        \"\"\"\n    )\n    summary_lines = [\n        \"*=== FAILURES ===*\",\n        #\n        \"*___ test_foo [[]foo subtest[]] ___*\",\n        \"*AssertionError: foo subtest failure\",\n        #\n        \"*___ test_foo ___*\",\n        \"contains 1 failed subtest\",\n        #\n        \"*___ test_bar [[]bar subtest[]] ___*\",\n        \"*AssertionError: bar subtest failure\",\n        #\n        \"*___ test_bar ___*\",\n        \"*AssertionError: test_bar also failed\",\n        #\n        \"*=== short test summary info ===*\",\n        \"SUBFAILED[[]foo subtest[]] test_*.py::test_foo - AssertionError*\",\n        \"FAILED test_*.py::test_foo - contains 1 failed subtest\",\n        \"SUBFAILED[[]bar subtest[]] test_*.py::test_bar - AssertionError*\",\n        \"FAILED test_*.py::test_bar - AssertionError*\",\n    ]\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"test_*.py uFuF.    *     [[]100%[]]\",\n            *summary_lines,\n            \"* 4 failed, 1 passed in *\",\n        ]\n    )\n\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"test_*.py::test_foo SUBFAILED[[]foo subtest[]]    *     [[] 33%[]]\",\n            \"test_*.py::test_foo FAILED                        *     [[] 33%[]]\",\n            \"test_*.py::test_bar SUBFAILED[[]bar subtest[]]    *     [[] 66%[]]\",\n            \"test_*.py::test_bar FAILED                        *     [[] 66%[]]\",\n            \"test_*.py::test_zaz SUBPASSED[[]zaz subtest[]]    *     [[]100%[]]\",\n            \"test_*.py::test_zaz PASSED                        *     [[]100%[]]\",\n            *summary_lines,\n            \"* 4 failed, 1 passed, 1 subtests passed in *\",\n        ]\n    )\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        verbosity_subtests = 0\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"test_*.py::test_foo SUBFAILED[[]foo subtest[]]    *     [[] 33%[]]\",\n            \"test_*.py::test_foo FAILED                        *     [[] 33%[]]\",\n            \"test_*.py::test_bar SUBFAILED[[]bar subtest[]]    *     [[] 66%[]]\",\n            \"test_*.py::test_bar FAILED                        *     [[] 66%[]]\",\n            \"test_*.py::test_zaz PASSED                        *     [[]100%[]]\",\n            *summary_lines,\n            \"* 4 failed, 1 passed in *\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"test_*.py::test_zaz SUBPASSED[[]zaz subtest[]]*\")\n\n\ndef test_passes(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> None:\n    monkeypatch.setenv(\"COLUMNS\", \"120\")\n    pytester.makepyfile(\n        \"\"\"\n        def test_foo(subtests):\n            with subtests.test(\"foo subtest\"):\n                pass\n\n        def test_bar(subtests):\n            with subtests.test(\"bar subtest\"):\n                pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"test_*.py ..    *     [[]100%[]]\",\n            \"* 2 passed in *\",\n        ]\n    )\n\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*.py::test_foo SUBPASSED[[]foo subtest[]]      * [[] 50%[]]\",\n            \"*.py::test_foo PASSED                          * [[] 50%[]]\",\n            \"*.py::test_bar SUBPASSED[[]bar subtest[]]      * [[]100%[]]\",\n            \"*.py::test_bar PASSED                          * [[]100%[]]\",\n            \"* 2 passed, 2 subtests passed in *\",\n        ]\n    )\n\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        verbosity_subtests = 0\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*.py::test_foo PASSED                          * [[] 50%[]]\",\n            \"*.py::test_bar PASSED                          * [[]100%[]]\",\n            \"* 2 passed in *\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*.py::test_foo SUBPASSED[[]foo subtest[]]*\")\n    result.stdout.no_fnmatch_line(\"*.py::test_bar SUBPASSED[[]bar subtest[]]*\")\n\n\ndef test_skip(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> None:\n    monkeypatch.setenv(\"COLUMNS\", \"120\")\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def test_foo(subtests):\n            with subtests.test(\"foo subtest\"):\n                pytest.skip(\"skip foo subtest\")\n\n        def test_bar(subtests):\n            with subtests.test(\"bar subtest\"):\n                pytest.skip(\"skip bar subtest\")\n            pytest.skip(\"skip test_bar\")\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-ra\")\n    result.stdout.fnmatch_lines(\n        [\n            \"test_*.py .s    *     [[]100%[]]\",\n            \"*=== short test summary info ===*\",\n            \"SKIPPED [[]1[]] test_skip.py:9: skip test_bar\",\n            \"* 1 passed, 1 skipped in *\",\n        ]\n    )\n\n    result = pytester.runpytest(\"-v\", \"-ra\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*.py::test_foo SUBSKIPPED[[]foo subtest[]] (skip foo subtest)  * [[] 50%[]]\",\n            \"*.py::test_foo PASSED                                          * [[] 50%[]]\",\n            \"*.py::test_bar SUBSKIPPED[[]bar subtest[]] (skip bar subtest)  * [[]100%[]]\",\n            \"*.py::test_bar SKIPPED (skip test_bar)                         * [[]100%[]]\",\n            \"*=== short test summary info ===*\",\n            \"SUBSKIPPED[[]foo subtest[]] [[]1[]] *.py:*: skip foo subtest\",\n            \"SUBSKIPPED[[]foo subtest[]] [[]1[]] *.py:*: skip bar subtest\",\n            \"SUBSKIPPED[[]foo subtest[]] [[]1[]] *.py:*: skip test_bar\",\n            \"* 1 passed, 3 skipped in *\",\n        ]\n    )\n\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        verbosity_subtests = 0\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\", \"-ra\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*.py::test_foo PASSED                          * [[] 50%[]]\",\n            \"*.py::test_bar SKIPPED (skip test_bar)         * [[]100%[]]\",\n            \"*=== short test summary info ===*\",\n            \"* 1 passed, 1 skipped in *\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*.py::test_foo SUBPASSED[[]foo subtest[]]*\")\n    result.stdout.no_fnmatch_line(\"*.py::test_bar SUBPASSED[[]bar subtest[]]*\")\n    result.stdout.no_fnmatch_line(\n        \"SUBSKIPPED[[]foo subtest[]] [[]1[]] *.py:*: skip foo subtest\"\n    )\n    result.stdout.no_fnmatch_line(\n        \"SUBSKIPPED[[]foo subtest[]] [[]1[]] *.py:*: skip test_bar\"\n    )\n\n\ndef test_xfail(pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch) -> None:\n    monkeypatch.setenv(\"COLUMNS\", \"120\")\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def test_foo(subtests):\n            with subtests.test(\"foo subtest\"):\n                pytest.xfail(\"xfail foo subtest\")\n\n        def test_bar(subtests):\n            with subtests.test(\"bar subtest\"):\n                pytest.xfail(\"xfail bar subtest\")\n            pytest.xfail(\"xfail test_bar\")\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-ra\")\n    result.stdout.fnmatch_lines(\n        [\n            \"test_*.py .x    *     [[]100%[]]\",\n            \"*=== short test summary info ===*\",\n            \"* 1 passed, 1 xfailed in *\",\n        ]\n    )\n\n    result = pytester.runpytest(\"-v\", \"-ra\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*.py::test_foo SUBXFAIL[[]foo subtest[]] (xfail foo subtest)    * [[] 50%[]]\",\n            \"*.py::test_foo PASSED                                           * [[] 50%[]]\",\n            \"*.py::test_bar SUBXFAIL[[]bar subtest[]] (xfail bar subtest)    * [[]100%[]]\",\n            \"*.py::test_bar XFAIL (xfail test_bar)                           * [[]100%[]]\",\n            \"*=== short test summary info ===*\",\n            \"SUBXFAIL[[]foo subtest[]] *.py::test_foo - xfail foo subtest\",\n            \"SUBXFAIL[[]bar subtest[]] *.py::test_bar - xfail bar subtest\",\n            \"XFAIL *.py::test_bar - xfail test_bar\",\n            \"* 1 passed, 3 xfailed in *\",\n        ]\n    )\n\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        verbosity_subtests = 0\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\", \"-ra\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*.py::test_foo PASSED                          * [[] 50%[]]\",\n            \"*.py::test_bar XFAIL (xfail test_bar)         * [[]100%[]]\",\n            \"*=== short test summary info ===*\",\n            \"* 1 passed, 1 xfailed in *\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\n        \"SUBXFAIL[[]foo subtest[]] *.py::test_foo - xfail foo subtest\"\n    )\n    result.stdout.no_fnmatch_line(\n        \"SUBXFAIL[[]bar subtest[]] *.py::test_bar - xfail bar subtest\"\n    )\n\n\ndef test_typing_exported(pytester: pytest.Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        from pytest import Subtests\n\n        def test_typing_exported(subtests: Subtests) -> None:\n            assert isinstance(subtests, Subtests)\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_subtests_and_parametrization(\n    pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    monkeypatch.setenv(\"COLUMNS\", \"120\")\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.parametrize(\"x\", [0, 1])\n        def test_foo(subtests, x):\n            for i in range(3):\n                with subtests.test(\"custom\", i=i):\n                    assert i % 2 == 0\n            assert x == 0\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*.py::test_foo[[]0[]] SUBFAILED[[]custom[]] (i=1) *[[] 50%[]]\",\n            \"*.py::test_foo[[]0[]] FAILED                        *[[] 50%[]]\",\n            \"*.py::test_foo[[]1[]] SUBFAILED[[]custom[]] (i=1) *[[]100%[]]\",\n            \"*.py::test_foo[[]1[]] FAILED                        *[[]100%[]]\",\n            \"contains 1 failed subtest\",\n            \"* 4 failed, 4 subtests passed in *\",\n        ]\n    )\n\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        verbosity_subtests = 0\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*.py::test_foo[[]0[]] SUBFAILED[[]custom[]] (i=1) *[[] 50%[]]\",\n            \"*.py::test_foo[[]0[]] FAILED                        *[[] 50%[]]\",\n            \"*.py::test_foo[[]1[]] SUBFAILED[[]custom[]] (i=1) *[[]100%[]]\",\n            \"*.py::test_foo[[]1[]] FAILED                        *[[]100%[]]\",\n            \"contains 1 failed subtest\",\n            \"* 4 failed in *\",\n        ]\n    )\n\n\ndef test_subtests_fail_top_level_test(pytester: pytest.Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def test_foo(subtests):\n            for i in range(3):\n                with subtests.test(\"custom\", i=i):\n                    assert i % 2 == 0\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"* 2 failed, 2 subtests passed in *\",\n        ]\n    )\n\n\ndef test_subtests_do_not_overwrite_top_level_failure(pytester: pytest.Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def test_foo(subtests):\n            for i in range(3):\n                with subtests.test(\"custom\", i=i):\n                    assert i % 2 == 0\n            assert False, \"top-level failure\"\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*AssertionError: top-level failure\",\n            \"* 2 failed, 2 subtests passed in *\",\n        ]\n    )\n\n\ndef test_msg_not_a_string(\n    pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch\n) -> None:\n    \"\"\"\n    Using a non-string in subtests.test() should still show it in the terminal (#14195).\n\n    Note: this was not a problem originally with the subtests fixture, only with TestCase.subTest; this test\n    was added for symmetry.\n    \"\"\"\n    monkeypatch.setenv(\"COLUMNS\", \"120\")\n    pytester.makepyfile(\n        \"\"\"\n        def test_int_msg(subtests):\n            with subtests.test(42):\n                assert False, \"subtest failure\"\n\n        def test_no_msg(subtests):\n            with subtests.test():\n                assert False, \"subtest failure\"\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"SUBFAILED[[]42[]] test_msg_not_a_string.py::test_int_msg - AssertionError: subtest failure\",\n            \"SUBFAILED(<subtest>) test_msg_not_a_string.py::test_no_msg - AssertionError: subtest failure\",\n        ]\n    )\n\n\n@pytest.mark.parametrize(\"flag\", [\"--last-failed\", \"--stepwise\"])\ndef test_subtests_last_failed_step_wise(pytester: pytest.Pytester, flag: str) -> None:\n    \"\"\"Check that --last-failed and --step-wise correctly rerun tests with failed subtests.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def test_foo(subtests):\n            for i in range(3):\n                with subtests.test(\"custom\", i=i):\n                    assert i % 2 == 0\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"* 2 failed, 2 subtests passed in *\",\n        ]\n    )\n\n    result = pytester.runpytest(\"-v\", flag)\n    result.stdout.fnmatch_lines(\n        [\n            \"* 2 failed, 2 subtests passed in *\",\n        ]\n    )\n\n\nclass TestUnittestSubTest:\n    \"\"\"Test unittest.TestCase.subTest functionality.\"\"\"\n\n    def test_failures(\n        self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"COLUMNS\", \"120\")\n        pytester.makepyfile(\n            \"\"\"\n            from unittest import TestCase\n\n            class T(TestCase):\n                def test_foo(self):\n                    with self.subTest(\"foo subtest\"):\n                        assert False, \"foo subtest failure\"\n\n                def test_bar(self):\n                    with self.subTest(\"bar subtest\"):\n                        assert False, \"bar subtest failure\"\n                    assert False, \"test_bar also failed\"\n\n                def test_zaz(self):\n                    with self.subTest(\"zaz subtest\"):\n                        pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"* 3 failed, 2 passed in *\",\n            ]\n        )\n\n    def test_passes(\n        self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"COLUMNS\", \"120\")\n        pytester.makepyfile(\n            \"\"\"\n            from unittest import TestCase\n\n            class T(TestCase):\n                def test_foo(self):\n                    with self.subTest(\"foo subtest\"):\n                        pass\n\n                def test_bar(self):\n                    with self.subTest(\"bar subtest\"):\n                        pass\n\n                def test_zaz(self):\n                    with self.subTest(\"zaz subtest\"):\n                        pass\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"* 3 passed in *\",\n            ]\n        )\n\n    def test_skip(\n        self,\n        pytester: pytest.Pytester,\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            from unittest import TestCase, main\n\n            class T(TestCase):\n\n                def test_foo(self):\n                    for i in range(5):\n                        with self.subTest(msg=\"custom\", i=i):\n                            if i % 2 == 0:\n                                self.skipTest('even number')\n        \"\"\"\n        )\n        # This output might change #13756.\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n    def test_non_subtest_skip(\n        self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        monkeypatch.setenv(\"COLUMNS\", \"120\")\n        pytester.makepyfile(\n            \"\"\"\n            from unittest import TestCase, main\n\n            class T(TestCase):\n\n                def test_foo(self):\n                    with self.subTest(msg=\"subtest\"):\n                        assert False, \"failed subtest\"\n                    self.skipTest('non-subtest skip')\n        \"\"\"\n        )\n        # This output might change #13756.\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"SUBFAILED[[]subtest[]] test_non_subtest_skip.py::T::test_foo*\",\n                \"* 1 failed, 1 skipped in *\",\n            ]\n        )\n\n    def test_xfail(\n        self,\n        pytester: pytest.Pytester,\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            from unittest import expectedFailure, TestCase\n\n            class T(TestCase):\n                @expectedFailure\n                def test_foo(self):\n                    for i in range(5):\n                        with self.subTest(msg=\"custom\", i=i):\n                            if i % 2 == 0:\n                                raise pytest.xfail('even number')\n\n            if __name__ == '__main__':\n                main()\n        \"\"\"\n        )\n        # This output might change #13756.\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"* 1 xfailed in *\"])\n\n    def test_only_original_skip_is_called(\n        self,\n        pytester: pytest.Pytester,\n        monkeypatch: pytest.MonkeyPatch,\n    ) -> None:\n        \"\"\"Regression test for pytest-dev/pytest-subtests#173.\"\"\"\n        monkeypatch.setenv(\"COLUMNS\", \"120\")\n        pytester.makepyfile(\n            \"\"\"\n            import unittest\n            from unittest import TestCase\n\n            @unittest.skip(\"skip this test\")\n            class T(unittest.TestCase):\n                def test_foo(self):\n                    assert 1 == 2\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-v\", \"-rsf\")\n        result.stdout.fnmatch_lines(\n            [\"SKIPPED [1] test_only_original_skip_is_called.py:6: skip this test\"]\n        )\n\n    def test_skip_with_failure(\n        self,\n        pytester: pytest.Pytester,\n        monkeypatch: pytest.MonkeyPatch,\n    ) -> None:\n        monkeypatch.setenv(\"COLUMNS\", \"120\")\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            from unittest import TestCase\n\n            class T(TestCase):\n                def test_foo(self):\n                    with self.subTest(\"subtest 1\"):\n                        self.skipTest(f\"skip subtest 1\")\n                    with self.subTest(\"subtest 2\"):\n                        assert False, \"fail subtest 2\"\n            \"\"\"\n        )\n\n        result = pytester.runpytest(\"-ra\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*.py u.                                                           *            [[]100%[]]\",\n                \"*=== short test summary info ===*\",\n                \"SUBFAILED[[]subtest 2[]] *.py::T::test_foo - AssertionError: fail subtest 2\",\n                \"* 1 failed, 1 passed in *\",\n            ]\n        )\n\n        result = pytester.runpytest(\"-v\", \"-ra\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*.py::T::test_foo SUBSKIPPED[[]subtest 1[]] (skip subtest 1)      *            [[]100%[]]\",\n                \"*.py::T::test_foo SUBFAILED[[]subtest 2[]]                        *            [[]100%[]]\",\n                \"*.py::T::test_foo PASSED                                          *            [[]100%[]]\",\n                \"SUBSKIPPED[[]subtest 1[]] [[]1[]] *.py:*: skip subtest 1\",\n                \"SUBFAILED[[]subtest 2[]] *.py::T::test_foo - AssertionError: fail subtest 2\",\n                \"* 1 failed, 1 passed, 1 skipped in *\",\n            ]\n        )\n\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            verbosity_subtests = 0\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-v\", \"-ra\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*.py::T::test_foo SUBFAILED[[]subtest 2[]]                        *            [[]100%[]]\",\n                \"*.py::T::test_foo PASSED                                          *            [[]100%[]]\",\n                \"*=== short test summary info ===*\",\n                r\"SUBFAILED[[]subtest 2[]] *.py::T::test_foo - AssertionError: fail subtest 2\",\n                r\"* 1 failed, 1 passed in *\",\n            ]\n        )\n        result.stdout.no_fnmatch_line(\n            \"*.py::T::test_foo SUBSKIPPED[[]subtest 1[]] (skip subtest 1) * [[]100%[]]\"\n        )\n        result.stdout.no_fnmatch_line(\n            \"SUBSKIPPED[[]subtest 1[]] [[]1[]] *.py:*: skip subtest 1\"\n        )\n\n    def test_msg_not_a_string(\n        self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        \"\"\"Using a non-string in TestCase.subTest should still show it in the terminal (#14195).\"\"\"\n        monkeypatch.setenv(\"COLUMNS\", \"120\")\n        pytester.makepyfile(\n            \"\"\"\n            from unittest import TestCase\n\n            class T(TestCase):\n                def test_int_msg(self):\n                    with self.subTest(42):\n                        assert False, \"subtest failure\"\n\n                def test_no_msg(self):\n                    with self.subTest():\n                        assert False, \"subtest failure\"\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"SUBFAILED[[]42[]] test_msg_not_a_string.py::T::test_int_msg - AssertionError: subtest failure\",\n                \"SUBFAILED(<subtest>) test_msg_not_a_string.py::T::test_no_msg - AssertionError: subtest failure\",\n            ]\n        )\n\n\nclass TestCapture:\n    def create_file(self, pytester: pytest.Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import sys\n            def test(subtests):\n                print()\n                print('start test')\n\n                with subtests.test(i='A'):\n                    print(\"hello stdout A\")\n                    print(\"hello stderr A\", file=sys.stderr)\n                    assert 0\n\n                with subtests.test(i='B'):\n                    print(\"hello stdout B\")\n                    print(\"hello stderr B\", file=sys.stderr)\n                    assert 0\n\n                print('end test')\n                assert 0\n        \"\"\"\n        )\n\n    @pytest.mark.parametrize(\"mode\", [\"fd\", \"sys\"])\n    def test_capturing(self, pytester: pytest.Pytester, mode: str) -> None:\n        self.create_file(pytester)\n        result = pytester.runpytest(f\"--capture={mode}\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*__ test (i='A') __*\",\n                \"*Captured stdout call*\",\n                \"hello stdout A\",\n                \"*Captured stderr call*\",\n                \"hello stderr A\",\n                \"*__ test (i='B') __*\",\n                \"*Captured stdout call*\",\n                \"hello stdout B\",\n                \"*Captured stderr call*\",\n                \"hello stderr B\",\n                \"*__ test __*\",\n                \"*Captured stdout call*\",\n                \"start test\",\n                \"end test\",\n            ]\n        )\n\n    def test_no_capture(self, pytester: pytest.Pytester) -> None:\n        self.create_file(pytester)\n        result = pytester.runpytest(\"-s\")\n        result.stdout.fnmatch_lines(\n            [\n                \"start test\",\n                \"hello stdout A\",\n                \"uhello stdout B\",\n                \"uend test\",\n                \"*__ test (i='A') __*\",\n                \"*__ test (i='B') __*\",\n                \"*__ test __*\",\n            ]\n        )\n        result.stderr.fnmatch_lines([\"hello stderr A\", \"hello stderr B\"])\n\n    @pytest.mark.parametrize(\"fixture\", [\"capsys\", \"capfd\"])\n    def test_capture_with_fixture(\n        self, pytester: pytest.Pytester, fixture: Literal[\"capsys\", \"capfd\"]\n    ) -> None:\n        pytester.makepyfile(\n            rf\"\"\"\n            import sys\n\n            def test(subtests, {fixture}):\n                print('start test')\n\n                with subtests.test(i='A'):\n                    print(\"hello stdout A\")\n                    print(\"hello stderr A\", file=sys.stderr)\n\n                out, err = {fixture}.readouterr()\n                assert out == 'start test\\nhello stdout A\\n'\n                assert err == 'hello stderr A\\n'\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*1 passed*\",\n            ]\n        )\n\n\nclass TestLogging:\n    def create_file(self, pytester: pytest.Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import logging\n\n            def test_foo(subtests):\n                logging.info(\"before\")\n\n                with subtests.test(\"sub1\"):\n                    print(\"sub1 stdout\")\n                    logging.info(\"sub1 logging\")\n                    logging.debug(\"sub1 logging debug\")\n\n                with subtests.test(\"sub2\"):\n                    print(\"sub2 stdout\")\n                    logging.info(\"sub2 logging\")\n                    logging.debug(\"sub2 logging debug\")\n                    assert False\n            \"\"\"\n        )\n\n    def test_capturing_info(self, pytester: pytest.Pytester) -> None:\n        self.create_file(pytester)\n        result = pytester.runpytest(\"--log-level=INFO\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*___ test_foo [[]sub2[]] __*\",\n                \"*-- Captured stdout call --*\",\n                \"sub2 stdout\",\n                \"*-- Captured log call ---*\",\n                \"INFO     * before\",\n                \"INFO     * sub1 logging\",\n                \"INFO     * sub2 logging\",\n                \"*== short test summary info ==*\",\n            ]\n        )\n        result.stdout.no_fnmatch_line(\"sub1 logging debug\")\n        result.stdout.no_fnmatch_line(\"sub2 logging debug\")\n\n    def test_capturing_debug(self, pytester: pytest.Pytester) -> None:\n        self.create_file(pytester)\n        result = pytester.runpytest(\"--log-level=DEBUG\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*___ test_foo [[]sub2[]] __*\",\n                \"*-- Captured stdout call --*\",\n                \"sub2 stdout\",\n                \"*-- Captured log call ---*\",\n                \"INFO     * before\",\n                \"INFO     * sub1 logging\",\n                \"DEBUG    * sub1 logging debug\",\n                \"INFO     * sub2 logging\",\n                \"DEBUG    * sub2 logging debug\",\n                \"*== short test summary info ==*\",\n            ]\n        )\n\n    def test_caplog(self, pytester: pytest.Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import logging\n\n            def test(subtests, caplog):\n                caplog.set_level(logging.INFO)\n                logging.info(\"start test\")\n\n                with subtests.test(\"sub1\"):\n                    logging.info(\"inside %s\", \"subtest1\")\n\n                assert len(caplog.records) == 2\n                assert caplog.records[0].getMessage() == \"start test\"\n                assert caplog.records[1].getMessage() == \"inside subtest1\"\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*1 passed*\",\n            ]\n        )\n\n    def test_no_logging(self, pytester: pytest.Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import logging\n\n            def test(subtests):\n                logging.info(\"start log line\")\n\n                with subtests.test(\"sub passing\"):\n                    logging.info(\"inside %s\", \"passing log line\")\n\n                with subtests.test(\"sub failing\"):\n                    logging.info(\"inside %s\", \"failing log line\")\n                    assert False\n\n                logging.info(\"end log line\")\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-p no:logging\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*2 failed in*\",\n            ]\n        )\n        result.stdout.no_fnmatch_line(\"*root:test_no_logging.py*log line*\")\n\n\nclass TestDebugging:\n    \"\"\"Check --pdb support for subtests fixture and TestCase.subTest.\"\"\"\n\n    class _FakePdb:\n        \"\"\"Fake debugger class implementation that tracks which methods were called on it.\"\"\"\n\n        quitting: bool = False\n        calls: list[str] = []\n\n        def __init__(self, *_: object, **__: object) -> None:\n            self.calls.append(\"init\")\n\n        def reset(self) -> None:\n            self.calls.append(\"reset\")\n\n        def interaction(self, *_: object) -> None:\n            self.calls.append(\"interaction\")\n\n    @pytest.fixture(autouse=True)\n    def cleanup_calls(self) -> None:\n        self._FakePdb.calls.clear()\n\n    def test_pdb_fixture(\n        self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test(subtests):\n                with subtests.test():\n                    assert 0\n            \"\"\"\n        )\n        self.runpytest_and_check_pdb(pytester, monkeypatch)\n\n    def test_pdb_unittest(\n        self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            from unittest import TestCase\n            class Test(TestCase):\n                def test(self):\n                    with self.subTest():\n                        assert 0\n            \"\"\"\n        )\n        self.runpytest_and_check_pdb(pytester, monkeypatch)\n\n    def runpytest_and_check_pdb(\n        self, pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch\n    ) -> None:\n        # Install the fake pdb implementation in _pytest.subtests so we can reference\n        # it in the command line (any module would do).\n        import _pytest.subtests\n\n        monkeypatch.setattr(\n            _pytest.subtests, \"_CustomPdb\", self._FakePdb, raising=False\n        )\n        result = pytester.runpytest(\"--pdb\", \"--pdbcls=_pytest.subtests:_CustomPdb\")\n\n        # Ensure pytest entered in debugging mode when encountering the failing\n        # assert.\n        result.stdout.fnmatch_lines(\"*entering PDB*\")\n        assert self._FakePdb.calls == [\"init\", \"reset\", \"interaction\"]\n\n\ndef test_exitfirst(pytester: pytest.Pytester) -> None:\n    \"\"\"Validate that when passing --exitfirst the test exits after the first failed subtest.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        def test_foo(subtests):\n            with subtests.test(\"sub1\"):\n                assert False\n\n            with subtests.test(\"sub2\"):\n                assert False\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--exitfirst\")\n    assert result.parseoutcomes()[\"failed\"] == 2\n    result.stdout.fnmatch_lines(\n        [\n            \"SUBFAILED*[[]sub1[]] *.py::test_foo - assert False*\",\n            \"FAILED *.py::test_foo - assert False\",\n            \"* stopping after 2 failures*\",\n        ],\n        consecutive=True,\n    )\n    result.stdout.no_fnmatch_line(\"*sub2*\")  # sub2 not executed.\n\n\ndef test_do_not_swallow_pytest_exit(pytester: pytest.Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def test(subtests):\n            with subtests.test():\n                pytest.exit()\n\n        def test2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest_subprocess()\n    result.stdout.fnmatch_lines(\n        [\n            \"* _pytest.outcomes.Exit *\",\n            \"* 1 failed in *\",\n        ]\n    )\n\n\ndef test_nested(pytester: pytest.Pytester) -> None:\n    \"\"\"\n    Currently we do nothing special with nested subtests.\n\n    This test only sediments how they work now, we might reconsider adding some kind of nesting support in the future.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        def test(subtests):\n            with subtests.test(\"a\"):\n                with subtests.test(\"b\"):\n                    assert False, \"b failed\"\n                assert False, \"a failed\"\n        \"\"\"\n    )\n    result = pytester.runpytest_subprocess()\n    result.stdout.fnmatch_lines(\n        [\n            \"SUBFAILED[b] test_nested.py::test - AssertionError: b failed\",\n            \"SUBFAILED[a] test_nested.py::test - AssertionError: a failed\",\n            \"* 3 failed in *\",\n        ]\n    )\n\n\nclass MyEnum(Enum):\n    \"\"\"Used in test_serialization, needs to be declared at the module level to be pickled.\"\"\"\n\n    A = \"A\"\n\n\ndef test_serialization() -> None:\n    \"\"\"Ensure subtest's kwargs are serialized using `saferepr` (pytest-dev/pytest-xdist#1273).\"\"\"\n    from _pytest.subtests import pytest_report_from_serializable\n    from _pytest.subtests import pytest_report_to_serializable\n\n    report = SubtestReport(\n        \"test_foo::test_foo\",\n        (\"test_foo.py\", 12, \"\"),\n        keywords={},\n        outcome=\"passed\",\n        when=\"call\",\n        longrepr=None,\n        context=SubtestContext(msg=\"custom message\", kwargs=dict(i=10, a=MyEnum.A)),\n    )\n    data = pytest_report_to_serializable(report)\n    assert data is not None\n    # Ensure the report is actually serializable to JSON.\n    _ = json.dumps(data)\n    new_report = pytest_report_from_serializable(data)\n    assert new_report is not None\n    assert new_report.context == SubtestContext(\n        msg=\"custom message\", kwargs=dict(i=saferepr(10), a=saferepr(MyEnum.A))\n    )\n\n\ndef test_serialization_xdist(pytester: pytest.Pytester) -> None:  # pragma: no cover\n    \"\"\"Regression test for pytest-dev/pytest-xdist#1273.\"\"\"\n    pytest.importorskip(\"xdist\")\n    pytester.makepyfile(\n        \"\"\"\n        from enum import Enum\n        import unittest\n\n        class MyEnum(Enum):\n            A = \"A\"\n\n        def test(subtests):\n            with subtests.test(a=MyEnum.A):\n                pass\n\n        class T(unittest.TestCase):\n\n            def test(self):\n                with self.subTest(a=MyEnum.A):\n                    pass\n        \"\"\"\n    )\n    pytester.syspathinsert()\n    result = pytester.runpytest(\"-n1\", \"-pxdist.plugin\")\n    result.assert_outcomes(passed=2)\n"
  },
  {
    "path": "testing/test_terminal.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"Terminal reporting of the full testing process.\"\"\"\n\nfrom __future__ import annotations\n\nfrom io import StringIO\nimport os\nfrom pathlib import Path\nimport sys\nimport textwrap\nfrom types import SimpleNamespace\nfrom typing import cast\nfrom typing import Literal\nfrom typing import NamedTuple\nfrom unittest import mock\n\nimport pluggy\n\nfrom _pytest._io.wcwidth import wcswidth\nimport _pytest.config\nfrom _pytest.config import Config\nfrom _pytest.config import ExitCode\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nfrom _pytest.reports import BaseReport\nfrom _pytest.reports import CollectReport\nfrom _pytest.reports import TestReport\nimport _pytest.terminal\nfrom _pytest.terminal import _folded_skips\nfrom _pytest.terminal import _format_trimmed\nfrom _pytest.terminal import _get_line_with_reprcrash_message\nfrom _pytest.terminal import _get_raw_skip_reason\nfrom _pytest.terminal import _plugin_nameversions\nfrom _pytest.terminal import getreportopt\nfrom _pytest.terminal import TerminalProgressPlugin\nfrom _pytest.terminal import TerminalReporter\nimport pytest\n\n\nclass DistInfo(NamedTuple):\n    project_name: str\n    version: int\n\n\nTRANS_FNMATCH = str.maketrans({\"[\": \"[[]\", \"]\": \"[]]\"})\n\n\nclass Option:\n    def __init__(self, verbosity=0):\n        self.verbosity = verbosity\n\n    @property\n    def args(self):\n        values = []\n        values.append(f\"--verbosity={self.verbosity}\")\n        return values\n\n\n@pytest.fixture(\n    params=[Option(verbosity=0), Option(verbosity=1), Option(verbosity=-1)],\n    ids=[\"default\", \"verbose\", \"quiet\"],\n)\ndef option(request):\n    return request.param\n\n\n@pytest.mark.parametrize(\n    \"input,expected\",\n    [\n        ([DistInfo(project_name=\"test\", version=1)], [\"test-1\"]),\n        ([DistInfo(project_name=\"pytest-test\", version=1)], [\"test-1\"]),\n        (\n            [\n                DistInfo(project_name=\"test\", version=1),\n                DistInfo(project_name=\"test\", version=1),\n            ],\n            [\"test-1\"],\n        ),\n    ],\n    ids=[\"normal\", \"prefix-strip\", \"deduplicate\"],\n)\ndef test_plugin_nameversion(input, expected):\n    pluginlist = [(None, x) for x in input]\n    result = _plugin_nameversions(pluginlist)\n    assert result == expected\n\n\nclass TestTerminal:\n    def test_pass_skip_fail(self, pytester: Pytester, option) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_ok():\n                pass\n            def test_skip():\n                pytest.skip(\"xx\")\n            def test_func():\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(*option.args)\n        if option.verbosity > 0:\n            result.stdout.fnmatch_lines(\n                [\n                    \"*test_pass_skip_fail.py::test_ok PASS*\",\n                    \"*test_pass_skip_fail.py::test_skip SKIP*\",\n                    \"*test_pass_skip_fail.py::test_func FAIL*\",\n                ]\n            )\n        elif option.verbosity == 0:\n            result.stdout.fnmatch_lines([\"*test_pass_skip_fail.py .sF*\"])\n        else:\n            result.stdout.fnmatch_lines([\".sF*\"])\n        result.stdout.fnmatch_lines(\n            [\"    def test_func():\", \">       assert 0\", \"E       assert 0\"]\n        )\n\n    def test_console_output_style_times_with_skipped_and_passed(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            test_repro=\"\"\"\n                def test_hello():\n                    pass\n            \"\"\",\n            test_repro_skip=\"\"\"\n                import pytest\n                pytest.importorskip(\"fakepackage_does_not_exist\")\n            \"\"\",\n        )\n        result = pytester.runpytest(\n            \"test_repro.py\",\n            \"test_repro_skip.py\",\n            \"-o\",\n            \"console_output_style=times\",\n        )\n\n        result.stdout.fnmatch_lines(\"* 1 passed, 1 skipped in *\")\n\n        combined = \"\\n\".join(result.stdout.lines + result.stderr.lines)\n        assert \"INTERNALERROR\" not in combined\n\n    def test_internalerror(self, pytester: Pytester, linecomp) -> None:\n        modcol = pytester.getmodulecol(\"def test_one(): pass\")\n        rep = TerminalReporter(modcol.config, file=linecomp.stringio)\n        with pytest.raises(ValueError) as excinfo:\n            raise ValueError(\"hello\")\n        rep.pytest_internalerror(excinfo.getrepr())\n        linecomp.assert_contains_lines([\"INTERNALERROR> *ValueError*hello*\"])\n\n    def test_writeline(self, pytester: Pytester, linecomp) -> None:\n        modcol = pytester.getmodulecol(\"def test_one(): pass\")\n        rep = TerminalReporter(modcol.config, file=linecomp.stringio)\n        rep.write_fspath_result(modcol.nodeid, \".\")\n        rep.write_line(\"hello world\")\n        lines = linecomp.stringio.getvalue().split(\"\\n\")\n        assert not lines[0]\n        assert lines[1].endswith(modcol.name + \" .\")\n        assert lines[2] == \"hello world\"\n\n    def test_show_runtest_logstart(self, pytester: Pytester, linecomp) -> None:\n        item = pytester.getitem(\"def test_func(): pass\")\n        tr = TerminalReporter(item.config, file=linecomp.stringio)\n        item.config.pluginmanager.register(tr)\n        location = item.reportinfo()\n        tr.config.hook.pytest_runtest_logstart(\n            nodeid=item.nodeid, location=location, fspath=str(item.path)\n        )\n        linecomp.assert_contains_lines([\"*test_show_runtest_logstart.py*\"])\n\n    def test_runtest_location_shown_before_test_starts(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                import time\n                time.sleep(20)\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(\"\")\n        child.expect(\".*test_runtest_location.*py\")\n        child.sendeof()\n        child.kill(15)\n\n    def test_report_collect_after_half_a_second(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"Test for \"collecting\" being updated after 0.5s\"\"\"\n        pytester.makepyfile(\n            **{\n                \"test1.py\": \"\"\"\n                import _pytest.terminal\n\n                _pytest.terminal.REPORT_COLLECTING_RESOLUTION = 0\n\n                def test_1():\n                    pass\n                    \"\"\",\n                \"test2.py\": \"def test_2(): pass\",\n            }\n        )\n        # Explicitly test colored output.\n        monkeypatch.setenv(\"PY_COLORS\", \"1\")\n\n        child = pytester.spawn_pytest(\"-v test1.py test2.py\")\n        child.expect(r\"collecting \\.\\.\\.\")\n        child.expect(r\"collecting 1 item\")\n        child.expect(r\"collecting 2 items\")\n        child.expect(r\"collected 2 items\")\n        rest = child.read().decode(\"utf8\")\n        assert \"= \\x1b[32m\\x1b[1m2 passed\\x1b[0m\\x1b[32m in\" in rest\n\n    def test_itemreport_subclasses_show_subclassed_file(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            **{\n                \"tests/test_p1\": \"\"\"\n            class BaseTests(object):\n                fail = False\n\n                def test_p1(self):\n                    if self.fail: assert 0\n                \"\"\",\n                \"tests/test_p2\": \"\"\"\n            from test_p1 import BaseTests\n\n            class TestMore(BaseTests): pass\n                \"\"\",\n                \"tests/test_p3.py\": \"\"\"\n            from test_p1 import BaseTests\n\n            BaseTests.fail = True\n\n            class TestMore(BaseTests): pass\n        \"\"\",\n            }\n        )\n        result = pytester.runpytest(\"tests/test_p2.py\", \"--rootdir=tests\")\n        result.stdout.fnmatch_lines([\"tests/test_p2.py .*\", \"=* 1 passed in *\"])\n\n        result = pytester.runpytest(\"-vv\", \"-rA\", \"tests/test_p2.py\", \"--rootdir=tests\")\n        result.stdout.fnmatch_lines(\n            [\n                \"tests/test_p2.py::TestMore::test_p1 <- test_p1.py PASSED *\",\n                \"*= short test summary info =*\",\n                \"PASSED tests/test_p2.py::TestMore::test_p1\",\n            ]\n        )\n        result = pytester.runpytest(\"-vv\", \"-rA\", \"tests/test_p3.py\", \"--rootdir=tests\")\n        result.stdout.fnmatch_lines(\n            [\n                \"tests/test_p3.py::TestMore::test_p1 <- test_p1.py FAILED *\",\n                \"*_ TestMore.test_p1 _*\",\n                \"    def test_p1(self):\",\n                \">       if self.fail: assert 0\",\n                \"E       assert 0\",\n                \"\",\n                \"tests/test_p1.py:5: AssertionError\",\n                \"*= short test summary info =*\",\n                \"FAILED tests/test_p3.py::TestMore::test_p1 - assert 0\",\n                \"*= 1 failed in *\",\n            ]\n        )\n\n    def test_itemreport_directclasses_not_shown_as_subclasses(\n        self, pytester: Pytester\n    ) -> None:\n        a = pytester.mkpydir(\"a123\")\n        a.joinpath(\"test_hello123.py\").write_text(\n            textwrap.dedent(\n                \"\"\"\\\n                class TestClass(object):\n                    def test_method(self):\n                        pass\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n        result = pytester.runpytest(\"-vv\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines([\"*a123/test_hello123.py*PASS*\"])\n        result.stdout.no_fnmatch_line(\"* <- *\")\n\n    @pytest.mark.parametrize(\"fulltrace\", (\"\", \"--fulltrace\"))\n    def test_keyboard_interrupt(self, pytester: Pytester, fulltrace) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foobar():\n                assert 0\n            def test_spamegg():\n                import py; pytest.skip('skip me please!')\n            def test_interrupt_me():\n                raise KeyboardInterrupt   # simulating the user\n        \"\"\"\n        )\n\n        result = pytester.runpytest(fulltrace, no_reraise_ctrlc=True)\n        result.stdout.fnmatch_lines(\n            [\n                \"    def test_foobar():\",\n                \">       assert 0\",\n                \"E       assert 0\",\n                \"*_keyboard_interrupt.py:6: KeyboardInterrupt*\",\n            ]\n        )\n        if fulltrace:\n            result.stdout.fnmatch_lines(\n                [\"*raise KeyboardInterrupt   # simulating the user*\"]\n            )\n        else:\n            result.stdout.fnmatch_lines(\n                [\"(to show a full traceback on KeyboardInterrupt use --full-trace)\"]\n            )\n        result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])\n\n    def test_keyboard_in_sessionstart(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_sessionstart():\n                raise KeyboardInterrupt\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_foobar():\n                pass\n        \"\"\"\n        )\n\n        result = pytester.runpytest(no_reraise_ctrlc=True)\n        assert result.ret == 2\n        result.stdout.fnmatch_lines([\"*KeyboardInterrupt*\"])\n\n    def test_collect_single_item(self, pytester: Pytester) -> None:\n        \"\"\"Use singular 'item' when reporting a single test item\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def test_foobar():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"collected 1 item\"])\n\n    def test_rewrite(self, pytester: Pytester, monkeypatch) -> None:\n        config = pytester.parseconfig()\n        f = StringIO()\n        monkeypatch.setattr(f, \"isatty\", lambda *args: True)\n        tr = TerminalReporter(config, f)\n        tr._tw.fullwidth = 10\n        tr.write(\"hello\")\n        tr.rewrite(\"hey\", erase=True)\n        assert f.getvalue() == \"hello\" + \"\\r\" + \"hey\" + (6 * \" \")\n\n    @pytest.mark.parametrize(\"category\", [\"foo\", \"failed\", \"error\", \"passed\"])\n    def test_report_teststatus_explicit_markup(\n        self, monkeypatch: MonkeyPatch, pytester: Pytester, color_mapping, category: str\n    ) -> None:\n        \"\"\"Test that TerminalReporter handles markup explicitly provided by\n        a pytest_report_teststatus hook.\"\"\"\n        monkeypatch.setenv(\"PY_COLORS\", \"1\")\n        pytester.makeconftest(\n            f\"\"\"\n            def pytest_report_teststatus(report):\n                return {category!r}, 'F', ('FOO', {{'red': True}})\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            def test_foobar():\n                pass\n        \"\"\"\n        )\n\n        result = pytester.runpytest(\"-v\")\n        assert not result.stderr.lines\n        result.stdout.fnmatch_lines(\n            color_mapping.format_for_fnmatch([\"*{red}FOO{reset}*\"])\n        )\n\n    def test_verbose_skip_reason(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.skip(reason=\"123\")\n            def test_1():\n                pass\n\n            @pytest.mark.xfail(reason=\"456\")\n            def test_2():\n                pass\n\n            @pytest.mark.xfail(reason=\"789\")\n            def test_3():\n                assert False\n\n            @pytest.mark.xfail(reason=\"\")\n            def test_4():\n                assert False\n\n            @pytest.mark.skip\n            def test_5():\n                pass\n\n            @pytest.mark.xfail\n            def test_6():\n                pass\n\n            def test_7():\n                pytest.skip()\n\n            def test_8():\n                pytest.skip(\"888 is great\")\n\n            def test_9():\n                pytest.xfail()\n\n            def test_10():\n                pytest.xfail(\"It's 🕙 o'clock\")\n\n            @pytest.mark.skip(\n                reason=\"1 cannot do foobar because baz is missing due to I don't know what\"\n            )\n            def test_long_skip():\n                pass\n\n            @pytest.mark.xfail(\n                reason=\"2 cannot do foobar because baz is missing due to I don't know what\"\n            )\n            def test_long_xfail():\n                print(1 / 0)\n        \"\"\"\n        )\n\n        common_output = [\n            \"test_verbose_skip_reason.py::test_1 SKIPPED (123) *\",\n            \"test_verbose_skip_reason.py::test_2 XPASS (456) *\",\n            \"test_verbose_skip_reason.py::test_3 XFAIL (789) *\",\n            \"test_verbose_skip_reason.py::test_4 XFAIL  *\",\n            \"test_verbose_skip_reason.py::test_5 SKIPPED (unconditional skip) *\",\n            \"test_verbose_skip_reason.py::test_6 XPASS  *\",\n            \"test_verbose_skip_reason.py::test_7 SKIPPED  *\",\n            \"test_verbose_skip_reason.py::test_8 SKIPPED (888 is great) *\",\n            \"test_verbose_skip_reason.py::test_9 XFAIL  *\",\n            \"test_verbose_skip_reason.py::test_10 XFAIL (It's 🕙 o'clock) *\",\n        ]\n\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines(\n            [\n                *common_output,\n                \"test_verbose_skip_reason.py::test_long_skip SKIPPED (1 cannot *...) *\",\n                \"test_verbose_skip_reason.py::test_long_xfail XFAIL (2 cannot *...) *\",\n            ]\n        )\n\n        result = pytester.runpytest(\"-vv\")\n        result.stdout.fnmatch_lines(\n            [\n                *common_output,\n                \"test_verbose_skip_reason.py::test_long_skip SKIPPED\"\n                \" (1 cannot do foobar\",\n                \"because baz is missing due to I don't know what) *\",\n                \"test_verbose_skip_reason.py::test_long_xfail XFAIL\"\n                \" (2 cannot do foobar\",\n                \"because baz is missing due to I don't know what) *\",\n            ]\n        )\n\n    @pytest.mark.parametrize(\"isatty\", [True, False])\n    def test_isatty(self, pytester: Pytester, monkeypatch, isatty: bool) -> None:\n        config = pytester.parseconfig()\n        f = StringIO()\n        monkeypatch.setattr(f, \"isatty\", lambda: isatty)\n        tr = TerminalReporter(config, f)\n        assert tr.isatty() == isatty\n        # It was incorrectly implemented as a boolean so we still support using it as one.\n        assert bool(tr.isatty) == isatty\n\n\nclass TestCollectonly:\n    def test_collectonly_basic(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_func():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir test_collectonly_basic0>\",\n                \"  <Module test_collectonly_basic.py>\",\n                \"    <Function test_func>\",\n            ]\n        )\n\n    def test_collectonly_skipped_module(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            pytest.skip(\"hello\")\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\", \"-rs\")\n        result.stdout.fnmatch_lines([\"*ERROR collecting*\"])\n\n    def test_collectonly_displays_test_description(\n        self, pytester: Pytester, dummy_yaml_custom_test\n    ) -> None:\n        \"\"\"Used dummy_yaml_custom_test for an Item without ``obj``.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def test_with_description():\n                '''  This test has a description.\n\n                  more1.\n                    more2.'''\n            \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\", \"--verbose\")\n        result.stdout.fnmatch_lines(\n            [\n                \"<Dir test_collectonly_displays_test_description0>\",\n                \"  <YamlFile test1.yaml>\",\n                \"    <YamlItem test1.yaml>\",\n                \"  <Module test_collectonly_displays_test_description.py>\",\n                \"    <Function test_with_description>\",\n                \"      This test has a description.\",\n                \"      \",\n                \"      more1.\",\n                \"        more2.\",\n            ],\n            consecutive=True,\n        )\n\n    def test_collectonly_failed_module(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\"\"\"raise ValueError(0)\"\"\")\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines([\"*raise ValueError*\", \"*1 error*\"])\n\n    def test_collectonly_fatal(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_collectstart(collector):\n                assert 0, \"urgs\"\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines([\"*INTERNAL*args*\"])\n        assert result.ret == 3\n\n    def test_collectonly_simple(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_func1():\n                pass\n            class TestClass(object):\n                def test_method(self):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--collect-only\", p)\n        # assert stderr.startswith(\"inserting into sys.path\")\n        assert result.ret == 0\n        result.stdout.fnmatch_lines(\n            [\n                \"*<Module *.py>\",\n                \"* <Function test_func1>\",\n                \"* <Class TestClass>\",\n                \"*   <Function test_method>\",\n            ]\n        )\n\n    def test_collectonly_error(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\"import Errlkjqweqwe\")\n        result = pytester.runpytest(\"--collect-only\", p)\n        assert result.ret == 2\n        result.stdout.fnmatch_lines(\n            textwrap.dedent(\n                \"\"\"\\\n                *ERROR*\n                *ImportError*\n                *No module named *Errlk*\n                *1 error*\n                \"\"\"\n            ).strip()\n        )\n\n    def test_collectonly_missing_path(self, pytester: Pytester) -> None:\n        \"\"\"Issue 115: failure in parseargs will cause session not to\n        have the items attribute.\"\"\"\n        result = pytester.runpytest(\"--collect-only\", \"uhm_missing_path\")\n        assert result.ret == 4\n        result.stderr.fnmatch_lines(\n            [\"*ERROR: file or directory not found: uhm_missing_path\"]\n        )\n\n    def test_collectonly_quiet(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\"def test_foo(): pass\")\n        result = pytester.runpytest(\"--collect-only\", \"-q\")\n        result.stdout.fnmatch_lines([\"*test_foo*\"])\n\n    def test_collectonly_more_quiet(self, pytester: Pytester) -> None:\n        pytester.makepyfile(test_fun=\"def test_foo(): pass\")\n        result = pytester.runpytest(\"--collect-only\", \"-qq\")\n        result.stdout.fnmatch_lines([\"*test_fun.py: 1*\"])\n\n    def test_collect_only_summary_status(self, pytester: Pytester) -> None:\n        \"\"\"Custom status depending on test selection using -k or -m. #7701.\"\"\"\n        pytester.makepyfile(\n            test_collect_foo=\"\"\"\n            def test_foo(): pass\n            \"\"\",\n            test_collect_bar=\"\"\"\n            def test_foobar(): pass\n            def test_bar(): pass\n            \"\"\",\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines(\"*== 3 tests collected in * ==*\")\n\n        result = pytester.runpytest(\"--collect-only\", \"test_collect_foo.py\")\n        result.stdout.fnmatch_lines(\"*== 1 test collected in * ==*\")\n\n        result = pytester.runpytest(\"--collect-only\", \"-k\", \"foo\")\n        result.stdout.fnmatch_lines(\"*== 2/3 tests collected (1 deselected) in * ==*\")\n\n        result = pytester.runpytest(\"--collect-only\", \"-k\", \"test_bar\")\n        result.stdout.fnmatch_lines(\"*== 1/3 tests collected (2 deselected) in * ==*\")\n\n        result = pytester.runpytest(\"--collect-only\", \"-k\", \"invalid\")\n        result.stdout.fnmatch_lines(\"*== no tests collected (3 deselected) in * ==*\")\n\n        pytester.mkdir(\"no_tests_here\")\n        result = pytester.runpytest(\"--collect-only\", \"no_tests_here\")\n        result.stdout.fnmatch_lines(\"*== no tests collected in * ==*\")\n\n        pytester.makepyfile(\n            test_contains_error=\"\"\"\n            raise RuntimeError\n            \"\"\",\n        )\n        result = pytester.runpytest(\"--collect-only\")\n        result.stdout.fnmatch_lines(\"*== 3 tests collected, 1 error in * ==*\")\n        result = pytester.runpytest(\"--collect-only\", \"-k\", \"foo\")\n        result.stdout.fnmatch_lines(\n            \"*== 2/3 tests collected (1 deselected), 1 error in * ==*\"\n        )\n\n\nclass TestFixtureReporting:\n    def test_setup_fixture_error(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def setup_function(function):\n                print(\"setup func\")\n                assert 0\n            def test_nada():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*ERROR at setup of test_nada*\",\n                \"*setup_function(function):*\",\n                \"*setup func*\",\n                \"*assert 0*\",\n                \"*1 error*\",\n            ]\n        )\n        assert result.ret != 0\n\n    def test_teardown_fixture_error(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_nada():\n                pass\n            def teardown_function(function):\n                print(\"teardown func\")\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*ERROR at teardown*\",\n                \"*teardown_function(function):*\",\n                \"*assert 0*\",\n                \"*Captured stdout*\",\n                \"*teardown func*\",\n                \"*1 passed*1 error*\",\n            ]\n        )\n\n    def test_teardown_fixture_error_and_test_failure(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_fail():\n                assert 0, \"failingfunc\"\n\n            def teardown_function(function):\n                print(\"teardown func\")\n                assert False\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*ERROR at teardown of test_fail*\",\n                \"*teardown_function(function):*\",\n                \"*assert False*\",\n                \"*Captured stdout*\",\n                \"*teardown func*\",\n                \"*test_fail*\",\n                \"*def test_fail():\",\n                \"*failingfunc*\",\n                \"*1 failed*1 error*\",\n            ]\n        )\n\n    def test_setup_teardown_output_and_test_failure(self, pytester: Pytester) -> None:\n        \"\"\"Test for issue #442.\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def setup_function(function):\n                print(\"setup func\")\n\n            def test_fail():\n                assert 0, \"failingfunc\"\n\n            def teardown_function(function):\n                print(\"teardown func\")\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_fail*\",\n                \"*def test_fail():\",\n                \"*failingfunc*\",\n                \"*Captured stdout setup*\",\n                \"*setup func*\",\n                \"*Captured stdout teardown*\",\n                \"*teardown func*\",\n                \"*1 failed*\",\n            ]\n        )\n\n\nclass TestTerminalFunctional:\n    def test_deselected(self, pytester: Pytester) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n                def test_one():\n                    pass\n                def test_two():\n                    pass\n                def test_three():\n                    pass\n           \"\"\"\n        )\n        result = pytester.runpytest(\"-k\", \"test_t\", testpath)\n        result.stdout.fnmatch_lines(\n            [\"collected 3 items / 1 deselected / 2 selected\", \"*test_deselected.py ..*\"]\n        )\n        assert result.ret == 0\n\n    def test_deselected_with_hook_wrapper(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.hookimpl(wrapper=True)\n            def pytest_collection_modifyitems(config, items):\n                yield\n                deselected = items.pop()\n                config.hook.pytest_deselected(items=[deselected])\n            \"\"\"\n        )\n        testpath = pytester.makepyfile(\n            \"\"\"\n                def test_one():\n                    pass\n                def test_two():\n                    pass\n                def test_three():\n                    pass\n           \"\"\"\n        )\n        result = pytester.runpytest(testpath)\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 3 items / 1 deselected / 2 selected\",\n                \"*= 2 passed, 1 deselected in*\",\n            ]\n        )\n        assert result.ret == 0\n\n    def test_show_deselected_items_using_markexpr_before_test_execution(\n        self, pytester: Pytester\n    ) -> None:\n        pytester.makepyfile(\n            test_show_deselected=\"\"\"\n            import pytest\n\n            @pytest.mark.foo\n            def test_foobar():\n                pass\n\n            @pytest.mark.bar\n            def test_bar():\n                pass\n\n            def test_pass():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-m\", \"not foo\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 3 items / 1 deselected / 2 selected\",\n                \"*test_show_deselected.py ..*\",\n                \"*= 2 passed, 1 deselected in * =*\",\n            ]\n        )\n        result.stdout.no_fnmatch_line(\"*= 1 deselected =*\")\n        assert result.ret == 0\n\n    def test_selected_count_with_error(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_selected_count_3=\"\"\"\n                def test_one():\n                    pass\n                def test_two():\n                    pass\n                def test_three():\n                    pass\n            \"\"\",\n            test_selected_count_error=\"\"\"\n                5/0\n                def test_foo():\n                    pass\n                def test_bar():\n                    pass\n            \"\"\",\n        )\n        result = pytester.runpytest(\"-k\", \"test_t\")\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 3 items / 1 error / 1 deselected / 2 selected\",\n                \"* ERROR collecting test_selected_count_error.py *\",\n            ]\n        )\n        assert result.ret == ExitCode.INTERRUPTED\n\n    def test_no_skip_summary_if_failure(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_ok():\n                pass\n            def test_fail():\n                assert 0\n            def test_skip():\n                pytest.skip(\"dontshow\")\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        assert result.stdout.str().find(\"skip test summary\") == -1\n        assert result.ret == 1\n\n    def test_passes(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_passes():\n                pass\n            class TestClass(object):\n                def test_method(self):\n                    pass\n        \"\"\"\n        )\n        old = p1.parent\n        pytester.chdir()\n        try:\n            result = pytester.runpytest()\n        finally:\n            os.chdir(old)\n        result.stdout.fnmatch_lines([\"test_passes.py ..*\", \"* 2 pass*\"])\n        assert result.ret == 0\n\n    def test_header_trailer_info(\n        self, monkeypatch: MonkeyPatch, pytester: Pytester, request\n    ) -> None:\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\")\n        monkeypatch.delenv(\"PYTEST_PLUGINS\", raising=False)\n        pytester.makepyfile(\n            \"\"\"\n            def test_passes():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        verinfo = \".\".join(map(str, sys.version_info[:3]))\n        result.stdout.fnmatch_lines(\n            [\n                \"*===== test session starts ====*\",\n                f\"platform {sys.platform} -- Python {verinfo}*pytest-{pytest.__version__}**pluggy-{pluggy.__version__}\",\n                \"*test_header_trailer_info.py .*\",\n                \"=* 1 passed*in *.[0-9][0-9]s *=\",\n            ]\n        )\n        if request.config.pluginmanager.list_plugin_distinfo():\n            result.stdout.fnmatch_lines([\"plugins: *\"])\n\n    def test_no_header_trailer_info(\n        self, monkeypatch: MonkeyPatch, pytester: Pytester, request\n    ) -> None:\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\")\n        pytester.makepyfile(\n            \"\"\"\n            def test_passes():\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--no-header\")\n        verinfo = \".\".join(map(str, sys.version_info[:3]))\n        result.stdout.no_fnmatch_line(\n            f\"platform {sys.platform} -- Python {verinfo}*pytest-{pytest.__version__}**pluggy-{pluggy.__version__}\"\n        )\n        if request.config.pluginmanager.list_plugin_distinfo():\n            result.stdout.no_fnmatch_line(\"plugins: *\")\n\n    def test_header(self, pytester: Pytester) -> None:\n        pytester.path.joinpath(\"tests\").mkdir()\n        pytester.path.joinpath(\"gui\").mkdir()\n\n        # no configuration file\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"rootdir: *test_header0\"])\n\n        # with configfile\n        pytester.makeini(\"\"\"[pytest]\"\"\")\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines([\"rootdir: *test_header0\", \"configfile: tox.ini\"])\n\n        # with testpaths option, and not passing anything in the command-line\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            testpaths = tests gui\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\"rootdir: *test_header0\", \"configfile: tox.ini\", \"testpaths: tests, gui\"]\n        )\n\n        # with testpaths option, passing directory in command-line: do not show testpaths then\n        result = pytester.runpytest(\"tests\")\n        result.stdout.fnmatch_lines([\"rootdir: *test_header0\", \"configfile: tox.ini\"])\n\n    def test_header_absolute_testpath(\n        self, pytester: Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"Regression test for #7814.\"\"\"\n        tests = pytester.path.joinpath(\"tests\")\n        tests.mkdir()\n        pytester.makepyprojecttoml(\n            f\"\"\"\n            [tool.pytest.ini_options]\n            testpaths = ['{tests}']\n        \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\n                \"rootdir: *absolute_testpath0\",\n                \"configfile: pyproject.toml\",\n                f\"testpaths: {tests}\",\n            ]\n        )\n\n    def test_no_header(self, pytester: Pytester) -> None:\n        pytester.path.joinpath(\"tests\").mkdir()\n        pytester.path.joinpath(\"gui\").mkdir()\n\n        # with testpaths option, and not passing anything in the command-line\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            testpaths = tests gui\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--no-header\")\n        result.stdout.no_fnmatch_line(\n            \"rootdir: *test_header0, inifile: tox.ini, testpaths: tests, gui\"\n        )\n\n        # with testpaths option, passing directory in command-line: do not show testpaths then\n        result = pytester.runpytest(\"tests\", \"--no-header\")\n        result.stdout.no_fnmatch_line(\"rootdir: *test_header0, inifile: tox.ini\")\n\n    def test_no_summary(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_no_summary():\n                assert false\n        \"\"\"\n        )\n        result = pytester.runpytest(p1, \"--no-summary\")\n        result.stdout.no_fnmatch_line(\"*= FAILURES =*\")\n\n    def test_showlocals(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_showlocals():\n                x = 3\n                y = \"x\" * 5000\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(p1, \"-l\")\n        result.stdout.fnmatch_lines(\n            [\n                # \"_ _ * Locals *\",\n                \"x* = 3\",\n                \"y* = 'xxxxxx*\",\n            ]\n        )\n\n    def test_noshowlocals_addopts_override(self, pytester: Pytester) -> None:\n        pytester.makeini(\"[pytest]\\naddopts=--showlocals\")\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_noshowlocals():\n                x = 3\n                y = \"x\" * 5000\n                assert 0\n        \"\"\"\n        )\n\n        # Override global --showlocals for py.test via arg\n        result = pytester.runpytest(p1, \"--no-showlocals\")\n        result.stdout.no_fnmatch_line(\"x* = 3\")\n        result.stdout.no_fnmatch_line(\"y* = 'xxxxxx*\")\n\n    def test_showlocals_short(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\n            \"\"\"\n            def test_showlocals_short():\n                x = 3\n                y = \"xxxx\"\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(p1, \"-l\", \"--tb=short\")\n        result.stdout.fnmatch_lines(\n            [\n                \"test_showlocals_short.py:*\",\n                \"    assert 0\",\n                \"E   assert 0\",\n                \"        x          = 3\",\n                \"        y          = 'xxxx'\",\n            ]\n        )\n\n    @pytest.fixture\n    def verbose_testfile(self, pytester: Pytester) -> Path:\n        return pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_fail():\n                raise ValueError()\n            def test_pass():\n                pass\n            class TestClass(object):\n                def test_skip(self):\n                    pytest.skip(\"hello\")\n        \"\"\"\n        )\n\n    def test_verbose_reporting(self, verbose_testfile, pytester: Pytester) -> None:\n        result = pytester.runpytest(\n            verbose_testfile, \"-v\", \"-Walways::pytest.PytestWarning\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"*test_verbose_reporting.py::test_fail *FAIL*\",\n                \"*test_verbose_reporting.py::test_pass *PASS*\",\n                \"*test_verbose_reporting.py::TestClass::test_skip *SKIP*\",\n            ]\n        )\n        assert result.ret == 1\n\n    def test_verbose_reporting_xdist(\n        self,\n        verbose_testfile,\n        monkeypatch: MonkeyPatch,\n        pytester: Pytester,\n        pytestconfig,\n    ) -> None:\n        if not pytestconfig.pluginmanager.get_plugin(\"xdist\"):\n            pytest.skip(\"xdist plugin not installed\")\n\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\")\n        result = pytester.runpytest(\n            verbose_testfile, \"-v\", \"-n 1\", \"-Walways::pytest.PytestWarning\"\n        )\n        result.stdout.fnmatch_lines(\n            [\"*FAIL*test_verbose_reporting_xdist.py::test_fail*\"]\n        )\n        assert result.ret == 1\n\n    def test_quiet_reporting(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\"def test_pass(): pass\")\n        result = pytester.runpytest(p1, \"-q\")\n        s = result.stdout.str()\n        assert \"test session starts\" not in s\n        assert p1.name not in s\n        assert \"===\" not in s\n        assert \"passed\" in s\n\n    def test_more_quiet_reporting(self, pytester: Pytester) -> None:\n        p1 = pytester.makepyfile(\"def test_pass(): pass\")\n        result = pytester.runpytest(p1, \"-qq\")\n        s = result.stdout.str()\n        assert \"test session starts\" not in s\n        assert p1.name not in s\n        assert \"===\" not in s\n        assert \"passed\" not in s\n\n    @pytest.mark.parametrize(\n        \"params\", [(), (\"--collect-only\",)], ids=[\"no-params\", \"collect-only\"]\n    )\n    def test_report_collectionfinish_hook(self, pytester: Pytester, params) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_report_collectionfinish(config, start_path, items):\n                return [f'hello from hook: {len(items)} items']\n        \"\"\"\n        )\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            @pytest.mark.parametrize('i', range(3))\n            def test(i):\n                pass\n        \"\"\"\n        )\n        result = pytester.runpytest(*params)\n        result.stdout.fnmatch_lines([\"collected 3 items\", \"hello from hook: 3 items\"])\n\n    def test_summary_f_alias(self, pytester: Pytester) -> None:\n        \"\"\"Test that 'f' and 'F' report chars are aliases and don't show up twice in the summary (#6334)\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            def test():\n                assert False\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-rfF\")\n        expected = \"FAILED test_summary_f_alias.py::test - assert False\"\n        result.stdout.fnmatch_lines([expected])\n        assert result.stdout.lines.count(expected) == 1\n\n    def test_summary_s_alias(self, pytester: Pytester) -> None:\n        \"\"\"Test that 's' and 'S' report chars are aliases and don't show up twice in the summary\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.skip\n            def test():\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-rsS\")\n        expected = \"SKIPPED [1] test_summary_s_alias.py:3: unconditional skip\"\n        result.stdout.fnmatch_lines([expected])\n        assert result.stdout.lines.count(expected) == 1\n\n    def test_summary_s_folded(self, pytester: Pytester) -> None:\n        \"\"\"Test that skipped tests are correctly folded\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"param\", [True, False])\n            @pytest.mark.skip(\"Some reason\")\n            def test(param):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-rs\")\n        expected = \"SKIPPED [2] test_summary_s_folded.py:3: Some reason\"\n        result.stdout.fnmatch_lines([expected])\n        assert result.stdout.lines.count(expected) == 1\n\n    def test_summary_s_unfolded(self, pytester: Pytester) -> None:\n        \"\"\"Test that skipped tests are not folded if --no-fold-skipped is set\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"param\", [True, False])\n            @pytest.mark.skip(\"Some reason\")\n            def test(param):\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest(\"-rs\", \"--no-fold-skipped\")\n        expected = [\n            \"SKIPPED test_summary_s_unfolded.py::test[True] - Skipped: Some reason\",\n            \"SKIPPED test_summary_s_unfolded.py::test[False] - Skipped: Some reason\",\n        ]\n        result.stdout.fnmatch_lines(expected)\n        assert result.stdout.lines.count(expected[0]) == 1\n        assert result.stdout.lines.count(expected[1]) == 1\n\n\n@pytest.mark.parametrize(\n    (\"use_ci\", \"expected_message\"),\n    (\n        (True, f\"- AssertionError: {'this_failed' * 100}\"),\n        (False, \"- AssertionError: this_failedt...\"),\n    ),\n    ids=(\"on CI\", \"not on CI\"),\n)\ndef test_fail_extra_reporting(\n    pytester: Pytester, monkeypatch, use_ci: bool, expected_message: str\n) -> None:\n    if use_ci:\n        monkeypatch.setenv(\"CI\", \"true\")\n    else:\n        monkeypatch.delenv(\"CI\", raising=False)\n    monkeypatch.setenv(\"COLUMNS\", \"80\")\n    pytester.makepyfile(\"def test_this(): assert 0, 'this_failed' * 100\")\n    result = pytester.runpytest(\"-rN\")\n    result.stdout.no_fnmatch_line(\"*short test summary*\")\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"*test summary*\",\n            f\"FAILED test_fail_extra_reporting.py::test_this {expected_message}\",\n        ]\n    )\n\n\ndef test_fail_reporting_on_pass(pytester: Pytester) -> None:\n    pytester.makepyfile(\"def test_this(): assert 1\")\n    result = pytester.runpytest(\"-rf\")\n    result.stdout.no_fnmatch_line(\"*short test summary*\")\n\n\ndef test_pass_extra_reporting(pytester: Pytester) -> None:\n    pytester.makepyfile(\"def test_this(): assert 1\")\n    result = pytester.runpytest()\n    result.stdout.no_fnmatch_line(\"*short test summary*\")\n    result = pytester.runpytest(\"-rp\")\n    result.stdout.fnmatch_lines([\"*test summary*\", \"PASS*test_pass_extra_reporting*\"])\n\n\ndef test_pass_reporting_on_fail(pytester: Pytester) -> None:\n    pytester.makepyfile(\"def test_this(): assert 0\")\n    result = pytester.runpytest(\"-rp\")\n    result.stdout.no_fnmatch_line(\"*short test summary*\")\n\n\ndef test_pass_output_reporting(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def setup_module():\n            print(\"setup_module\")\n\n        def teardown_module():\n            print(\"teardown_module\")\n\n        def test_pass_has_output():\n            print(\"Four score and seven years ago...\")\n\n        def test_pass_no_output():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    s = result.stdout.str()\n    assert \"test_pass_has_output\" not in s\n    assert \"Four score and seven years ago...\" not in s\n    assert \"test_pass_no_output\" not in s\n    result = pytester.runpytest(\"-rPp\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*= PASSES =*\",\n            \"*_ test_pass_has_output _*\",\n            \"*- Captured stdout setup -*\",\n            \"setup_module\",\n            \"*- Captured stdout call -*\",\n            \"Four score and seven years ago...\",\n            \"*- Captured stdout teardown -*\",\n            \"teardown_module\",\n            \"*= short test summary info =*\",\n            \"PASSED test_pass_output_reporting.py::test_pass_has_output\",\n            \"PASSED test_pass_output_reporting.py::test_pass_no_output\",\n            \"*= 2 passed in *\",\n        ]\n    )\n\n\ndef test_color_yes(pytester: Pytester, color_mapping) -> None:\n    p1 = pytester.makepyfile(\n        \"\"\"\n        def fail():\n            assert 0\n\n        def test_this():\n            fail()\n        \"\"\"\n    )\n    result = pytester.runpytest(\"--color=yes\", str(p1))\n    result.stdout.fnmatch_lines(\n        color_mapping.format_for_fnmatch(\n            [\n                \"{bold}=*= test session starts =*={reset}\",\n                \"collected 1 item\",\n                \"\",\n                \"test_color_yes.py {red}F{reset}{red} * [100%]{reset}\",\n                \"\",\n                \"=*= FAILURES =*=\",\n                \"{red}{bold}_*_ test_this _*_{reset}\",\n                \"\",\n                \"    {reset}{kw}def{hl-reset}{kwspace}{function}test_this{hl-reset}():{endline}\",\n                \">       fail(){endline}\",\n                \"\",\n                \"{bold}{red}test_color_yes.py{reset}:5: \",\n                \"_ _ * _ _*\",\n                \"\",\n                \"    {reset}{kw}def{hl-reset}{kwspace}{function}fail{hl-reset}():{endline}\",\n                \">       {kw}assert{hl-reset} {number}0{hl-reset}{endline}\",\n                \"{bold}{red}E       assert 0{reset}\",\n                \"\",\n                \"{bold}{red}test_color_yes.py{reset}:2: AssertionError\",\n                \"{red}=*= {red}{bold}1 failed{reset}{red} in *s{reset}{red} =*={reset}\",\n            ]\n        )\n    )\n    result = pytester.runpytest(\"--color=yes\", \"--tb=short\", str(p1))\n    result.stdout.fnmatch_lines(\n        color_mapping.format_for_fnmatch(\n            [\n                \"{bold}=*= test session starts =*={reset}\",\n                \"collected 1 item\",\n                \"\",\n                \"test_color_yes.py {red}F{reset}{red} * [100%]{reset}\",\n                \"\",\n                \"=*= FAILURES =*=\",\n                \"{red}{bold}_*_ test_this _*_{reset}\",\n                \"{bold}{red}test_color_yes.py{reset}:5: in test_this\",\n                \"    {reset}fail(){endline}\",\n                \"{bold}{red}test_color_yes.py{reset}:2: in fail\",\n                \"    {reset}{kw}assert{hl-reset} {number}0{hl-reset}{endline}\",\n                \"{bold}{red}E   assert 0{reset}\",\n                \"{red}=*= {red}{bold}1 failed{reset}{red} in *s{reset}{red} =*={reset}\",\n            ]\n        )\n    )\n\n\ndef test_color_no(pytester: Pytester) -> None:\n    pytester.makepyfile(\"def test_this(): assert 1\")\n    result = pytester.runpytest(\"--color=no\")\n    assert \"test session starts\" in result.stdout.str()\n    result.stdout.no_fnmatch_line(\"*\\x1b[1m*\")\n\n\n@pytest.mark.parametrize(\"verbose\", [True, False])\ndef test_color_yes_collection_on_non_atty(pytester: Pytester, verbose) -> None:\n    \"\"\"#1397: Skip collect progress report when working on non-terminals.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.parametrize('i', range(10))\n        def test_this(i):\n            assert 1\n    \"\"\"\n    )\n    args = [\"--color=yes\"]\n    if verbose:\n        args.append(\"-vv\")\n    result = pytester.runpytest(*args)\n    assert \"test session starts\" in result.stdout.str()\n    assert \"\\x1b[1m\" in result.stdout.str()\n    result.stdout.no_fnmatch_line(\"*collecting 10 items*\")\n    if verbose:\n        assert \"collecting ...\" in result.stdout.str()\n    assert \"collected 10 items\" in result.stdout.str()\n\n\ndef test_getreportopt() -> None:\n    from _pytest.terminal import _REPORTCHARS_DEFAULT\n\n    class FakeConfig:\n        class Option:\n            reportchars = _REPORTCHARS_DEFAULT\n            disable_warnings = False\n\n        option = Option()\n\n    config = cast(Config, FakeConfig())\n\n    assert _REPORTCHARS_DEFAULT == \"fE\"\n\n    # Default.\n    assert getreportopt(config) == \"wfE\"\n\n    config.option.reportchars = \"sf\"\n    assert getreportopt(config) == \"wsf\"\n\n    config.option.reportchars = \"sfxw\"\n    assert getreportopt(config) == \"sfxw\"\n\n    config.option.reportchars = \"a\"\n    assert getreportopt(config) == \"wsxXEf\"\n\n    config.option.reportchars = \"N\"\n    assert getreportopt(config) == \"w\"\n\n    config.option.reportchars = \"NwfE\"\n    assert getreportopt(config) == \"wfE\"\n\n    config.option.reportchars = \"NfENx\"\n    assert getreportopt(config) == \"wx\"\n\n    # Now with --disable-warnings.\n    config.option.disable_warnings = True\n    config.option.reportchars = \"a\"\n    assert getreportopt(config) == \"sxXEf\"\n\n    config.option.reportchars = \"sfx\"\n    assert getreportopt(config) == \"sfx\"\n\n    config.option.reportchars = \"sfxw\"\n    assert getreportopt(config) == \"sfx\"\n\n    config.option.reportchars = \"a\"\n    assert getreportopt(config) == \"sxXEf\"\n\n    config.option.reportchars = \"A\"\n    assert getreportopt(config) == \"PpsxXEf\"\n\n    config.option.reportchars = \"AN\"\n    assert getreportopt(config) == \"\"\n\n    config.option.reportchars = \"NwfE\"\n    assert getreportopt(config) == \"fE\"\n\n\ndef test_terminalreporter_reportopt_addopts(pytester: Pytester) -> None:\n    pytester.makeini(\"[pytest]\\naddopts=-rs\")\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def tr(request):\n            tr = request.config.pluginmanager.getplugin(\"terminalreporter\")\n            return tr\n        def test_opt(tr):\n            assert tr.hasopt('skipped')\n            assert not tr.hasopt('qwe')\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\ndef test_tbstyle_short(pytester: Pytester) -> None:\n    p = pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.fixture\n        def arg(request):\n            return 42\n        def test_opt(arg):\n            x = 0\n            assert x\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--tb=short\")\n    s = result.stdout.str()\n    assert \"arg = 42\" not in s\n    assert \"x = 0\" not in s\n    result.stdout.fnmatch_lines([f\"*{p.name}:8*\", \"    assert x\", \"E   assert*\"])\n    result = pytester.runpytest()\n    s = result.stdout.str()\n    assert \"x = 0\" in s\n    assert \"assert x\" in s\n\n\ndef test_traceconfig(pytester: Pytester) -> None:\n    result = pytester.runpytest(\"--traceconfig\")\n    result.stdout.fnmatch_lines([\"*active plugins*\"])\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\nclass TestGenericReporting:\n    \"\"\"Test class which can be subclassed with a different option provider to\n    run e.g. distributed tests.\"\"\"\n\n    def test_collect_fail(self, pytester: Pytester, option) -> None:\n        pytester.makepyfile(\"import xyz\\n\")\n        result = pytester.runpytest(*option.args)\n        result.stdout.fnmatch_lines(\n            [\"ImportError while importing*\", \"*No module named *xyz*\", \"*1 error*\"]\n        )\n\n    def test_maxfailures(self, pytester: Pytester, option) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_1():\n                assert 0\n            def test_2():\n                assert 0\n            def test_3():\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--maxfail=2\", *option.args)\n        result.stdout.fnmatch_lines(\n            [\n                \"*def test_1():*\",\n                \"*def test_2():*\",\n                \"*! stopping after 2 failures !*\",\n                \"*2 failed*\",\n            ]\n        )\n\n    def test_maxfailures_with_interrupted(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test(request):\n                request.session.shouldstop = \"session_interrupted\"\n                assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--maxfail=1\", \"-ra\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*= short test summary info =*\",\n                \"FAILED *\",\n                \"*! stopping after 1 failures !*\",\n                \"*! session_interrupted !*\",\n                \"*= 1 failed in*\",\n            ]\n        )\n\n    def test_tb_option(self, pytester: Pytester, option) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def g():\n                raise IndexError\n            def test_func():\n                print(6*7)\n                g()  # --calling--\n        \"\"\"\n        )\n        for tbopt in [\"long\", \"short\", \"no\"]:\n            print(f\"testing --tb={tbopt}...\")\n            result = pytester.runpytest(\"-rN\", f\"--tb={tbopt}\")\n            s = result.stdout.str()\n            if tbopt == \"long\":\n                assert \"print(6*7)\" in s\n            else:\n                assert \"print(6*7)\" not in s\n            if tbopt != \"no\":\n                assert \"--calling--\" in s\n                assert \"IndexError\" in s\n            else:\n                assert \"FAILURES\" not in s\n                assert \"--calling--\" not in s\n                assert \"IndexError\" not in s\n\n    def test_tb_line_show_capture(self, pytester: Pytester, option) -> None:\n        output_to_capture = \"help! let me out!\"\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest\n            def test_fail():\n                print('{output_to_capture}')\n                assert False\n            \"\"\"\n        )\n        result = pytester.runpytest(\"--tb=line\")\n        result.stdout.fnmatch_lines([\"*- Captured stdout call -*\", output_to_capture])\n\n    def test_tb_crashline(self, pytester: Pytester, option) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def g():\n                raise IndexError\n            def test_func1():\n                print(6*7)\n                g()  # --calling--\n            def test_func2():\n                assert 0, \"hello\"\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--tb=line\")\n        bn = p.name\n        result.stdout.fnmatch_lines(\n            [f\"*{bn}:3: IndexError*\", f\"*{bn}:8: AssertionError: hello*\"]\n        )\n        s = result.stdout.str()\n        assert \"def test_func2\" not in s\n\n    def test_tb_crashline_pytrace_false(self, pytester: Pytester, option) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n            def test_func1():\n                pytest.fail('test_func1', pytrace=False)\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--tb=line\")\n        result.stdout.str()\n        bn = p.name\n        result.stdout.fnmatch_lines([f\"*{bn}:3: Failed: test_func1\"])\n\n    def test_pytest_report_header(self, pytester: Pytester, option) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            def pytest_sessionstart(session):\n                session.config._somevalue = 42\n            def pytest_report_header(config):\n                return \"hello: %s\" % config._somevalue\n        \"\"\"\n        )\n        pytester.mkdir(\"a\").joinpath(\"conftest.py\").write_text(\n            \"\"\"\ndef pytest_report_header(config, start_path):\n    return [\"line1\", str(start_path)]\n\"\"\",\n            encoding=\"utf-8\",\n        )\n        result = pytester.runpytest(\"a\")\n        result.stdout.fnmatch_lines([\"*hello: 42*\", \"line1\", str(pytester.path)])\n\n    def test_show_capture(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            import sys\n            import logging\n            def test_one():\n                sys.stdout.write('!This is stdout!')\n                sys.stderr.write('!This is stderr!')\n                logging.warning('!This is a warning log msg!')\n                assert False, 'Something failed'\n        \"\"\"\n        )\n\n        result = pytester.runpytest(\"--tb=short\")\n        result.stdout.fnmatch_lines(\n            [\n                \"!This is stdout!\",\n                \"!This is stderr!\",\n                \"*WARNING*!This is a warning log msg!\",\n            ]\n        )\n\n        result = pytester.runpytest(\"--show-capture=all\", \"--tb=short\")\n        result.stdout.fnmatch_lines(\n            [\n                \"!This is stdout!\",\n                \"!This is stderr!\",\n                \"*WARNING*!This is a warning log msg!\",\n            ]\n        )\n\n        stdout = pytester.runpytest(\"--show-capture=stdout\", \"--tb=short\").stdout.str()\n        assert \"!This is stderr!\" not in stdout\n        assert \"!This is stdout!\" in stdout\n        assert \"!This is a warning log msg!\" not in stdout\n\n        stdout = pytester.runpytest(\"--show-capture=stderr\", \"--tb=short\").stdout.str()\n        assert \"!This is stdout!\" not in stdout\n        assert \"!This is stderr!\" in stdout\n        assert \"!This is a warning log msg!\" not in stdout\n\n        stdout = pytester.runpytest(\"--show-capture=log\", \"--tb=short\").stdout.str()\n        assert \"!This is stdout!\" not in stdout\n        assert \"!This is stderr!\" not in stdout\n        assert \"!This is a warning log msg!\" in stdout\n\n        stdout = pytester.runpytest(\"--show-capture=no\", \"--tb=short\").stdout.str()\n        assert \"!This is stdout!\" not in stdout\n        assert \"!This is stderr!\" not in stdout\n        assert \"!This is a warning log msg!\" not in stdout\n\n    def test_show_capture_with_teardown_logs(self, pytester: Pytester) -> None:\n        \"\"\"Ensure that the capturing of teardown logs honor --show-capture setting\"\"\"\n        pytester.makepyfile(\n            \"\"\"\n            import logging\n            import sys\n            import pytest\n\n            @pytest.fixture(scope=\"function\", autouse=\"True\")\n            def hook_each_test(request):\n                yield\n                sys.stdout.write(\"!stdout!\")\n                sys.stderr.write(\"!stderr!\")\n                logging.warning(\"!log!\")\n\n            def test_func():\n                assert False\n        \"\"\"\n        )\n\n        result = pytester.runpytest(\"--show-capture=stdout\", \"--tb=short\").stdout.str()\n        assert \"!stdout!\" in result\n        assert \"!stderr!\" not in result\n        assert \"!log!\" not in result\n\n        result = pytester.runpytest(\"--show-capture=stderr\", \"--tb=short\").stdout.str()\n        assert \"!stdout!\" not in result\n        assert \"!stderr!\" in result\n        assert \"!log!\" not in result\n\n        result = pytester.runpytest(\"--show-capture=log\", \"--tb=short\").stdout.str()\n        assert \"!stdout!\" not in result\n        assert \"!stderr!\" not in result\n        assert \"!log!\" in result\n\n        result = pytester.runpytest(\"--show-capture=no\", \"--tb=short\").stdout.str()\n        assert \"!stdout!\" not in result\n        assert \"!stderr!\" not in result\n        assert \"!log!\" not in result\n\n\n@pytest.mark.xfail(\"not hasattr(os, 'dup')\")\ndef test_fdopen_kept_alive_issue124(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import os, sys\n        k = []\n        def test_open_file_and_keep_alive(capfd):\n            stdout = os.fdopen(1, 'w', buffering=1, encoding='utf-8')\n            k.append(stdout)\n\n        def test_close_kept_alive_file():\n            stdout = k.pop()\n            stdout.close()\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_tbstyle_native_setup_error(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.fixture\n        def setup_error_fixture():\n            raise Exception(\"error in exception\")\n\n        def test_error_fixture(setup_error_fixture):\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--tb=native\")\n    result.stdout.fnmatch_lines(\n        ['*File *test_tbstyle_native_setup_error.py\", line *, in setup_error_fixture*']\n    )\n\n\ndef test_terminal_summary(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_terminal_summary(terminalreporter, exitstatus):\n            w = terminalreporter\n            w.section(\"hello\")\n            w.line(\"world\")\n            w.line(\"exitstatus: {0}\".format(exitstatus))\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        *==== hello ====*\n        world\n        exitstatus: 5\n    \"\"\"\n    )\n\n\n@pytest.mark.filterwarnings(\"default::UserWarning\")\ndef test_terminal_summary_warnings_are_displayed(pytester: Pytester) -> None:\n    \"\"\"Test that warnings emitted during pytest_terminal_summary are displayed.\n    (#1305).\n    \"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        import warnings\n        def pytest_terminal_summary(terminalreporter):\n            warnings.warn(UserWarning('internal warning'))\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        def test_failure():\n            import warnings\n            warnings.warn(\"warning_from_\" + \"test\")\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-ra\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*= warnings summary =*\",\n            \"*warning_from_test*\",\n            \"*= short test summary info =*\",\n            \"*= warnings summary (final) =*\",\n            \"*conftest.py:3:*internal warning\",\n            \"*== 1 failed, 2 warnings in *\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*None*\")\n    stdout = result.stdout.str()\n    assert stdout.count(\"warning_from_test\") == 1\n    assert stdout.count(\"=== warnings summary \") == 2\n\n\n@pytest.mark.filterwarnings(\"default::UserWarning\")\ndef test_terminal_summary_warnings_header_once(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_failure():\n            import warnings\n            warnings.warn(\"warning_from_\" + \"test\")\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-ra\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*= warnings summary =*\",\n            \"*warning_from_test*\",\n            \"*= short test summary info =*\",\n            \"*== 1 failed, 1 warning in *\",\n        ]\n    )\n    result.stdout.no_fnmatch_line(\"*None*\")\n    stdout = result.stdout.str()\n    assert stdout.count(\"warning_from_test\") == 1\n    assert stdout.count(\"=== warnings summary \") == 1\n\n\n@pytest.mark.filterwarnings(\"default\")\ndef test_terminal_no_summary_warnings_header_once(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        def test_failure():\n            import warnings\n            warnings.warn(\"warning_from_\" + \"test\")\n            assert 0\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--no-summary\")\n    result.stdout.no_fnmatch_line(\"*= warnings summary =*\")\n    result.stdout.no_fnmatch_line(\"*= short test summary info =*\")\n\n\n@pytest.fixture(scope=\"session\")\ndef tr() -> TerminalReporter:\n    config = _pytest.config._prepareconfig([])\n    return TerminalReporter(config)\n\n\n@pytest.mark.parametrize(\n    \"exp_color, exp_line, stats_arg\",\n    [\n        # The method under test only cares about the length of each\n        # dict value, not the actual contents, so tuples of anything\n        # suffice\n        # Important statuses -- the highest priority of these always wins\n        (\"red\", [(\"1 failed\", {\"bold\": True, \"red\": True})], {\"failed\": [1]}),\n        (\n            \"red\",\n            [\n                (\"1 failed\", {\"bold\": True, \"red\": True}),\n                (\"1 passed\", {\"bold\": False, \"green\": True}),\n            ],\n            {\"failed\": [1], \"passed\": [1]},\n        ),\n        (\"red\", [(\"1 error\", {\"bold\": True, \"red\": True})], {\"error\": [1]}),\n        (\"red\", [(\"2 errors\", {\"bold\": True, \"red\": True})], {\"error\": [1, 2]}),\n        (\n            \"red\",\n            [\n                (\"1 passed\", {\"bold\": False, \"green\": True}),\n                (\"1 error\", {\"bold\": True, \"red\": True}),\n            ],\n            {\"error\": [1], \"passed\": [1]},\n        ),\n        # (a status that's not known to the code)\n        (\"yellow\", [(\"1 weird\", {\"bold\": True, \"yellow\": True})], {\"weird\": [1]}),\n        (\n            \"yellow\",\n            [\n                (\"1 passed\", {\"bold\": False, \"green\": True}),\n                (\"1 weird\", {\"bold\": True, \"yellow\": True}),\n            ],\n            {\"weird\": [1], \"passed\": [1]},\n        ),\n        (\"yellow\", [(\"1 warning\", {\"bold\": True, \"yellow\": True})], {\"warnings\": [1]}),\n        (\n            \"yellow\",\n            [\n                (\"1 passed\", {\"bold\": False, \"green\": True}),\n                (\"1 warning\", {\"bold\": True, \"yellow\": True}),\n            ],\n            {\"warnings\": [1], \"passed\": [1]},\n        ),\n        (\n            \"green\",\n            [(\"5 passed\", {\"bold\": True, \"green\": True})],\n            {\"passed\": [1, 2, 3, 4, 5]},\n        ),\n        # \"Boring\" statuses.  These have no effect on the color of the summary\n        # line.  Thus, if *every* test has a boring status, the summary line stays\n        # at its default color, i.e. yellow, to warn the user that the test run\n        # produced no useful information\n        (\"yellow\", [(\"1 skipped\", {\"bold\": True, \"yellow\": True})], {\"skipped\": [1]}),\n        (\n            \"green\",\n            [\n                (\"1 passed\", {\"bold\": True, \"green\": True}),\n                (\"1 skipped\", {\"bold\": False, \"yellow\": True}),\n            ],\n            {\"skipped\": [1], \"passed\": [1]},\n        ),\n        (\n            \"yellow\",\n            [(\"1 deselected\", {\"bold\": True, \"yellow\": True})],\n            {\"deselected\": [1]},\n        ),\n        (\n            \"green\",\n            [\n                (\"1 passed\", {\"bold\": True, \"green\": True}),\n                (\"1 deselected\", {\"bold\": False, \"yellow\": True}),\n            ],\n            {\"deselected\": [1], \"passed\": [1]},\n        ),\n        (\"yellow\", [(\"1 xfailed\", {\"bold\": True, \"yellow\": True})], {\"xfailed\": [1]}),\n        (\n            \"green\",\n            [\n                (\"1 passed\", {\"bold\": True, \"green\": True}),\n                (\"1 xfailed\", {\"bold\": False, \"yellow\": True}),\n            ],\n            {\"xfailed\": [1], \"passed\": [1]},\n        ),\n        (\"yellow\", [(\"1 xpassed\", {\"bold\": True, \"yellow\": True})], {\"xpassed\": [1]}),\n        (\n            \"yellow\",\n            [\n                (\"1 passed\", {\"bold\": False, \"green\": True}),\n                (\"1 xpassed\", {\"bold\": True, \"yellow\": True}),\n            ],\n            {\"xpassed\": [1], \"passed\": [1]},\n        ),\n        # Likewise if no tests were found at all\n        (\"yellow\", [(\"no tests ran\", {\"yellow\": True})], {}),\n        # Test the empty-key special case\n        (\"yellow\", [(\"no tests ran\", {\"yellow\": True})], {\"\": [1]}),\n        (\n            \"green\",\n            [(\"1 passed\", {\"bold\": True, \"green\": True})],\n            {\"\": [1], \"passed\": [1]},\n        ),\n        # A couple more complex combinations\n        (\n            \"red\",\n            [\n                (\"1 failed\", {\"bold\": True, \"red\": True}),\n                (\"2 passed\", {\"bold\": False, \"green\": True}),\n                (\"3 xfailed\", {\"bold\": False, \"yellow\": True}),\n            ],\n            {\"passed\": [1, 2], \"failed\": [1], \"xfailed\": [1, 2, 3]},\n        ),\n        (\n            \"green\",\n            [\n                (\"1 passed\", {\"bold\": True, \"green\": True}),\n                (\"2 skipped\", {\"bold\": False, \"yellow\": True}),\n                (\"3 deselected\", {\"bold\": False, \"yellow\": True}),\n                (\"2 xfailed\", {\"bold\": False, \"yellow\": True}),\n            ],\n            {\n                \"passed\": [1],\n                \"skipped\": [1, 2],\n                \"deselected\": [1, 2, 3],\n                \"xfailed\": [1, 2],\n            },\n        ),\n    ],\n)\ndef test_summary_stats(\n    tr: TerminalReporter,\n    exp_line: list[tuple[str, dict[str, bool]]],\n    exp_color: str,\n    stats_arg: dict[str, list[object]],\n) -> None:\n    tr.stats = stats_arg\n\n    # Fake \"_is_last_item\" to be True.\n    class fake_session:\n        testscollected = 0\n\n    tr._session = fake_session  # type: ignore[assignment]\n    assert tr._is_last_item\n\n    # Reset cache.\n    tr._main_color = None\n\n    print(f\"Based on stats: {stats_arg}\")\n    print(f'Expect summary: \"{exp_line}\"; with color \"{exp_color}\"')\n    (line, color) = tr.build_summary_stats_line()\n    print(f'Actually got:   \"{line}\"; with color \"{color}\"')\n    assert line == exp_line\n    assert color == exp_color\n\n\ndef test_skip_counting_towards_summary(tr):\n    class DummyReport(BaseReport):\n        count_towards_summary = True\n\n    r1 = DummyReport()\n    r2 = DummyReport()\n    tr.stats = {\"failed\": (r1, r2)}\n    tr._main_color = None\n    res = tr.build_summary_stats_line()\n    assert res == ([(\"2 failed\", {\"bold\": True, \"red\": True})], \"red\")\n\n    r1.count_towards_summary = False\n    tr.stats = {\"failed\": (r1, r2)}\n    tr._main_color = None\n    res = tr.build_summary_stats_line()\n    assert res == ([(\"1 failed\", {\"bold\": True, \"red\": True})], \"red\")\n\n\nclass TestClassicOutputStyle:\n    \"\"\"Ensure classic output style works as expected (#3883)\"\"\"\n\n    @pytest.fixture\n    def test_files(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            **{\n                \"test_one.py\": \"def test_one(): pass\",\n                \"test_two.py\": \"def test_two(): assert 0\",\n                \"sub/test_three.py\": \"\"\"\n                    def test_three_1(): pass\n                    def test_three_2(): assert 0\n                    def test_three_3(): pass\n                \"\"\",\n            }\n        )\n\n    def test_normal_verbosity(self, pytester: Pytester, test_files) -> None:\n        result = pytester.runpytest(\"-o\", \"console_output_style=classic\")\n        result.stdout.fnmatch_lines(\n            [\n                f\"sub{os.sep}test_three.py .F.\",\n                \"test_one.py .\",\n                \"test_two.py F\",\n                \"*2 failed, 3 passed in*\",\n            ]\n        )\n\n    def test_verbose(self, pytester: Pytester, test_files) -> None:\n        result = pytester.runpytest(\"-o\", \"console_output_style=classic\", \"-v\")\n        result.stdout.fnmatch_lines(\n            [\n                f\"sub{os.sep}test_three.py::test_three_1 PASSED\",\n                f\"sub{os.sep}test_three.py::test_three_2 FAILED\",\n                f\"sub{os.sep}test_three.py::test_three_3 PASSED\",\n                \"test_one.py::test_one PASSED\",\n                \"test_two.py::test_two FAILED\",\n                \"*2 failed, 3 passed in*\",\n            ]\n        )\n\n    def test_quiet(self, pytester: Pytester, test_files) -> None:\n        result = pytester.runpytest(\"-o\", \"console_output_style=classic\", \"-q\")\n        result.stdout.fnmatch_lines([\".F..F\", \"*2 failed, 3 passed in*\"])\n\n\nclass TestProgressOutputStyle:\n    @pytest.fixture\n    def many_tests_files(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_bar=\"\"\"\n                import pytest\n                @pytest.mark.parametrize('i', range(10))\n                def test_bar(i): pass\n            \"\"\",\n            test_foo=\"\"\"\n                import pytest\n                @pytest.mark.parametrize('i', range(5))\n                def test_foo(i): pass\n            \"\"\",\n            test_foobar=\"\"\"\n                import pytest\n                @pytest.mark.parametrize('i', range(5))\n                def test_foobar(i): pass\n            \"\"\",\n        )\n\n    @pytest.fixture\n    def more_tests_files(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            test_bar=\"\"\"\n                import pytest\n                @pytest.mark.parametrize('i', range(30))\n                def test_bar(i): pass\n            \"\"\",\n            test_foo=\"\"\"\n                import pytest\n                @pytest.mark.parametrize('i', range(5))\n                def test_foo(i): pass\n            \"\"\",\n        )\n\n    def test_zero_tests_collected(self, pytester: Pytester) -> None:\n        \"\"\"Some plugins (testmon for example) might issue pytest_runtest_logreport without any tests being\n        actually collected (#2971).\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n        def pytest_collection_modifyitems(items, config):\n            from _pytest.runner import CollectReport\n            for node_id in ('nodeid1', 'nodeid2'):\n                rep = CollectReport(node_id, 'passed', None, None)\n                rep.when = 'passed'\n                rep.duration = 0.1\n                config.hook.pytest_runtest_logreport(report=rep)\n        \"\"\"\n        )\n        output = pytester.runpytest()\n        output.stdout.no_fnmatch_line(\"*ZeroDivisionError*\")\n        output.stdout.fnmatch_lines([\"=* 2 passed in *=\"])\n\n    def test_normal(self, many_tests_files, pytester: Pytester) -> None:\n        output = pytester.runpytest()\n        output.stdout.re_match_lines(\n            [\n                r\"test_bar.py \\.{10} \\s+ \\[ 50%\\]\",\n                r\"test_foo.py \\.{5} \\s+ \\[ 75%\\]\",\n                r\"test_foobar.py \\.{5} \\s+ \\[100%\\]\",\n            ]\n        )\n\n    def test_colored_progress(\n        self, pytester: Pytester, monkeypatch, color_mapping\n    ) -> None:\n        monkeypatch.setenv(\"PY_COLORS\", \"1\")\n        pytester.makepyfile(\n            test_axfail=\"\"\"\n                import pytest\n                @pytest.mark.xfail\n                def test_axfail(): assert 0\n            \"\"\",\n            test_bar=\"\"\"\n                import pytest\n                @pytest.mark.parametrize('i', range(10))\n                def test_bar(i): pass\n            \"\"\",\n            test_foo=\"\"\"\n                import pytest\n                import warnings\n                @pytest.mark.parametrize('i', range(5))\n                def test_foo(i):\n                    warnings.warn(DeprecationWarning(\"collection\"))\n                    pass\n            \"\"\",\n            test_foobar=\"\"\"\n                import pytest\n                @pytest.mark.parametrize('i', range(5))\n                def test_foobar(i): raise ValueError()\n            \"\"\",\n        )\n        result = pytester.runpytest()\n        result.stdout.re_match_lines(\n            color_mapping.format_for_rematch(\n                [\n                    r\"test_axfail.py {yellow}x{reset}{green} \\s+ \\[  4%\\]{reset}\",\n                    r\"test_bar.py ({green}\\.{reset}){{10}}{green} \\s+ \\[ 52%\\]{reset}\",\n                    r\"test_foo.py ({green}\\.{reset}){{5}}{yellow} \\s+ \\[ 76%\\]{reset}\",\n                    r\"test_foobar.py ({red}F{reset}){{5}}{red} \\s+ \\[100%\\]{reset}\",\n                ]\n            )\n        )\n\n        # Only xfail should have yellow progress indicator.\n        result = pytester.runpytest(\"test_axfail.py\")\n        result.stdout.re_match_lines(\n            color_mapping.format_for_rematch(\n                [\n                    r\"test_axfail.py {yellow}x{reset}{yellow} \\s+ \\[100%\\]{reset}\",\n                    r\"^{yellow}=+ ({yellow}{bold}|{bold}{yellow})1 xfailed{reset}{yellow} in \",\n                ]\n            )\n        )\n\n    def test_count(self, many_tests_files, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style = count\n        \"\"\"\n        )\n        output = pytester.runpytest()\n        output.stdout.re_match_lines(\n            [\n                r\"test_bar.py \\.{10} \\s+ \\[10/20\\]\",\n                r\"test_foo.py \\.{5} \\s+ \\[15/20\\]\",\n                r\"test_foobar.py \\.{5} \\s+ \\[20/20\\]\",\n            ]\n        )\n\n    def test_times(self, many_tests_files, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style = times\n        \"\"\"\n        )\n        output = pytester.runpytest()\n        output.stdout.re_match_lines(\n            [\n                r\"test_bar.py \\.{10} \\s+ \\d{1,3}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2}$\",\n                r\"test_foo.py \\.{5} \\s+ \\d{1,3}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2}$\",\n                r\"test_foobar.py \\.{5} \\s+ \\d{1,3}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2}$\",\n            ]\n        )\n\n    def test_times_multiline(\n        self, more_tests_files, monkeypatch, pytester: Pytester\n    ) -> None:\n        monkeypatch.setenv(\"COLUMNS\", \"40\")\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style = times\n        \"\"\"\n        )\n        output = pytester.runpytest()\n        output.stdout.re_match_lines(\n            [\n                r\"test_bar.py ...................\",\n                r\"........... \\s+ \\d{1,4}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2}$\",\n                r\"test_foo.py \\.{5} \\s+ \\d{1,4}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2}$\",\n            ],\n            consecutive=True,\n        )\n\n    def test_times_none_collected(self, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style = times\n        \"\"\"\n        )\n        output = pytester.runpytest()\n        assert output.ret == ExitCode.NO_TESTS_COLLECTED\n\n    def test_verbose(self, many_tests_files, pytester: Pytester) -> None:\n        output = pytester.runpytest(\"-v\")\n        output.stdout.re_match_lines(\n            [\n                r\"test_bar.py::test_bar\\[0\\] PASSED \\s+ \\[  5%\\]\",\n                r\"test_foo.py::test_foo\\[4\\] PASSED \\s+ \\[ 75%\\]\",\n                r\"test_foobar.py::test_foobar\\[4\\] PASSED \\s+ \\[100%\\]\",\n            ]\n        )\n\n    def test_verbose_count(self, many_tests_files, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style = count\n        \"\"\"\n        )\n        output = pytester.runpytest(\"-v\")\n        output.stdout.re_match_lines(\n            [\n                r\"test_bar.py::test_bar\\[0\\] PASSED \\s+ \\[ 1/20\\]\",\n                r\"test_foo.py::test_foo\\[4\\] PASSED \\s+ \\[15/20\\]\",\n                r\"test_foobar.py::test_foobar\\[4\\] PASSED \\s+ \\[20/20\\]\",\n            ]\n        )\n\n    def test_verbose_times(self, many_tests_files, pytester: Pytester) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style = times\n        \"\"\"\n        )\n        output = pytester.runpytest(\"-v\")\n        output.stdout.re_match_lines(\n            [\n                r\"test_bar.py::test_bar\\[0\\] PASSED \\s+ \\d{1,3}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2}$\",\n                r\"test_foo.py::test_foo\\[4\\] PASSED \\s+ \\d{1,3}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2}$\",\n                r\"test_foobar.py::test_foobar\\[4\\] PASSED \\s+ \\d{1,3}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2}$\",\n            ]\n        )\n\n    def test_xdist_normal(\n        self, many_tests_files, pytester: Pytester, monkeypatch\n    ) -> None:\n        pytest.importorskip(\"xdist\")\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n        output = pytester.runpytest(\"-n2\")\n        output.stdout.re_match_lines([r\"\\.{20} \\s+ \\[100%\\]\"])\n\n    def test_xdist_normal_count(\n        self, many_tests_files, pytester: Pytester, monkeypatch\n    ) -> None:\n        pytest.importorskip(\"xdist\")\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style = count\n        \"\"\"\n        )\n        output = pytester.runpytest(\"-n2\")\n        output.stdout.re_match_lines([r\"\\.{20} \\s+ \\[20/20\\]\"])\n\n    def test_xdist_verbose(\n        self, many_tests_files, pytester: Pytester, monkeypatch\n    ) -> None:\n        pytest.importorskip(\"xdist\")\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n        output = pytester.runpytest(\"-n2\", \"-v\")\n        output.stdout.re_match_lines_random(\n            [\n                r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_bar.py::test_bar\\[1\\]\",\n                r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_foo.py::test_foo\\[1\\]\",\n                r\"\\[gw\\d\\] \\[\\s*\\d+%\\] PASSED test_foobar.py::test_foobar\\[1\\]\",\n            ]\n        )\n        output.stdout.fnmatch_lines_random(\n            [\n                line.translate(TRANS_FNMATCH)\n                for line in [\n                    \"test_bar.py::test_bar[0] \",\n                    \"test_foo.py::test_foo[0] \",\n                    \"test_foobar.py::test_foobar[0] \",\n                    \"[gw?] [  5%] PASSED test_*[?] \",\n                    \"[gw?] [ 10%] PASSED test_*[?] \",\n                    \"[gw?] [ 55%] PASSED test_*[?] \",\n                    \"[gw?] [ 60%] PASSED test_*[?] \",\n                    \"[gw?] [ 95%] PASSED test_*[?] \",\n                    \"[gw?] [100%] PASSED test_*[?] \",\n                ]\n            ]\n        )\n\n    def test_xdist_times(\n        self, many_tests_files, pytester: Pytester, monkeypatch\n    ) -> None:\n        pytest.importorskip(\"xdist\")\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style = times\n        \"\"\"\n        )\n        output = pytester.runpytest(\"-n2\", \"-v\")\n        output.stdout.re_match_lines_random(\n            [\n                r\"\\[gw\\d\\] \\d{1,3}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2} PASSED test_bar.py::test_bar\\[1\\]\",\n                r\"\\[gw\\d\\] \\d{1,3}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2} PASSED test_foo.py::test_foo\\[1\\]\",\n                r\"\\[gw\\d\\] \\d{1,3}[\\.[a-z\\ ]{1,2}\\d{0,3}\\w{1,2} PASSED test_foobar.py::test_foobar\\[1\\]\",\n            ]\n        )\n\n    def test_capture_no(self, many_tests_files, pytester: Pytester) -> None:\n        output = pytester.runpytest(\"-s\")\n        output.stdout.re_match_lines(\n            [r\"test_bar.py \\.{10}\", r\"test_foo.py \\.{5}\", r\"test_foobar.py \\.{5}\"]\n        )\n\n        output = pytester.runpytest(\"--capture=no\")\n        output.stdout.no_fnmatch_line(\"*%]*\")\n\n    def test_capture_no_progress_enabled(\n        self, many_tests_files, pytester: Pytester\n    ) -> None:\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            console_output_style = progress-even-when-capture-no\n        \"\"\"\n        )\n        output = pytester.runpytest(\"-s\")\n        output.stdout.re_match_lines(\n            [\n                r\"test_bar.py \\.{10} \\s+ \\[ 50%\\]\",\n                r\"test_foo.py \\.{5} \\s+ \\[ 75%\\]\",\n                r\"test_foobar.py \\.{5} \\s+ \\[100%\\]\",\n            ]\n        )\n\n\nclass TestProgressWithTeardown:\n    \"\"\"Ensure we show the correct percentages for tests that fail during teardown (#3088)\"\"\"\n\n    @pytest.fixture\n    def contest_with_teardown_fixture(self, pytester: Pytester) -> None:\n        pytester.makeconftest(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def fail_teardown():\n                yield\n                assert False\n        \"\"\"\n        )\n\n    @pytest.fixture\n    def many_files(self, pytester: Pytester, contest_with_teardown_fixture) -> None:\n        pytester.makepyfile(\n            test_bar=\"\"\"\n                import pytest\n                @pytest.mark.parametrize('i', range(5))\n                def test_bar(fail_teardown, i):\n                    pass\n            \"\"\",\n            test_foo=\"\"\"\n                import pytest\n                @pytest.mark.parametrize('i', range(15))\n                def test_foo(fail_teardown, i):\n                    pass\n            \"\"\",\n        )\n\n    def test_teardown_simple(\n        self, pytester: Pytester, contest_with_teardown_fixture\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo(fail_teardown):\n                pass\n        \"\"\"\n        )\n        output = pytester.runpytest()\n        output.stdout.re_match_lines([r\"test_teardown_simple.py \\.E\\s+\\[100%\\]\"])\n\n    def test_teardown_with_test_also_failing(\n        self, pytester: Pytester, contest_with_teardown_fixture\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo(fail_teardown):\n                assert 0\n        \"\"\"\n        )\n        output = pytester.runpytest(\"-rfE\")\n        output.stdout.re_match_lines(\n            [\n                r\"test_teardown_with_test_also_failing.py FE\\s+\\[100%\\]\",\n                \"FAILED test_teardown_with_test_also_failing.py::test_foo - assert 0\",\n                \"ERROR test_teardown_with_test_also_failing.py::test_foo - assert False\",\n            ]\n        )\n\n    def test_teardown_many(self, pytester: Pytester, many_files) -> None:\n        output = pytester.runpytest()\n        output.stdout.re_match_lines(\n            [r\"test_bar.py (\\.E){5}\\s+\\[ 25%\\]\", r\"test_foo.py (\\.E){15}\\s+\\[100%\\]\"]\n        )\n\n    def test_teardown_many_verbose(\n        self, pytester: Pytester, many_files, color_mapping\n    ) -> None:\n        result = pytester.runpytest(\"-v\")\n        result.stdout.fnmatch_lines(\n            color_mapping.format_for_fnmatch(\n                [\n                    \"test_bar.py::test_bar[0] PASSED  * [  5%]\",\n                    \"test_bar.py::test_bar[0] ERROR   * [  5%]\",\n                    \"test_bar.py::test_bar[4] PASSED  * [ 25%]\",\n                    \"test_foo.py::test_foo[14] PASSED * [100%]\",\n                    \"test_foo.py::test_foo[14] ERROR  * [100%]\",\n                    \"=* 20 passed, 20 errors in *\",\n                ]\n            )\n        )\n\n    def test_xdist_normal(self, many_files, pytester: Pytester, monkeypatch) -> None:\n        pytest.importorskip(\"xdist\")\n        monkeypatch.delenv(\"PYTEST_DISABLE_PLUGIN_AUTOLOAD\", raising=False)\n        output = pytester.runpytest(\"-n2\")\n        output.stdout.re_match_lines([r\"[\\.E]{40} \\s+ \\[100%\\]\"])\n\n\ndef test_skip_reasons_folding() -> None:\n    path = \"xyz\"\n    lineno = 3\n    message = \"justso\"\n    longrepr = (path, lineno, message)\n\n    class X:\n        pass\n\n    ev1 = cast(CollectReport, X())\n    ev1.when = \"execute\"\n    ev1.skipped = True  # type: ignore[misc]\n    ev1.longrepr = longrepr\n\n    ev2 = cast(CollectReport, X())\n    ev2.when = \"execute\"\n    ev2.longrepr = longrepr\n    ev2.skipped = True  # type: ignore[misc]\n\n    # ev3 might be a collection report\n    ev3 = cast(CollectReport, X())\n    ev3.when = \"collect\"\n    ev3.longrepr = longrepr\n    ev3.skipped = True  # type: ignore[misc]\n\n    values = _folded_skips(Path.cwd(), [ev1, ev2, ev3])\n    assert len(values) == 1\n    num, fspath, lineno_, reason = values[0]\n    assert num == 3\n    assert fspath == path\n    assert lineno_ == lineno\n    assert reason == message\n\n\ndef test_line_with_reprcrash(monkeypatch: MonkeyPatch) -> None:\n    mocked_verbose_word = \"FAILED\"\n\n    mocked_pos = \"some::nodeid\"\n\n    def mock_get_pos(*args):\n        return mocked_pos\n\n    monkeypatch.setattr(_pytest.terminal, \"_get_node_id_with_markup\", mock_get_pos)\n\n    class Namespace:\n        def __init__(self, **kwargs):\n            self.__dict__.update(kwargs)\n\n    class config:\n        def __init__(self):\n            self.option = Namespace(verbose=0)\n\n    class rep:\n        def _get_verbose_word_with_markup(self, *args):\n            return mocked_verbose_word, {}\n\n        class longrepr:\n            class reprcrash:\n                pass\n\n    def check(msg, width, expected):\n        class DummyTerminalWriter:\n            fullwidth = width\n\n            def markup(self, word: str, **markup: str):\n                return word\n\n        __tracebackhide__ = True\n        if msg:\n            rep.longrepr.reprcrash.message = msg  # type: ignore\n        actual = _get_line_with_reprcrash_message(\n            config(),  # type: ignore[arg-type]\n            rep(),  # type: ignore[arg-type]\n            DummyTerminalWriter(),  # type: ignore[arg-type]\n            {},\n        )\n\n        assert actual == expected\n        if actual != f\"{mocked_verbose_word} {mocked_pos}\":\n            assert len(actual) <= width\n            assert wcswidth(actual) <= width\n\n    # AttributeError with message\n    check(None, 80, \"FAILED some::nodeid\")\n\n    check(\"msg\", 80, \"FAILED some::nodeid - msg\")\n    check(\"msg\", 3, \"FAILED some::nodeid\")\n\n    check(\"msg\", 24, \"FAILED some::nodeid\")\n    check(\"msg\", 25, \"FAILED some::nodeid - msg\")\n\n    check(\"some longer msg\", 24, \"FAILED some::nodeid\")\n    check(\"some longer msg\", 25, \"FAILED some::nodeid - ...\")\n    check(\"some longer msg\", 26, \"FAILED some::nodeid - s...\")\n\n    check(\"some\\nmessage\", 25, \"FAILED some::nodeid - ...\")\n    check(\"some\\nmessage\", 26, \"FAILED some::nodeid - some\")\n    check(\"some\\nmessage\", 80, \"FAILED some::nodeid - some\")\n\n    # Test unicode safety.\n    check(\"🉐🉐🉐🉐🉐\\n2nd line\", 25, \"FAILED some::nodeid - ...\")\n    check(\"🉐🉐🉐🉐🉐\\n2nd line\", 26, \"FAILED some::nodeid - ...\")\n    check(\"🉐🉐🉐🉐🉐\\n2nd line\", 27, \"FAILED some::nodeid - 🉐...\")\n    check(\"🉐🉐🉐🉐🉐\\n2nd line\", 28, \"FAILED some::nodeid - 🉐...\")\n    check(\"🉐🉐🉐🉐🉐\\n2nd line\", 29, \"FAILED some::nodeid - 🉐🉐...\")\n\n    # NOTE: constructed, not sure if this is supported.\n    mocked_pos = \"nodeid::🉐::withunicode\"\n    check(\"🉐🉐🉐🉐🉐\\n2nd line\", 29, \"FAILED nodeid::🉐::withunicode\")\n    check(\"🉐🉐🉐🉐🉐\\n2nd line\", 40, \"FAILED nodeid::🉐::withunicode - 🉐🉐...\")\n    check(\"🉐🉐🉐🉐🉐\\n2nd line\", 41, \"FAILED nodeid::🉐::withunicode - 🉐🉐...\")\n    check(\"🉐🉐🉐🉐🉐\\n2nd line\", 42, \"FAILED nodeid::🉐::withunicode - 🉐🉐🉐...\")\n    check(\"🉐🉐🉐🉐🉐\\n2nd line\", 80, \"FAILED nodeid::🉐::withunicode - 🉐🉐🉐🉐🉐\")\n\n\ndef test_short_summary_with_verbose(\n    monkeypatch: MonkeyPatch, pytester: Pytester\n) -> None:\n    \"\"\"With -vv do not truncate the summary info (#11777).\"\"\"\n    # On CI we also do not truncate the summary info, monkeypatch it to ensure we\n    # are testing against the -vv flag on CI.\n    monkeypatch.setattr(_pytest.terminal, \"running_on_ci\", lambda: False)\n\n    string_length = 200\n    pytester.makepyfile(\n        f\"\"\"\n        def test():\n            s1 = \"A\" * {string_length}\n            s2 = \"B\" * {string_length}\n            assert s1 == s2\n        \"\"\"\n    )\n\n    # No -vv, summary info should be truncated.\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"*short test summary info*\",\n            \"* assert 'AAA...\",\n        ],\n    )\n\n    # No truncation with -vv.\n    result = pytester.runpytest(\"-vv\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*short test summary info*\",\n            f\"*{'A' * string_length}*{'B' * string_length}'\",\n        ]\n    )\n\n\ndef test_full_sequence_print_with_vv(\n    monkeypatch: MonkeyPatch, pytester: Pytester\n) -> None:\n    \"\"\"Do not truncate sequences in summaries with -vv (#11777).\"\"\"\n    monkeypatch.setattr(_pytest.terminal, \"running_on_ci\", lambda: False)\n\n    pytester.makepyfile(\n        \"\"\"\n        def test_len_list():\n            l = list(range(10))\n            assert len(l) == 9\n\n        def test_len_dict():\n            d = dict(zip(range(10), range(10)))\n            assert len(d) == 9\n        \"\"\"\n    )\n\n    result = pytester.runpytest(\"-vv\")\n    assert result.ret == 1\n    result.stdout.fnmatch_lines(\n        [\n            \"*short test summary info*\",\n            f\"*{list(range(10))}*\",\n            f\"*{dict(zip(range(10), range(10), strict=True))}*\",\n        ]\n    )\n\n\ndef test_force_short_summary(monkeypatch: MonkeyPatch, pytester: Pytester) -> None:\n    monkeypatch.setattr(_pytest.terminal, \"running_on_ci\", lambda: False)\n\n    pytester.makepyfile(\n        \"\"\"\n        def test():\n            assert \"a\\\\n\" * 10 == \"\"\n        \"\"\"\n    )\n\n    result = pytester.runpytest(\"-vv\", \"--force-short-summary\")\n    assert result.ret == 1\n    result.stdout.fnmatch_lines(\n        [\"*short test summary info*\", \"*AssertionError: assert 'a\\\\na\\\\na\\\\na...\"]\n    )\n\n\n@pytest.mark.parametrize(\n    \"seconds, expected\",\n    [\n        (10.0, \"10.00s\"),\n        (10.34, \"10.34s\"),\n        (59.99, \"59.99s\"),\n        (60.55, \"60.55s (0:01:00)\"),\n        (123.55, \"123.55s (0:02:03)\"),\n        (60 * 60 + 0.5, \"3600.50s (1:00:00)\"),\n    ],\n)\ndef test_format_session_duration(seconds, expected):\n    from _pytest.terminal import format_session_duration\n\n    assert format_session_duration(seconds) == expected\n\n\n@pytest.mark.parametrize(\n    \"seconds, expected\",\n    [\n        (3600 * 100 - 60, \" 99h 59m\"),\n        (31 * 60 - 1, \" 30m 59s\"),\n        (10.1236, \" 10.124s\"),\n        (9.1236, \" 9.124s\"),\n        (0.1236, \" 123.6ms\"),\n        (0.01236, \" 12.36ms\"),\n        (0.001236, \" 1.236ms\"),\n        (0.0001236, \" 123.6us\"),\n        (0.00001236, \" 12.36us\"),\n        (0.000001236, \" 1.236us\"),\n    ],\n)\ndef test_format_node_duration(seconds: float, expected: str) -> None:\n    from _pytest.terminal import format_node_duration\n\n    assert format_node_duration(seconds) == expected\n\n\ndef test_collecterror(pytester: Pytester) -> None:\n    p1 = pytester.makepyfile(\"raise SyntaxError()\")\n    result = pytester.runpytest(\"-ra\", str(p1))\n    result.stdout.fnmatch_lines(\n        [\n            \"collected 0 items / 1 error\",\n            \"*= ERRORS =*\",\n            \"*_ ERROR collecting test_collecterror.py _*\",\n            \"E   SyntaxError: *\",\n            \"*= short test summary info =*\",\n            \"ERROR test_collecterror.py\",\n            \"*! Interrupted: 1 error during collection !*\",\n            \"*= 1 error in *\",\n        ]\n    )\n\n\ndef test_no_summary_collecterror(pytester: Pytester) -> None:\n    p1 = pytester.makepyfile(\"raise SyntaxError()\")\n    result = pytester.runpytest(\"-ra\", \"--no-summary\", str(p1))\n    result.stdout.no_fnmatch_line(\"*= ERRORS =*\")\n\n\ndef test_via_exec(pytester: Pytester) -> None:\n    p1 = pytester.makepyfile(\"exec('def test_via_exec(): pass')\")\n    result = pytester.runpytest(str(p1), \"-vv\")\n    result.stdout.fnmatch_lines(\n        [\"test_via_exec.py::test_via_exec <- <string> PASSED*\", \"*= 1 passed in *\"]\n    )\n\n\nclass TestCodeHighlight:\n    def test_code_highlight_simple(self, pytester: Pytester, color_mapping) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert 1 == 10\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--color=yes\")\n        result.stdout.fnmatch_lines(\n            color_mapping.format_for_fnmatch(\n                [\n                    \"    {reset}{kw}def{hl-reset}{kwspace}{function}test_foo{hl-reset}():{endline}\",\n                    \">       {kw}assert{hl-reset} {number}1{hl-reset} == {number}10{hl-reset}{endline}\",\n                    \"{bold}{red}E       assert 1 == 10{reset}\",\n                ]\n            )\n        )\n\n    def test_code_highlight_continuation(\n        self, pytester: Pytester, color_mapping\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                print('''\n                '''); assert 0\n        \"\"\"\n        )\n        result = pytester.runpytest(\"--color=yes\")\n\n        result.stdout.fnmatch_lines(\n            color_mapping.format_for_fnmatch(\n                [\n                    \"    {reset}{kw}def{hl-reset}{kwspace}{function}test_foo{hl-reset}():{endline}\",\n                    \"        {print}print{hl-reset}({str}'''{hl-reset}{str}{hl-reset}\",\n                    \">   {str}    {hl-reset}{str}'''{hl-reset}); {kw}assert{hl-reset} {number}0{hl-reset}{endline}\",\n                    \"{bold}{red}E       assert 0{reset}\",\n                ]\n            )\n        )\n\n    def test_code_highlight_custom_theme(\n        self, pytester: Pytester, color_mapping, monkeypatch: MonkeyPatch\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert 1 == 10\n        \"\"\"\n        )\n        monkeypatch.setenv(\"PYTEST_THEME\", \"solarized-dark\")\n        monkeypatch.setenv(\"PYTEST_THEME_MODE\", \"dark\")\n        result = pytester.runpytest(\"--color=yes\")\n        result.stdout.fnmatch_lines(\n            color_mapping.format_for_fnmatch(\n                [\n                    \"    {reset}{kw}def{hl-reset}{kwspace}{function}test_foo{hl-reset}():{endline}\",\n                    \">       {kw}assert{hl-reset} {number}1{hl-reset} == {number}10{hl-reset}{endline}\",\n                    \"{bold}{red}E       assert 1 == 10{reset}\",\n                ]\n            )\n        )\n\n    def test_code_highlight_invalid_theme(\n        self, pytester: Pytester, color_mapping, monkeypatch: MonkeyPatch\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert 1 == 10\n        \"\"\"\n        )\n        monkeypatch.setenv(\"PYTEST_THEME\", \"invalid\")\n        result = pytester.runpytest_subprocess(\"--color=yes\")\n        result.stderr.fnmatch_lines(\n            \"ERROR: PYTEST_THEME environment variable has an invalid value: 'invalid'. \"\n            \"Hint: See available pygments styles with `pygmentize -L styles`.\"\n        )\n\n    def test_code_highlight_invalid_theme_mode(\n        self, pytester: Pytester, color_mapping, monkeypatch: MonkeyPatch\n    ) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            def test_foo():\n                assert 1 == 10\n        \"\"\"\n        )\n        monkeypatch.setenv(\"PYTEST_THEME_MODE\", \"invalid\")\n        result = pytester.runpytest_subprocess(\"--color=yes\")\n        result.stderr.fnmatch_lines(\n            \"ERROR: PYTEST_THEME_MODE environment variable has an invalid value: 'invalid'. \"\n            \"The allowed values are 'dark' (default) and 'light'.\"\n        )\n\n\ndef test_raw_skip_reason_skipped() -> None:\n    report = SimpleNamespace()\n    report.skipped = True\n    report.longrepr = (\"xyz\", 3, \"Skipped: Just so\")\n\n    reason = _get_raw_skip_reason(cast(TestReport, report))\n    assert reason == \"Just so\"\n\n\ndef test_raw_skip_reason_xfail() -> None:\n    report = SimpleNamespace()\n    report.wasxfail = \"reason: To everything there is a season\"\n\n    reason = _get_raw_skip_reason(cast(TestReport, report))\n    assert reason == \"To everything there is a season\"\n\n\ndef test_format_trimmed() -> None:\n    msg = \"unconditional skip\"\n\n    assert _format_trimmed(\" ({}) \", msg, len(msg) + 4) == \" (unconditional skip) \"\n    assert _format_trimmed(\" ({}) \", msg, len(msg) + 3) == \" (unconditional ...) \"\n\n\ndef test_warning_when_init_trumps_pyproject_toml(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    \"\"\"Regression test for #7814.\"\"\"\n    tests = pytester.path.joinpath(\"tests\")\n    tests.mkdir()\n    pytester.makepyprojecttoml(\n        f\"\"\"\n        [tool.pytest.ini_options]\n        testpaths = ['{tests}']\n    \"\"\"\n    )\n    pytester.makefile(\".ini\", pytest=\"\")\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"configfile: pytest.ini (WARNING: ignoring pytest config in pyproject.toml!)\",\n        ]\n    )\n\n\ndef test_warning_when_init_trumps_multiple_files(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    \"\"\"Regression test for #7814.\"\"\"\n    tests = pytester.path.joinpath(\"tests\")\n    tests.mkdir()\n    pytester.makepyprojecttoml(\n        f\"\"\"\n        [tool.pytest.ini_options]\n        testpaths = ['{tests}']\n    \"\"\"\n    )\n    pytester.makefile(\".ini\", pytest=\"\")\n    pytester.makeini(\n        \"\"\"\n        # tox.ini\n        [pytest]\n        minversion = 6.0\n        addopts = -ra -q\n        testpaths =\n            tests\n            integration\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"configfile: pytest.ini (WARNING: ignoring pytest config in pyproject.toml, tox.ini!)\",\n        ]\n    )\n\n\ndef test_no_warning_when_init_but_pyproject_toml_has_no_entry(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    \"\"\"Regression test for #7814.\"\"\"\n    tests = pytester.path.joinpath(\"tests\")\n    tests.mkdir()\n    pytester.makepyprojecttoml(\n        f\"\"\"\n        [tool]\n        testpaths = ['{tests}']\n    \"\"\"\n    )\n    pytester.makefile(\".ini\", pytest=\"\")\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"configfile: pytest.ini\",\n        ]\n    )\n\n\ndef test_no_warning_on_terminal_with_a_single_config_file(\n    pytester: Pytester, monkeypatch: MonkeyPatch\n) -> None:\n    \"\"\"Regression test for #7814.\"\"\"\n    tests = pytester.path.joinpath(\"tests\")\n    tests.mkdir()\n    pytester.makepyprojecttoml(\n        f\"\"\"\n        [tool.pytest.ini_options]\n        testpaths = ['{tests}']\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"configfile: pyproject.toml\",\n        ]\n    )\n\n\nclass TestFineGrainedTestCase:\n    DEFAULT_FILE_CONTENTS = \"\"\"\n            import pytest\n\n            @pytest.mark.parametrize(\"i\", range(4))\n            def test_ok(i):\n                '''\n                some docstring\n                '''\n                pass\n\n            def test_fail():\n                assert False\n            \"\"\"\n    LONG_SKIP_FILE_CONTENTS = \"\"\"\n            import pytest\n\n            @pytest.mark.skip(\n              \"some long skip reason that will not fit on a single line with other content that goes\"\n              \" on and on and on and on and on\"\n            )\n            def test_skip():\n                pass\n            \"\"\"\n\n    @pytest.mark.parametrize(\"verbosity\", [1, 2])\n    def test_execute_positive(self, verbosity, pytester: Pytester) -> None:\n        # expected: one test case per line (with file name), word describing result\n        p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=verbosity)\n        result = pytester.runpytest(p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 5 items\",\n                \"\",\n                f\"{p.name}::test_ok[0] PASSED                              [ 20%]\",\n                f\"{p.name}::test_ok[1] PASSED                              [ 40%]\",\n                f\"{p.name}::test_ok[2] PASSED                              [ 60%]\",\n                f\"{p.name}::test_ok[3] PASSED                              [ 80%]\",\n                f\"{p.name}::test_fail FAILED                               [100%]\",\n            ],\n            consecutive=True,\n        )\n\n    def test_execute_0_global_1(self, pytester: Pytester) -> None:\n        # expected: one file name per line, single character describing result\n        p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=0)\n        result = pytester.runpytest(\"-v\", p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collecting ... collected 5 items\",\n                \"\",\n                f\"{p.name} ....F                                         [100%]\",\n            ],\n            consecutive=True,\n        )\n\n    @pytest.mark.parametrize(\"verbosity\", [-1, -2])\n    def test_execute_negative(self, verbosity, pytester: Pytester) -> None:\n        # expected: single character describing result\n        p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=verbosity)\n        result = pytester.runpytest(p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 5 items\",\n                \"....F                                                                    [100%]\",\n            ],\n            consecutive=True,\n        )\n\n    def test_execute_skipped_positive_2(self, pytester: Pytester) -> None:\n        # expected: one test case per line (with file name), word describing result, full reason\n        p = TestFineGrainedTestCase._initialize_files(\n            pytester,\n            verbosity=2,\n            file_contents=TestFineGrainedTestCase.LONG_SKIP_FILE_CONTENTS,\n        )\n        result = pytester.runpytest(p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"\",\n                f\"{p.name}::test_skip SKIPPED (some long skip\",\n                \"reason that will not fit on a single line with other content that goes\",\n                \"on and on and on and on and on)                                          [100%]\",\n            ],\n            consecutive=True,\n        )\n\n    def test_execute_skipped_positive_1(self, pytester: Pytester) -> None:\n        # expected: one test case per line (with file name), word describing result, reason truncated\n        p = TestFineGrainedTestCase._initialize_files(\n            pytester,\n            verbosity=1,\n            file_contents=TestFineGrainedTestCase.LONG_SKIP_FILE_CONTENTS,\n        )\n        result = pytester.runpytest(p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"\",\n                f\"{p.name}::test_skip SKIPPED (some long ski...) [100%]\",\n            ],\n            consecutive=True,\n        )\n\n    def test_execute_skipped__0_global_1(self, pytester: Pytester) -> None:\n        # expected: one file name per line, single character describing result (no reason)\n        p = TestFineGrainedTestCase._initialize_files(\n            pytester,\n            verbosity=0,\n            file_contents=TestFineGrainedTestCase.LONG_SKIP_FILE_CONTENTS,\n        )\n        result = pytester.runpytest(\"-v\", p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collecting ... collected 1 item\",\n                \"\",\n                f\"{p.name} s                                    [100%]\",\n            ],\n            consecutive=True,\n        )\n\n    @pytest.mark.parametrize(\"verbosity\", [-1, -2])\n    def test_execute_skipped_negative(self, verbosity, pytester: Pytester) -> None:\n        # expected: single character describing result (no reason)\n        p = TestFineGrainedTestCase._initialize_files(\n            pytester,\n            verbosity=verbosity,\n            file_contents=TestFineGrainedTestCase.LONG_SKIP_FILE_CONTENTS,\n        )\n        result = pytester.runpytest(p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 1 item\",\n                \"s                                                                        [100%]\",\n            ],\n            consecutive=True,\n        )\n\n    @pytest.mark.parametrize(\"verbosity\", [1, 2])\n    def test__collect_only_positive(self, verbosity, pytester: Pytester) -> None:\n        p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=verbosity)\n        result = pytester.runpytest(\"--collect-only\", p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 5 items\",\n                \"\",\n                f\"<Dir {p.parent.name}>\",\n                f\"  <Module {p.name}>\",\n                \"    <Function test_ok[0]>\",\n                \"      some docstring\",\n                \"    <Function test_ok[1]>\",\n                \"      some docstring\",\n                \"    <Function test_ok[2]>\",\n                \"      some docstring\",\n                \"    <Function test_ok[3]>\",\n                \"      some docstring\",\n                \"    <Function test_fail>\",\n            ],\n            consecutive=True,\n        )\n\n    def test_collect_only_0_global_1(self, pytester: Pytester) -> None:\n        p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=0)\n        result = pytester.runpytest(\"-v\", \"--collect-only\", p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collecting ... collected 5 items\",\n                \"\",\n                f\"<Dir {p.parent.name}>\",\n                f\"  <Module {p.name}>\",\n                \"    <Function test_ok[0]>\",\n                \"    <Function test_ok[1]>\",\n                \"    <Function test_ok[2]>\",\n                \"    <Function test_ok[3]>\",\n                \"    <Function test_fail>\",\n            ],\n            consecutive=True,\n        )\n\n    def test_collect_only_negative_1(self, pytester: Pytester) -> None:\n        p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=-1)\n        result = pytester.runpytest(\"--collect-only\", p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 5 items\",\n                \"\",\n                f\"{p.name}::test_ok[0]\",\n                f\"{p.name}::test_ok[1]\",\n                f\"{p.name}::test_ok[2]\",\n                f\"{p.name}::test_ok[3]\",\n                f\"{p.name}::test_fail\",\n            ],\n            consecutive=True,\n        )\n\n    def test_collect_only_negative_2(self, pytester: Pytester) -> None:\n        p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=-2)\n        result = pytester.runpytest(\"--collect-only\", p)\n\n        result.stdout.fnmatch_lines(\n            [\n                \"collected 5 items\",\n                \"\",\n                f\"{p.name}: 5\",\n            ],\n            consecutive=True,\n        )\n\n    @staticmethod\n    def _initialize_files(\n        pytester: Pytester, verbosity: int, file_contents: str = DEFAULT_FILE_CONTENTS\n    ) -> Path:\n        p = pytester.makepyfile(file_contents)\n        pytester.makeini(\n            f\"\"\"\n            [pytest]\n            verbosity_test_cases = {verbosity}\n            \"\"\"\n        )\n        return p\n\n\ndef test_summary_xfail_reason(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.xfail\n        def test_xfail():\n            assert False\n\n        @pytest.mark.xfail(reason=\"foo\")\n        def test_xfail_reason():\n            assert False\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-rx\")\n    expect1 = \"XFAIL test_summary_xfail_reason.py::test_xfail\"\n    expect2 = \"XFAIL test_summary_xfail_reason.py::test_xfail_reason - foo\"\n    result.stdout.fnmatch_lines([expect1, expect2])\n    assert result.stdout.lines.count(expect1) == 1\n    assert result.stdout.lines.count(expect2) == 1\n\n\n@pytest.fixture()\ndef xfail_testfile(pytester: Pytester) -> Path:\n    return pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        def test_fail():\n            a, b = 1, 2\n            assert a == b\n\n        @pytest.mark.xfail\n        def test_xfail():\n            c, d = 3, 4\n            assert c == d\n        \"\"\"\n    )\n\n\ndef test_xfail_tb_default(xfail_testfile, pytester: Pytester) -> None:\n    result = pytester.runpytest(xfail_testfile)\n\n    # test_fail, show traceback\n    result.stdout.fnmatch_lines(\n        [\n            \"*= FAILURES =*\",\n            \"*_ test_fail _*\",\n            \"*def test_fail():*\",\n            \"*        a, b = 1, 2*\",\n            \"*>       assert a == b*\",\n            \"*E       assert 1 == 2*\",\n        ]\n    )\n\n    # test_xfail, don't show traceback\n    result.stdout.no_fnmatch_line(\"*= XFAILURES =*\")\n\n\ndef test_xfail_tb_true(xfail_testfile, pytester: Pytester) -> None:\n    result = pytester.runpytest(xfail_testfile, \"--xfail-tb\")\n\n    # both test_fail and test_xfail, show traceback\n    result.stdout.fnmatch_lines(\n        [\n            \"*= FAILURES =*\",\n            \"*_ test_fail _*\",\n            \"*def test_fail():*\",\n            \"*        a, b = 1, 2*\",\n            \"*>       assert a == b*\",\n            \"*E       assert 1 == 2*\",\n            \"*= XFAILURES =*\",\n            \"*_ test_xfail _*\",\n            \"*def test_xfail():*\",\n            \"*        c, d = 3, 4*\",\n            \"*>       assert c == d*\",\n            \"*E       assert 3 == 4*\",\n            \"*short test summary info*\",\n        ]\n    )\n\n\ndef test_xfail_tb_line(xfail_testfile, pytester: Pytester) -> None:\n    result = pytester.runpytest(xfail_testfile, \"--xfail-tb\", \"--tb=line\")\n\n    # both test_fail and test_xfail, show line\n    result.stdout.fnmatch_lines(\n        [\n            \"*= FAILURES =*\",\n            \"*test_xfail_tb_line.py:5: assert 1 == 2\",\n            \"*= XFAILURES =*\",\n            \"*test_xfail_tb_line.py:10: assert 3 == 4\",\n            \"*short test summary info*\",\n        ]\n    )\n\n\ndef test_summary_xpass_reason(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.xfail\n        def test_pass():\n            ...\n\n        @pytest.mark.xfail(reason=\"foo\")\n        def test_reason():\n            ...\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-rX\")\n    expect1 = \"XPASS test_summary_xpass_reason.py::test_pass\"\n    expect2 = \"XPASS test_summary_xpass_reason.py::test_reason - foo\"\n    result.stdout.fnmatch_lines([expect1, expect2])\n    assert result.stdout.lines.count(expect1) == 1\n    assert result.stdout.lines.count(expect2) == 1\n\n\ndef test_xpass_output(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.xfail\n        def test_pass():\n            print('hi there')\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-rX\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*= XPASSES =*\",\n            \"*_ test_pass _*\",\n            \"*- Captured stdout call -*\",\n            \"*= short test summary info =*\",\n            \"XPASS test_xpass_output.py::test_pass*\",\n            \"*= 1 xpassed in * =*\",\n        ]\n    )\n\n\nclass TestNodeIDHandling:\n    def test_nodeid_handling_windows_paths(self, pytester: Pytester, tmp_path) -> None:\n        \"\"\"Test the correct handling of Windows-style paths with backslashes.\"\"\"\n        pytester.makeini(\"[pytest]\")  # Change `config.rootpath`\n\n        test_path = pytester.path / \"tests\" / \"test_foo.py\"\n        test_path.parent.mkdir()\n        os.chdir(test_path.parent)  # Change `config.invocation_params.dir`\n\n        test_path.write_text(\n            textwrap.dedent(\n                \"\"\"\n                import pytest\n\n                @pytest.mark.parametrize(\"a\", [\"x/y\", \"C:/path\", \"\\\\\\\\\", \"C:\\\\\\\\path\", \"a::b/\"])\n                def test_x(a):\n                    assert False\n                \"\"\"\n            ),\n            encoding=\"utf-8\",\n        )\n\n        result = pytester.runpytest(\"-v\")\n\n        result.stdout.re_match_lines(\n            [\n                r\".*test_foo.py::test_x\\[x/y\\] .*FAILED.*\",\n                r\".*test_foo.py::test_x\\[C:/path\\] .*FAILED.*\",\n                r\".*test_foo.py::test_x\\[\\\\\\\\\\] .*FAILED.*\",\n                r\".*test_foo.py::test_x\\[C:\\\\\\\\path\\] .*FAILED.*\",\n                r\".*test_foo.py::test_x\\[a::b/\\] .*FAILED.*\",\n            ]\n        )\n\n\nclass TestTerminalProgressPlugin:\n    \"\"\"Tests for the TerminalProgressPlugin.\"\"\"\n\n    @pytest.fixture\n    def mock_file(self) -> StringIO:\n        return StringIO()\n\n    @pytest.fixture\n    def mock_tr(self, mock_file: StringIO) -> pytest.TerminalReporter:\n        tr: pytest.TerminalReporter = mock.create_autospec(pytest.TerminalReporter)\n\n        def write_raw(content: str, *, flush: bool = False) -> None:\n            mock_file.write(content)\n\n        tr.write_raw = write_raw  # type: ignore[method-assign]\n        tr._progress_nodeids_reported = set()\n        return tr\n\n    @pytest.mark.skipif(sys.platform != \"win32\", reason=\"#13896\")\n    def test_plugin_registration_enabled_by_default(\n        self, pytester: pytest.Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"Test that the plugin registration is enabled by default.\n\n        Currently only on Windows (#13896).\n        \"\"\"\n        monkeypatch.setattr(sys.stdout, \"isatty\", lambda: True)\n        # The plugin module should be registered as a default plugin.\n        config = pytester.parseconfigure()\n        plugin = config.pluginmanager.get_plugin(\"terminalprogress\")\n        assert plugin is not None\n\n    def test_plugin_registred_on_all_platforms_when_explicitly_requested(\n        self, pytester: pytest.Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"Test that the plugin is registered on any platform if explicitly requested.\"\"\"\n        monkeypatch.setattr(sys.stdout, \"isatty\", lambda: True)\n        # The plugin module should be registered as a default plugin.\n        config = pytester.parseconfigure(\"-p\", \"terminalprogress\")\n        plugin = config.pluginmanager.get_plugin(\"terminalprogress\")\n        assert plugin is not None\n\n    def test_disabled_for_non_tty(\n        self, pytester: pytest.Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"Test that plugin is disabled for non-TTY output.\"\"\"\n        monkeypatch.setattr(sys.stdout, \"isatty\", lambda: False)\n        config = pytester.parseconfigure(\"-p\", \"terminalprogress\")\n        plugin = config.pluginmanager.get_plugin(\"terminalprogress-plugin\")\n        assert plugin is None\n\n    def test_disabled_for_dumb_terminal(\n        self, pytester: pytest.Pytester, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"Test that plugin is disabled when TERM=dumb.\"\"\"\n        monkeypatch.setenv(\"TERM\", \"dumb\")\n        monkeypatch.setattr(sys.stdout, \"isatty\", lambda: True)\n        config = pytester.parseconfigure(\"-p\", \"terminalprogress\")\n        plugin = config.pluginmanager.get_plugin(\"terminalprogress-plugin\")\n        assert plugin is None\n\n    @pytest.mark.parametrize(\n        [\"state\", \"progress\", \"expected\"],\n        [\n            (\"indeterminate\", None, \"\\x1b]9;4;3;\\x1b\\\\\"),\n            (\"normal\", 50, \"\\x1b]9;4;1;50\\x1b\\\\\"),\n            (\"error\", 75, \"\\x1b]9;4;2;75\\x1b\\\\\"),\n            (\"paused\", None, \"\\x1b]9;4;4;\\x1b\\\\\"),\n            (\"paused\", 80, \"\\x1b]9;4;4;80\\x1b\\\\\"),\n            (\"remove\", None, \"\\x1b]9;4;0;\\x1b\\\\\"),\n        ],\n    )\n    def test_emit_progress_sequences(\n        self,\n        mock_file: StringIO,\n        mock_tr: pytest.TerminalReporter,\n        state: Literal[\"remove\", \"normal\", \"error\", \"indeterminate\", \"paused\"],\n        progress: int | None,\n        expected: str,\n    ) -> None:\n        \"\"\"Test that progress sequences are emitted correctly.\"\"\"\n        plugin = TerminalProgressPlugin(mock_tr)\n        plugin._emit_progress(state, progress)\n        assert expected in mock_file.getvalue()\n\n    def test_session_lifecycle(\n        self, mock_file: StringIO, mock_tr: pytest.TerminalReporter\n    ) -> None:\n        \"\"\"Test progress updates during session lifecycle.\"\"\"\n        plugin = TerminalProgressPlugin(mock_tr)\n\n        session = mock.create_autospec(pytest.Session)\n        session.testscollected = 3\n\n        # Session start - should emit indeterminate progress.\n        plugin.pytest_sessionstart(session)\n        assert \"\\x1b]9;4;3;\\x1b\\\\\" in mock_file.getvalue()\n        mock_file.truncate(0)\n        mock_file.seek(0)\n\n        # Collection finish - should emit 0% progress.\n        plugin.pytest_collection_finish()\n        assert \"\\x1b]9;4;1;0\\x1b\\\\\" in mock_file.getvalue()\n        mock_file.truncate(0)\n        mock_file.seek(0)\n\n        # First test - 33% progress.\n        report1 = pytest.TestReport(\n            nodeid=\"test_1\",\n            location=(\"test.py\", 0, \"test_1\"),\n            when=\"call\",\n            outcome=\"passed\",\n            keywords={},\n            longrepr=None,\n        )\n        mock_tr.reported_progress = 1  # type: ignore[misc]\n        plugin.pytest_runtest_logreport(report1)\n        assert \"\\x1b]9;4;1;33\\x1b\\\\\" in mock_file.getvalue()\n        mock_file.truncate(0)\n        mock_file.seek(0)\n\n        # Second test with failure - 66% in error state.\n        report2 = pytest.TestReport(\n            nodeid=\"test_2\",\n            location=(\"test.py\", 1, \"test_2\"),\n            when=\"call\",\n            outcome=\"failed\",\n            keywords={},\n            longrepr=None,\n        )\n        mock_tr.reported_progress = 2  # type: ignore[misc]\n        plugin.pytest_runtest_logreport(report2)\n        assert \"\\x1b]9;4;2;66\\x1b\\\\\" in mock_file.getvalue()\n        mock_file.truncate(0)\n        mock_file.seek(0)\n\n        # Session finish - should remove progress.\n        plugin.pytest_sessionfinish()\n        assert \"\\x1b]9;4;0;\\x1b\\\\\" in mock_file.getvalue()\n"
  },
  {
    "path": "testing/test_threadexception.py",
    "content": "from __future__ import annotations\n\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\n@pytest.mark.filterwarnings(\"default::pytest.PytestUnhandledThreadExceptionWarning\")\ndef test_unhandled_thread_exception(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import threading\n\n        def test_it():\n            def oops():\n                raise ValueError(\"Oops\")\n\n            t = threading.Thread(target=oops, name=\"MyThread\")\n            t.start()\n            t.join()\n\n        def test_2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.assert_outcomes(passed=2, warnings=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"*= warnings summary =*\",\n            \"test_it.py::test_it\",\n            \"  * PytestUnhandledThreadExceptionWarning: Exception in thread MyThread\",\n            \"  \",\n            \"  Traceback (most recent call last):\",\n            \"  ValueError: Oops\",\n            \"  \",\n            \"    warnings.warn(pytest.PytestUnhandledThreadExceptionWarning(msg))\",\n        ]\n    )\n\n\n@pytest.mark.filterwarnings(\"default::pytest.PytestUnhandledThreadExceptionWarning\")\ndef test_unhandled_thread_exception_in_setup(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import threading\n        import pytest\n\n        @pytest.fixture\n        def threadexc():\n            def oops():\n                raise ValueError(\"Oops\")\n            t = threading.Thread(target=oops, name=\"MyThread\")\n            t.start()\n            t.join()\n\n        def test_it(threadexc): pass\n        def test_2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.assert_outcomes(passed=2, warnings=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"*= warnings summary =*\",\n            \"test_it.py::test_it\",\n            \"  * PytestUnhandledThreadExceptionWarning: Exception in thread MyThread\",\n            \"  \",\n            \"  Traceback (most recent call last):\",\n            \"  ValueError: Oops\",\n            \"  \",\n            \"    warnings.warn(pytest.PytestUnhandledThreadExceptionWarning(msg))\",\n        ]\n    )\n\n\n@pytest.mark.filterwarnings(\"default::pytest.PytestUnhandledThreadExceptionWarning\")\ndef test_unhandled_thread_exception_in_teardown(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import threading\n        import pytest\n\n        @pytest.fixture\n        def threadexc():\n            def oops():\n                raise ValueError(\"Oops\")\n            yield\n            t = threading.Thread(target=oops, name=\"MyThread\")\n            t.start()\n            t.join()\n\n        def test_it(threadexc): pass\n        def test_2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.assert_outcomes(passed=2, warnings=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"*= warnings summary =*\",\n            \"test_it.py::test_it\",\n            \"  * PytestUnhandledThreadExceptionWarning: Exception in thread MyThread\",\n            \"  \",\n            \"  Traceback (most recent call last):\",\n            \"  ValueError: Oops\",\n            \"  \",\n            \"    warnings.warn(pytest.PytestUnhandledThreadExceptionWarning(msg))\",\n        ]\n    )\n\n\n@pytest.mark.filterwarnings(\"error::pytest.PytestUnhandledThreadExceptionWarning\")\ndef test_unhandled_thread_exception_warning_error(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import threading\n        import pytest\n\n        def test_it():\n            def oops():\n                raise ValueError(\"Oops\")\n            t = threading.Thread(target=oops, name=\"MyThread\")\n            t.start()\n            t.join()\n\n        def test_2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == pytest.ExitCode.TESTS_FAILED\n    result.assert_outcomes(passed=1, failed=1)\n\n\n@pytest.mark.filterwarnings(\"error::pytest.PytestUnhandledThreadExceptionWarning\")\ndef test_threadexception_warning_multiple_errors(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import threading\n\n        def test_it():\n            def oops():\n                raise ValueError(\"Oops\")\n\n            t = threading.Thread(target=oops, name=\"MyThread\")\n            t.start()\n            t.join()\n\n            t = threading.Thread(target=oops, name=\"MyThread2\")\n            t.start()\n            t.join()\n\n        def test_2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == pytest.ExitCode.TESTS_FAILED\n    result.assert_outcomes(passed=1, failed=1)\n    result.stdout.fnmatch_lines(\n        [\"  | *ExceptionGroup: multiple thread exception warnings (2 sub-exceptions)\"]\n    )\n\n\ndef test_unraisable_collection_failure(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import threading\n\n        class Thread(threading.Thread):\n            @property\n            def name(self):\n                raise RuntimeError(\"oops!\")\n\n        def test_it():\n            def oops():\n                raise ValueError(\"Oops\")\n\n            t = Thread(target=oops, name=\"MyThread\")\n            t.start()\n            t.join()\n\n        def test_2(): pass\n        \"\"\"\n    )\n\n    result = pytester.runpytest()\n    assert result.ret == 1\n    result.assert_outcomes(passed=1, failed=1)\n    result.stdout.fnmatch_lines(\n        [\"E               RuntimeError: Failed to process thread exception\"]\n    )\n\n\ndef test_unhandled_thread_exception_after_teardown(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import threading\n        import pytest\n\n        def thread():\n            def oops():\n                raise ValueError(\"Oops\")\n\n            t = threading.Thread(target=oops, name=\"MyThread\")\n            t.start()\n            t.join()\n\n        def test_it(request):\n            request.config.add_cleanup(thread)\n        \"\"\"\n    )\n\n    result = pytester.runpytest(\"-Werror\")\n\n    # TODO: should be a test failure or error\n    assert result.ret == pytest.ExitCode.INTERNAL_ERROR\n\n    result.assert_outcomes(passed=1)\n    result.stderr.fnmatch_lines(\"ValueError: Oops\")\n\n\n@pytest.mark.filterwarnings(\"error::pytest.PytestUnhandledThreadExceptionWarning\")\ndef test_possibly_none_excinfo(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import threading\n        import types\n\n        def test_it():\n            threading.excepthook(\n                types.SimpleNamespace(\n                    exc_type=RuntimeError,\n                    exc_value=None,\n                    exc_traceback=None,\n                    thread=None,\n                )\n            )\n        \"\"\"\n    )\n\n    result = pytester.runpytest()\n\n    # TODO: should be a test failure or error\n    assert result.ret == pytest.ExitCode.TESTS_FAILED\n\n    result.assert_outcomes(failed=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"E                   pytest.PytestUnhandledThreadExceptionWarning:\"\n            \" Exception in thread <unknown>\",\n            \"E                   \",\n            \"E                   NoneType: None\",\n        ]\n    )\n"
  },
  {
    "path": "testing/test_tmpdir.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nimport dataclasses\nimport os\nfrom pathlib import Path\nimport stat\nimport sys\nfrom typing import cast\nimport warnings\n\nfrom _pytest import pathlib\nfrom _pytest.config import Config\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pathlib import cleanup_numbered_dir\nfrom _pytest.pathlib import create_cleanup_lock\nfrom _pytest.pathlib import make_numbered_dir\nfrom _pytest.pathlib import maybe_delete_a_numbered_dir\nfrom _pytest.pathlib import on_rm_rf_error\nfrom _pytest.pathlib import register_cleanup_lock_removal\nfrom _pytest.pathlib import rm_rf\nfrom _pytest.pytester import Pytester\nfrom _pytest.tmpdir import get_user\nfrom _pytest.tmpdir import TempPathFactory\nimport pytest\n\n\ndef test_tmp_path_fixture(pytester: Pytester) -> None:\n    p = pytester.copy_example(\"tmpdir/tmp_path_fixture.py\")\n    results = pytester.runpytest(p)\n    results.stdout.fnmatch_lines([\"*1 passed*\"])\n\n\n@dataclasses.dataclass\nclass FakeConfig:\n    basetemp: str | Path\n\n    @property\n    def trace(self):\n        return self\n\n    def get(self, key):\n        return lambda *k: None\n\n    def getini(self, name):\n        if name == \"tmp_path_retention_count\":\n            return 3\n        elif name == \"tmp_path_retention_policy\":\n            return \"all\"\n        else:\n            assert False\n\n    @property\n    def option(self):\n        return self\n\n\nclass TestTmpPathHandler:\n    def test_mktemp(self, tmp_path: Path) -> None:\n        config = cast(Config, FakeConfig(tmp_path))\n        t = TempPathFactory.from_config(config, _ispytest=True)\n        tmp = t.mktemp(\"world\")\n        assert str(tmp.relative_to(t.getbasetemp())) == \"world0\"\n        tmp = t.mktemp(\"this\")\n        assert str(tmp.relative_to(t.getbasetemp())).startswith(\"this\")\n        tmp2 = t.mktemp(\"this\")\n        assert str(tmp2.relative_to(t.getbasetemp())).startswith(\"this\")\n        assert tmp2 != tmp\n\n    def test_tmppath_relative_basetemp_absolute(\n        self, tmp_path: Path, monkeypatch: MonkeyPatch\n    ) -> None:\n        \"\"\"#4425\"\"\"\n        monkeypatch.chdir(tmp_path)\n        config = cast(Config, FakeConfig(\"hello\"))\n        t = TempPathFactory.from_config(config, _ispytest=True)\n        assert t.getbasetemp().resolve() == (tmp_path / \"hello\").resolve()\n\n\nclass TestConfigTmpPath:\n    def test_getbasetemp_custom_removes_old(self, pytester: Pytester) -> None:\n        mytemp = pytester.path.joinpath(\"xyz\")\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_1(tmp_path):\n                pass\n        \"\"\"\n        )\n        pytester.runpytest(p, f\"--basetemp={mytemp}\")\n        assert mytemp.exists()\n        mytemp.joinpath(\"hello\").touch()\n\n        pytester.runpytest(p, f\"--basetemp={mytemp}\")\n        assert mytemp.exists()\n        assert not mytemp.joinpath(\"hello\").exists()\n\n    def test_policy_failed_removes_only_passed_dir(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_1(tmp_path):\n                assert 0 == 0\n            def test_2(tmp_path):\n                assert 0 == 1\n        \"\"\"\n        )\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest.ini_options]\n            tmp_path_retention_policy = \"failed\"\n        \"\"\"\n        )\n\n        pytester.inline_run(p)\n        root = pytester._test_tmproot\n\n        for child in root.iterdir():\n            base_dir = list(\n                filter(lambda x: x.is_dir() and not x.is_symlink(), child.iterdir())\n            )\n            assert len(base_dir) == 1\n            test_dir = list(\n                filter(\n                    lambda x: x.is_dir() and not x.is_symlink(), base_dir[0].iterdir()\n                )\n            )\n            # Check only the failed one remains\n            assert len(test_dir) == 1\n            assert test_dir[0].name == \"test_20\"\n\n    def test_policy_failed_removes_basedir_when_all_passed(\n        self, pytester: Pytester\n    ) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            def test_1(tmp_path):\n                assert 0 == 0\n        \"\"\"\n        )\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest.ini_options]\n            tmp_path_retention_policy = \"failed\"\n        \"\"\"\n        )\n\n        pytester.inline_run(p)\n        root = pytester._test_tmproot\n        for child in root.iterdir():\n            # This symlink will be deleted by cleanup_numbered_dir **after**\n            # the test finishes because it's triggered by atexit.\n            # So it has to be ignored here.\n            base_dir = filter(lambda x: not x.is_symlink(), child.iterdir())\n            # Check the base dir itself is gone\n            assert len(list(base_dir)) == 0\n\n    # issue #10502\n    def test_policy_failed_removes_dir_when_skipped_from_fixture(\n        self, pytester: Pytester\n    ) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def fixt(tmp_path):\n                pytest.skip()\n\n            def test_fixt(fixt):\n                pass\n        \"\"\"\n        )\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest.ini_options]\n            tmp_path_retention_policy = \"failed\"\n        \"\"\"\n        )\n\n        pytester.inline_run(p)\n\n        # Check if the whole directory is removed\n        root = pytester._test_tmproot\n        for child in root.iterdir():\n            base_dir = list(\n                filter(lambda x: x.is_dir() and not x.is_symlink(), child.iterdir())\n            )\n            assert len(base_dir) == 0\n\n    # issue #10502\n    def test_policy_all_keeps_dir_when_skipped_from_fixture(\n        self, pytester: Pytester\n    ) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.fixture\n            def fixt(tmp_path):\n                pytest.skip()\n\n            def test_fixt(fixt):\n                pass\n        \"\"\"\n        )\n        pytester.makepyprojecttoml(\n            \"\"\"\n            [tool.pytest.ini_options]\n            tmp_path_retention_policy = \"all\"\n        \"\"\"\n        )\n        pytester.inline_run(p)\n\n        # Check if the whole directory is kept\n        root = pytester._test_tmproot\n        for child in root.iterdir():\n            base_dir = list(\n                filter(lambda x: x.is_dir() and not x.is_symlink(), child.iterdir())\n            )\n            assert len(base_dir) == 1\n            test_dir = list(\n                filter(\n                    lambda x: x.is_dir() and not x.is_symlink(), base_dir[0].iterdir()\n                )\n            )\n            assert len(test_dir) == 1\n\n\ntestdata = [\n    (\"mypath\", True),\n    (\"/mypath1\", False),\n    (\"./mypath1\", True),\n    (\"../mypath3\", False),\n    (\"../../mypath4\", False),\n    (\"mypath5/..\", False),\n    (\"mypath6/../mypath6\", True),\n    (\"mypath7/../mypath7/..\", False),\n]\n\n\n@pytest.mark.parametrize(\"basename, is_ok\", testdata)\ndef test_mktemp(pytester: Pytester, basename: str, is_ok: bool) -> None:\n    mytemp = pytester.mkdir(\"mytemp\")\n    p = pytester.makepyfile(\n        f\"\"\"\n        def test_abs_path(tmp_path_factory):\n            tmp_path_factory.mktemp('{basename}', numbered=False)\n        \"\"\"\n    )\n\n    result = pytester.runpytest(p, f\"--basetemp={mytemp}\")\n    if is_ok:\n        assert result.ret == 0\n        assert mytemp.joinpath(basename).exists()\n    else:\n        assert result.ret == 1\n        result.stdout.fnmatch_lines(\"*ValueError*\")\n\n\ndef test_tmp_path_always_is_realpath(pytester: Pytester, monkeypatch) -> None:\n    # the reason why tmp_path should be a realpath is that\n    # when you cd to it and do \"os.getcwd()\" you will anyway\n    # get the realpath.  Using the symlinked path can thus\n    # easily result in path-inequality\n    # XXX if that proves to be a problem, consider using\n    # os.environ[\"PWD\"]\n    realtemp = pytester.mkdir(\"myrealtemp\")\n    linktemp = pytester.path.joinpath(\"symlinktemp\")\n    attempt_symlink_to(linktemp, str(realtemp))\n    monkeypatch.setenv(\"PYTEST_DEBUG_TEMPROOT\", str(linktemp))\n    pytester.makepyfile(\n        \"\"\"\n        def test_1(tmp_path):\n            assert tmp_path.resolve() == tmp_path\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(passed=1)\n\n\ndef test_tmp_path_too_long_on_parametrization(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.mark.parametrize(\"arg\", [\"1\"*1000])\n        def test_some(arg, tmp_path):\n            tmp_path.joinpath(\"hello\").touch()\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(passed=1)\n\n\ndef test_tmp_path_factory(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        @pytest.fixture(scope='session')\n        def session_dir(tmp_path_factory):\n            return tmp_path_factory.mktemp('data', numbered=False)\n        def test_some(session_dir):\n            assert session_dir.is_dir()\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(passed=1)\n\n\ndef test_tmp_path_fallback_tox_env(pytester: Pytester, monkeypatch) -> None:\n    \"\"\"Test that tmp_path works even if environment variables required by getpass\n    module are missing (#1010).\n    \"\"\"\n    monkeypatch.delenv(\"USER\", raising=False)\n    monkeypatch.delenv(\"USERNAME\", raising=False)\n    pytester.makepyfile(\n        \"\"\"\n        def test_some(tmp_path):\n            assert tmp_path.is_dir()\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(passed=1)\n\n\n@pytest.fixture\ndef break_getuser(monkeypatch):\n    monkeypatch.setattr(\"os.getuid\", lambda: -1)\n    # taken from python 2.7/3.4\n    for envvar in (\"LOGNAME\", \"USER\", \"LNAME\", \"USERNAME\"):\n        monkeypatch.delenv(envvar, raising=False)\n\n\n@pytest.mark.usefixtures(\"break_getuser\")\n@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no os.getuid on windows\")\ndef test_tmp_path_fallback_uid_not_found(pytester: Pytester) -> None:\n    \"\"\"Test that tmp_path works even if the current process's user id does not\n    correspond to a valid user.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        def test_some(tmp_path):\n            assert tmp_path.is_dir()\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(passed=1)\n\n\n@pytest.mark.usefixtures(\"break_getuser\")\n@pytest.mark.skipif(sys.platform.startswith(\"win\"), reason=\"no os.getuid on windows\")\ndef test_get_user_uid_not_found():\n    \"\"\"Test that get_user() function works even if the current process's\n    user id does not correspond to a valid user (e.g. running pytest in a\n    Docker container with 'docker run -u'.\n    \"\"\"\n    assert get_user() is None\n\n\n@pytest.mark.skipif(not sys.platform.startswith(\"win\"), reason=\"win only\")\ndef test_get_user(monkeypatch):\n    \"\"\"Test that get_user() function works even if environment variables\n    required by getpass module are missing from the environment on Windows\n    (#1010).\n    \"\"\"\n    monkeypatch.delenv(\"USER\", raising=False)\n    monkeypatch.delenv(\"USERNAME\", raising=False)\n    assert get_user() is None\n\n\nclass TestNumberedDir:\n    PREFIX = \"fun-\"\n\n    def test_make(self, tmp_path):\n        for i in range(10):\n            d = make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n            assert d.name.startswith(self.PREFIX)\n            assert d.name.endswith(str(i))\n\n        symlink = tmp_path.joinpath(self.PREFIX + \"current\")\n        if symlink.exists():\n            # unix\n            assert symlink.is_symlink()\n            assert symlink.resolve() == d.resolve()\n\n    def test_cleanup_lock_create(self, tmp_path):\n        d = tmp_path.joinpath(\"test\")\n        d.mkdir()\n        lockfile = create_cleanup_lock(d)\n        with pytest.raises(OSError, match=r\"cannot create lockfile in .*\"):\n            create_cleanup_lock(d)\n\n        lockfile.unlink()\n\n    def test_lock_register_cleanup_removal(self, tmp_path: Path) -> None:\n        lock = create_cleanup_lock(tmp_path)\n\n        registry: list[Callable[..., None]] = []\n        register_cleanup_lock_removal(lock, register=registry.append)\n\n        (cleanup_func,) = registry\n\n        assert lock.is_file()\n\n        cleanup_func(original_pid=\"intentionally_different\")\n\n        assert lock.is_file()\n\n        cleanup_func()\n\n        assert not lock.exists()\n\n        cleanup_func()\n\n        assert not lock.exists()\n\n    def _do_cleanup(self, tmp_path: Path, keep: int = 2) -> None:\n        self.test_make(tmp_path)\n        cleanup_numbered_dir(\n            root=tmp_path,\n            prefix=self.PREFIX,\n            keep=keep,\n            consider_lock_dead_if_created_before=0,\n        )\n\n    def test_cleanup_keep(self, tmp_path):\n        self._do_cleanup(tmp_path)\n        a, b = (x for x in tmp_path.iterdir() if not x.is_symlink())\n        print(a, b)\n\n    def test_cleanup_keep_0(self, tmp_path: Path):\n        self._do_cleanup(tmp_path, 0)\n        dir_num = len(list(tmp_path.iterdir()))\n        assert dir_num == 0\n\n    def test_cleanup_locked(self, tmp_path):\n        p = make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n\n        create_cleanup_lock(p)\n\n        assert not pathlib.ensure_deletable(\n            p, consider_lock_dead_if_created_before=p.stat().st_mtime - 1\n        )\n        assert pathlib.ensure_deletable(\n            p, consider_lock_dead_if_created_before=p.stat().st_mtime + 1\n        )\n\n    def test_cleanup_ignores_symlink(self, tmp_path):\n        the_symlink = tmp_path / (self.PREFIX + \"current\")\n        attempt_symlink_to(the_symlink, tmp_path / (self.PREFIX + \"5\"))\n        self._do_cleanup(tmp_path)\n\n    def test_removal_accepts_lock(self, tmp_path):\n        dir = make_numbered_dir(root=tmp_path, prefix=self.PREFIX)\n        create_cleanup_lock(dir)\n        maybe_delete_a_numbered_dir(dir)\n        assert dir.is_dir()\n\n\nclass TestRmRf:\n    def test_rm_rf(self, tmp_path):\n        adir = tmp_path / \"adir\"\n        adir.mkdir()\n        rm_rf(adir)\n\n        assert not adir.exists()\n\n        adir.mkdir()\n        afile = adir / \"afile\"\n        afile.write_bytes(b\"aa\")\n\n        rm_rf(adir)\n        assert not adir.exists()\n\n    def test_rm_rf_with_read_only_file(self, tmp_path):\n        \"\"\"Ensure rm_rf can remove directories with read-only files in them (#5524)\"\"\"\n        fn = tmp_path / \"dir/foo.txt\"\n        fn.parent.mkdir()\n\n        fn.touch()\n\n        self.chmod_r(fn)\n\n        rm_rf(fn.parent)\n\n        assert not fn.parent.is_dir()\n\n    def chmod_r(self, path):\n        mode = os.stat(str(path)).st_mode\n        os.chmod(str(path), mode & ~stat.S_IWRITE)\n\n    def test_rm_rf_with_read_only_directory(self, tmp_path):\n        \"\"\"Ensure rm_rf can remove read-only directories (#5524)\"\"\"\n        adir = tmp_path / \"dir\"\n        adir.mkdir()\n\n        (adir / \"foo.txt\").touch()\n        self.chmod_r(adir)\n\n        rm_rf(adir)\n\n        assert not adir.is_dir()\n\n    def test_on_rm_rf_error(self, tmp_path: Path) -> None:\n        adir = tmp_path / \"dir\"\n        adir.mkdir()\n\n        fn = adir / \"foo.txt\"\n        fn.touch()\n        self.chmod_r(fn)\n\n        # unknown exception\n        with pytest.warns(pytest.PytestWarning):\n            exc_info1 = (RuntimeError, RuntimeError(), None)\n            on_rm_rf_error(os.unlink, str(fn), exc_info1, start_path=tmp_path)\n            assert fn.is_file()\n\n        # we ignore FileNotFoundError\n        exc_info2 = (FileNotFoundError, FileNotFoundError(), None)\n        assert not on_rm_rf_error(None, str(fn), exc_info2, start_path=tmp_path)\n\n        # unknown function\n        with pytest.warns(\n            pytest.PytestWarning,\n            match=r\"^\\(rm_rf\\) unknown function None when removing .*foo.txt:\\n<class 'PermissionError'>: \",\n        ):\n            exc_info3 = (PermissionError, PermissionError(), None)\n            on_rm_rf_error(None, str(fn), exc_info3, start_path=tmp_path)\n            assert fn.is_file()\n\n        # ignored function\n        with warnings.catch_warnings(record=True) as w:\n            exc_info4 = PermissionError()\n            on_rm_rf_error(os.open, str(fn), exc_info4, start_path=tmp_path)\n            assert fn.is_file()\n            assert not [x.message for x in w]\n\n        exc_info5 = PermissionError()\n        on_rm_rf_error(os.unlink, str(fn), exc_info5, start_path=tmp_path)\n        assert not fn.is_file()\n\n\ndef attempt_symlink_to(path, to_path):\n    \"\"\"Try to make a symlink from \"path\" to \"to_path\", skipping in case this platform\n    does not support it or we don't have sufficient privileges (common on Windows).\"\"\"\n    try:\n        Path(path).symlink_to(Path(to_path))\n    except OSError:\n        pytest.skip(\"could not create symbolic link\")\n\n\ndef test_basetemp_with_read_only_files(pytester: Pytester) -> None:\n    \"\"\"Integration test for #5524\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import os\n        import stat\n\n        def test(tmp_path):\n            fn = tmp_path / 'foo.txt'\n            fn.write_text('hello', encoding='utf-8')\n            mode = os.stat(str(fn)).st_mode\n            os.chmod(str(fn), mode & ~stat.S_IREAD)\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--basetemp=tmp\")\n    assert result.ret == 0\n    # running a second time and ensure we don't crash\n    result = pytester.runpytest(\"--basetemp=tmp\")\n    assert result.ret == 0\n\n\ndef test_tmp_path_factory_handles_invalid_dir_characters(\n    tmp_path_factory: TempPathFactory, monkeypatch: MonkeyPatch\n) -> None:\n    monkeypatch.setattr(\"getpass.getuser\", lambda: \"os/<:*?;>agnostic\")\n    # _basetemp / _given_basetemp are cached / set in parallel runs, patch them\n    monkeypatch.setattr(tmp_path_factory, \"_basetemp\", None)\n    monkeypatch.setattr(tmp_path_factory, \"_given_basetemp\", None)\n    p = tmp_path_factory.getbasetemp()\n    assert \"pytest-of-unknown\" in str(p)\n\n\n@pytest.mark.skipif(not hasattr(os, \"getuid\"), reason=\"checks unix permissions\")\ndef test_tmp_path_factory_create_directory_with_safe_permissions(\n    tmp_path: Path, monkeypatch: MonkeyPatch\n) -> None:\n    \"\"\"Verify that pytest creates directories under /tmp with private permissions.\"\"\"\n    # Use the test's tmp_path as the system temproot (/tmp).\n    monkeypatch.setenv(\"PYTEST_DEBUG_TEMPROOT\", str(tmp_path))\n    tmp_factory = TempPathFactory(None, 3, \"all\", lambda *args: None, _ispytest=True)\n    basetemp = tmp_factory.getbasetemp()\n\n    # No world-readable permissions.\n    assert (basetemp.stat().st_mode & 0o077) == 0\n    # Parent too (pytest-of-foo).\n    assert (basetemp.parent.stat().st_mode & 0o077) == 0\n\n\n@pytest.mark.skipif(not hasattr(os, \"getuid\"), reason=\"checks unix permissions\")\ndef test_tmp_path_factory_fixes_up_world_readable_permissions(\n    tmp_path: Path, monkeypatch: MonkeyPatch\n) -> None:\n    \"\"\"Verify that if a /tmp/pytest-of-foo directory already exists with\n    world-readable permissions, it is fixed.\n\n    pytest used to mkdir with such permissions, that's why we fix it up.\n    \"\"\"\n    # Use the test's tmp_path as the system temproot (/tmp).\n    monkeypatch.setenv(\"PYTEST_DEBUG_TEMPROOT\", str(tmp_path))\n    tmp_factory = TempPathFactory(None, 3, \"all\", lambda *args: None, _ispytest=True)\n    basetemp = tmp_factory.getbasetemp()\n\n    # Before - simulate bad perms.\n    os.chmod(basetemp.parent, 0o777)\n    assert (basetemp.parent.stat().st_mode & 0o077) != 0\n\n    tmp_factory = TempPathFactory(None, 3, \"all\", lambda *args: None, _ispytest=True)\n    basetemp = tmp_factory.getbasetemp()\n\n    # After - fixed.\n    assert (basetemp.parent.stat().st_mode & 0o077) == 0\n"
  },
  {
    "path": "testing/test_unittest.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport sys\n\nfrom _pytest.config import ExitCode\nfrom _pytest.monkeypatch import MonkeyPatch\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\ndef test_simple_unittest(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            def testpassing(self):\n                self.assertEqual('foo', 'foo')\n            def test_failing(self):\n                self.assertEqual('foo', 'bar')\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    assert reprec.matchreport(\"testpassing\").passed\n    assert reprec.matchreport(\"test_failing\").failed\n\n\ndef test_runTest_method(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCaseWithRunTest(unittest.TestCase):\n            def runTest(self):\n                self.assertEqual('foo', 'foo')\n        class MyTestCaseWithoutRunTest(unittest.TestCase):\n            def runTest(self):\n                self.assertEqual('foo', 'foo')\n            def test_something(self):\n                pass\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        *MyTestCaseWithRunTest::runTest*\n        *MyTestCaseWithoutRunTest::test_something*\n        *2 passed*\n    \"\"\"\n    )\n\n\ndef test_isclasscheck_issue53(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class _E(object):\n            def __getattr__(self, tag):\n                pass\n        E = _E()\n    \"\"\"\n    )\n    result = pytester.runpytest(testpath)\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_setup(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            def setUp(self):\n                self.foo = 1\n            def setup_method(self, method):\n                self.foo2 = 1\n            def test_both(self):\n                self.assertEqual(1, self.foo)\n                assert self.foo2 == 1\n            def teardown_method(self, method):\n                assert 0, \"42\"\n\n    \"\"\"\n    )\n    reprec = pytester.inline_run(\"-s\", testpath)\n    assert reprec.matchreport(\"test_both\", when=\"call\").passed\n    rep = reprec.matchreport(\"test_both\", when=\"teardown\")\n    assert rep.failed and \"42\" in str(rep.longrepr)\n\n\ndef test_setUpModule(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        values = []\n\n        def setUpModule():\n            values.append(1)\n\n        def tearDownModule():\n            del values[0]\n\n        def test_hello():\n            assert values == [1]\n\n        def test_world():\n            assert values == [1]\n        \"\"\"\n    )\n    result = pytester.runpytest(testpath)\n    result.stdout.fnmatch_lines([\"*2 passed*\"])\n\n\ndef test_setUpModule_failing_no_teardown(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        values = []\n\n        def setUpModule():\n            0/0\n\n        def tearDownModule():\n            values.append(1)\n\n        def test_hello():\n            pass\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    reprec.assertoutcome(passed=0, failed=1)\n    call = reprec.getcalls(\"pytest_runtest_setup\")[0]\n    assert not call.item.module.values\n\n\ndef test_new_instances(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            def test_func1(self):\n                self.x = 2\n            def test_func2(self):\n                assert not hasattr(self, 'x')\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    reprec.assertoutcome(passed=2)\n\n\ndef test_function_item_obj_is_instance(pytester: Pytester) -> None:\n    \"\"\"item.obj should be a bound method on unittest.TestCase function items (#5390).\"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_runtest_makereport(item, call):\n            if call.when == 'call':\n                class_ = item.parent.obj\n                assert isinstance(item.obj.__self__, class_)\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n\n        class Test(unittest.TestCase):\n            def test_foo(self):\n                pass\n    \"\"\"\n    )\n    result = pytester.runpytest_inprocess()\n    result.stdout.fnmatch_lines([\"* 1 passed in*\"])\n\n\ndef test_teardown(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            values = []\n            def test_one(self):\n                pass\n            def tearDown(self):\n                self.values.append(None)\n        class Second(unittest.TestCase):\n            def test_check(self):\n                self.assertEqual(MyTestCase.values, [None])\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    passed, skipped, failed = reprec.countoutcomes()\n    assert failed == 0, failed\n    assert passed == 2\n    assert passed + skipped + failed == 2\n\n\ndef test_teardown_issue1649(pytester: Pytester) -> None:\n    \"\"\"\n    Are TestCase objects cleaned up? Often unittest TestCase objects set\n    attributes that are large and expensive during test run or setUp.\n\n    The TestCase will not be cleaned up if the test fails, because it\n    would then exist in the stackframe.\n\n    Regression test for #1649 (see also #12367).\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n        import gc\n\n        class TestCaseObjectsShouldBeCleanedUp(unittest.TestCase):\n            def test_expensive(self):\n                self.an_expensive_obj = object()\n\n            def test_is_it_still_alive(self):\n                gc.collect()\n                for obj in gc.get_objects():\n                    if type(obj).__name__ == \"TestCaseObjectsShouldBeCleanedUp\":\n                        assert not hasattr(obj, \"an_expensive_obj\")\n                        break\n                else:\n                    assert False, \"Could not find TestCaseObjectsShouldBeCleanedUp instance\"\n        \"\"\"\n    )\n\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.OK\n\n\ndef test_unittest_skip_issue148(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n\n        @unittest.skip(\"hello\")\n        class MyTestCase(unittest.TestCase):\n            @classmethod\n            def setUpClass(self):\n                xxx\n            def test_one(self):\n                pass\n            @classmethod\n            def tearDownClass(self):\n                xxx\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    reprec.assertoutcome(skipped=1)\n\n\ndef test_method_and_teardown_failing_reporting(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class TC(unittest.TestCase):\n            def tearDown(self):\n                assert 0, \"down1\"\n            def test_method(self):\n                assert False, \"down2\"\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-s\")\n    assert result.ret == 1\n    result.stdout.fnmatch_lines(\n        [\n            \"*tearDown*\",\n            \"*assert 0*\",\n            \"*test_method*\",\n            \"*assert False*\",\n            \"*1 failed*1 error*\",\n        ]\n    )\n\n\ndef test_setup_failure_is_shown(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n        import pytest\n        class TC(unittest.TestCase):\n            def setUp(self):\n                assert 0, \"down1\"\n            def test_method(self):\n                print(\"never42\")\n                xyz\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-s\")\n    assert result.ret == 1\n    result.stdout.fnmatch_lines([\"*setUp*\", \"*assert 0*down1*\", \"*1 failed*\"])\n    result.stdout.no_fnmatch_line(\"*never42*\")\n\n\ndef test_setup_setUpClass(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        import pytest\n        class MyTestCase(unittest.TestCase):\n            x = 0\n            @classmethod\n            def setUpClass(cls):\n                cls.x += 1\n            def test_func1(self):\n                assert self.x == 1\n            def test_func2(self):\n                assert self.x == 1\n            @classmethod\n            def tearDownClass(cls):\n                cls.x -= 1\n        def test_torn_down():\n            assert MyTestCase.x == 0\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    reprec.assertoutcome(passed=3)\n\n\ndef test_fixtures_setup_setUpClass_issue8394(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            @classmethod\n            def setUpClass(cls):\n                pass\n            def test_func1(self):\n                pass\n            @classmethod\n            def tearDownClass(cls):\n                pass\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--fixtures\")\n    assert result.ret == 0\n    result.stdout.no_fnmatch_line(\"*no docstring available*\")\n\n    result = pytester.runpytest(\"--fixtures\", \"-v\")\n    assert result.ret == 0\n    result.stdout.fnmatch_lines([\"*no docstring available*\"])\n\n\ndef test_setup_class(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        import pytest\n        class MyTestCase(unittest.TestCase):\n            x = 0\n            def setup_class(cls):\n                cls.x += 1\n            def test_func1(self):\n                assert self.x == 1\n            def test_func2(self):\n                assert self.x == 1\n            def teardown_class(cls):\n                cls.x -= 1\n        def test_torn_down():\n            assert MyTestCase.x == 0\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    reprec.assertoutcome(passed=3)\n\n\n@pytest.mark.parametrize(\"type\", [\"Error\", \"Failure\"])\ndef test_testcase_adderrorandfailure_defers(pytester: Pytester, type: str) -> None:\n    pytester.makepyfile(\n        f\"\"\"\n        from unittest import TestCase\n        import pytest\n        class MyTestCase(TestCase):\n            def run(self, result):\n                excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)\n                try:\n                    result.add{type}(self, excinfo._excinfo)\n                except KeyboardInterrupt:\n                    raise\n                except:\n                    pytest.fail(\"add{type} should not raise\")\n            def test_hello(self):\n                pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.no_fnmatch_line(\"*should not raise*\")\n\n\n@pytest.mark.parametrize(\"type\", [\"Error\", \"Failure\"])\ndef test_testcase_custom_exception_info(pytester: Pytester, type: str) -> None:\n    pytester.makepyfile(\n        f\"\"\"\n        from typing import Generic, TypeVar\n        from unittest import TestCase\n        import pytest, _pytest._code\n\n        class MyTestCase(TestCase):\n            def run(self, result):\n                excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)\n                # We fake an incompatible exception info.\n                class FakeExceptionInfo(Generic[TypeVar(\"E\")]):\n                    def __init__(self, *args, **kwargs):\n                        mp.undo()\n                        raise TypeError()\n                    @classmethod\n                    def from_current(cls):\n                        return cls()\n                    @classmethod\n                    def from_exc_info(cls, *args, **kwargs):\n                        return cls()\n                mp = pytest.MonkeyPatch()\n                mp.setattr(_pytest._code, 'ExceptionInfo', FakeExceptionInfo)\n                try:\n                    excinfo = excinfo._excinfo\n                    result.add{type}(self, excinfo)\n                finally:\n                    mp.undo()\n\n            def test_hello(self):\n                pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"NOTE: Incompatible Exception Representation*\",\n            \"*ZeroDivisionError*\",\n            \"*1 failed*\",\n        ]\n    )\n\n\ndef test_testcase_totally_incompatible_exception_info(pytester: Pytester) -> None:\n    import _pytest.unittest\n\n    (item,) = pytester.getitems(\n        \"\"\"\n        from unittest import TestCase\n        class MyTestCase(TestCase):\n            def test_hello(self):\n                pass\n    \"\"\"\n    )\n    assert isinstance(item, _pytest.unittest.TestCaseFunction)\n    item.addError(None, 42)  # type: ignore[arg-type]\n    excinfo = item._excinfo\n    assert excinfo is not None\n    assert \"ERROR: Unknown Incompatible\" in str(excinfo.pop(0).getrepr())\n\n\ndef test_module_level_pytestmark(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        import pytest\n        pytestmark = pytest.mark.xfail\n        class MyTestCase(unittest.TestCase):\n            def test_func1(self):\n                assert 0\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath, \"-s\")\n    reprec.assertoutcome(skipped=1)\n\n\nclass TestTrialUnittest:\n    def setup_class(cls):\n        cls.ut = pytest.importorskip(\"twisted.trial.unittest\")\n        # on windows trial uses a socket for a reactor and apparently doesn't close it properly\n        # https://twistedmatrix.com/trac/ticket/9227\n        cls.ignore_unclosed_socket_warning = (\"-W\", \"always\")\n\n    def test_trial_testcase_runtest_not_collected(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            from twisted.trial.unittest import TestCase\n\n            class TC(TestCase):\n                def test_hello(self):\n                    pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(*self.ignore_unclosed_socket_warning)\n        reprec.assertoutcome(passed=1)\n        pytester.makepyfile(\n            \"\"\"\n            from twisted.trial.unittest import TestCase\n\n            class TC(TestCase):\n                def runTest(self):\n                    pass\n        \"\"\"\n        )\n        reprec = pytester.inline_run(*self.ignore_unclosed_socket_warning)\n        reprec.assertoutcome(passed=1)\n\n    def test_trial_exceptions_with_skips(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            from twisted.trial import unittest\n            import pytest\n            class TC(unittest.TestCase):\n                def test_hello(self):\n                    pytest.skip(\"skip_in_method\")\n                @pytest.mark.skipif(\"sys.version_info != 1\")\n                def test_hello2(self):\n                    pass\n                @pytest.mark.xfail(reason=\"iwanto\")\n                def test_hello3(self):\n                    assert 0\n                def test_hello4(self):\n                    pytest.xfail(\"i2wanto\")\n                def test_trial_skip(self):\n                    pass\n                test_trial_skip.skip = \"trialselfskip\"\n\n                def test_trial_todo(self):\n                    assert 0\n                test_trial_todo.todo = \"mytodo\"\n\n                def test_trial_todo_success(self):\n                    pass\n                test_trial_todo_success.todo = \"mytodo\"\n\n            class TC2(unittest.TestCase):\n                def setup_class(cls):\n                    pytest.skip(\"skip_in_setup_class\")\n                def test_method(self):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-rxs\", *self.ignore_unclosed_socket_warning)\n        result.stdout.fnmatch_lines_random(\n            [\n                \"*XFAIL*test_trial_todo*\",\n                \"*trialselfskip*\",\n                \"*skip_in_setup_class*\",\n                \"*iwanto*\",\n                \"*i2wanto*\",\n                \"*sys.version_info*\",\n                \"*skip_in_method*\",\n                \"*1 failed*4 skipped*3 xfailed*\",\n            ]\n        )\n        assert result.ret == 1\n\n    def test_trial_error(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\n            from twisted.trial.unittest import TestCase\n            from twisted.internet.defer import Deferred\n            from twisted.internet import reactor\n\n            class TC(TestCase):\n                def test_one(self):\n                    crash\n\n                def test_two(self):\n                    def f(_):\n                        crash\n\n                    d = Deferred()\n                    d.addCallback(f)\n                    reactor.callLater(0.3, d.callback, None)\n                    return d\n\n                def test_three(self):\n                    def f():\n                        pass # will never get called\n                    reactor.callLater(0.3, f)\n                # will crash at teardown\n\n                def test_four(self):\n                    def f(_):\n                        reactor.callLater(0.3, f)\n                        crash\n\n                    d = Deferred()\n                    d.addCallback(f)\n                    reactor.callLater(0.3, d.callback, None)\n                    return d\n                # will crash both at test time and at teardown\n        \"\"\"\n        )\n        result = pytester.runpytest(\n            \"-vv\", \"-oconsole_output_style=classic\", \"-W\", \"ignore::DeprecationWarning\"\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"test_trial_error.py::TC::test_four FAILED\",\n                \"test_trial_error.py::TC::test_four ERROR\",\n                \"test_trial_error.py::TC::test_one FAILED\",\n                \"test_trial_error.py::TC::test_three FAILED\",\n                \"test_trial_error.py::TC::test_two FAILED\",\n                \"*ERRORS*\",\n                \"*_ ERROR at teardown of TC.test_four _*\",\n                \"*DelayedCalls*\",\n                \"*= FAILURES =*\",\n                \"*_ TC.test_four _*\",\n                \"*NameError*crash*\",\n                \"*_ TC.test_one _*\",\n                \"*NameError*crash*\",\n                \"*_ TC.test_three _*\",\n                \"*DelayedCalls*\",\n                \"*_ TC.test_two _*\",\n                \"*NameError*crash*\",\n                \"*= 4 failed, 1 error in *\",\n            ]\n        )\n\n    def test_trial_pdb(self, pytester: Pytester) -> None:\n        p = pytester.makepyfile(\n            \"\"\"\n            from twisted.trial import unittest\n            import pytest\n            class TC(unittest.TestCase):\n                def test_hello(self):\n                    assert 0, \"hellopdb\"\n        \"\"\"\n        )\n        child = pytester.spawn_pytest(str(p))\n        child.expect(\"hellopdb\")\n        child.sendeof()\n\n    def test_trial_testcase_skip_property(self, pytester: Pytester) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n            from twisted.trial import unittest\n            class MyTestCase(unittest.TestCase):\n                skip = 'dont run'\n                def test_func(self):\n                    pass\n            \"\"\"\n        )\n        reprec = pytester.inline_run(testpath, \"-s\")\n        reprec.assertoutcome(skipped=1)\n\n    def test_trial_testfunction_skip_property(self, pytester: Pytester) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n            from twisted.trial import unittest\n            class MyTestCase(unittest.TestCase):\n                def test_func(self):\n                    pass\n                test_func.skip = 'dont run'\n            \"\"\"\n        )\n        reprec = pytester.inline_run(testpath, \"-s\")\n        reprec.assertoutcome(skipped=1)\n\n    def test_trial_testcase_todo_property(self, pytester: Pytester) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n            from twisted.trial import unittest\n            class MyTestCase(unittest.TestCase):\n                todo = 'dont run'\n                def test_func(self):\n                    assert 0\n            \"\"\"\n        )\n        reprec = pytester.inline_run(testpath, \"-s\")\n        reprec.assertoutcome(skipped=1)\n\n    def test_trial_testfunction_todo_property(self, pytester: Pytester) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n            from twisted.trial import unittest\n            class MyTestCase(unittest.TestCase):\n                def test_func(self):\n                    assert 0\n                test_func.todo = 'dont run'\n            \"\"\"\n        )\n        reprec = pytester.inline_run(\n            testpath, \"-s\", *self.ignore_unclosed_socket_warning\n        )\n        reprec.assertoutcome(skipped=1)\n\n\ndef test_djangolike_testcase(pytester: Pytester) -> None:\n    # contributed from Morten Breekevold\n    pytester.makepyfile(\n        \"\"\"\n        from unittest import TestCase, main\n\n        class DjangoLikeTestCase(TestCase):\n\n            def setUp(self):\n                print(\"setUp()\")\n\n            def test_presetup_has_been_run(self):\n                print(\"test_thing()\")\n                self.assertTrue(hasattr(self, 'was_presetup'))\n\n            def tearDown(self):\n                print(\"tearDown()\")\n\n            def __call__(self, result=None):\n                try:\n                    self._pre_setup()\n                except (KeyboardInterrupt, SystemExit):\n                    raise\n                except Exception:\n                    import sys\n                    result.addError(self, sys.exc_info())\n                    return\n                super(DjangoLikeTestCase, self).__call__(result)\n                try:\n                    self._post_teardown()\n                except (KeyboardInterrupt, SystemExit):\n                    raise\n                except Exception:\n                    import sys\n                    result.addError(self, sys.exc_info())\n                    return\n\n            def _pre_setup(self):\n                print(\"_pre_setup()\")\n                self.was_presetup = True\n\n            def _post_teardown(self):\n                print(\"_post_teardown()\")\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-s\")\n    assert result.ret == 0\n    result.stdout.fnmatch_lines(\n        [\n            \"*_pre_setup()*\",\n            \"*setUp()*\",\n            \"*test_thing()*\",\n            \"*tearDown()*\",\n            \"*_post_teardown()*\",\n        ]\n    )\n\n\ndef test_unittest_not_shown_in_traceback(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class t(unittest.TestCase):\n            def test_hello(self):\n                x = 3\n                self.assertEqual(x, 4)\n    \"\"\"\n    )\n    res = pytester.runpytest()\n    res.stdout.no_fnmatch_line(\"*failUnlessEqual*\")\n\n\ndef test_unorderable_types(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class TestJoinEmpty(unittest.TestCase):\n            pass\n\n        def make_test():\n            class Test(unittest.TestCase):\n                pass\n            Test.__name__ = \"TestFoo\"\n            return Test\n        TestFoo = make_test()\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.no_fnmatch_line(\"*TypeError*\")\n    assert result.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_unittest_typerror_traceback(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class TestJoinEmpty(unittest.TestCase):\n            def test_hello(self, arg1):\n                pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert \"TypeError\" in result.stdout.str()\n    assert result.ret == 1\n\n\n@pytest.mark.parametrize(\"runner\", [\"pytest\", \"unittest\"])\ndef test_unittest_expected_failure_for_failing_test_is_xfail(\n    pytester: Pytester, runner\n) -> None:\n    script = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            @unittest.expectedFailure\n            def test_failing_test_is_xfail(self):\n                assert False\n        if __name__ == '__main__':\n            unittest.main()\n    \"\"\"\n    )\n    if runner == \"pytest\":\n        result = pytester.runpytest(\"-rxX\")\n        result.stdout.fnmatch_lines(\n            [\"*XFAIL*MyTestCase*test_failing_test_is_xfail*\", \"*1 xfailed*\"]\n        )\n    else:\n        result = pytester.runpython(script)\n        result.stderr.fnmatch_lines([\"*1 test in*\", \"*OK*(expected failures=1)*\"])\n    assert result.ret == 0\n\n\n@pytest.mark.parametrize(\"runner\", [\"pytest\", \"unittest\"])\ndef test_unittest_expected_failure_for_passing_test_is_fail(\n    pytester: Pytester,\n    runner: str,\n) -> None:\n    script = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            @unittest.expectedFailure\n            def test_passing_test_is_fail(self):\n                assert True\n        if __name__ == '__main__':\n            unittest.main()\n    \"\"\"\n    )\n\n    if runner == \"pytest\":\n        result = pytester.runpytest(\"-rxX\")\n        result.stdout.fnmatch_lines(\n            [\n                \"*MyTestCase*test_passing_test_is_fail*\",\n                \"Unexpected success\",\n                \"*1 failed*\",\n            ]\n        )\n    else:\n        result = pytester.runpython(script)\n        result.stderr.fnmatch_lines([\"*1 test in*\", \"*(unexpected successes=1)*\"])\n\n    assert result.ret == 1\n\n\n@pytest.mark.parametrize(\"stmt\", [\"return\", \"yield\"])\ndef test_unittest_setup_interaction(pytester: Pytester, stmt: str) -> None:\n    pytester.makepyfile(\n        f\"\"\"\n        import unittest\n        import pytest\n        class MyTestCase(unittest.TestCase):\n            @pytest.fixture(scope=\"class\", autouse=True)\n            def perclass(self, request):\n                request.cls.hello = \"world\"\n                {stmt}\n            @pytest.fixture(scope=\"function\", autouse=True)\n            def perfunction(self, request):\n                request.instance.funcname = request.function.__name__\n                {stmt}\n\n            def test_method1(self):\n                assert self.funcname == \"test_method1\"\n                assert self.hello == \"world\"\n\n            def test_method2(self):\n                assert self.funcname == \"test_method2\"\n\n            def test_classattr(self):\n                assert self.__class__.hello == \"world\"\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*3 passed*\"])\n\n\ndef test_non_unittest_no_setupclass_support(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        class TestFoo(object):\n            x = 0\n\n            @classmethod\n            def setUpClass(cls):\n                cls.x = 1\n\n            def test_method1(self):\n                assert self.x == 0\n\n            @classmethod\n            def tearDownClass(cls):\n                cls.x = 1\n\n        def test_not_torn_down():\n            assert TestFoo.x == 0\n\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    reprec.assertoutcome(passed=2)\n\n\ndef test_no_teardown_if_setupclass_failed(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n\n        class MyTestCase(unittest.TestCase):\n            x = 0\n\n            @classmethod\n            def setUpClass(cls):\n                cls.x = 1\n                assert False\n\n            def test_func1(self):\n                cls.x = 10\n\n            @classmethod\n            def tearDownClass(cls):\n                cls.x = 100\n\n        def test_notTornDown():\n            assert MyTestCase.x == 1\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    reprec.assertoutcome(passed=1, failed=1)\n\n\ndef test_cleanup_functions(pytester: Pytester) -> None:\n    \"\"\"Ensure functions added with addCleanup are always called after each test ends (#6947)\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n\n        cleanups = []\n\n        class Test(unittest.TestCase):\n\n            def test_func_1(self):\n                self.addCleanup(cleanups.append, \"test_func_1\")\n\n            def test_func_2(self):\n                self.addCleanup(cleanups.append, \"test_func_2\")\n                assert 0\n\n            def test_func_3_check_cleanups(self):\n                assert cleanups == [\"test_func_1\", \"test_func_2\"]\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-v\")\n    result.stdout.fnmatch_lines(\n        [\n            \"*::test_func_1 PASSED *\",\n            \"*::test_func_2 FAILED *\",\n            \"*::test_func_3_check_cleanups PASSED *\",\n        ]\n    )\n\n\ndef test_issue333_result_clearing(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        import pytest\n        @pytest.hookimpl(wrapper=True)\n        def pytest_runtest_call(item):\n            yield\n            assert 0\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class TestIt(unittest.TestCase):\n            def test_func(self):\n                0/0\n    \"\"\"\n    )\n\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(failed=1)\n\n\ndef test_unittest_raise_skip_issue748(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_foo=\"\"\"\n        import unittest\n\n        class MyTestCase(unittest.TestCase):\n            def test_one(self):\n                raise unittest.SkipTest('skipping due to reasons')\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-v\", \"-rs\")\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        *SKIP*[1]*test_foo.py*skipping due to reasons*\n        *1 skipped*\n    \"\"\"\n    )\n\n\ndef test_unittest_skip_issue1169(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_foo=\"\"\"\n        import unittest\n\n        class MyTestCase(unittest.TestCase):\n            @unittest.skip(\"skipping due to reasons\")\n            def test_skip(self):\n                 self.fail()\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-v\", \"-rs\")\n    result.stdout.fnmatch_lines(\n        \"\"\"\n        *SKIP*[1]*skipping due to reasons*\n        *1 skipped*\n    \"\"\"\n    )\n\n\ndef test_class_method_containing_test_issue1558(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_foo=\"\"\"\n        import unittest\n\n        class MyTestCase(unittest.TestCase):\n            def test_should_run(self):\n                pass\n            def test_should_not_run(self):\n                pass\n            test_should_not_run.__test__ = False\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(passed=1)\n\n\n@pytest.mark.parametrize(\"base\", [\"builtins.object\", \"unittest.TestCase\"])\ndef test_usefixtures_marker_on_unittest(base, pytester: Pytester) -> None:\n    \"\"\"#3498\"\"\"\n    module = base.rsplit(\".\", 1)[0]\n    pytest.importorskip(module)\n    pytester.makepyfile(\n        conftest=\"\"\"\n        import pytest\n\n        @pytest.fixture(scope='function')\n        def fixture1(request, monkeypatch):\n            monkeypatch.setattr(request.instance, 'fixture1', True )\n\n\n        @pytest.fixture(scope='function')\n        def fixture2(request, monkeypatch):\n            monkeypatch.setattr(request.instance, 'fixture2', True )\n\n        def node_and_marks(item):\n            print(item.nodeid)\n            for mark in item.iter_markers():\n                print(\"  \", mark)\n\n        @pytest.fixture(autouse=True)\n        def my_marks(request):\n            node_and_marks(request.node)\n\n        def pytest_collection_modifyitems(items):\n            for item in items:\n               node_and_marks(item)\n\n        \"\"\"\n    )\n\n    pytester.makepyfile(\n        f\"\"\"\n        import pytest\n        import {module}\n\n        class Tests({base}):\n            fixture1 = False\n            fixture2 = False\n\n            @pytest.mark.usefixtures(\"fixture1\")\n            def test_one(self):\n                assert self.fixture1\n                assert not self.fixture2\n\n            @pytest.mark.usefixtures(\"fixture1\", \"fixture2\")\n            def test_two(self):\n                assert self.fixture1\n                assert self.fixture2\n\n\n    \"\"\"\n    )\n\n    result = pytester.runpytest(\"-s\")\n    result.assert_outcomes(passed=2)\n\n\ndef test_skip_setup_class(pytester: Pytester) -> None:\n    \"\"\"Skipping tests in a class by raising unittest.SkipTest in `setUpClass` (#13985).\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n\n        class Test(unittest.TestCase):\n\n            @classmethod\n            def setUpClass(cls):\n                raise unittest.SkipTest('Skipping setupclass')\n\n            def test_foo(self):\n                assert False\n\n            def test_bar(self):\n                assert False\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(skipped=2)\n\n\ndef test_unittest_skip_function(pytester: Pytester) -> None:\n    \"\"\"\n    Ensure raising an explicit unittest.SkipTest skips standard pytest functions.\n\n    Support for this is debatable -- technically we only support unittest.SkipTest in TestCase subclasses,\n    but stating this support here in this test because users currently expect this to work,\n    so if we ever break it we at least know we are breaking this use case (#13985).\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n\n        def test_foo():\n            raise unittest.SkipTest('Skipping test_foo')\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.assert_outcomes(skipped=1)\n\n\ndef test_testcase_handles_init_exceptions(pytester: Pytester) -> None:\n    \"\"\"\n    Regression test to make sure exceptions in the __init__ method are bubbled up correctly.\n    See https://github.com/pytest-dev/pytest/issues/3788\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        from unittest import TestCase\n        import pytest\n        class MyTestCase(TestCase):\n            def __init__(self, *args, **kwargs):\n                raise Exception(\"should raise this exception\")\n            def test_hello(self):\n                pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert \"should raise this exception\" in result.stdout.str()\n    result.stdout.no_fnmatch_line(\"*ERROR at teardown of MyTestCase.test_hello*\")\n\n\ndef test_error_message_with_parametrized_fixtures(pytester: Pytester) -> None:\n    pytester.copy_example(\"unittest/test_parametrized_fixture_error_message.py\")\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            \"*test_two does not support fixtures*\",\n            \"*TestSomethingElse::test_two\",\n            \"*Function type: TestCaseFunction\",\n        ]\n    )\n\n\n@pytest.mark.parametrize(\n    \"test_name, expected_outcome\",\n    [\n        (\"test_setup_skip.py\", \"1 skipped\"),\n        (\"test_setup_skip_class.py\", \"1 skipped\"),\n        (\"test_setup_skip_module.py\", \"1 error\"),\n    ],\n)\ndef test_setup_inheritance_skipping(\n    pytester: Pytester, test_name, expected_outcome\n) -> None:\n    \"\"\"Issue #4700\"\"\"\n    pytester.copy_example(f\"unittest/{test_name}\")\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([f\"* {expected_outcome} in *\"])\n\n\ndef test_BdbQuit(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_foo=\"\"\"\n        import unittest\n\n        class MyTestCase(unittest.TestCase):\n            def test_bdbquit(self):\n                import bdb\n                raise bdb.BdbQuit()\n\n            def test_should_not_run(self):\n                pass\n    \"\"\"\n    )\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(failed=1, passed=1)\n\n\ndef test_exit_outcome(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_foo=\"\"\"\n        import pytest\n        import unittest\n\n        class MyTestCase(unittest.TestCase):\n            def test_exit_outcome(self):\n                pytest.exit(\"pytest_exit called\")\n\n            def test_should_not_run(self):\n                pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*Exit: pytest_exit called*\", \"*= no tests ran in *\"])\n\n\ndef test_trace(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n    calls = []\n\n    def check_call(*args, **kwargs):\n        calls.append((args, kwargs))\n        assert args == (\"runcall\",)\n\n        class _pdb:\n            def runcall(*args, **kwargs):\n                calls.append((args, kwargs))\n\n        return _pdb\n\n    monkeypatch.setattr(\"_pytest.debugging.pytestPDB._init_pdb\", check_call)\n\n    p1 = pytester.makepyfile(\n        \"\"\"\n        import unittest\n\n        class MyTestCase(unittest.TestCase):\n            def test(self):\n                self.assertEqual('foo', 'foo')\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--trace\", str(p1))\n    assert len(calls) == 2\n    assert result.ret == 0\n\n\ndef test_pdb_teardown_called(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:\n    \"\"\"Ensure tearDown() is always called when --pdb is given in the command-line.\n\n    We delay the normal tearDown() calls when --pdb is given, so this ensures we are calling\n    tearDown() eventually to avoid memory leaks when using --pdb.\n    \"\"\"\n    teardowns: list[str] = []\n    monkeypatch.setattr(\n        pytest, \"test_pdb_teardown_called_teardowns\", teardowns, raising=False\n    )\n\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n        import pytest\n\n        class MyTestCase(unittest.TestCase):\n\n            def tearDown(self):\n                pytest.test_pdb_teardown_called_teardowns.append(self.id())\n\n            def test_1(self):\n                pass\n            def test_2(self):\n                pass\n    \"\"\"\n    )\n    result = pytester.runpytest_inprocess(\"--pdb\")\n    result.stdout.fnmatch_lines(\"* 2 passed in *\")\n    assert teardowns == [\n        \"test_pdb_teardown_called.MyTestCase.test_1\",\n        \"test_pdb_teardown_called.MyTestCase.test_2\",\n    ]\n\n\n@pytest.mark.parametrize(\"mark\", [\"@unittest.skip\", \"@pytest.mark.skip\"])\ndef test_pdb_teardown_skipped_for_functions(\n    pytester: Pytester, monkeypatch: MonkeyPatch, mark: str\n) -> None:\n    \"\"\"\n    With --pdb, setUp and tearDown should not be called for tests skipped\n    via a decorator (#7215).\n    \"\"\"\n    tracked: list[str] = []\n    monkeypatch.setattr(pytest, \"track_pdb_teardown_skipped\", tracked, raising=False)\n\n    pytester.makepyfile(\n        f\"\"\"\n        import unittest\n        import pytest\n\n        class MyTestCase(unittest.TestCase):\n\n            def setUp(self):\n                pytest.track_pdb_teardown_skipped.append(\"setUp:\" + self.id())\n\n            def tearDown(self):\n                pytest.track_pdb_teardown_skipped.append(\"tearDown:\" + self.id())\n\n            {mark}(\"skipped for reasons\")\n            def test_1(self):\n                pass\n\n    \"\"\"\n    )\n    result = pytester.runpytest_inprocess(\"--pdb\")\n    result.stdout.fnmatch_lines(\"* 1 skipped in *\")\n    assert tracked == []\n\n\n@pytest.mark.parametrize(\"mark\", [\"@unittest.skip\", \"@pytest.mark.skip\"])\ndef test_pdb_teardown_skipped_for_classes(\n    pytester: Pytester, monkeypatch: MonkeyPatch, mark: str\n) -> None:\n    \"\"\"\n    With --pdb, setUp and tearDown should not be called for tests skipped\n    via a decorator on the class (#10060).\n    \"\"\"\n    tracked: list[str] = []\n    monkeypatch.setattr(pytest, \"track_pdb_teardown_skipped\", tracked, raising=False)\n\n    pytester.makepyfile(\n        f\"\"\"\n        import unittest\n        import pytest\n\n        {mark}(\"skipped for reasons\")\n        class MyTestCase(unittest.TestCase):\n\n            def setUp(self):\n                pytest.track_pdb_teardown_skipped.append(\"setUp:\" + self.id())\n\n            def tearDown(self):\n                pytest.track_pdb_teardown_skipped.append(\"tearDown:\" + self.id())\n\n            def test_1(self):\n                pass\n\n    \"\"\"\n    )\n    result = pytester.runpytest_inprocess(\"--pdb\")\n    result.stdout.fnmatch_lines(\"* 1 skipped in *\")\n    assert tracked == []\n\n\ndef test_async_support(pytester: Pytester) -> None:\n    pytest.importorskip(\"unittest.async_case\")\n\n    pytester.copy_example(\"unittest/test_unittest_asyncio.py\")\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(failed=1, passed=2)\n\n\n@pytest.mark.skipif(\n    sys.version_info >= (3, 11), reason=\"asynctest is not compatible with Python 3.11+\"\n)\ndef test_asynctest_support(pytester: Pytester) -> None:\n    \"\"\"Check asynctest support (#7110)\"\"\"\n    pytest.importorskip(\"asynctest\")\n    pytester.copy_example(\"unittest/test_unittest_asynctest.py\")\n    reprec = pytester.inline_run()\n    reprec.assertoutcome(failed=1, passed=2)\n\n\ndef test_plain_unittest_does_not_support_async(pytester: Pytester) -> None:\n    \"\"\"Async functions in plain unittest.TestCase subclasses are not supported without plugins.\n\n    This test exists here to avoid introducing this support by accident, leading users\n    to expect that it works, rather than doing so intentionally as a feature.\n\n    See https://github.com/pytest-dev/pytest-asyncio/issues/180 for more context.\n    \"\"\"\n    pytester.copy_example(\"unittest/test_unittest_plain_async.py\")\n    result = pytester.runpytest_subprocess()\n    if hasattr(sys, \"pypy_version_info\"):\n        # in PyPy we can't reliable get the warning about the coroutine not being awaited,\n        # because it depends on the coroutine being garbage collected; given that\n        # we are running in a subprocess, that's difficult to enforce\n        expected_lines = [\"*1 passed*\"]\n    else:\n        expected_lines = [\n            \"*RuntimeWarning: coroutine * was never awaited\",\n            \"*1 passed*\",\n        ]\n    result.stdout.fnmatch_lines(expected_lines)\n\n\ndef test_do_class_cleanups_on_success(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            values = []\n            @classmethod\n            def setUpClass(cls):\n                def cleanup():\n                    cls.values.append(1)\n                cls.addClassCleanup(cleanup)\n            def test_one(self):\n                pass\n            def test_two(self):\n                pass\n        def test_cleanup_called_exactly_once():\n            assert MyTestCase.values == [1]\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    passed, _skipped, failed = reprec.countoutcomes()\n    assert failed == 0\n    assert passed == 3\n\n\ndef test_do_class_cleanups_on_setupclass_failure(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            values = []\n            @classmethod\n            def setUpClass(cls):\n                def cleanup():\n                    cls.values.append(1)\n                cls.addClassCleanup(cleanup)\n                assert False\n            def test_one(self):\n                pass\n        def test_cleanup_called_exactly_once():\n            assert MyTestCase.values == [1]\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    passed, _skipped, failed = reprec.countoutcomes()\n    assert failed == 1\n    assert passed == 1\n\n\ndef test_do_class_cleanups_on_teardownclass_failure(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            values = []\n            @classmethod\n            def setUpClass(cls):\n                def cleanup():\n                    cls.values.append(1)\n                cls.addClassCleanup(cleanup)\n            @classmethod\n            def tearDownClass(cls):\n                assert False\n            def test_one(self):\n                pass\n            def test_two(self):\n                pass\n        def test_cleanup_called_exactly_once():\n            assert MyTestCase.values == [1]\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    passed, _skipped, _failed = reprec.countoutcomes()\n    assert passed == 3\n\n\ndef test_do_cleanups_on_success(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            values = []\n            def setUp(self):\n                def cleanup():\n                    self.values.append(1)\n                self.addCleanup(cleanup)\n            def test_one(self):\n                pass\n            def test_two(self):\n                pass\n        def test_cleanup_called_the_right_number_of_times():\n            assert MyTestCase.values == [1, 1]\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    passed, _skipped, failed = reprec.countoutcomes()\n    assert failed == 0\n    assert passed == 3\n\n\ndef test_do_cleanups_on_setup_failure(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            values = []\n            def setUp(self):\n                def cleanup():\n                    self.values.append(1)\n                self.addCleanup(cleanup)\n                assert False\n            def test_one(self):\n                pass\n            def test_two(self):\n                pass\n        def test_cleanup_called_the_right_number_of_times():\n            assert MyTestCase.values == [1, 1]\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    passed, _skipped, failed = reprec.countoutcomes()\n    assert failed == 2\n    assert passed == 1\n\n\ndef test_do_cleanups_on_teardown_failure(pytester: Pytester) -> None:\n    testpath = pytester.makepyfile(\n        \"\"\"\n        import unittest\n        class MyTestCase(unittest.TestCase):\n            values = []\n            def setUp(self):\n                def cleanup():\n                    self.values.append(1)\n                self.addCleanup(cleanup)\n            def tearDown(self):\n                assert False\n            def test_one(self):\n                pass\n            def test_two(self):\n                pass\n        def test_cleanup_called_the_right_number_of_times():\n            assert MyTestCase.values == [1, 1]\n    \"\"\"\n    )\n    reprec = pytester.inline_run(testpath)\n    passed, _skipped, failed = reprec.countoutcomes()\n    assert failed == 2\n    assert passed == 1\n\n\nclass TestClassCleanupErrors:\n    \"\"\"\n    Make sure to show exceptions raised during class cleanup function (those registered\n    via addClassCleanup()).\n\n    See #11728.\n    \"\"\"\n\n    def test_class_cleanups_failure_in_setup(self, pytester: Pytester) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n            import unittest\n            class MyTestCase(unittest.TestCase):\n                @classmethod\n                def setUpClass(cls):\n                    def cleanup(n):\n                        raise Exception(f\"fail {n}\")\n                    cls.addClassCleanup(cleanup, 2)\n                    cls.addClassCleanup(cleanup, 1)\n                    raise Exception(\"fail 0\")\n                def test(self):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\", testpath)\n        result.assert_outcomes(passed=0, errors=1)\n        result.stdout.fnmatch_lines(\n            [\n                \"*Unittest class cleanup errors *2 sub-exceptions*\",\n                \"*Exception: fail 1\",\n                \"*Exception: fail 2\",\n            ]\n        )\n        result.stdout.fnmatch_lines(\n            [\n                \"* ERROR at setup of MyTestCase.test *\",\n                \"E * Exception: fail 0\",\n            ]\n        )\n\n    def test_class_cleanups_failure_in_teardown(self, pytester: Pytester) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n            import unittest\n            class MyTestCase(unittest.TestCase):\n                @classmethod\n                def setUpClass(cls):\n                    def cleanup(n):\n                        raise Exception(f\"fail {n}\")\n                    cls.addClassCleanup(cleanup, 2)\n                    cls.addClassCleanup(cleanup, 1)\n                def test(self):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\", testpath)\n        result.assert_outcomes(passed=1, errors=1)\n        result.stdout.fnmatch_lines(\n            [\n                \"*Unittest class cleanup errors *2 sub-exceptions*\",\n                \"*Exception: fail 1\",\n                \"*Exception: fail 2\",\n            ]\n        )\n\n    def test_class_cleanup_1_failure_in_teardown(self, pytester: Pytester) -> None:\n        testpath = pytester.makepyfile(\n            \"\"\"\n            import unittest\n            class MyTestCase(unittest.TestCase):\n                @classmethod\n                def setUpClass(cls):\n                    def cleanup(n):\n                        raise Exception(f\"fail {n}\")\n                    cls.addClassCleanup(cleanup, 1)\n                def test(self):\n                    pass\n        \"\"\"\n        )\n        result = pytester.runpytest(\"-s\", testpath)\n        result.assert_outcomes(passed=1, errors=1)\n        result.stdout.fnmatch_lines(\n            [\n                \"*ERROR at teardown of MyTestCase.test*\",\n                \"*Exception: fail 1\",\n            ]\n        )\n\n\ndef test_traceback_pruning(pytester: Pytester) -> None:\n    \"\"\"Regression test for #9610 - doesn't crash during traceback pruning.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n\n        class MyTestCase(unittest.TestCase):\n            def __init__(self, test_method):\n                unittest.TestCase.__init__(self, test_method)\n\n        class TestIt(MyTestCase):\n            @classmethod\n            def tearDownClass(cls) -> None:\n                assert False\n\n            def test_it(self):\n                pass\n        \"\"\"\n    )\n    reprec = pytester.inline_run()\n    passed, _skipped, failed = reprec.countoutcomes()\n    assert passed == 1\n    assert failed == 1\n    assert reprec.ret == 1\n\n\ndef test_raising_unittest_skiptest_during_collection(\n    pytester: Pytester,\n) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import unittest\n\n        class TestIt(unittest.TestCase):\n            def test_it(self): pass\n            def test_it2(self): pass\n\n        raise unittest.SkipTest()\n\n        class TestIt2(unittest.TestCase):\n            def test_it(self): pass\n            def test_it2(self): pass\n        \"\"\"\n    )\n    reprec = pytester.inline_run()\n    passed, skipped, failed = reprec.countoutcomes()\n    assert passed == 0\n    # Unittest reports one fake test for a skipped module.\n    assert skipped == 1\n    assert failed == 0\n    assert reprec.ret == ExitCode.NO_TESTS_COLLECTED\n\n\ndef test_abstract_testcase_is_not_collected(pytester: Pytester) -> None:\n    \"\"\"Regression test for #12275.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import abc\n        import unittest\n\n        class TestBase(unittest.TestCase, abc.ABC):\n            @abc.abstractmethod\n            def abstract1(self): pass\n\n            @abc.abstractmethod\n            def abstract2(self): pass\n\n            def test_it(self): pass\n\n        class TestPartial(TestBase):\n            def abstract1(self): pass\n\n        class TestConcrete(TestPartial):\n            def abstract2(self): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == ExitCode.OK\n    result.assert_outcomes(passed=1)\n"
  },
  {
    "path": "testing/test_unraisableexception.py",
    "content": "from __future__ import annotations\n\nimport gc\nimport sys\nfrom unittest import mock\n\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nPYPY = hasattr(sys, \"pypy_version_info\")\n\nUNRAISABLE_LINE = (\n    (\n        \"  * PytestUnraisableExceptionWarning: Exception ignored while calling \"\n        \"deallocator <function BrokenDel.__del__ at *>: None\"\n    )\n    if sys.version_info >= (3, 14)\n    else \"  * PytestUnraisableExceptionWarning: Exception ignored in: <function BrokenDel.__del__ at *>\"\n)\n\nTRACEMALLOC_LINES = (\n    ()\n    if sys.version_info >= (3, 14)\n    else (\n        \"  Enable tracemalloc to get traceback where the object was allocated.\",\n        \"  See https* for more info.\",\n    )\n)\n\n\n@pytest.mark.skipif(PYPY, reason=\"garbage-collection differences make this flaky\")\n@pytest.mark.filterwarnings(\"default::pytest.PytestUnraisableExceptionWarning\")\ndef test_unraisable(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        class BrokenDel:\n            def __del__(self):\n                raise ValueError(\"del is broken\")\n\n        def test_it():\n            obj = BrokenDel()\n            del obj\n\n        def test_2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.assert_outcomes(passed=2, warnings=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"*= warnings summary =*\",\n            \"test_it.py::test_it\",\n            UNRAISABLE_LINE,\n            \"  \",\n            \"  Traceback (most recent call last):\",\n            \"  ValueError: del is broken\",\n            \"  \",\n            *TRACEMALLOC_LINES,\n            \"    warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))\",\n        ]\n    )\n\n\n@pytest.mark.skipif(PYPY, reason=\"garbage-collection differences make this flaky\")\n@pytest.mark.filterwarnings(\"default::pytest.PytestUnraisableExceptionWarning\")\ndef test_unraisable_in_setup(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import pytest\n\n        class BrokenDel:\n            def __del__(self):\n                raise ValueError(\"del is broken\")\n\n        @pytest.fixture\n        def broken_del():\n            obj = BrokenDel()\n            del obj\n\n        def test_it(broken_del): pass\n        def test_2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.assert_outcomes(passed=2, warnings=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"*= warnings summary =*\",\n            \"test_it.py::test_it\",\n            UNRAISABLE_LINE,\n            \"  \",\n            \"  Traceback (most recent call last):\",\n            \"  ValueError: del is broken\",\n            \"  \",\n            *TRACEMALLOC_LINES,\n            \"    warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))\",\n        ]\n    )\n\n\n@pytest.mark.skipif(PYPY, reason=\"garbage-collection differences make this flaky\")\n@pytest.mark.filterwarnings(\"default::pytest.PytestUnraisableExceptionWarning\")\ndef test_unraisable_in_teardown(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import pytest\n\n        class BrokenDel:\n            def __del__(self):\n                raise ValueError(\"del is broken\")\n\n        @pytest.fixture\n        def broken_del():\n            yield\n            obj = BrokenDel()\n            del obj\n\n        def test_it(broken_del): pass\n        def test_2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == 0\n    result.assert_outcomes(passed=2, warnings=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"*= warnings summary =*\",\n            \"test_it.py::test_it\",\n            UNRAISABLE_LINE,\n            \"  \",\n            \"  Traceback (most recent call last):\",\n            \"  ValueError: del is broken\",\n            \"  \",\n            *TRACEMALLOC_LINES,\n            \"    warnings.warn(pytest.PytestUnraisableExceptionWarning(msg))\",\n        ]\n    )\n\n\n@pytest.mark.filterwarnings(\"error::pytest.PytestUnraisableExceptionWarning\")\ndef test_unraisable_warning_error(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=f\"\"\"\n        class BrokenDel:\n            def __del__(self) -> None:\n                raise ValueError(\"del is broken\")\n\n        def test_it() -> None:\n            obj = BrokenDel()\n            del obj\n            {\"import gc; gc.collect()\" * PYPY}\n\n        def test_2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == pytest.ExitCode.TESTS_FAILED\n    result.assert_outcomes(passed=1, failed=1)\n\n\n@pytest.mark.filterwarnings(\"error::pytest.PytestUnraisableExceptionWarning\")\ndef test_unraisable_warning_multiple_errors(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=f\"\"\"\n        class BrokenDel:\n            def __init__(self, msg: str):\n                self.msg = msg\n\n            def __del__(self) -> None:\n                raise ValueError(self.msg)\n\n        def test_it() -> None:\n            BrokenDel(\"del is broken 1\")\n            BrokenDel(\"del is broken 2\")\n            {\"import gc; gc.collect()\" * PYPY}\n\n        def test_2(): pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    assert result.ret == pytest.ExitCode.TESTS_FAILED\n    result.assert_outcomes(passed=1, failed=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"  | *ExceptionGroup: multiple unraisable exception warnings (2 sub-exceptions)\"\n        ]\n    )\n\n\ndef test_unraisable_collection_failure(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=f\"\"\"\n        class BrokenDel:\n            def __del__(self):\n                raise ValueError(\"del is broken\")\n\n        def test_it():\n            obj = BrokenDel()\n            del obj\n            {\"import gc; gc.collect()\" * PYPY}\n\n        def test_2(): pass\n        \"\"\"\n    )\n\n    class MyError(BaseException):\n        pass\n\n    with mock.patch(\"traceback.format_exception\", side_effect=MyError):\n        result = pytester.runpytest()\n    assert result.ret == 1\n    result.assert_outcomes(passed=1, failed=1)\n    result.stdout.fnmatch_lines(\n        [\"E               RuntimeError: Failed to process unraisable exception\"]\n    )\n\n\ndef _set_gc_state(enabled: bool) -> bool:\n    was_enabled = gc.isenabled()\n    if enabled:\n        gc.enable()\n    else:\n        gc.disable()\n    return was_enabled\n\n\ndef test_refcycle_unraisable(pytester: Pytester) -> None:\n    # see: https://github.com/pytest-dev/pytest/issues/10404\n    pytester.makepyfile(\n        test_it=\"\"\"\n        # Should catch the unraisable exception even if gc is disabled.\n        import gc; gc.disable()\n\n        import pytest\n\n        class BrokenDel:\n            def __init__(self):\n                self.self = self  # make a reference cycle\n\n            def __del__(self):\n                raise ValueError(\"del is broken\")\n\n        def test_it():\n            BrokenDel()\n        \"\"\"\n    )\n\n    result = pytester.runpytest_subprocess(\n        \"-Wdefault::pytest.PytestUnraisableExceptionWarning\"\n    )\n\n    assert result.ret == 0\n\n    result.assert_outcomes(passed=1)\n    result.stderr.fnmatch_lines(\"ValueError: del is broken\")\n\n\ndef test_refcycle_unraisable_warning_filter(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        # Should catch the unraisable exception even if gc is disabled.\n        import gc; gc.disable()\n\n        import pytest\n\n        class BrokenDel:\n            def __init__(self):\n                self.self = self  # make a reference cycle\n\n            def __del__(self):\n                raise ValueError(\"del is broken\")\n\n        def test_it():\n            BrokenDel()\n        \"\"\"\n    )\n\n    result = pytester.runpytest_subprocess(\n        \"-Werror::pytest.PytestUnraisableExceptionWarning\"\n    )\n\n    # TODO: Should be a test failure or error. Currently the exception\n    # propagates all the way to the top resulting in exit code 1.\n    assert result.ret == 1\n\n    result.assert_outcomes(passed=1)\n    result.stderr.fnmatch_lines(\"ValueError: del is broken\")\n\n\ndef test_create_task_raises_unraisable_warning_filter(pytester: Pytester) -> None:\n    # note that the host pytest warning filter is disabled and the pytester\n    # warning filter applies during config teardown of unraisablehook.\n    # see: https://github.com/pytest-dev/pytest/issues/10404\n    # This is a dupe of the above test, but using the exact reproducer from\n    # the issue\n    pytester.makepyfile(\n        test_it=\"\"\"\n        # Should catch the unraisable exception even if gc is disabled.\n        import gc; gc.disable()\n\n        import asyncio\n        import pytest\n\n        async def my_task():\n            pass\n\n        def test_scheduler_must_be_created_within_running_loop() -> None:\n            with pytest.raises(RuntimeError) as _:\n                asyncio.create_task(my_task())\n        \"\"\"\n    )\n\n    result = pytester.runpytest_subprocess(\"-Werror\")\n\n    # TODO: Should be a test failure or error. Currently the exception\n    # propagates all the way to the top resulting in exit code 1.\n    assert result.ret == 1\n\n    result.assert_outcomes(passed=1)\n    result.stderr.fnmatch_lines(\"RuntimeWarning: coroutine 'my_task' was never awaited\")\n\n\ndef test_refcycle_unraisable_warning_filter_default(pytester: Pytester) -> None:\n    # note this time we use a default warning filter for pytester\n    # and run it in a subprocess, because the warning can only go to the\n    # sys.stdout rather than the terminal reporter, which has already\n    # finished.\n    # see: https://github.com/pytest-dev/pytest/pull/13057#discussion_r1888396126\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import gc\n        gc.disable()\n\n        import pytest\n\n        class BrokenDel:\n            def __init__(self):\n                self.self = self  # make a reference cycle\n\n            def __del__(self):\n                raise ValueError(\"del is broken\")\n\n        def test_it():\n            BrokenDel()\n        \"\"\"\n    )\n\n    # since we use subprocess we need to disable gc inside test_it\n    result = pytester.runpytest_subprocess(\"-Wdefault\")\n\n    assert result.ret == pytest.ExitCode.OK\n\n    # TODO: should be warnings=1, but the outcome has already come out\n    # by the time the warning triggers\n    result.assert_outcomes(passed=1)\n    result.stderr.fnmatch_lines(\"ValueError: del is broken\")\n\n\n@pytest.mark.filterwarnings(\"error::pytest.PytestUnraisableExceptionWarning\")\ndef test_possibly_none_excinfo(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        test_it=\"\"\"\n        import sys\n        import types\n\n        def test_it():\n            sys.unraisablehook(\n                types.SimpleNamespace(\n                    exc_type=RuntimeError,\n                    exc_value=None,\n                    exc_traceback=None,\n                    err_msg=None,\n                    object=None,\n                )\n            )\n        \"\"\"\n    )\n\n    result = pytester.runpytest()\n\n    # TODO: should be a test failure or error\n    assert result.ret == pytest.ExitCode.TESTS_FAILED\n\n    result.assert_outcomes(failed=1)\n    result.stdout.fnmatch_lines(\n        [\n            \"E                   pytest.PytestUnraisableExceptionWarning:\"\n            \" Exception ignored in: None\",\n            \"E                   \",\n            \"E                   NoneType: None\",\n        ]\n    )\n"
  },
  {
    "path": "testing/test_warning_types.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport inspect\n\nfrom _pytest import warning_types\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\n@pytest.mark.parametrize(\n    \"warning_class\",\n    [\n        w\n        for n, w in vars(warning_types).items()\n        if inspect.isclass(w) and issubclass(w, Warning)\n    ],\n)\ndef test_warning_types(warning_class: UserWarning) -> None:\n    \"\"\"Make sure all warnings declared in _pytest.warning_types are displayed as coming\n    from 'pytest' instead of the internal module (#5452).\n    \"\"\"\n    assert warning_class.__module__ == \"pytest\"\n\n\n@pytest.mark.filterwarnings(\"error::pytest.PytestWarning\")\ndef test_pytest_warnings_repr_integration_test(pytester: Pytester) -> None:\n    \"\"\"Small integration test to ensure our small hack of setting the __module__ attribute\n    of our warnings actually works (#5452).\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import warnings\n\n        def test():\n            warnings.warn(pytest.PytestWarning(\"some warning\"))\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"E       pytest.PytestWarning: some warning\"])\n\n\n@pytest.mark.filterwarnings(\"error\")\ndef test_warn_explicit_for_annotates_errors_with_location():\n    with pytest.raises(Warning, match=r\"(?m)test\\n at .*raises.py:\\d+\"):\n        warning_types.warn_explicit_for(\n            pytest.raises,  # type: ignore[arg-type]\n            warning_types.PytestWarning(\"test\"),\n        )\n"
  },
  {
    "path": "testing/test_warnings.py",
    "content": "# mypy: allow-untyped-defs\nfrom __future__ import annotations\n\nimport os\nimport sys\nimport warnings\n\nfrom _pytest.fixtures import FixtureRequest\nfrom _pytest.pytester import Pytester\nimport pytest\n\n\nWARNINGS_SUMMARY_HEADER = \"warnings summary\"\n\n\n@pytest.fixture\ndef pyfile_with_warnings(pytester: Pytester, request: FixtureRequest) -> str:\n    \"\"\"Create a test file which calls a function in a module which generates warnings.\"\"\"\n    pytester.syspathinsert()\n    module_name = request.function.__name__[len(\"test_\") :] + \"_module\"\n    test_file = pytester.makepyfile(\n        f\"\"\"\n        import {module_name}\n        def test_func():\n            assert {module_name}.foo() == 1\n        \"\"\",\n        **{\n            module_name: \"\"\"\n            import warnings\n            def foo():\n                warnings.warn(UserWarning(\"user warning\"))\n                warnings.warn(RuntimeWarning(\"runtime warning\"))\n                return 1\n            \"\"\",\n        },\n    )\n    return str(test_file)\n\n\n@pytest.mark.filterwarnings(\"default::UserWarning\", \"default::RuntimeWarning\")\ndef test_normal_flow(pytester: Pytester, pyfile_with_warnings) -> None:\n    \"\"\"Check that the warnings section is displayed.\"\"\"\n    result = pytester.runpytest(pyfile_with_warnings)\n    result.stdout.fnmatch_lines(\n        [\n            f\"*== {WARNINGS_SUMMARY_HEADER} ==*\",\n            \"test_normal_flow.py::test_func\",\n            \"*normal_flow_module.py:3: UserWarning: user warning\",\n            '*  warnings.warn(UserWarning(\"user warning\"))',\n            \"*normal_flow_module.py:4: RuntimeWarning: runtime warning\",\n            '*  warnings.warn(RuntimeWarning(\"runtime warning\"))',\n            \"* 1 passed, 2 warnings*\",\n        ]\n    )\n\n\n@pytest.mark.filterwarnings(\"always::UserWarning\")\ndef test_setup_teardown_warnings(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import warnings\n        import pytest\n\n        @pytest.fixture\n        def fix():\n            warnings.warn(UserWarning(\"warning during setup\"))\n            yield\n            warnings.warn(UserWarning(\"warning during teardown\"))\n\n        def test_func(fix):\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            f\"*== {WARNINGS_SUMMARY_HEADER} ==*\",\n            \"*test_setup_teardown_warnings.py:6: UserWarning: warning during setup\",\n            '*warnings.warn(UserWarning(\"warning during setup\"))',\n            \"*test_setup_teardown_warnings.py:8: UserWarning: warning during teardown\",\n            '*warnings.warn(UserWarning(\"warning during teardown\"))',\n            \"* 1 passed, 2 warnings*\",\n        ]\n    )\n\n\n@pytest.mark.parametrize(\"method\", [\"cmdline\", \"ini\"])\ndef test_as_errors(pytester: Pytester, pyfile_with_warnings, method) -> None:\n    args = (\"-W\", \"error\") if method == \"cmdline\" else ()\n    if method == \"ini\":\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            filterwarnings=error\n            \"\"\"\n        )\n    # Use a subprocess, since changing logging level affects other threads\n    # (xdist).\n    result = pytester.runpytest_subprocess(*args, pyfile_with_warnings)\n    result.stdout.fnmatch_lines(\n        [\n            \"E       UserWarning: user warning\",\n            \"as_errors_module.py:3: UserWarning\",\n            \"* 1 failed in *\",\n        ]\n    )\n\n\n@pytest.mark.parametrize(\"method\", [\"cmdline\", \"ini\"])\ndef test_ignore(pytester: Pytester, pyfile_with_warnings, method) -> None:\n    args = (\"-W\", \"ignore\") if method == \"cmdline\" else ()\n    if method == \"ini\":\n        pytester.makeini(\n            \"\"\"\n        [pytest]\n        filterwarnings= ignore\n        \"\"\"\n        )\n\n    result = pytester.runpytest(*args, pyfile_with_warnings)\n    result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n    assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n\n@pytest.mark.filterwarnings(\"always::UserWarning\")\ndef test_unicode(pytester: Pytester) -> None:\n    pytester.makepyfile(\n        \"\"\"\n        import warnings\n        import pytest\n\n\n        @pytest.fixture\n        def fix():\n            warnings.warn(\"测试\")\n            yield\n\n        def test_func(fix):\n            pass\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            f\"*== {WARNINGS_SUMMARY_HEADER} ==*\",\n            \"*test_unicode.py:7: UserWarning: \\u6d4b\\u8bd5*\",\n            \"* 1 passed, 1 warning*\",\n        ]\n    )\n\n\n@pytest.mark.skip(\"issue #13485\")\ndef test_works_with_filterwarnings(pytester: Pytester) -> None:\n    \"\"\"Ensure our warnings capture does not mess with pre-installed filters (#2430).\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import warnings\n\n        class MyWarning(Warning):\n            pass\n\n        warnings.filterwarnings(\"error\", category=MyWarning)\n\n        class TestWarnings(object):\n            def test_my_warning(self):\n                try:\n                    warnings.warn(MyWarning(\"warn!\"))\n                    assert False\n                except MyWarning:\n                    assert True\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines([\"*== 1 passed in *\"])\n\n\n@pytest.mark.parametrize(\"default_config\", [\"ini\", \"cmdline\"])\ndef test_filterwarnings_mark(pytester: Pytester, default_config) -> None:\n    \"\"\"Test ``filterwarnings`` mark works and takes precedence over command\n    line and ini options.\"\"\"\n    if default_config == \"ini\":\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            filterwarnings = always::RuntimeWarning\n        \"\"\"\n        )\n    pytester.makepyfile(\n        \"\"\"\n        import warnings\n        import pytest\n\n        @pytest.mark.filterwarnings('ignore::RuntimeWarning')\n        def test_ignore_runtime_warning():\n            warnings.warn(RuntimeWarning())\n\n        @pytest.mark.filterwarnings('error')\n        def test_warning_error():\n            warnings.warn(RuntimeWarning())\n\n        def test_show_warning():\n            warnings.warn(RuntimeWarning())\n    \"\"\"\n    )\n    result = pytester.runpytest(\n        \"-W always::RuntimeWarning\" if default_config == \"cmdline\" else \"\"\n    )\n    result.stdout.fnmatch_lines([\"*= 1 failed, 2 passed, 1 warning in *\"])\n\n\ndef test_non_string_warning_argument(pytester: Pytester) -> None:\n    \"\"\"Non-str argument passed to warning breaks pytest (#2956)\"\"\"\n    pytester.makepyfile(\n        \"\"\"\\\n        import warnings\n        import pytest\n\n        def test():\n            warnings.warn(UserWarning(1, 'foo'))\n        \"\"\"\n    )\n    result = pytester.runpytest(\"-W\", \"always::UserWarning\")\n    result.stdout.fnmatch_lines([\"*= 1 passed, 1 warning in *\"])\n\n\ndef test_filterwarnings_mark_registration(pytester: Pytester) -> None:\n    \"\"\"Ensure filterwarnings mark is registered\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n\n        @pytest.mark.filterwarnings('error')\n        def test_func():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest(\"--strict-markers\")\n    assert result.ret == 0\n\n\n@pytest.mark.filterwarnings(\"always::UserWarning\")\ndef test_warning_recorded_hook(pytester: Pytester) -> None:\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_configure(config):\n            config.issue_config_time_warning(UserWarning(\"config warning\"), stacklevel=2)\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest, warnings\n\n        warnings.warn(UserWarning(\"collect warning\"))\n\n        @pytest.fixture\n        def fix():\n            warnings.warn(UserWarning(\"setup warning\"))\n            yield 1\n            warnings.warn(UserWarning(\"teardown warning\"))\n\n        def test_func(fix):\n            warnings.warn(UserWarning(\"call warning\"))\n            assert fix == 1\n        \"\"\"\n    )\n\n    collected = []\n\n    class WarningCollector:\n        def pytest_warning_recorded(self, warning_message, when, nodeid, location):\n            collected.append((str(warning_message.message), when, nodeid, location))\n\n    result = pytester.runpytest(plugins=[WarningCollector()])\n    result.stdout.fnmatch_lines([\"*1 passed*\"])\n\n    expected = [\n        (\"config warning\", \"config\", \"\"),\n        (\"collect warning\", \"collect\", \"\"),\n        (\"setup warning\", \"runtest\", \"test_warning_recorded_hook.py::test_func\"),\n        (\"call warning\", \"runtest\", \"test_warning_recorded_hook.py::test_func\"),\n        (\"teardown warning\", \"runtest\", \"test_warning_recorded_hook.py::test_func\"),\n    ]\n    for collected_result, expected_result in zip(collected, expected, strict=True):\n        assert collected_result[0] == expected_result[0], str(collected)\n        assert collected_result[1] == expected_result[1], str(collected)\n        assert collected_result[2] == expected_result[2], str(collected)\n\n        # NOTE: collected_result[3] is location, which differs based on the platform you are on\n        #       thus, the best we can do here is assert the types of the parameters match what we expect\n        #       and not try and preload it in the expected array\n        if collected_result[3] is not None:\n            assert type(collected_result[3][0]) is str, str(collected)\n            assert type(collected_result[3][1]) is int, str(collected)\n            assert type(collected_result[3][2]) is str, str(collected)\n        else:\n            assert collected_result[3] is None, str(collected)\n\n\n@pytest.mark.filterwarnings(\"always::UserWarning\")\ndef test_collection_warnings(pytester: Pytester) -> None:\n    \"\"\"Check that we also capture warnings issued during test collection (#3251).\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import warnings\n\n        warnings.warn(UserWarning(\"collection warning\"))\n\n        def test_foo():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            f\"*== {WARNINGS_SUMMARY_HEADER} ==*\",\n            \"  *collection_warnings.py:3: UserWarning: collection warning\",\n            '    warnings.warn(UserWarning(\"collection warning\"))',\n            \"* 1 passed, 1 warning*\",\n        ]\n    )\n\n\n@pytest.mark.filterwarnings(\"always::UserWarning\")\ndef test_mark_regex_escape(pytester: Pytester) -> None:\n    \"\"\"@pytest.mark.filterwarnings should not try to escape regex characters (#3936)\"\"\"\n    pytester.makepyfile(\n        r\"\"\"\n        import pytest, warnings\n\n        @pytest.mark.filterwarnings(r\"ignore:some \\(warning\\)\")\n        def test_foo():\n            warnings.warn(UserWarning(\"some (warning)\"))\n    \"\"\"\n    )\n    result = pytester.runpytest()\n    assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n\n@pytest.mark.filterwarnings(\"default::pytest.PytestWarning\")\n@pytest.mark.parametrize(\"ignore_pytest_warnings\", [\"no\", \"ini\", \"cmdline\"])\ndef test_hide_pytest_internal_warnings(\n    pytester: Pytester, ignore_pytest_warnings\n) -> None:\n    \"\"\"Make sure we can ignore internal pytest warnings using a warnings filter.\"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import pytest\n        import warnings\n\n        warnings.warn(pytest.PytestWarning(\"some internal warning\"))\n\n        def test_bar():\n            pass\n    \"\"\"\n    )\n    if ignore_pytest_warnings == \"ini\":\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            filterwarnings = ignore::pytest.PytestWarning\n        \"\"\"\n        )\n    args = (\n        [\"-W\", \"ignore::pytest.PytestWarning\"]\n        if ignore_pytest_warnings == \"cmdline\"\n        else []\n    )\n    result = pytester.runpytest(*args)\n    if ignore_pytest_warnings != \"no\":\n        assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n    else:\n        result.stdout.fnmatch_lines(\n            [\n                f\"*== {WARNINGS_SUMMARY_HEADER} ==*\",\n                \"*test_hide_pytest_internal_warnings.py:4: PytestWarning: some internal warning\",\n                \"* 1 passed, 1 warning *\",\n            ]\n        )\n\n\n@pytest.mark.parametrize(\"ignore_on_cmdline\", [True, False])\ndef test_option_precedence_cmdline_over_ini(\n    pytester: Pytester, ignore_on_cmdline\n) -> None:\n    \"\"\"Filters defined in the command-line should take precedence over filters in config files (#3946).\"\"\"\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        filterwarnings = error::UserWarning\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import warnings\n        def test():\n            warnings.warn(UserWarning('hello'))\n    \"\"\"\n    )\n    args = [\"-W\", \"ignore\"] if ignore_on_cmdline else []\n    result = pytester.runpytest(*args)\n    if ignore_on_cmdline:\n        result.stdout.fnmatch_lines([\"* 1 passed in*\"])\n    else:\n        result.stdout.fnmatch_lines([\"* 1 failed in*\"])\n\n\ndef test_option_precedence_mark(pytester: Pytester) -> None:\n    \"\"\"Filters defined by marks should always take precedence (#3946).\"\"\"\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        filterwarnings = ignore\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        import pytest, warnings\n        @pytest.mark.filterwarnings('error')\n        def test():\n            warnings.warn(UserWarning('hello'))\n    \"\"\"\n    )\n    result = pytester.runpytest(\"-W\", \"ignore\")\n    result.stdout.fnmatch_lines([\"* 1 failed in*\"])\n\n\ndef test_accept_unknown_category(pytester: Pytester) -> None:\n    \"\"\"Category types that can't be imported don't cause failure (#13732).\"\"\"\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        filterwarnings =\n            always:Failed to import filter module.*:pytest.PytestConfigWarning\n            ignore::foobar.Foobar\n    \"\"\"\n    )\n    pytester.makepyfile(\n        \"\"\"\n        def test():\n            pass\n    \"\"\"\n    )\n    result = pytester.runpytest_subprocess(\"-W\", \"ignore::bizbaz.Bizbaz\")\n    result.stdout.fnmatch_lines(\n        [\n            f\"*== {WARNINGS_SUMMARY_HEADER} ==*\",\n            \"*PytestConfigWarning: Failed to import filter module 'foobar': ignore::foobar.Foobar\",\n            \"*PytestConfigWarning: Failed to import filter module 'bizbaz': ignore::bizbaz.Bizbaz\",\n            \"* 1 passed, * warning*\",\n        ]\n    )\n\n\nclass TestDeprecationWarningsByDefault:\n    \"\"\"\n    Note: all pytest runs are executed in a subprocess so we don't inherit warning filters\n    from pytest's own test suite\n    \"\"\"\n\n    def create_file(self, pytester: Pytester, mark=\"\") -> None:\n        pytester.makepyfile(\n            f\"\"\"\n            import pytest, warnings\n\n            warnings.warn(DeprecationWarning(\"collection\"))\n\n            {mark}\n            def test_foo():\n                warnings.warn(PendingDeprecationWarning(\"test run\"))\n        \"\"\"\n        )\n\n    @pytest.mark.parametrize(\"customize_filters\", [True, False])\n    def test_shown_by_default(self, pytester: Pytester, customize_filters) -> None:\n        \"\"\"Show deprecation warnings by default, even if user has customized the warnings filters (#4013).\"\"\"\n        self.create_file(pytester)\n        if customize_filters:\n            pytester.makeini(\n                \"\"\"\n                [pytest]\n                filterwarnings =\n                    once::UserWarning\n            \"\"\"\n            )\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines(\n            [\n                f\"*== {WARNINGS_SUMMARY_HEADER} ==*\",\n                \"*test_shown_by_default.py:3: DeprecationWarning: collection\",\n                \"*test_shown_by_default.py:7: PendingDeprecationWarning: test run\",\n                \"* 1 passed, 2 warnings*\",\n            ]\n        )\n\n    def test_hidden_by_ini(self, pytester: Pytester) -> None:\n        self.create_file(pytester)\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            filterwarnings =\n                ignore::DeprecationWarning\n                ignore::PendingDeprecationWarning\n        \"\"\"\n        )\n        result = pytester.runpytest_subprocess()\n        assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n    def test_hidden_by_mark(self, pytester: Pytester) -> None:\n        \"\"\"Should hide the deprecation warning from the function, but the warning during collection should\n        be displayed normally.\n        \"\"\"\n        self.create_file(\n            pytester,\n            mark='@pytest.mark.filterwarnings(\"ignore::PendingDeprecationWarning\")',\n        )\n        result = pytester.runpytest_subprocess()\n        result.stdout.fnmatch_lines(\n            [\n                f\"*== {WARNINGS_SUMMARY_HEADER} ==*\",\n                \"*test_hidden_by_mark.py:3: DeprecationWarning: collection\",\n                \"* 1 passed, 1 warning*\",\n            ]\n        )\n\n    def test_hidden_by_cmdline(self, pytester: Pytester) -> None:\n        self.create_file(pytester)\n        result = pytester.runpytest_subprocess(\n            \"-W\",\n            \"ignore::DeprecationWarning\",\n            \"-W\",\n            \"ignore::PendingDeprecationWarning\",\n        )\n        assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n    def test_hidden_by_system(self, pytester: Pytester, monkeypatch) -> None:\n        self.create_file(pytester)\n        monkeypatch.setenv(\"PYTHONWARNINGS\", \"once::UserWarning\")\n        result = pytester.runpytest_subprocess()\n        assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()\n\n    def test_invalid_regex_in_filterwarning(self, pytester: Pytester) -> None:\n        self.create_file(pytester)\n        pytester.makeini(\n            \"\"\"\n                [pytest]\n                filterwarnings =\n                    ignore::DeprecationWarning:*\n            \"\"\"\n        )\n        result = pytester.runpytest_subprocess()\n        assert result.ret == pytest.ExitCode.USAGE_ERROR\n        result.stderr.fnmatch_lines(\n            [\n                \"ERROR: while parsing the following warning configuration:\",\n                \"\",\n                \"  ignore::DeprecationWarning:[*]\",\n                \"\",\n                \"This error occurred:\",\n                \"\",\n                \"Invalid regex '[*]': nothing to repeat at position 0\",\n            ]\n        )\n\n\n# In 9.1, uncomment below and change RemovedIn9 -> RemovedIn10.\n# @pytest.mark.skip(\"not relevant until pytest 10.0\")\n@pytest.mark.parametrize(\"change_default\", [None, \"ini\", \"cmdline\"])\ndef test_removed_in_x_warning_as_error(pytester: Pytester, change_default) -> None:\n    \"\"\"This ensures that PytestRemovedInXWarnings raised by pytest are turned into errors.\n\n    This test should be enabled as part of each major release, and skipped again afterwards\n    to ensure our deprecations are turning into warnings as expected.\n    \"\"\"\n    pytester.makepyfile(\n        \"\"\"\n        import warnings, pytest\n        def test():\n            warnings.warn(pytest.PytestRemovedIn9Warning(\"some warning\"))\n    \"\"\"\n    )\n    if change_default == \"ini\":\n        pytester.makeini(\n            \"\"\"\n            [pytest]\n            filterwarnings =\n                ignore::pytest.PytestRemovedIn9Warning\n        \"\"\"\n        )\n\n    args = (\n        (\"-Wignore::pytest.PytestRemovedIn9Warning\",)\n        if change_default == \"cmdline\"\n        else ()\n    )\n    result = pytester.runpytest(*args)\n    if change_default is None:\n        result.stdout.fnmatch_lines([\"* 1 failed in *\"])\n    else:\n        assert change_default in (\"ini\", \"cmdline\")\n        result.stdout.fnmatch_lines([\"* 1 passed in *\"])\n\n\nclass TestAssertionWarnings:\n    @staticmethod\n    def assert_result_warns(result, msg) -> None:\n        result.stdout.fnmatch_lines([f\"*PytestAssertRewriteWarning: {msg}*\"])\n\n    def test_tuple_warning(self, pytester: Pytester) -> None:\n        pytester.makepyfile(\n            \"\"\"\\\n            def test_foo():\n                assert (1,2)\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        self.assert_result_warns(\n            result, \"assertion is always true, perhaps remove parentheses?\"\n        )\n\n\ndef test_warnings_checker_twice() -> None:\n    \"\"\"Issue #4617\"\"\"\n    expectation = pytest.warns(UserWarning)\n    with expectation:\n        warnings.warn(\"Message A\", UserWarning)\n    with expectation:\n        warnings.warn(\"Message B\", UserWarning)\n\n\n@pytest.mark.filterwarnings(\"always::UserWarning\")\ndef test_group_warnings_by_message(pytester: Pytester) -> None:\n    pytester.copy_example(\"warnings/test_group_warnings_by_message.py\")\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            f\"*== {WARNINGS_SUMMARY_HEADER} ==*\",\n            \"test_group_warnings_by_message.py::test_foo[[]0[]]\",\n            \"test_group_warnings_by_message.py::test_foo[[]1[]]\",\n            \"test_group_warnings_by_message.py::test_foo[[]2[]]\",\n            \"test_group_warnings_by_message.py::test_foo[[]3[]]\",\n            \"test_group_warnings_by_message.py::test_foo[[]4[]]\",\n            \"test_group_warnings_by_message.py::test_foo_1\",\n            \"  */test_group_warnings_by_message.py:*: UserWarning: foo\",\n            \"    warnings.warn(UserWarning(msg))\",\n            \"\",\n            \"test_group_warnings_by_message.py::test_bar[[]0[]]\",\n            \"test_group_warnings_by_message.py::test_bar[[]1[]]\",\n            \"test_group_warnings_by_message.py::test_bar[[]2[]]\",\n            \"test_group_warnings_by_message.py::test_bar[[]3[]]\",\n            \"test_group_warnings_by_message.py::test_bar[[]4[]]\",\n            \"  */test_group_warnings_by_message.py:*: UserWarning: bar\",\n            \"    warnings.warn(UserWarning(msg))\",\n            \"\",\n            \"-- Docs: *\",\n            \"*= 11 passed, 11 warnings *\",\n        ],\n        consecutive=True,\n    )\n\n\n@pytest.mark.filterwarnings(\"always::UserWarning\")\ndef test_group_warnings_by_message_summary(pytester: Pytester) -> None:\n    pytester.copy_example(\"warnings/test_group_warnings_by_message_summary\")\n    pytester.syspathinsert()\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\n            f\"*== {WARNINGS_SUMMARY_HEADER} ==*\",\n            \"test_1.py: 21 warnings\",\n            \"test_2.py: 1 warning\",\n            \"  */test_1.py:10: UserWarning: foo\",\n            \"    warnings.warn(UserWarning(msg))\",\n            \"\",\n            \"test_1.py: 20 warnings\",\n            \"  */test_1.py:10: UserWarning: bar\",\n            \"    warnings.warn(UserWarning(msg))\",\n            \"\",\n            \"-- Docs: *\",\n            \"*= 42 passed, 42 warnings *\",\n        ],\n        consecutive=True,\n    )\n\n\ndef test_pytest_configure_warning(pytester: Pytester, recwarn) -> None:\n    \"\"\"Issue 5115.\"\"\"\n    pytester.makeconftest(\n        \"\"\"\n        def pytest_configure():\n            import warnings\n\n            warnings.warn(\"from pytest_configure\")\n        \"\"\"\n    )\n\n    result = pytester.runpytest()\n    assert result.ret == 5\n    assert \"INTERNALERROR\" not in result.stderr.str()\n    warning = recwarn.pop()\n    assert str(warning.message) == \"from pytest_configure\"\n\n\nclass TestStackLevel:\n    @pytest.fixture\n    def capwarn(self, pytester: Pytester):\n        class CapturedWarnings:\n            captured: list[\n                tuple[warnings.WarningMessage, tuple[str, int, str] | None]\n            ] = []\n\n            @classmethod\n            def pytest_warning_recorded(cls, warning_message, when, nodeid, location):\n                cls.captured.append((warning_message, location))\n\n        pytester.plugins = [CapturedWarnings()]\n\n        return CapturedWarnings\n\n    def test_issue4445_rewrite(self, pytester: Pytester, capwarn) -> None:\n        \"\"\"#4445: Make sure the warning points to a reasonable location\n        See origin of _issue_warning_captured at: _pytest.assertion.rewrite.py:241\n        \"\"\"\n        pytester.makepyfile(some_mod=\"\")\n        conftest = pytester.makeconftest(\n            \"\"\"\n                import some_mod\n                import pytest\n\n                pytest.register_assert_rewrite(\"some_mod\")\n            \"\"\"\n        )\n        pytester.parseconfig()\n\n        # with stacklevel=5 the warning originates from register_assert_rewrite\n        # function in the created conftest.py\n        assert len(capwarn.captured) == 1\n        warning, location = capwarn.captured.pop()\n        file, lineno, func = location\n\n        assert \"Module already imported\" in str(warning.message)\n        assert file == str(conftest)\n        assert func == \"<module>\"  # the above conftest.py\n        assert lineno == 4\n\n    def test_issue4445_initial_conftest(self, pytester: Pytester, capwarn) -> None:\n        \"\"\"#4445: Make sure the warning points to a reasonable location.\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import nothing\n            \"\"\"\n        )\n        pytester.parseconfig(\"--help\")\n\n        # with stacklevel=2 the warning should originate from config._preparse and is\n        # thrown by an erroneous conftest.py\n        assert len(capwarn.captured) == 1\n        warning, location = capwarn.captured.pop()\n        file, _, func = location\n\n        assert \"could not load initial conftests\" in str(warning.message)\n        assert f\"config{os.sep}__init__.py\" in file\n        assert func == \"parse\"\n\n    @pytest.mark.filterwarnings(\"default\")\n    def test_conftest_warning_captured(self, pytester: Pytester) -> None:\n        \"\"\"Warnings raised during importing of conftest.py files is captured (#2891).\"\"\"\n        pytester.makeconftest(\n            \"\"\"\n            import warnings\n            warnings.warn(UserWarning(\"my custom warning\"))\n            \"\"\"\n        )\n        result = pytester.runpytest()\n        result.stdout.fnmatch_lines(\n            [\"conftest.py:2\", \"*UserWarning: my custom warning*\"]\n        )\n\n    def test_issue4445_import_plugin(self, pytester: Pytester, capwarn) -> None:\n        \"\"\"#4445: Make sure the warning points to a reasonable location\"\"\"\n        pytester.makepyfile(\n            some_plugin=\"\"\"\n            import pytest\n            pytest.skip(\"thing\", allow_module_level=True)\n            \"\"\"\n        )\n        pytester.syspathinsert()\n        pytester.parseconfig(\"-p\", \"some_plugin\")\n\n        # with stacklevel=2 the warning should originate from\n        # config.PytestPluginManager.import_plugin is thrown by a skipped plugin\n\n        assert len(capwarn.captured) == 1\n        warning, location = capwarn.captured.pop()\n        file, _, func = location\n\n        assert \"skipped plugin 'some_plugin': thing\" in str(warning.message)\n        assert f\"config{os.sep}__init__.py\" in file\n        assert func == \"_warn_about_skipped_plugins\"\n\n    def test_issue4445_issue5928_mark_generator(self, pytester: Pytester) -> None:\n        \"\"\"#4445 and #5928: Make sure the warning from an unknown mark points to\n        the test file where this mark is used.\n        \"\"\"\n        testfile = pytester.makepyfile(\n            \"\"\"\n            import pytest\n\n            @pytest.mark.unknown\n            def test_it():\n                pass\n            \"\"\"\n        )\n        result = pytester.runpytest_subprocess()\n        # with stacklevel=2 the warning should originate from the above created test file\n        result.stdout.fnmatch_lines_random(\n            [\n                f\"*{testfile}:3*\",\n                \"*Unknown pytest.mark.unknown*\",\n            ]\n        )\n\n\ndef test_warning_on_testpaths_not_found(pytester: Pytester) -> None:\n    # Check for warning when testpaths set, but not found by glob\n    pytester.makeini(\n        \"\"\"\n        [pytest]\n        testpaths = absent\n        \"\"\"\n    )\n    result = pytester.runpytest()\n    result.stdout.fnmatch_lines(\n        [\"*ConfigWarning: No files were found in testpaths*\", \"*1 warning*\"]\n    )\n\n\ndef test_resource_warning(pytester: Pytester, monkeypatch: pytest.MonkeyPatch) -> None:\n    # Some platforms (notably PyPy) don't have tracemalloc.\n    # We choose to explicitly not skip this in case tracemalloc is not\n    # available, using `importorskip(\"tracemalloc\")` for example,\n    # because we want to ensure the same code path does not break in those platforms.\n    try:\n        import tracemalloc  # noqa: F401\n\n        has_tracemalloc = True\n    except ImportError:\n        has_tracemalloc = False\n\n    # Explicitly disable PYTHONTRACEMALLOC in case pytest's test suite is running\n    # with it enabled.\n    monkeypatch.delenv(\"PYTHONTRACEMALLOC\", raising=False)\n\n    pytester.makepyfile(\n        \"\"\"\n        def open_file(p):\n            f = p.open(\"r\", encoding=\"utf-8\")\n            assert p.read_text() == \"hello\"\n\n        def test_resource_warning(tmp_path):\n            p = tmp_path.joinpath(\"foo.txt\")\n            p.write_text(\"hello\", encoding=\"utf-8\")\n            open_file(p)\n        \"\"\"\n    )\n    result = pytester.run(sys.executable, \"-Xdev\", \"-m\", \"pytest\")\n    expected_extra = (\n        [\n            \"*ResourceWarning* unclosed file*\",\n            \"*Enable tracemalloc to get traceback where the object was allocated*\",\n            \"*See https* for more info.\",\n        ]\n        if has_tracemalloc\n        else []\n    )\n    result.stdout.fnmatch_lines([*expected_extra, \"*1 passed*\"])\n\n    monkeypatch.setenv(\"PYTHONTRACEMALLOC\", \"20\")\n\n    result = pytester.run(sys.executable, \"-Xdev\", \"-m\", \"pytest\")\n    expected_extra = (\n        [\n            \"*ResourceWarning* unclosed file*\",\n            \"*Object allocated at*\",\n        ]\n        if has_tracemalloc\n        else []\n    )\n    result.stdout.fnmatch_lines([*expected_extra, \"*1 passed*\"])\n"
  },
  {
    "path": "testing/typing_checks.py",
    "content": "# mypy: allow-untyped-defs\n\"\"\"File for checking typing issues.\n\nThis file is not executed, it is only checked by mypy to ensure that\nnone of the code triggers any mypy errors.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nfrom typing import Literal\n\nfrom typing_extensions import assert_type\n\nimport pytest\nfrom pytest import MonkeyPatch\nfrom pytest import TestReport\n\n\n# Issue #7488.\n@pytest.mark.xfail(raises=RuntimeError)\ndef check_mark_xfail_raises() -> None:\n    pass\n\n\n# Issue #7494.\n@pytest.fixture(params=[(0, 0), (1, 1)], ids=lambda x: str(x[0]))\ndef check_fixture_ids_callable() -> None:\n    pass\n\n\n# Issue #7494.\n@pytest.mark.parametrize(\"func\", [str, int], ids=lambda x: str(x.__name__))\ndef check_parametrize_ids_callable(func) -> None:\n    pass\n\n\n# Issue #10999.\ndef check_monkeypatch_typeddict(monkeypatch: MonkeyPatch) -> None:\n    from typing import TypedDict\n\n    class Foo(TypedDict):\n        x: int\n        y: float\n\n    a: Foo = {\"x\": 1, \"y\": 3.14}\n    monkeypatch.setitem(a, \"x\", 2)\n    monkeypatch.delitem(a, \"y\")\n\n\ndef check_raises_is_a_context_manager(val: bool) -> None:\n    with pytest.raises(RuntimeError) if val else contextlib.nullcontext() as excinfo:\n        pass\n    assert_type(excinfo, pytest.ExceptionInfo[RuntimeError] | None)\n\n\n# Issue #12941.\ndef check_testreport_attributes(report: TestReport) -> None:\n    assert_type(report.when, Literal[\"setup\", \"call\", \"teardown\"])\n    assert_type(report.location, tuple[str, int | None, str])\n\n\n# Test @pytest.mark.parametrize iterator argvalues deprecation.\n# Will be complain about unused type ignore if doesn't work.\n@pytest.mark.parametrize(\"x\", iter(range(10)))  # type: ignore[deprecated]\ndef test_it(x: int) -> None:\n    pass\n"
  },
  {
    "path": "testing/typing_raises_group.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Callable\nimport sys\n\nfrom typing_extensions import assert_type\n\nfrom _pytest.main import Failed as main_Failed\nfrom _pytest.outcomes import Failed\nfrom pytest import raises\nfrom pytest import RaisesExc\nfrom pytest import RaisesGroup\n\n\n# does not work\nassert_type(raises.Exception, Failed)  # type: ignore[assert-type, attr-defined]\n\n# FIXME: these are different for some reason(?)\nassert Failed is not main_Failed  # type: ignore[comparison-overlap]\n\nif sys.version_info < (3, 11):\n    from exceptiongroup import BaseExceptionGroup\n    from exceptiongroup import ExceptionGroup\n\n# split into functions to isolate the different scopes\n\n\ndef check_raisesexc_typevar_default(e: RaisesExc) -> None:\n    assert e.expected_exceptions is not None\n    _exc: type[BaseException] | tuple[type[BaseException], ...] = e.expected_exceptions\n    # this would previously pass, as the type would be `Any`\n    e.exception_type().blah()  # type: ignore\n\n\ndef check_basic_contextmanager() -> None:\n    with RaisesGroup(ValueError) as e:\n        raise ExceptionGroup(\"foo\", (ValueError(),))\n    assert_type(e.value, ExceptionGroup[ValueError])\n\n\ndef check_basic_matches() -> None:\n    # check that matches gets rid of the naked ValueError in the union\n    exc: ExceptionGroup[ValueError] | ValueError = ExceptionGroup(\"\", (ValueError(),))\n    if RaisesGroup(ValueError).matches(exc):\n        assert_type(exc, ExceptionGroup[ValueError])\n\n    # also check that BaseExceptionGroup shows up for BaseExceptions\n    if RaisesGroup(KeyboardInterrupt).matches(exc):\n        assert_type(exc, BaseExceptionGroup[KeyboardInterrupt])\n\n\ndef check_matches_with_different_exception_type() -> None:\n    e: BaseExceptionGroup[KeyboardInterrupt] = BaseExceptionGroup(\n        \"\",\n        (KeyboardInterrupt(),),\n    )\n\n    # note: it might be tempting to have this warn.\n    # however, that isn't possible with current typing\n    if RaisesGroup(ValueError).matches(e):\n        assert_type(e, ExceptionGroup[ValueError])\n\n\ndef check_raisesexc_init() -> None:\n    def check_exc(exc: BaseException) -> bool:\n        return isinstance(exc, ValueError)\n\n    # Check various combinations of constructor signatures.\n    # At least 1 arg must be provided.\n    RaisesExc()  # type: ignore\n    RaisesExc(ValueError)\n    RaisesExc(ValueError, match=\"regex\")\n    RaisesExc(ValueError, match=\"regex\", check=check_exc)\n    RaisesExc(match=\"regex\")\n    RaisesExc(check=check_exc)\n    RaisesExc(ValueError, match=\"regex\")\n    RaisesExc(match=\"regex\", check=check_exc)\n\n    def check_filenotfound(exc: FileNotFoundError) -> bool:\n        return not exc.filename.endswith(\".tmp\")\n\n    # If exception_type is provided, that narrows the `check` method's argument.\n    RaisesExc(FileNotFoundError, check=check_filenotfound)\n    RaisesExc(ValueError, check=check_filenotfound)  # type: ignore\n    RaisesExc(check=check_filenotfound)  # type: ignore\n    RaisesExc(FileNotFoundError, match=\"regex\", check=check_filenotfound)\n\n    # exceptions are pos-only\n    RaisesExc(expected_exception=ValueError)  # type: ignore\n    # match and check are kw-only\n    RaisesExc(ValueError, \"regex\")  # type: ignore\n\n\ndef raisesgroup_check_type_narrowing() -> None:\n    \"\"\"Check type narrowing on the `check` argument to `RaisesGroup`.\n    All `type: ignore`s are correctly pointing out type errors.\n    \"\"\"\n\n    def handle_exc(e: BaseExceptionGroup[BaseException]) -> bool:\n        return True\n\n    def handle_kbi(e: BaseExceptionGroup[KeyboardInterrupt]) -> bool:\n        return True\n\n    def handle_value(e: BaseExceptionGroup[ValueError]) -> bool:\n        return True\n\n    RaisesGroup(BaseException, check=handle_exc)\n    RaisesGroup(BaseException, check=handle_kbi)  # type: ignore\n\n    RaisesGroup(Exception, check=handle_exc)\n    RaisesGroup(Exception, check=handle_value)  # type: ignore\n\n    RaisesGroup(KeyboardInterrupt, check=handle_exc)\n    RaisesGroup(KeyboardInterrupt, check=handle_kbi)\n    RaisesGroup(KeyboardInterrupt, check=handle_value)  # type: ignore\n\n    RaisesGroup(ValueError, check=handle_exc)\n    RaisesGroup(ValueError, check=handle_kbi)  # type: ignore\n    RaisesGroup(ValueError, check=handle_value)\n\n    RaisesGroup(ValueError, KeyboardInterrupt, check=handle_exc)\n    RaisesGroup(ValueError, KeyboardInterrupt, check=handle_kbi)  # type: ignore\n    RaisesGroup(ValueError, KeyboardInterrupt, check=handle_value)  # type: ignore\n\n\ndef raisesgroup_narrow_baseexceptiongroup() -> None:\n    \"\"\"Check type narrowing specifically for the container exceptiongroup.\"\"\"\n\n    def handle_group(e: ExceptionGroup[Exception]) -> bool:\n        return True\n\n    def handle_group_value(e: ExceptionGroup[ValueError]) -> bool:\n        return True\n\n    RaisesGroup(ValueError, check=handle_group_value)\n\n    RaisesGroup(Exception, check=handle_group)\n\n\ndef check_raisesexc_transparent() -> None:\n    with RaisesGroup(RaisesExc(ValueError)) as e:\n        ...\n    _: BaseExceptionGroup[ValueError] = e.value\n    assert_type(e.value, ExceptionGroup[ValueError])\n\n\ndef check_nested_raisesgroups_contextmanager() -> None:\n    with RaisesGroup(RaisesGroup(ValueError)) as excinfo:\n        raise ExceptionGroup(\"foo\", (ValueError(),))\n\n    _: BaseExceptionGroup[BaseExceptionGroup[ValueError]] = excinfo.value\n\n    assert_type(\n        excinfo.value,\n        ExceptionGroup[ExceptionGroup[ValueError]],\n    )\n\n    assert_type(\n        excinfo.value.exceptions[0],\n        # this union is because of how typeshed defines .exceptions\n        ExceptionGroup[ValueError] | ExceptionGroup[ExceptionGroup[ValueError]],\n    )\n\n\ndef check_nested_raisesgroups_matches() -> None:\n    \"\"\"Check nested RaisesGroup with .matches\"\"\"\n    exc: ExceptionGroup[ExceptionGroup[ValueError]] = ExceptionGroup(\n        \"\",\n        (ExceptionGroup(\"\", (ValueError(),)),),\n    )\n\n    if RaisesGroup(RaisesGroup(ValueError)).matches(exc):\n        assert_type(exc, ExceptionGroup[ExceptionGroup[ValueError]])\n\n\ndef check_multiple_exceptions_1() -> None:\n    a = RaisesGroup(ValueError, ValueError)\n    b = RaisesGroup(RaisesExc(ValueError), RaisesExc(ValueError))\n    c = RaisesGroup(ValueError, RaisesExc(ValueError))\n\n    d: RaisesGroup[ValueError]\n    d = a\n    d = b\n    d = c\n    assert d\n\n\ndef check_multiple_exceptions_2() -> None:\n    # This previously failed due to lack of covariance in the TypeVar\n    a = RaisesGroup(RaisesExc(ValueError), RaisesExc(TypeError))\n    b = RaisesGroup(RaisesExc(ValueError), TypeError)\n    c = RaisesGroup(ValueError, TypeError)\n\n    d: RaisesGroup[Exception]\n    d = a\n    d = b\n    d = c\n    assert d\n\n\ndef check_raisesgroup_overloads() -> None:\n    # allow_unwrapped=True does not allow:\n    # multiple exceptions\n    RaisesGroup(ValueError, TypeError, allow_unwrapped=True)  # type: ignore\n    # nested RaisesGroup\n    RaisesGroup(RaisesGroup(ValueError), allow_unwrapped=True)  # type: ignore\n    # specifying match\n    RaisesGroup(ValueError, match=\"foo\", allow_unwrapped=True)  # type: ignore\n    # specifying check\n    RaisesGroup(ValueError, check=bool, allow_unwrapped=True)  # type: ignore\n    # allowed variants\n    RaisesGroup(ValueError, allow_unwrapped=True)\n    RaisesGroup(ValueError, allow_unwrapped=True, flatten_subgroups=True)\n    RaisesGroup(RaisesExc(ValueError), allow_unwrapped=True)\n\n    # flatten_subgroups=True does not allow nested RaisesGroup\n    RaisesGroup(RaisesGroup(ValueError), flatten_subgroups=True)  # type: ignore\n    # but rest is plenty fine\n    RaisesGroup(ValueError, TypeError, flatten_subgroups=True)\n    RaisesGroup(ValueError, match=\"foo\", flatten_subgroups=True)\n    RaisesGroup(ValueError, check=bool, flatten_subgroups=True)\n    RaisesGroup(ValueError, flatten_subgroups=True)\n    RaisesGroup(RaisesExc(ValueError), flatten_subgroups=True)\n\n    # if they're both false we can of course specify nested raisesgroup\n    RaisesGroup(RaisesGroup(ValueError))\n\n\ndef check_triple_nested_raisesgroup() -> None:\n    with RaisesGroup(RaisesGroup(RaisesGroup(ValueError))) as e:\n        assert_type(e.value, ExceptionGroup[ExceptionGroup[ExceptionGroup[ValueError]]])\n\n\ndef check_check_typing() -> None:\n    # `BaseExceptiongroup` should perhaps be `ExceptionGroup`, but close enough\n    assert_type(\n        RaisesGroup(ValueError).check,\n        Callable[[BaseExceptionGroup[ValueError]], bool] | None,\n    )\n"
  },
  {
    "path": "tox.ini",
    "content": "[tox]\nrequires =\n    tox >= 4\nenvlist =\n    linting\n    py310\n    py311\n    py312\n    py313\n    py314\n    pypy3\n    py310-{pexpect,xdist,twisted24,twisted25,asynctest,numpy,pluggymain,pylib}\n    doctesting\n    doctesting-coverage\n    plugins\n    py310-freeze\n    docs\n    docs-checklinks\n\n    # checks that 3.11 native ExceptionGroup works with exceptiongroup\n    # not included in CI.\n    py311-exceptiongroup\n\n\n\n[pkgenv]\n# NOTE: This section tweaks how Tox manages the PEP 517 build\n# NOTE: environment where it assembles wheels (editable and regular)\n# NOTE: for further installing them into regular testenvs.\n#\n# NOTE: `[testenv:.pkg]` does not work due to a regression in tox v4.14.1\n# NOTE: so `[pkgenv]` is being used in place of it.\n# Refs:\n# * https://github.com/tox-dev/tox/pull/3237\n# * https://github.com/tox-dev/tox/issues/3238\n# * https://github.com/tox-dev/tox/issues/3292\n# * https://hynek.me/articles/turbo-charge-tox/\n#\n# NOTE: The `SETUPTOOLS_SCM_PRETEND_VERSION_FOR_PYTEST` environment\n# NOTE: variable allows enforcing a pre-determined version for use in\n# NOTE: the wheel being installed into usual testenvs.\npass_env =\n  SETUPTOOLS_SCM_PRETEND_VERSION_FOR_PYTEST\n\n\n[testenv]\ndescription =\n    run the tests\n    coverage: collecting coverage\n    exceptiongroup: against `exceptiongroup`\n    nobyte: in no-bytecode mode\n    lsof: with `--lsof` pytest CLI option\n    numpy: against `numpy`\n    pexpect: against `pexpect`\n    pluggymain: against the bleeding edge `pluggy` from Git\n    pylib: against `py` lib\n    twisted24: against the unit test extras with twisted prior to 24.0\n    twisted25: against the unit test extras with twisted 25.0 or later\n    asynctest: against the unit test extras with asynctest\n    xdist: with pytest in parallel mode\n    under `{basepython}`\n    doctesting: including doctests\ncommands =\n    {env:_PYTEST_TOX_COVERAGE_RUN:} pytest {posargs:{env:_PYTEST_TOX_DEFAULT_POSARGS:}}\n    doctesting: {env:_PYTEST_TOX_COVERAGE_RUN:} pytest --doctest-modules {env:_PYTEST_TOX_POSARGS_JUNIT:} --pyargs _pytest\n    coverage: coverage combine\n    coverage: coverage report -m\n    # Run `coverage xml` only on CI.\n    coverage: python -c 'import os; os.environ.get(\"CI\") and os.execlp(\"coverage\", \"coverage\", \"xml\")'\npassenv =\n    COVERAGE_*\n    PYTEST_ADDOPTS\n    TERM\n    CI\nsetenv =\n    _PYTEST_TOX_DEFAULT_POSARGS={env:_PYTEST_TOX_POSARGS_DOCTESTING:} {env:_PYTEST_TOX_POSARGS_JUNIT:} {env:_PYTEST_TOX_POSARGS_LSOF:} {env:_PYTEST_TOX_POSARGS_XDIST:} {env:_PYTEST_FILES:}\n\n    # See https://docs.python.org/3/library/io.html#io-encoding-warning\n    # If we don't enable this, neither can any of our downstream users!\n    # pylib is not PYTHONWARNDEFAULTENCODING clean, so don't set for it.\n    !pylib: PYTHONWARNDEFAULTENCODING=1\n\n    # Configuration to run with coverage similar to CI, e.g.\n    # \"tox -e py313-coverage\".\n    coverage: _PYTEST_TOX_COVERAGE_RUN=coverage run -m\n\n    doctesting: _PYTEST_TOX_POSARGS_DOCTESTING=doc/en\n\n    # The configurations below are related only to standard unittest support.\n    # Run only tests from test_unittest.py.\n    asynctest: _PYTEST_FILES=testing/test_unittest.py\n    twisted24: _PYTEST_FILES=testing/test_unittest.py\n    twisted25: _PYTEST_FILES=testing/test_unittest.py\n\n    nobyte: PYTHONDONTWRITEBYTECODE=1\n\n    lsof: _PYTEST_TOX_POSARGS_LSOF=--lsof\n\n    xdist: _PYTEST_TOX_POSARGS_XDIST=-n auto\nextras = dev\ndeps =\n    coverage: coverage>=7.10\n    doctesting: PyYAML\n    exceptiongroup: exceptiongroup>=1.0.0rc8\n    numpy: numpy>=1.19.4\n    pexpect: pexpect>=4.8.0\n    pluggymain: pluggy @ git+https://github.com/pytest-dev/pluggy.git\n    pylib: py>=1.8.2\n    twisted24: twisted<25\n    twisted25: twisted>=25\n    asynctest: asynctest\n    xdist: pytest-xdist>=2.1.0\n# Can use the same wheel for all environments.\npackage = wheel\nwheel_build_env = .pkg\n\n[testenv:linting]\ndescription =\n    run pre-commit-defined linters under `{basepython}`\nskip_install = True\ndeps = pre-commit>=2.9.3\ncommands = pre-commit run --all-files --show-diff-on-failure {posargs:}\nsetenv =\n    # pre-commit and tools it launches are not clean of this warning.\n    PYTHONWARNDEFAULTENCODING=\n\n[testenv:docs]\ndescription =\n    build the documentation site under \\\n    `{toxinidir}{/}doc{/}en{/}_build{/}html` with `{basepython}`\nbasepython = python3.13 # Sync with .readthedocs.yaml to get errors.\nusedevelop = True\ndeps =\n    -r{toxinidir}/doc/en/requirements.txt\ncommands =\n    sphinx-build \\\n      -j auto \\\n      -W --keep-going \\\n      -b html doc/en doc/en/_build/html \\\n      {posargs:}\nsetenv =\n    # Sphinx is not clean of this warning.\n    PYTHONWARNDEFAULTENCODING=\n\n[testenv:docs-checklinks]\ndescription =\n    check the links in the documentation with `{basepython}`\nusedevelop = True\nchangedir = doc/en\ndeps = -r{toxinidir}/doc/en/requirements.txt\ncommands =\n    sphinx-build -W -q --keep-going -b linkcheck . _build\nsetenv =\n    # Sphinx is not clean of this warning.\n    PYTHONWARNDEFAULTENCODING=\n\n[testenv:regen]\ndescription =\n    regenerate documentation examples under `{basepython}`\nchangedir = doc/en\ndeps =\n    PyYAML\n    regendoc>=0.8.1\n    sphinx\nallowlist_externals =\n    make\ncommands =\n    make regen\nsetenv =\n    # We don't want this warning to reach regen output.\n    PYTHONWARNDEFAULTENCODING=\n    # Remove CI markers: pytest auto-detects those and uses more verbose output, which is undesirable\n    # for the example documentation.\n    CI=\n    BUILD_NUMBER=\n\n[testenv:plugins]\ndescription =\n    run reverse dependency testing against pytest plugins under `{basepython}`\n# use latest versions of all plugins, including pre-releases\npip_pre=true\nchangedir = testing/plugins_integration\ndeps = -rtesting/plugins_integration/requirements.txt\nsetenv =\n    PYTHONPATH=.\ncommands =\n    pip check\n    pytest bdd_wallet.py\n    pytest --cov=. simple_integration.py\n    pytest --ds=django_settings simple_integration.py\n    pytest --html=simple.html simple_integration.py\n    pytest --reruns 5 simple_integration.py pytest_rerunfailures_integration.py\n    pytest pytest_anyio_integration.py\n    pytest pytest_asyncio_integration.py\n    pytest pytest_mock_integration.py\n    pytest pytest_trio_integration.py\n    pytest pytest_twisted_integration.py\n    pytest simple_integration.py --force-sugar --flakes\n\n[testenv:py310-freeze]\ndescription =\n    test pytest frozen with `pyinstaller` under `{basepython}`\nchangedir = testing/freeze\ndeps =\n    pyinstaller\ncommands =\n    {envpython} create_executable.py\n    {envpython} tox_run.py\n\n[testenv:release]\ndescription = do a release, required posarg of the version number\nusedevelop = True\npassenv = *\ndeps =\n    colorama\n    pre-commit>=2.9.3\n    towncrier\ncommands = python scripts/release.py {posargs}\n\n[testenv:prepare-release-pr]\ndescription = prepare a release PR from a manual trigger in GitHub actions\nusedevelop = {[testenv:release]usedevelop}\npassenv = {[testenv:release]passenv}\ndeps = {[testenv:release]deps}\ncommands = python scripts/prepare-release-pr.py {posargs}\n\n[testenv:generate-gh-release-notes]\ndescription = generate release notes that can be published as GitHub Release\nusedevelop = True\ndeps =\n    pypandoc_binary\ncommands = python scripts/generate-gh-release-notes.py {posargs}\n\n[testenv:update-plugin-list]\ndescription = update the plugin list\nskip_install = True\ndeps =\n    packaging\n    requests\n    tabulate[widechars]\n    tqdm\n    requests-cache\n    platformdirs\ncommands = python scripts/update-plugin-list.py {posargs}\n"
  }
]