Compare commits
458 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2b595ad32b | |||
| a98b00cd09 | |||
| 215ea7fd03 | |||
| b31db4809b | |||
| f6adebb990 | |||
| b90e7b84d0 | |||
| 19807ab79a | |||
| 3e52124185 | |||
| 1eca228bd5 | |||
| cab02e67d7 | |||
| 64dbc7a0a1 | |||
| 60d992677d | |||
| 0079decf29 | |||
| 3a58fc2d44 | |||
| 39b6bb551c | |||
| 9fbd67dd4b | |||
| eca93db05b | |||
| fb701b538c | |||
| 314e623304 | |||
| 62e75c7d55 | |||
| fd30759d94 | |||
| eb984a717a | |||
| 54f0fb3c63 | |||
| 49a4ed14cf | |||
| f513d33d5a | |||
| 857e34ef85 | |||
| 99dfc19fe6 | |||
| 56544c11b5 | |||
| 7710e18b4c | |||
| 791b51d0fa | |||
| bc4e70e048 | |||
| b817aa457c | |||
| 66b28912ac | |||
| cca029d55e | |||
| d5466b3917 | |||
| 4fce29f15d | |||
| 69e3973d86 | |||
| c842893b02 | |||
| 506b10d295 | |||
| 05061493cb | |||
| f97f3dc3a3 | |||
| 3c31b0132f | |||
| 593178d909 | |||
| 54d5a63d14 | |||
| b55e264a67 | |||
| 13d6114c0a | |||
| b635e16d30 | |||
| a092b3ab36 | |||
| a006dabf6e | |||
| aa7e9de91d | |||
| 6aec32163d | |||
| 2f33ea87c8 | |||
| 1ada62e237 | |||
| 50b232b0cb | |||
| 496196b15c | |||
| 0314b50c52 | |||
| 8e2de91bf8 | |||
| 692ab1160b | |||
| 549839bac5 | |||
| 646a46e5f4 | |||
| f07017f91b | |||
| a17d3b0c44 | |||
| bbec1ce67f | |||
| 5a040aef97 | |||
| c1d2168df6 | |||
| bbe7cbae4a | |||
| deae8f47f6 | |||
| 10f55f79af | |||
| a6d244343f | |||
| 2b552c2240 | |||
| 54d7b9a08e | |||
| 6afc02abca | |||
| e75e2d66a0 | |||
| 66db0b7522 | |||
| 3a68c08426 | |||
| 9e1804a6ee | |||
| bc2c3b66aa | |||
| d84ed48f39 | |||
| ffe49ac17c | |||
| d352098261 | |||
| c5c562b645 | |||
| d543a45a68 | |||
| f341a5c559 | |||
| 1027dc8c09 | |||
| 6b905ee6dc | |||
| 508be0b2bf | |||
| 02a9371259 | |||
| dc0cb0d149 | |||
| 82344ba4f8 | |||
| 59d8f8a223 | |||
| ed4c18f686 | |||
| 6660d45521 | |||
| af078f3a96 | |||
| 73349ef3e1 | |||
| 63c4d45c59 | |||
| eebbfc65c9 | |||
| 382209d9e9 | |||
| 00e2f1c15c | |||
| 8a151774b8 | |||
| a7c1fc204b | |||
| 965e942dfb | |||
| 349f4bffa0 | |||
| 49abbf2485 | |||
| 19dda7c9bd | |||
| baada535a3 | |||
| c477ecd146 | |||
| 36d19f2135 | |||
| 8490ff5277 | |||
| 3dac833a52 | |||
| 36b6384ff2 | |||
| 31df38f6a7 | |||
| 2a33e6ab61 | |||
| 7fada7127e | |||
| 3a8d401ac7 | |||
| 2b6622fdd3 | |||
| 0bc9ffcc87 | |||
| f3d7e984ab | |||
| 452617686c | |||
| 6e7917c1a0 | |||
| 15ac0349b2 | |||
| 86602ce6e0 | |||
| c543e0c4e8 | |||
| f13f4360d3 | |||
| b7d4de1ea9 | |||
| a9c66172d4 | |||
| 3de63f9a9b | |||
| f5797abb62 | |||
| b735f9377a | |||
| d8c5e8805f | |||
| 07b380bb3a | |||
| 78c2c48c67 | |||
| 8a40fc5315 | |||
| 196f01965e | |||
| 3bf2bc55b1 | |||
| 571dc6b220 | |||
| d0abfb1c2a | |||
| 81113c1a90 | |||
| 784ba85b17 | |||
| a28d595b46 | |||
| c42bb36009 | |||
| 13e594a314 | |||
| 4e7486d3fb | |||
| d8c783268c | |||
| 3c1534944c | |||
| a501518a26 | |||
| 680f3e2097 | |||
| ed5d4e1269 | |||
| 8e7ce60c7d | |||
| 2bc036e50a | |||
| 79c2e92bb8 | |||
| 4da0689653 | |||
| 9be1e3fac8 | |||
| 0c21d60349 | |||
| 4545fcff05 | |||
| 24ef7c98e8 | |||
| c4981f5a1b | |||
| 7a15bad89b | |||
| 72cac9b1af | |||
| 2df0d9656c | |||
| 4677580cae | |||
| 14919c4bbb | |||
| 06007de7ba | |||
| 4ee6e900a0 | |||
| eab875509d | |||
| 2be1b8f355 | |||
| 594413e8f0 | |||
| ce3e2e922b | |||
| 59b8ec3ce1 | |||
| ae9dbf5006 | |||
| 7e8a4849d8 | |||
| e3294398d6 | |||
| b1fb9a9c8d | |||
| 8c52dc5b7e | |||
| 0fdacb6db5 | |||
| 256ab097a2 | |||
| 5bd41befa8 | |||
| 246129089c | |||
| 34765f6b2e | |||
| 33a083e844 | |||
| 77d2c9631a | |||
| d416fbab91 | |||
| f53b49c8c4 | |||
| 85da6cad11 | |||
| c326bd5669 | |||
| a734dab00d | |||
| 1e0aa16908 | |||
| b34eb0860c | |||
| 77e34526e8 | |||
| abf4941f3e | |||
| b4ae5e4a35 | |||
| 649b2e7f30 | |||
| 6ad32a9c5c | |||
| 50f390f015 | |||
| 4ed2b3a733 | |||
| 7f4b63b143 | |||
| 245a8c23dd | |||
| a9bbfb87d6 | |||
| 1caa099e42 | |||
| 4b77638ba8 | |||
| 0fc3a977a9 | |||
| adaa463ee3 | |||
| 42776c0949 | |||
| 059bc2443a | |||
| 932264d8fd | |||
| d9d890ee15 | |||
| 71aa1388e0 | |||
| 69f2855cc8 | |||
| 3039391b83 | |||
| 832100955a | |||
| bec2b8ee3a | |||
| 7378f35b03 | |||
| b6eaf319d1 | |||
| 2e7c718373 | |||
| 08dfd3124c | |||
| 56862c03cb | |||
| 67e29d2548 | |||
| cb65f64572 | |||
| f425dfc158 | |||
| 63d2f7f7f8 | |||
| 739322af03 | |||
| beae7fd0ba | |||
| 7431750bb6 | |||
| cb7f5ed3b1 | |||
| c72d202317 | |||
| cc0092b9d8 | |||
| 433efaeaa9 | |||
| 4d430ea6ff | |||
| abd5df4b3c | |||
| 58cf20edf0 | |||
| f43ddd8acd | |||
| 1c31a7e659 | |||
| c0e3071fdf | |||
| b4ab2f0942 | |||
| dbc1017b08 | |||
| 70659b8c34 | |||
| 3bf15135e4 | |||
| 6c57cc1727 | |||
| c0843f94e4 | |||
| 8c5487fd6b | |||
| 4696ba74f9 | |||
| 34a285986e | |||
| b8e2f42ec1 | |||
| 70cac3d464 | |||
| c1d134172c | |||
| cbcb3a356e | |||
| 09b2c95320 | |||
| c2b1d5b368 | |||
| 5c513a5fb3 | |||
| 7b9f71d84f | |||
| 334d6514c6 | |||
| f6dc71c8de | |||
| 8c60fa1ef9 | |||
| b83a74a303 | |||
| 9c5b6fbab2 | |||
| b1948c60ac | |||
| da68c9d5bc | |||
| 29041e1e1f | |||
| dda7673f57 | |||
| 7dc540f258 | |||
| 4cd0322ca1 | |||
| 966d4fb3e4 | |||
| 8726597321 | |||
| aa83fa353c | |||
| 4449bdc068 | |||
| 929e7d5ae0 | |||
| 6d7973942f | |||
| 4414c4adae | |||
| b99541e744 | |||
| 5f57481563 | |||
| 04de180f41 | |||
| b08c1dcf0e | |||
| 3e590fe79e | |||
| 7dcabc1f49 | |||
| 2941da0f2b | |||
| 1b47de7d7f | |||
| 85000f037f | |||
| c34eaaaa1c | |||
| 06738e36df | |||
| 94bc31b07d | |||
| b961ef5b79 | |||
| bd642fac70 | |||
| da9a2b584e | |||
| 8bbd35aa69 | |||
| 0b1e9ba270 | |||
| f92c4a77ad | |||
| 9a037a5713 | |||
| 11fb5cd331 | |||
| 62d975a69e | |||
| aafac5578c | |||
| 2b70e7f4df | |||
| d2a206683c | |||
| f29f79e39f | |||
| c7e784f95d | |||
| 0a7b8722e5 | |||
| aa55975c7d | |||
| 141c5e5a89 | |||
| cba65e74b3 | |||
| 74691346bd | |||
| 6db715c205 | |||
| 1e6a587363 | |||
| 052da7128b | |||
| cdc287d21a | |||
| 5a9536cf42 | |||
| 17c385180d | |||
| fab696dcd1 | |||
| 2cd41651bb | |||
| 5ef064b602 | |||
| d6b837e2d3 | |||
| 96412d19ab | |||
| bb94e83b49 | |||
| 1a50e5222f | |||
| 27c94f573c | |||
| 04be900d06 | |||
| fe2c74cb1a | |||
| 083285948f | |||
| 433c7376c5 | |||
| 5adfb0e187 | |||
| c2f684fcd6 | |||
| 130c954bb1 | |||
| e54c6a1362 | |||
| 9a8f5dd73e | |||
| 6017666fe1 | |||
| a72e8b3d3e | |||
| 0efd7a6ec6 | |||
| c533015c56 | |||
| e547cd565d | |||
| a47e91e077 | |||
| 420dc7824b | |||
| c988e49af6 | |||
| 31f9e5bcdd | |||
| 9a9acf13f8 | |||
| 8ac6dce2c7 | |||
| 0e62861e84 | |||
| 611b579d21 | |||
| 8469f44401 | |||
| a1ed6839e3 | |||
| 08c0eb661e | |||
| 1feb857fcc | |||
| 296b642eb3 | |||
| ee10ecdf7e | |||
| 73c2d1c6e3 | |||
| 7b977f4beb | |||
| 5d28a58640 | |||
| 5d20e28538 | |||
| cc0fbbefa0 | |||
| 56c266640e | |||
| 69fb79e741 | |||
| 90d2adf0e8 | |||
| c5432a18e7 | |||
| 16781f9b8c | |||
| a88c0f3bb0 | |||
| ccdee08ddd | |||
| a29f4aff98 | |||
| 58af76122f | |||
| 29462b1277 | |||
| 37316ed0de | |||
| 231e220635 | |||
| 93fdb3ecb7 | |||
| a4a8763ebf | |||
| 31a9c5c667 | |||
| db139307ce | |||
| 644a81af37 | |||
| f6aa9d661d | |||
| 933156b296 | |||
| 23c8f3d234 | |||
| 5f9d68c8d9 | |||
| 2f62e6ec96 | |||
| 4ddf48b0a3 | |||
| f25b9f619b | |||
| 33bf91482e | |||
| 2ba8fd5bc5 | |||
| 306b33e755 | |||
| 3444d35c54 | |||
| 97383d2d5d | |||
| e580534df0 | |||
| f6db7ae749 | |||
| eb8b3ad929 | |||
| 21091a45d0 | |||
| d949b3f7d9 | |||
| 246815de13 | |||
| e598429c73 | |||
| 0347957aa7 | |||
| 1e8e46d456 | |||
| 7df405747a | |||
| 28e8c8582e | |||
| 1285caadf2 | |||
| 12971a37e1 | |||
| 715d0ca9d0 | |||
| 2b9f8f2f9b | |||
| ac9b65d890 | |||
| 8514fab409 | |||
| 988197c795 | |||
| 1ea7081752 | |||
| 6a3168e770 | |||
| 5800d39053 | |||
| 045dbc895d | |||
| a60a6a3fea | |||
| 4e3ec26487 | |||
| 86b62067b7 | |||
| ace71037ab | |||
| 2e8a319828 | |||
| 61095e4ba6 | |||
| 752a059cc2 | |||
| 99e20713fd | |||
| 26c62e1793 | |||
| 61dfdfcc3f | |||
| 9c2ee32069 | |||
| 765583dc34 | |||
| f0cf63a84a | |||
| 8fa775bcee | |||
| 539a5d70f2 | |||
| 1527130476 | |||
| 238b25ffa9 | |||
| e2269f8a5c | |||
| 16345bf689 | |||
| 79725c9102 | |||
| 387ec02021 | |||
| 3fcdbaf0c5 | |||
| 141b301d3d | |||
| 31595e8733 | |||
| 63c7338028 | |||
| 0eae340e13 | |||
| 1f10c59cd3 | |||
| 00ad12b9db | |||
| 592fee2263 | |||
| 176d2d7b4e | |||
| 05dcb22365 | |||
| cccb9d8530 | |||
| 67ab712480 | |||
| 250a0344ad | |||
| 3c359455e2 | |||
| d5ce9f5a16 | |||
| 0ebfa1d76d | |||
| e9dd3dffab | |||
| 3297bb24a9 | |||
| 6a6a32ceca | |||
| e503faeb6e | |||
| 4b6b91fda3 | |||
| 4c16b5af03 | |||
| b75cbee290 | |||
| eb22339dc3 | |||
| 63126643b9 | |||
| 8f64a39d0a | |||
| a18655f729 | |||
| 22756c28e5 | |||
| f196701cc1 | |||
| 1d70b022f0 | |||
| d52a6e6074 | |||
| 2bec21ef5f | |||
| 5c1756343f | |||
| a854ab97b9 | |||
| abfae83130 | |||
| 37fa0fb4d3 | |||
| e75cdae2bc | |||
| f0bf4c9681 | |||
| d87e1e67dd | |||
| 61f2b265a3 | |||
| f3053017b9 |
@@ -9,3 +9,9 @@ updates:
|
||||
allow:
|
||||
- dependency-type: direct
|
||||
- dependency-type: indirect
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
time: "03:00"
|
||||
open-pull-requests-limit: 10
|
||||
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: true
|
||||
|
||||
@@ -23,13 +23,13 @@ jobs:
|
||||
contents: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v2
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: "3.7"
|
||||
|
||||
@@ -43,9 +43,8 @@ jobs:
|
||||
python -m build
|
||||
|
||||
- name: Publish package to PyPI
|
||||
uses: pypa/gh-action-pypi-publish@master
|
||||
uses: pypa/gh-action-pypi-publish@release/v1
|
||||
with:
|
||||
user: __token__
|
||||
password: ${{ secrets.pypi_token }}
|
||||
|
||||
- name: Publish GitHub release notes
|
||||
|
||||
@@ -27,12 +27,12 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v2
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: "3.8"
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ jobs:
|
||||
- name: "windows-py37-pluggy"
|
||||
python: "3.7"
|
||||
os: windows-latest
|
||||
tox_env: "py37-pluggymain-xdist"
|
||||
tox_env: "py37-pluggymain-pylib-xdist"
|
||||
- name: "windows-py38"
|
||||
python: "3.8"
|
||||
os: windows-latest
|
||||
@@ -93,7 +93,7 @@ jobs:
|
||||
- name: "ubuntu-py37-pluggy"
|
||||
python: "3.7"
|
||||
os: ubuntu-latest
|
||||
tox_env: "py37-pluggymain-xdist"
|
||||
tox_env: "py37-pluggymain-pylib-xdist"
|
||||
- name: "ubuntu-py37-freeze"
|
||||
python: "3.7"
|
||||
os: ubuntu-latest
|
||||
@@ -154,13 +154,13 @@ jobs:
|
||||
use_coverage: true
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Python ${{ matrix.python }}
|
||||
uses: actions/setup-python@v2
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python }}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ on:
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
createPullRequest:
|
||||
update-plugin-list:
|
||||
if: github.repository_owner == 'pytest-dev'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
@@ -20,12 +20,12 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v2
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: 3.8
|
||||
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
run: python scripts/update-plugin-list.py
|
||||
|
||||
- name: Create Pull Request
|
||||
uses: peter-evans/create-pull-request@2455e1596942c2902952003bbb574afbbe2ab2e6
|
||||
uses: peter-evans/create-pull-request@2b011faafdcbc9ceb11414d64d0573f37c774b04
|
||||
with:
|
||||
commit-message: '[automated] Update plugin list'
|
||||
author: 'pytest bot <pytestbot@users.noreply.github.com>'
|
||||
|
||||
@@ -50,6 +50,7 @@ coverage.xml
|
||||
.project
|
||||
.settings
|
||||
.vscode
|
||||
__pycache__/
|
||||
|
||||
# generated by pip
|
||||
pip-wheel-metadata/
|
||||
|
||||
+12
-11
@@ -1,6 +1,8 @@
|
||||
default_language_version:
|
||||
python: "3.10"
|
||||
repos:
|
||||
- repo: https://github.com/psf/black
|
||||
rev: 22.3.0
|
||||
rev: 22.12.0
|
||||
hooks:
|
||||
- id: black
|
||||
args: [--safe, --quiet]
|
||||
@@ -10,7 +12,7 @@ repos:
|
||||
- id: blacken-docs
|
||||
additional_dependencies: [black==20.8b1]
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.1.0
|
||||
rev: v4.4.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: end-of-file-fixer
|
||||
@@ -20,8 +22,8 @@ repos:
|
||||
- id: debug-statements
|
||||
exclude: _pytest/(debugging|hookspec).py
|
||||
language_version: python3
|
||||
- repo: https://github.com/myint/autoflake
|
||||
rev: v1.4
|
||||
- repo: https://github.com/PyCQA/autoflake
|
||||
rev: v2.0.0
|
||||
hooks:
|
||||
- id: autoflake
|
||||
name: autoflake
|
||||
@@ -29,7 +31,7 @@ repos:
|
||||
language: python
|
||||
files: \.py$
|
||||
- repo: https://github.com/PyCQA/flake8
|
||||
rev: 4.0.1
|
||||
rev: 6.0.0
|
||||
hooks:
|
||||
- id: flake8
|
||||
language_version: python3
|
||||
@@ -37,33 +39,32 @@ repos:
|
||||
- flake8-typing-imports==1.12.0
|
||||
- flake8-docstrings==1.5.0
|
||||
- repo: https://github.com/asottile/reorder_python_imports
|
||||
rev: v3.0.1
|
||||
rev: v3.9.0
|
||||
hooks:
|
||||
- id: reorder-python-imports
|
||||
args: ['--application-directories=.:src', --py37-plus]
|
||||
- repo: https://github.com/asottile/pyupgrade
|
||||
rev: v2.31.0
|
||||
rev: v3.3.1
|
||||
hooks:
|
||||
- id: pyupgrade
|
||||
args: [--py37-plus]
|
||||
- repo: https://github.com/asottile/setup-cfg-fmt
|
||||
rev: v1.20.0
|
||||
rev: v2.2.0
|
||||
hooks:
|
||||
- id: setup-cfg-fmt
|
||||
args: [--max-py-version=3.10]
|
||||
args: ["--max-py-version=3.11", "--include-version-classifiers"]
|
||||
- repo: https://github.com/pre-commit/pygrep-hooks
|
||||
rev: v1.9.0
|
||||
hooks:
|
||||
- id: python-use-type-annotations
|
||||
- repo: https://github.com/pre-commit/mirrors-mypy
|
||||
rev: v0.931
|
||||
rev: v0.991
|
||||
hooks:
|
||||
- id: mypy
|
||||
files: ^(src/|testing/)
|
||||
args: []
|
||||
additional_dependencies:
|
||||
- iniconfig>=1.1.0
|
||||
- py>=1.8.2
|
||||
- attrs>=19.2.0
|
||||
- packaging
|
||||
- tomli
|
||||
|
||||
+6
-3
@@ -2,9 +2,12 @@ version: 2
|
||||
|
||||
python:
|
||||
install:
|
||||
- requirements: doc/en/requirements.txt
|
||||
- method: pip
|
||||
path: .
|
||||
# Install pytest first, then doc/en/requirements.txt.
|
||||
# This order is important to honor any pins in doc/en/requirements.txt
|
||||
# when the pinned library is also a dependency of pytest.
|
||||
- method: pip
|
||||
path: .
|
||||
- requirements: doc/en/requirements.txt
|
||||
|
||||
build:
|
||||
os: ubuntu-20.04
|
||||
|
||||
@@ -43,8 +43,10 @@ Ariel Pillemer
|
||||
Armin Rigo
|
||||
Aron Coyle
|
||||
Aron Curzon
|
||||
Ashish Kurmi
|
||||
Aviral Verma
|
||||
Aviv Palivoda
|
||||
Babak Keyvani
|
||||
Barney Gale
|
||||
Ben Gartner
|
||||
Ben Webb
|
||||
@@ -56,6 +58,7 @@ Brian Maissy
|
||||
Brian Okken
|
||||
Brianna Laugher
|
||||
Bruno Oliveira
|
||||
Cal Jacobson
|
||||
Cal Leeming
|
||||
Carl Friedrich Bolz
|
||||
Carlos Jenkins
|
||||
@@ -63,9 +66,11 @@ Ceridwen
|
||||
Charles Cloud
|
||||
Charles Machalow
|
||||
Charnjit SiNGH (CCSJ)
|
||||
Cheuk Ting Ho
|
||||
Chris Lamb
|
||||
Chris NeJame
|
||||
Chris Rose
|
||||
Chris Wheeler
|
||||
Christian Boelsen
|
||||
Christian Fetzer
|
||||
Christian Neumüller
|
||||
@@ -85,6 +90,7 @@ Daniel Grana
|
||||
Daniel Hahler
|
||||
Daniel Nuri
|
||||
Daniel Sánchez Castelló
|
||||
Daniel Valenzuela Zenteno
|
||||
Daniel Wandschneider
|
||||
Daniele Procida
|
||||
Danielle Jenkins
|
||||
@@ -126,6 +132,7 @@ Feng Ma
|
||||
Florian Bruhin
|
||||
Florian Dahlitz
|
||||
Floris Bruynooghe
|
||||
Gabriel Landau
|
||||
Gabriel Reis
|
||||
Garvit Shubham
|
||||
Gene Wood
|
||||
@@ -151,12 +158,12 @@ Ian Bicking
|
||||
Ian Lesperance
|
||||
Ilya Konstantinov
|
||||
Ionuț Turturică
|
||||
Itxaso Aizpurua
|
||||
Iwan Briquemont
|
||||
Jaap Broekhuizen
|
||||
Jakob van Santen
|
||||
Jakub Mitoraj
|
||||
James Bourbeau
|
||||
James Frost
|
||||
Jan Balster
|
||||
Janne Vanhala
|
||||
Jason R. Coombs
|
||||
@@ -168,6 +175,7 @@ Jenni Rinker
|
||||
John Eddie Ayson
|
||||
John Litborn
|
||||
John Towler
|
||||
Jon Parise
|
||||
Jon Sonesen
|
||||
Jonas Obrist
|
||||
Jordan Guymon
|
||||
@@ -177,8 +185,8 @@ Joseph Hunkeler
|
||||
Josh Karpel
|
||||
Joshua Bronson
|
||||
Jurko Gospodnetić
|
||||
Justyna Janczyszyn
|
||||
Justice Ndou
|
||||
Justyna Janczyszyn
|
||||
Kale Kundert
|
||||
Kamran Ahmad
|
||||
Karl O. Pinc
|
||||
@@ -187,6 +195,7 @@ Katarzyna Jachim
|
||||
Katarzyna Król
|
||||
Katerina Koukiou
|
||||
Keri Volans
|
||||
Kevin C
|
||||
Kevin Cox
|
||||
Kevin Hierro Carrasco
|
||||
Kevin J. Foley
|
||||
@@ -216,6 +225,7 @@ Marcin Bachry
|
||||
Marco Gorelli
|
||||
Mark Abramowitz
|
||||
Mark Dickinson
|
||||
Marko Pacak
|
||||
Markus Unterwaditzer
|
||||
Martijn Faassen
|
||||
Martin Altmayer
|
||||
@@ -229,7 +239,6 @@ Matthias Hafner
|
||||
Maxim Filipenko
|
||||
Maximilian Cosmo Sitter
|
||||
mbyt
|
||||
Mickey Pashov
|
||||
Michael Aquilina
|
||||
Michael Birtwell
|
||||
Michael Droettboom
|
||||
@@ -238,6 +247,7 @@ Michael Krebs
|
||||
Michael Seifert
|
||||
Michal Wajszczuk
|
||||
Michał Zięba
|
||||
Mickey Pashov
|
||||
Mihai Capotă
|
||||
Mike Hoyle (hoylemd)
|
||||
Mike Lundy
|
||||
@@ -252,9 +262,9 @@ Niclas Olofsson
|
||||
Nicolas Delaby
|
||||
Nikolay Kondratyev
|
||||
Nipunn Koorapati
|
||||
Olga Matoula
|
||||
Oleg Pidsadnyi
|
||||
Oleg Sushchenko
|
||||
Olga Matoula
|
||||
Oliver Bestwalter
|
||||
Omar Kohl
|
||||
Omer Hadari
|
||||
@@ -270,6 +280,7 @@ Paweł Adamczak
|
||||
Pedro Algarvio
|
||||
Petter Strandmark
|
||||
Philipp Loose
|
||||
Pierre Sassoulas
|
||||
Pieter Mulder
|
||||
Piotr Banaszkiewicz
|
||||
Piotr Helm
|
||||
@@ -280,8 +291,8 @@ Pulkit Goyal
|
||||
Punyashloka Biswal
|
||||
Quentin Pradet
|
||||
Ralf Schmitt
|
||||
Ram Rachum
|
||||
Ralph Giles
|
||||
Ram Rachum
|
||||
Ran Benita
|
||||
Raphael Castaneda
|
||||
Raphael Pierzina
|
||||
@@ -298,6 +309,7 @@ Ruaridh Williamson
|
||||
Russel Winder
|
||||
Ryan Wooden
|
||||
Saiprasad Kale
|
||||
Samuel Colvin
|
||||
Samuel Dion-Girardeau
|
||||
Samuel Searles-Bryant
|
||||
Samuele Pedroni
|
||||
@@ -334,6 +346,7 @@ Thomas Grainger
|
||||
Thomas Hisch
|
||||
Tim Hoffmann
|
||||
Tim Strazny
|
||||
Tobias Diez
|
||||
Tom Dalton
|
||||
Tom Viner
|
||||
Tomáš Gavenčiak
|
||||
@@ -350,6 +363,7 @@ Victor Uriarte
|
||||
Vidar T. Fauske
|
||||
Virgil Dupras
|
||||
Vitaly Lashmanov
|
||||
Vivaan Verma
|
||||
Vlad Dragos
|
||||
Vlad Radziuk
|
||||
Vladyslav Rachek
|
||||
@@ -363,9 +377,11 @@ Xixi Zhao
|
||||
Xuan Luong
|
||||
Xuecong Liao
|
||||
Yoav Caspi
|
||||
Yusuke Kadowaki
|
||||
Yuval Shimon
|
||||
Zac Hatfield-Dodds
|
||||
Zachary Kneupper
|
||||
Zachary OBrien
|
||||
Zhouxin Qiu
|
||||
Zoltán Máté
|
||||
Zsolt Cserna
|
||||
|
||||
+7
-2
@@ -244,6 +244,11 @@ Here is a simple overview, with pytest-specific bits:
|
||||
be released in micro releases whereas features will be released in
|
||||
minor releases and incompatible changes in major releases.
|
||||
|
||||
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::
|
||||
|
||||
$ git remote add upstream https://github.com/pytest-dev/pytest
|
||||
$ git fetch upstream --tags
|
||||
|
||||
If you need some help with Git, follow this quick start
|
||||
guide: https://git.wiki.kernel.org/index.php/QuickStart
|
||||
|
||||
@@ -380,7 +385,7 @@ them.
|
||||
Backporting bug fixes for the next patch release
|
||||
------------------------------------------------
|
||||
|
||||
Pytest makes feature release every few weeks or months. In between, patch releases
|
||||
Pytest makes a feature release every few weeks or months. In between, patch releases
|
||||
are made to the previous feature release, containing bug fixes only. The bug fixes
|
||||
usually fix regressions, but may be any change that should reach users before the
|
||||
next feature release.
|
||||
@@ -389,7 +394,7 @@ Suppose for example that the latest release was 1.2.3, and you want to include
|
||||
a bug fix in 1.2.4 (check https://github.com/pytest-dev/pytest/releases for the
|
||||
actual latest release). The procedure for this is:
|
||||
|
||||
#. First, make sure the bug is fixed the ``main`` branch, with a regular pull
|
||||
#. First, make sure the bug is fixed in the ``main`` branch, with a regular pull
|
||||
request, as described above. An exception to this is if the bug fix is not
|
||||
applicable to ``main`` anymore.
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
If multiple errors are raised in teardown, we now re-raise an ``ExceptionGroup`` of them instead of discarding all but the last.
|
||||
@@ -0,0 +1 @@
|
||||
Fix 'importlib.abc.TraversableResources' deprecation warning in Python 3.12.
|
||||
@@ -0,0 +1 @@
|
||||
If a test is skipped from inside a fixture, the test summary now shows the test location instead of the fixture location.
|
||||
@@ -0,0 +1 @@
|
||||
Fix bug where sometimes pytest would use the file system root directory as :ref:`rootdir <rootdir>` on Windows.
|
||||
@@ -0,0 +1 @@
|
||||
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.
|
||||
@@ -1 +0,0 @@
|
||||
The documentation webpages now links to a canonical version to reduce outdated documentation in search engine results.
|
||||
@@ -0,0 +1,2 @@
|
||||
The full output of a test is no longer truncated if the truncation message would be longer than
|
||||
the hidden text. The line number shown has also been fixed.
|
||||
@@ -0,0 +1 @@
|
||||
``--log-disable`` CLI option added to disable individual loggers.
|
||||
@@ -0,0 +1,2 @@
|
||||
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.
|
||||
The default behavior has changed to keep only directories for failed tests, equivalent to `tmp_path_retention_policy="failed"`.
|
||||
@@ -1 +0,0 @@
|
||||
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``.
|
||||
@@ -6,6 +6,7 @@ Release announcements
|
||||
:maxdepth: 2
|
||||
|
||||
|
||||
release-7.2.0
|
||||
release-7.1.3
|
||||
release-7.1.2
|
||||
release-7.1.1
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
pytest-7.2.0
|
||||
=======================================
|
||||
|
||||
The pytest team is proud to announce the 7.2.0 release!
|
||||
|
||||
This release contains new features, improvements, and bug fixes,
|
||||
the full list of changes is available in the changelog:
|
||||
|
||||
https://docs.pytest.org/en/stable/changelog.html
|
||||
|
||||
For complete documentation, please visit:
|
||||
|
||||
https://docs.pytest.org/en/stable/
|
||||
|
||||
As usual, you can upgrade from PyPI via:
|
||||
|
||||
pip install -U pytest
|
||||
|
||||
Thanks to all of the contributors to this release:
|
||||
|
||||
* Aaron Berdy
|
||||
* Adam Turner
|
||||
* Albert Villanova del Moral
|
||||
* Alice Purcell
|
||||
* Anthony Sottile
|
||||
* Anton Yakutovich
|
||||
* Babak Keyvani
|
||||
* Brandon Chinn
|
||||
* Bruno Oliveira
|
||||
* Chanvin Xiao
|
||||
* Cheuk Ting Ho
|
||||
* Chris Wheeler
|
||||
* EmptyRabbit
|
||||
* Ezio Melotti
|
||||
* Florian Best
|
||||
* Florian Bruhin
|
||||
* Fredrik Berndtsson
|
||||
* Gabriel Landau
|
||||
* Gergely Kalmár
|
||||
* Hugo van Kemenade
|
||||
* James Gerity
|
||||
* John Litborn
|
||||
* Jon Parise
|
||||
* Kevin C
|
||||
* Kian Eliasi
|
||||
* MatthewFlamm
|
||||
* Miro Hrončok
|
||||
* Nate Meyvis
|
||||
* Neil Girdhar
|
||||
* Nhieuvu1802
|
||||
* Nipunn Koorapati
|
||||
* Ofek Lev
|
||||
* Paul Müller
|
||||
* Paul Reece
|
||||
* Pax
|
||||
* Pete Baughman
|
||||
* Peyman Salehi
|
||||
* Philipp A
|
||||
* Ran Benita
|
||||
* Robert O'Shea
|
||||
* Ronny Pfannschmidt
|
||||
* Rowin
|
||||
* Ruth Comer
|
||||
* Samuel Colvin
|
||||
* Samuel Gaist
|
||||
* Sandro Tosi
|
||||
* Shantanu
|
||||
* Simon K
|
||||
* Stephen Rosen
|
||||
* Sviatoslav Sydorenko
|
||||
* Tatiana Ovary
|
||||
* Thierry Moisan
|
||||
* Thomas Grainger
|
||||
* Tim Hoffmann
|
||||
* Tobias Diez
|
||||
* Tony Narlock
|
||||
* Vivaan Verma
|
||||
* Wolfremium
|
||||
* Zac Hatfield-Dodds
|
||||
* Zach OBrien
|
||||
* aizpurua23a
|
||||
* gresm
|
||||
* holesch
|
||||
* itxasos23
|
||||
* johnkangw
|
||||
* skhomuti
|
||||
* sommersoft
|
||||
* wodny
|
||||
* zx.qiu
|
||||
|
||||
|
||||
Happy testing,
|
||||
The pytest Development Team
|
||||
+15
-12
@@ -33,7 +33,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
|
||||
|
||||
Values can be any object handled by the json stdlib module.
|
||||
|
||||
capsys -- .../_pytest/capture.py:878
|
||||
capsys -- .../_pytest/capture.py:905
|
||||
Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.
|
||||
|
||||
The captured output is made available via ``capsys.readouterr()`` method
|
||||
@@ -51,7 +51,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
|
||||
captured = capsys.readouterr()
|
||||
assert captured.out == "hello\n"
|
||||
|
||||
capsysbinary -- .../_pytest/capture.py:906
|
||||
capsysbinary -- .../_pytest/capture.py:933
|
||||
Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.
|
||||
|
||||
The captured output is made available via ``capsysbinary.readouterr()``
|
||||
@@ -69,7 +69,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
|
||||
captured = capsysbinary.readouterr()
|
||||
assert captured.out == b"hello\n"
|
||||
|
||||
capfd -- .../_pytest/capture.py:934
|
||||
capfd -- .../_pytest/capture.py:961
|
||||
Enable text capturing of writes to file descriptors ``1`` and ``2``.
|
||||
|
||||
The captured output is made available via ``capfd.readouterr()`` method
|
||||
@@ -87,7 +87,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
|
||||
captured = capfd.readouterr()
|
||||
assert captured.out == "hello\n"
|
||||
|
||||
capfdbinary -- .../_pytest/capture.py:962
|
||||
capfdbinary -- .../_pytest/capture.py:989
|
||||
Enable bytes capturing of writes to file descriptors ``1`` and ``2``.
|
||||
|
||||
The captured output is made available via ``capfd.readouterr()`` method
|
||||
@@ -105,7 +105,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
|
||||
captured = capfdbinary.readouterr()
|
||||
assert captured.out == b"hello\n"
|
||||
|
||||
doctest_namespace [session scope] -- .../_pytest/doctest.py:735
|
||||
doctest_namespace [session scope] -- .../_pytest/doctest.py:738
|
||||
Fixture that returns a :py:class:`dict` that will be injected into the
|
||||
namespace of doctests.
|
||||
|
||||
@@ -119,7 +119,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
|
||||
|
||||
For more details: :ref:`doctest_namespace`.
|
||||
|
||||
pytestconfig [session scope] -- .../_pytest/fixtures.py:1344
|
||||
pytestconfig [session scope] -- .../_pytest/fixtures.py:1351
|
||||
Session-scoped fixture that returns the session's :class:`pytest.Config`
|
||||
object.
|
||||
|
||||
@@ -163,7 +163,10 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
|
||||
record_testsuite_property("ARCH", "PPC")
|
||||
record_testsuite_property("STORAGE_TYPE", "CEPH")
|
||||
|
||||
``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.
|
||||
:param name:
|
||||
The property name.
|
||||
:param value:
|
||||
The property value. Will be converted to a string.
|
||||
|
||||
.. warning::
|
||||
|
||||
@@ -193,7 +196,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
|
||||
|
||||
.. _legacy_path: https://py.readthedocs.io/en/latest/path.html
|
||||
|
||||
caplog -- .../_pytest/logging.py:487
|
||||
caplog -- .../_pytest/logging.py:491
|
||||
Access and control log capturing.
|
||||
|
||||
Captured logs are available through the following properties/methods::
|
||||
@@ -228,16 +231,16 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
|
||||
To undo modifications done by the fixture in a contained scope,
|
||||
use :meth:`context() <pytest.MonkeyPatch.context>`.
|
||||
|
||||
recwarn -- .../_pytest/recwarn.py:29
|
||||
recwarn -- .../_pytest/recwarn.py:30
|
||||
Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
|
||||
|
||||
See https://docs.python.org/library/how-to/capture-warnings.html for information
|
||||
See https://docs.pytest.org/en/latest/how-to/capture-warnings.html for information
|
||||
on warning categories.
|
||||
|
||||
tmp_path_factory [session scope] -- .../_pytest/tmpdir.py:184
|
||||
tmp_path_factory [session scope] -- .../_pytest/tmpdir.py:188
|
||||
Return a :class:`pytest.TempPathFactory` instance for the test session.
|
||||
|
||||
tmp_path -- .../_pytest/tmpdir.py:199
|
||||
tmp_path -- .../_pytest/tmpdir.py:203
|
||||
Return a temporary directory path object which is unique to each test
|
||||
function invocation, created as a sub directory of the base temporary
|
||||
directory.
|
||||
|
||||
@@ -28,6 +28,149 @@ with advance notice in the **Deprecations** section of releases.
|
||||
|
||||
.. towncrier release notes start
|
||||
|
||||
pytest 7.2.0 (2022-10-23)
|
||||
=========================
|
||||
|
||||
Deprecations
|
||||
------------
|
||||
|
||||
- `#10012 <https://github.com/pytest-dev/pytest/issues/10012>`_: Update :class:`pytest.PytestUnhandledCoroutineWarning` to a deprecation; it will raise an error in pytest 8.
|
||||
|
||||
|
||||
- `#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.
|
||||
|
||||
|
||||
- `#4562 <https://github.com/pytest-dev/pytest/issues/4562>`_: Deprecate configuring hook specs/impls using attributes/marks.
|
||||
|
||||
Instead use :py:func:`pytest.hookimpl` and :py:func:`pytest.hookspec`.
|
||||
For more details, see the :ref:`docs <legacy-path-hooks-deprecated>`.
|
||||
|
||||
|
||||
- `#9886 <https://github.com/pytest-dev/pytest/issues/9886>`_: The functionality for running tests written for ``nose`` has been officially deprecated.
|
||||
|
||||
This includes:
|
||||
|
||||
* 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.
|
||||
* Setup/teardown using the `@with_setup <with-setup-nose>`_ decorator.
|
||||
|
||||
For more details, consult the :ref:`deprecation docs <nose-deprecation>`.
|
||||
|
||||
.. _`with-setup-nose`: https://nose.readthedocs.io/en/latest/testing_tools.html?highlight=with_setup#nose.tools.with_setup
|
||||
|
||||
- `#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.
|
||||
|
||||
|
||||
Features
|
||||
--------
|
||||
|
||||
- `#9897 <https://github.com/pytest-dev/pytest/issues/9897>`_: Added shell-style wildcard support to ``testpaths``.
|
||||
|
||||
|
||||
|
||||
Improvements
|
||||
------------
|
||||
|
||||
- `#10218 <https://github.com/pytest-dev/pytest/issues/10218>`_: ``@pytest.mark.parametrize()`` (and similar functions) now accepts any ``Sequence[str]`` for the argument names,
|
||||
instead of just ``list[str]`` and ``tuple[str, ...]``.
|
||||
|
||||
(Note that ``str``, which is itself a ``Sequence[str]``, is still treated as a
|
||||
comma-delimited name list, as before).
|
||||
|
||||
|
||||
- `#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``.
|
||||
|
||||
|
||||
- `#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.
|
||||
|
||||
|
||||
- `#8508 <https://github.com/pytest-dev/pytest/issues/8508>`_: Introduce multiline display for warning matching via :py:func:`pytest.warns` and
|
||||
enhance match comparison for :py:func:`_pytest._code.ExceptionInfo.match` as returned by :py:func:`pytest.raises`.
|
||||
|
||||
|
||||
- `#8646 <https://github.com/pytest-dev/pytest/issues/8646>`_: Improve :py:func:`pytest.raises`. Previously passing an empty tuple would give a confusing
|
||||
error. We now raise immediately with a more helpful message.
|
||||
|
||||
|
||||
- `#9741 <https://github.com/pytest-dev/pytest/issues/9741>`_: On Python 3.11, use the standard library's :mod:`tomllib` to parse TOML.
|
||||
|
||||
:mod:`tomli` is no longer a dependency on Python 3.11.
|
||||
|
||||
|
||||
- `#9742 <https://github.com/pytest-dev/pytest/issues/9742>`_: Display assertion message without escaped newline characters with ``-vv``.
|
||||
|
||||
|
||||
- `#9823 <https://github.com/pytest-dev/pytest/issues/9823>`_: Improved error message that is shown when no collector is found for a given file.
|
||||
|
||||
|
||||
- `#9873 <https://github.com/pytest-dev/pytest/issues/9873>`_: Some coloring has been added to the short test summary.
|
||||
|
||||
|
||||
- `#9883 <https://github.com/pytest-dev/pytest/issues/9883>`_: Normalize the help description of all command-line options.
|
||||
|
||||
|
||||
- `#9920 <https://github.com/pytest-dev/pytest/issues/9920>`_: Display full crash messages in ``short test summary info``, when running in a CI environment.
|
||||
|
||||
|
||||
- `#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``.
|
||||
|
||||
|
||||
|
||||
Bug Fixes
|
||||
---------
|
||||
|
||||
- `#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.
|
||||
|
||||
|
||||
- `#10382 <https://github.com/pytest-dev/pytest/issues/10382>`_: Do not break into pdb when ``raise unittest.SkipTest()`` appears top-level in a file.
|
||||
|
||||
|
||||
- `#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.
|
||||
|
||||
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.
|
||||
|
||||
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:`pytest.Node.iter_markers` instead.
|
||||
|
||||
|
||||
- `#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``.
|
||||
|
||||
|
||||
- `#9877 <https://github.com/pytest-dev/pytest/issues/9877>`_: Ensure ``caplog.get_records(when)`` returns current/correct data after invoking ``caplog.clear()``.
|
||||
|
||||
|
||||
|
||||
Improved Documentation
|
||||
----------------------
|
||||
|
||||
- `#10344 <https://github.com/pytest-dev/pytest/issues/10344>`_: Update information on writing plugins to use ``pyproject.toml`` instead of ``setup.py``.
|
||||
|
||||
|
||||
- `#9248 <https://github.com/pytest-dev/pytest/issues/9248>`_: The documentation is now built using Sphinx 5.x (up from 3.x previously).
|
||||
|
||||
|
||||
- `#9291 <https://github.com/pytest-dev/pytest/issues/9291>`_: Update documentation on how :func:`pytest.warns` affects :class:`DeprecationWarning`.
|
||||
|
||||
|
||||
|
||||
Trivial/Internal Changes
|
||||
------------------------
|
||||
|
||||
- `#10313 <https://github.com/pytest-dev/pytest/issues/10313>`_: Made ``_pytest.doctest.DoctestItem`` export ``pytest.DoctestItem`` for
|
||||
type check and runtime purposes. Made `_pytest.doctest` use internal APIs
|
||||
to avoid circular imports.
|
||||
|
||||
|
||||
- `#9906 <https://github.com/pytest-dev/pytest/issues/9906>`_: Made ``_pytest.compat`` re-export ``importlib_metadata`` in the eyes of type checkers.
|
||||
|
||||
|
||||
- `#9910 <https://github.com/pytest-dev/pytest/issues/9910>`_: Fix default encoding warning (``EncodingWarning``) in ``cacheprovider``
|
||||
|
||||
|
||||
- `#9984 <https://github.com/pytest-dev/pytest/issues/9984>`_: Improve the error message when we attempt to access a fixture that has been
|
||||
torn down.
|
||||
Add an additional sentence to the docstring explaining when it's not a good
|
||||
idea to call ``getfixturevalue``.
|
||||
|
||||
|
||||
pytest 7.1.3 (2022-08-31)
|
||||
=========================
|
||||
|
||||
|
||||
+6
-10
@@ -38,6 +38,7 @@ release = ".".join(version.split(".")[:2])
|
||||
|
||||
autodoc_member_order = "bysource"
|
||||
autodoc_typehints = "description"
|
||||
autodoc_typehints_description_target = "documented"
|
||||
todo_include_todos = 1
|
||||
|
||||
latex_engine = "lualatex"
|
||||
@@ -162,11 +163,11 @@ linkcheck_workers = 5
|
||||
|
||||
_repo = "https://github.com/pytest-dev/pytest"
|
||||
extlinks = {
|
||||
"bpo": ("https://bugs.python.org/issue%s", "bpo-"),
|
||||
"pypi": ("https://pypi.org/project/%s/", ""),
|
||||
"issue": (f"{_repo}/issues/%s", "issue #"),
|
||||
"pull": (f"{_repo}/pull/%s", "pull request #"),
|
||||
"user": ("https://github.com/%s", "@"),
|
||||
"bpo": ("https://bugs.python.org/issue%s", "bpo-%s"),
|
||||
"pypi": ("https://pypi.org/project/%s/", "%s"),
|
||||
"issue": (f"{_repo}/issues/%s", "issue #%s"),
|
||||
"pull": (f"{_repo}/pull/%s", "pull request #%s"),
|
||||
"user": ("https://github.com/%s", "@%s"),
|
||||
}
|
||||
|
||||
|
||||
@@ -272,9 +273,6 @@ html_show_sourcelink = False
|
||||
# Output file base name for HTML help builder.
|
||||
htmlhelp_basename = "pytestdoc"
|
||||
|
||||
# The base URL which points to the root of the HTML documentation. It is used
|
||||
# to indicate the location of document using the canonical link relation (#12363).
|
||||
html_baseurl = "https://docs.pytest.org/en/stable/"
|
||||
|
||||
# -- Options for LaTeX output --------------------------------------------------
|
||||
|
||||
@@ -423,8 +421,6 @@ def configure_logging(app: "sphinx.application.Sphinx") -> None:
|
||||
|
||||
|
||||
def setup(app: "sphinx.application.Sphinx") -> None:
|
||||
# from sphinx.ext.autodoc import cut_lines
|
||||
# app.connect('autodoc-process-docstring', cut_lines(4, what=['module']))
|
||||
app.add_crossref_type(
|
||||
"fixture",
|
||||
"fixture",
|
||||
|
||||
@@ -18,6 +18,113 @@ Deprecated Features
|
||||
Below is a complete list of all pytest features which are considered deprecated. Using those features will issue
|
||||
:class:`~pytest.PytestWarning` or subclasses, which can be filtered using :ref:`standard warning filters <warnings>`.
|
||||
|
||||
|
||||
.. _nose-deprecation:
|
||||
|
||||
Support for tests written for nose
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. deprecated:: 7.2
|
||||
|
||||
Support for running tests written for `nose <https://nose.readthedocs.io/en/latest/>`__ is now deprecated.
|
||||
|
||||
``nose`` has been in maintenance mode-only for years, and maintaining the plugin is not trivial as it spills
|
||||
over the code base (see :issue:`9886` for more details).
|
||||
|
||||
setup/teardown
|
||||
^^^^^^^^^^^^^^
|
||||
|
||||
One thing that might catch users by surprise is that plain ``setup`` and ``teardown`` methods are not pytest native,
|
||||
they are in fact part of the ``nose`` support.
|
||||
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class Test:
|
||||
def setup(self):
|
||||
self.resource = make_resource()
|
||||
|
||||
def teardown(self):
|
||||
self.resource.close()
|
||||
|
||||
def test_foo(self):
|
||||
...
|
||||
|
||||
def test_bar(self):
|
||||
...
|
||||
|
||||
|
||||
|
||||
Native pytest support uses ``setup_method`` and ``teardown_method`` (see :ref:`xunit-method-setup`), so the above should be changed to:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
class Test:
|
||||
def setup_method(self):
|
||||
self.resource = make_resource()
|
||||
|
||||
def teardown_method(self):
|
||||
self.resource.close()
|
||||
|
||||
def test_foo(self):
|
||||
...
|
||||
|
||||
def test_bar(self):
|
||||
...
|
||||
|
||||
|
||||
This is easy to do in an entire code base by doing a simple find/replace.
|
||||
|
||||
@with_setup
|
||||
^^^^^^^^^^^
|
||||
|
||||
Code using `@with_setup <with-setup-nose>`_ such as this:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from nose.tools import with_setup
|
||||
|
||||
|
||||
def setup_some_resource():
|
||||
...
|
||||
|
||||
|
||||
def teardown_some_resource():
|
||||
...
|
||||
|
||||
|
||||
@with_setup(setup_some_resource, teardown_some_resource)
|
||||
def test_foo():
|
||||
...
|
||||
|
||||
Will also need to be ported to a supported pytest style. One way to do it is using a fixture:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def setup_some_resource():
|
||||
...
|
||||
|
||||
|
||||
def teardown_some_resource():
|
||||
...
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def some_resource():
|
||||
setup_some_resource()
|
||||
yield
|
||||
teardown_some_resource()
|
||||
|
||||
|
||||
def test_foo(some_resource):
|
||||
...
|
||||
|
||||
|
||||
.. _`with-setup-nose`: https://nose.readthedocs.io/en/latest/testing_tools.html?highlight=with_setup#nose.tools.with_setup
|
||||
|
||||
.. _instance-collector-deprecation:
|
||||
|
||||
The ``pytest.Instance`` collector
|
||||
@@ -78,6 +185,50 @@ no matter what argument was used in the constructor. We expect to deprecate the
|
||||
|
||||
.. _legacy-path-hooks-deprecated:
|
||||
|
||||
Configuring hook specs/impls using markers
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
Before pluggy, pytest's plugin library, was its own package and had a clear API,
|
||||
pytest just used ``pytest.mark`` to configure hooks.
|
||||
|
||||
The :py:func:`pytest.hookimpl` and :py:func:`pytest.hookspec` decorators
|
||||
have been available since years and should be used instead.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@pytest.mark.tryfirst
|
||||
def pytest_runtest_call():
|
||||
...
|
||||
|
||||
|
||||
# or
|
||||
def pytest_runtest_call():
|
||||
...
|
||||
|
||||
|
||||
pytest_runtest_call.tryfirst = True
|
||||
|
||||
should be changed to:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@pytest.hookimpl(tryfirst=True)
|
||||
def pytest_runtest_call():
|
||||
...
|
||||
|
||||
Changed ``hookimpl`` attributes:
|
||||
|
||||
* ``tryfirst``
|
||||
* ``trylast``
|
||||
* ``optionalhook``
|
||||
* ``hookwrapper``
|
||||
|
||||
Changed ``hookwrapper`` attributes:
|
||||
|
||||
* ``firstresult``
|
||||
* ``historic``
|
||||
|
||||
|
||||
``py.path.local`` arguments for hooks replaced with ``pathlib.Path``
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
@@ -252,6 +403,47 @@ or ``pytest.warns(Warning)``.
|
||||
|
||||
See :ref:`warns use cases` for examples.
|
||||
|
||||
|
||||
Returning non-None value in test functions
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
.. deprecated:: 7.2
|
||||
|
||||
A :class:`pytest.PytestReturnNotNoneWarning` 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` would cause a test to pass or fail, for example:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
["a", "b", "result"],
|
||||
[
|
||||
[1, 2, 5],
|
||||
[2, 3, 8],
|
||||
[5, 3, 18],
|
||||
],
|
||||
)
|
||||
def test_foo(a, b, result):
|
||||
return foo(a, b) == result
|
||||
|
||||
Given that pytest ignores the return value, this might be surprising that it will never fail.
|
||||
|
||||
The proper fix is to change the `return` to an `assert`:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
["a", "b", "result"],
|
||||
[
|
||||
[1, 2, 5],
|
||||
[2, 3, 8],
|
||||
[5, 3, 18],
|
||||
],
|
||||
)
|
||||
def test_foo(a, b, result):
|
||||
assert foo(a, b) == result
|
||||
|
||||
|
||||
The ``--strict`` command-line option
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ example: specifying and selecting acceptance tests
|
||||
self.tmpdir = request.config.mktemp(request.function.__name__, numbered=True)
|
||||
|
||||
def run(self, *cmd):
|
||||
""" called by test code to execute an acceptance test. """
|
||||
"""called by test code to execute an acceptance test."""
|
||||
self.tmpdir.chdir()
|
||||
return subprocess.check_output(cmd).decode()
|
||||
|
||||
|
||||
@@ -246,9 +246,9 @@ You can ask which markers exist for your test suite - the list includes our just
|
||||
|
||||
@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
|
||||
|
||||
@pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible.
|
||||
@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.
|
||||
|
||||
@pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible.
|
||||
@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.
|
||||
|
||||
|
||||
For an example on how to add and work with markers from a plugin, see
|
||||
@@ -346,7 +346,7 @@ Custom marker and command line option to control test runs
|
||||
Plugins can provide custom markers and implement specific behaviour
|
||||
based on it. This is a self-contained example which adds a command
|
||||
line option and a parametrized test function marker to run tests
|
||||
specifies via named environments:
|
||||
specified via named environments:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
@@ -375,7 +375,7 @@ specifies via named environments:
|
||||
envnames = [mark.args[0] for mark in item.iter_markers(name="env")]
|
||||
if envnames:
|
||||
if item.config.getoption("-E") not in envnames:
|
||||
pytest.skip("test requires env in {!r}".format(envnames))
|
||||
pytest.skip(f"test requires env in {envnames!r}")
|
||||
|
||||
A test file using this local plugin:
|
||||
|
||||
@@ -438,9 +438,9 @@ The ``--markers`` option always gives you a list of available markers:
|
||||
|
||||
@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
|
||||
|
||||
@pytest.mark.tryfirst: mark a hook implementation function such that the plugin machinery will try to call it first/as early as possible.
|
||||
@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.
|
||||
|
||||
@pytest.mark.trylast: mark a hook implementation function such that the plugin machinery will try to call it last/as late as possible.
|
||||
@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.
|
||||
|
||||
|
||||
.. _`passing callables to custom markers`:
|
||||
@@ -528,7 +528,7 @@ test function. From a conftest file we can read it like this:
|
||||
|
||||
def pytest_runtest_setup(item):
|
||||
for mark in item.iter_markers(name="glob"):
|
||||
print("glob args={} kwargs={}".format(mark.args, mark.kwargs))
|
||||
print(f"glob args={mark.args} kwargs={mark.kwargs}")
|
||||
sys.stdout.flush()
|
||||
|
||||
Let's run this without capturing output and see what we get:
|
||||
@@ -558,6 +558,7 @@ for your particular platform, you could use the following plugin:
|
||||
# content of conftest.py
|
||||
#
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ALL = set("darwin linux win32".split())
|
||||
@@ -567,7 +568,7 @@ for your particular platform, you could use the following plugin:
|
||||
supported_platforms = ALL.intersection(mark.name for mark in item.iter_markers())
|
||||
plat = sys.platform
|
||||
if supported_platforms and plat not in supported_platforms:
|
||||
pytest.skip("cannot run on platform {}".format(plat))
|
||||
pytest.skip(f"cannot run on platform {plat}")
|
||||
|
||||
then tests will be skipped if they were specified for a different platform.
|
||||
Let's do a little test file to show how this looks like:
|
||||
@@ -610,7 +611,7 @@ then you will see two tests skipped and two executed tests as expected:
|
||||
test_plat.py s.s. [100%]
|
||||
|
||||
========================= short test summary info ==========================
|
||||
SKIPPED [2] conftest.py:12: cannot run on platform linux
|
||||
SKIPPED [2] conftest.py:13: cannot run on platform linux
|
||||
======================= 2 passed, 2 skipped in 0.12s =======================
|
||||
|
||||
Note that if you specify a platform via the marker-command line option like this:
|
||||
|
||||
+18
-14
@@ -342,7 +342,7 @@ Example:
|
||||
def checkconfig(x):
|
||||
__tracebackhide__ = True
|
||||
if not hasattr(x, "config"):
|
||||
pytest.fail("not configured: {}".format(x))
|
||||
pytest.fail(f"not configured: {x}")
|
||||
|
||||
|
||||
def test_something():
|
||||
@@ -376,6 +376,7 @@ this to make sure unexpected exception types aren't hidden:
|
||||
.. code-block:: python
|
||||
|
||||
import operator
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -386,7 +387,7 @@ this to make sure unexpected exception types aren't hidden:
|
||||
def checkconfig(x):
|
||||
__tracebackhide__ = operator.methodcaller("errisinstance", ConfigException)
|
||||
if not hasattr(x, "config"):
|
||||
raise ConfigException("not configured: {}".format(x))
|
||||
raise ConfigException(f"not configured: {x}")
|
||||
|
||||
|
||||
def test_something():
|
||||
@@ -565,6 +566,7 @@ an ``incremental`` marker which is to be used on classes:
|
||||
# content of conftest.py
|
||||
|
||||
from typing import Dict, Tuple
|
||||
|
||||
import pytest
|
||||
|
||||
# store history of failures per test class name and per index in parametrize (if parametrize used)
|
||||
@@ -608,7 +610,7 @@ an ``incremental`` marker which is to be used on classes:
|
||||
test_name = _test_failed_incremental[cls_name].get(parametrize_index, None)
|
||||
# if name found, test has failed for the combination of class name & test name
|
||||
if test_name is not None:
|
||||
pytest.xfail("previous test failed ({})".format(test_name))
|
||||
pytest.xfail(f"previous test failed ({test_name})")
|
||||
|
||||
|
||||
These two hook implementations work together to abort incremental-marked
|
||||
@@ -659,8 +661,7 @@ If we run this:
|
||||
|
||||
test_step.py:11: AssertionError
|
||||
========================= short test summary info ==========================
|
||||
XFAIL test_step.py::TestUserHandling::test_deletion
|
||||
reason: previous test failed (test_modification)
|
||||
XFAIL test_step.py::TestUserHandling::test_deletion - reason: previous test failed (test_modification)
|
||||
================== 1 failed, 2 passed, 1 xfailed in 0.12s ==================
|
||||
|
||||
We'll see that ``test_deletion`` was not executed because ``test_modification``
|
||||
@@ -802,9 +803,10 @@ case we just write some information out to a ``failures`` file:
|
||||
|
||||
# content of conftest.py
|
||||
|
||||
import pytest
|
||||
import os.path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
|
||||
def pytest_runtest_makereport(item, call):
|
||||
@@ -893,6 +895,8 @@ here is a little example implemented via a local plugin:
|
||||
|
||||
import pytest
|
||||
|
||||
phase_report_key = StashKey[Dict[str, CollectReport]]()
|
||||
|
||||
|
||||
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
|
||||
def pytest_runtest_makereport(item, call):
|
||||
@@ -900,10 +904,9 @@ here is a little example implemented via a local plugin:
|
||||
outcome = yield
|
||||
rep = outcome.get_result()
|
||||
|
||||
# set a report attribute for each phase of a call, which can
|
||||
# store test results for each phase of a call, which can
|
||||
# be "setup", "call", "teardown"
|
||||
|
||||
setattr(item, "rep_" + rep.when, rep)
|
||||
item.stash.setdefault(phase_report_key, {})[rep.when] = rep
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -911,11 +914,11 @@ here is a little example implemented via a local plugin:
|
||||
yield
|
||||
# request.node is an "item" because we use the default
|
||||
# "function" scope
|
||||
if request.node.rep_setup.failed:
|
||||
print("setting up a test failed!", request.node.nodeid)
|
||||
elif request.node.rep_setup.passed:
|
||||
if request.node.rep_call.failed:
|
||||
print("executing test failed", request.node.nodeid)
|
||||
report = request.node.stash[phase_report_key]
|
||||
if report["setup"].failed:
|
||||
print("setting up a test failed or skipped", request.node.nodeid)
|
||||
elif ("call" not in report) or report["call"].failed:
|
||||
print("executing test failed or skipped", request.node.nodeid)
|
||||
|
||||
|
||||
if you then have failing tests:
|
||||
@@ -1066,6 +1069,7 @@ like ``pytest-timeout`` they must be imported explicitly and passed on to pytest
|
||||
|
||||
# contents of app_main.py
|
||||
import sys
|
||||
|
||||
import pytest_timeout # Third party plugin
|
||||
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "--pytest":
|
||||
|
||||
@@ -50,8 +50,8 @@ Conventions for Python test discovery
|
||||
* In those directories, search for ``test_*.py`` or ``*_test.py`` files, imported by their `test package name`_.
|
||||
* From those files, collect test items:
|
||||
|
||||
* ``test`` prefixed test functions or methods outside of class
|
||||
* ``test`` prefixed test functions or methods inside ``Test`` prefixed test classes (without an ``__init__`` method)
|
||||
* ``test`` prefixed test functions or methods outside of class.
|
||||
* ``test`` prefixed test functions or methods inside ``Test`` prefixed test classes (without an ``__init__`` method). Methods decorated with ``@staticmethod`` and ``@classmethods`` are also considered.
|
||||
|
||||
For examples of how to customize your test discovery :doc:`/example/pythoncollection`.
|
||||
|
||||
@@ -88,14 +88,6 @@ This has the following benefits:
|
||||
|
||||
* Your tests can run against an installed version after executing ``pip install .``.
|
||||
* Your tests can run against the local copy with an editable install after executing ``pip install --editable .``.
|
||||
* If you don't use an editable install and are relying on the fact that Python by default puts the current
|
||||
directory in ``sys.path`` to import your package, you can execute ``python -m pytest`` to execute the tests against the
|
||||
local copy directly, without using ``pip``.
|
||||
|
||||
.. note::
|
||||
|
||||
See :ref:`pytest vs python -m pytest` for more information about the difference between calling ``pytest`` and
|
||||
``python -m pytest``.
|
||||
|
||||
For new projects, we recommend to use ``importlib`` :ref:`import mode <import-modes>`
|
||||
(see which-import-mode_ for a detailed explanation).
|
||||
@@ -120,6 +112,32 @@ which are better explained in this excellent `blog post`_ by Ionel Cristian Măr
|
||||
|
||||
.. _blog post: https://blog.ionelmc.ro/2014/05/25/python-packaging/#the-structure>
|
||||
|
||||
.. note::
|
||||
|
||||
If you do not use an editable install and use the ``src`` layout as above you need to extend the Python's
|
||||
search path for module files to execute the tests against the local copy directly. You can do it in an
|
||||
ad-hoc manner by setting the ``PYTHONPATH`` environment variable:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
PYTHONPATH=src pytest
|
||||
|
||||
or in a permanent manner by using the :confval:`pythonpath` configuration variable and adding the
|
||||
following to your ``pyproject.toml``:
|
||||
|
||||
.. code-block:: toml
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
pythonpath = "src"
|
||||
|
||||
.. note::
|
||||
|
||||
If you do not use an editable install and not use the ``src`` layout (``mypkg`` directly in the root
|
||||
directory) you can rely on the fact that Python by default puts the current directory in ``sys.path`` to
|
||||
import your package and run ``python -m pytest`` to execute the tests against the local copy directly.
|
||||
|
||||
See :ref:`pytest vs python -m pytest` for more information about the difference between calling ``pytest`` and
|
||||
``python -m pytest``.
|
||||
|
||||
Tests as part of application code
|
||||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
@@ -135,7 +153,7 @@ want to distribute them along with your application:
|
||||
__init__.py
|
||||
app.py
|
||||
view.py
|
||||
test/
|
||||
tests/
|
||||
__init__.py
|
||||
test_app.py
|
||||
test_view.py
|
||||
@@ -252,8 +270,8 @@ tox
|
||||
|
||||
Once you are done with your work and want to make sure that your actual
|
||||
package passes all tests you may want to look into :doc:`tox <tox:index>`, the
|
||||
virtualenv test automation tool and its :doc:`pytest support <tox:example/pytest>`.
|
||||
tox helps you to setup virtualenv environments with pre-defined
|
||||
virtualenv test automation tool.
|
||||
``tox`` helps you to setup virtualenv environments with pre-defined
|
||||
dependencies and then executing a pre-configured test command with
|
||||
options. It will run tests against the installed package and not
|
||||
against your source code checkout, helping to detect packaging
|
||||
|
||||
@@ -22,7 +22,7 @@ Install ``pytest``
|
||||
.. code-block:: bash
|
||||
|
||||
$ pytest --version
|
||||
pytest 7.1.3
|
||||
pytest 7.2.0
|
||||
|
||||
.. _`simpletest`:
|
||||
|
||||
|
||||
@@ -238,7 +238,7 @@ file which provides an alternative explanation for ``Foo`` objects:
|
||||
if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":
|
||||
return [
|
||||
"Comparing Foo instances:",
|
||||
" vals: {} != {}".format(left.val, right.val),
|
||||
f" vals: {left.val} != {right.val}",
|
||||
]
|
||||
|
||||
now, given this test module:
|
||||
|
||||
@@ -199,7 +199,6 @@ across pytest invocations:
|
||||
|
||||
# content of test_caching.py
|
||||
import pytest
|
||||
import time
|
||||
|
||||
|
||||
def expensive_computation():
|
||||
@@ -234,7 +233,7 @@ If you run this command for the first time, you can see the print statement:
|
||||
> assert mydata == 23
|
||||
E assert 42 == 23
|
||||
|
||||
test_caching.py:20: AssertionError
|
||||
test_caching.py:19: AssertionError
|
||||
-------------------------- Captured stdout setup ---------------------------
|
||||
running expensive computation...
|
||||
========================= short test summary info ==========================
|
||||
@@ -257,7 +256,7 @@ the cache and nothing will be printed:
|
||||
> assert mydata == 23
|
||||
E assert 42 == 23
|
||||
|
||||
test_caching.py:20: AssertionError
|
||||
test_caching.py:19: AssertionError
|
||||
========================= short test summary info ==========================
|
||||
FAILED test_caching.py::test_function - assert 42 == 23
|
||||
1 failed in 0.12s
|
||||
|
||||
@@ -42,6 +42,8 @@ Running pytest now produces this output:
|
||||
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
|
||||
======================= 1 passed, 1 warning in 0.12s =======================
|
||||
|
||||
.. _`controlling-warnings`:
|
||||
|
||||
Controlling warnings
|
||||
--------------------
|
||||
|
||||
@@ -176,11 +178,14 @@ using an external system.
|
||||
DeprecationWarning and PendingDeprecationWarning
|
||||
------------------------------------------------
|
||||
|
||||
|
||||
By default pytest will display ``DeprecationWarning`` and ``PendingDeprecationWarning`` warnings from
|
||||
user code and third-party libraries, as recommended by :pep:`565`.
|
||||
This helps users keep their code modern and avoid breakages when deprecated warnings are effectively removed.
|
||||
|
||||
However, in the specific case where users capture any type of warnings in their test, either with
|
||||
:func:`pytest.warns`, :func:`pytest.deprecated_call` or using the :ref:`recwarn <recwarn>` fixture,
|
||||
no warning will be displayed at all.
|
||||
|
||||
Sometimes it is useful to hide some specific deprecation warnings that happen in code that you have no control over
|
||||
(such as third-party libraries), in which case you might use the warning filters options (ini or marks) to ignore
|
||||
those warnings.
|
||||
@@ -197,6 +202,9 @@ For example:
|
||||
This will ignore all warnings of type ``DeprecationWarning`` where the start of the message matches
|
||||
the regular expression ``".*U.*mode is deprecated"``.
|
||||
|
||||
See :ref:`@pytest.mark.filterwarnings <filterwarnings>` and
|
||||
:ref:`Controlling warnings <controlling-warnings>` for more examples.
|
||||
|
||||
.. note::
|
||||
|
||||
If warnings are configured at the interpreter level, using
|
||||
@@ -245,14 +253,15 @@ when called with a ``17`` argument.
|
||||
Asserting warnings with the warns function
|
||||
------------------------------------------
|
||||
|
||||
|
||||
|
||||
You can check that code raises a particular warning using :func:`pytest.warns`,
|
||||
which works in a similar manner to :ref:`raises <assertraises>`:
|
||||
which works in a similar manner to :ref:`raises <assertraises>` (except that
|
||||
:ref:`raises <assertraises>` does not capture all exceptions, only the
|
||||
``expected_exception``):
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
import warnings
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -260,8 +269,8 @@ which works in a similar manner to :ref:`raises <assertraises>`:
|
||||
with pytest.warns(UserWarning):
|
||||
warnings.warn("my warning", UserWarning)
|
||||
|
||||
The test will fail if the warning in question is not raised. The keyword
|
||||
argument ``match`` to assert that the exception matches a text or regex::
|
||||
The test will fail if the warning in question is not raised. Use the keyword
|
||||
argument ``match`` to assert that the warning matches a text or regex::
|
||||
|
||||
>>> with warns(UserWarning, match='must be 0 or None'):
|
||||
... warnings.warn("value must be 0 or None", UserWarning)
|
||||
@@ -358,20 +367,32 @@ Additional use cases of warnings in tests
|
||||
|
||||
Here are some use cases involving warnings that often come up in tests, and suggestions on how to deal with them:
|
||||
|
||||
- To ensure that **at least one** warning is emitted, use:
|
||||
- To ensure that **at least one** of the indicated warnings is issued, use:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
with pytest.warns():
|
||||
def test_warning():
|
||||
with pytest.warns((RuntimeWarning, UserWarning)):
|
||||
...
|
||||
|
||||
- To ensure that **only** certain warnings are issued, use:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
def test_warning(recwarn):
|
||||
...
|
||||
assert len(recwarn) == 1
|
||||
user_warning = recwarn.pop(UserWarning)
|
||||
assert issubclass(user_warning.category, UserWarning)
|
||||
|
||||
- To ensure that **no** warnings are emitted, use:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error")
|
||||
...
|
||||
def test_warning():
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error")
|
||||
...
|
||||
|
||||
- To suppress warnings, use:
|
||||
|
||||
|
||||
@@ -242,7 +242,6 @@ which can then be used in your doctests directly:
|
||||
>>> len(a)
|
||||
10
|
||||
"""
|
||||
pass
|
||||
|
||||
Note that like the normal ``conftest.py``, the fixtures are discovered in the directory tree conftest is in.
|
||||
Meaning that if you put your doctest with your source code, the relevant conftest.py needs to be in the same directory tree.
|
||||
|
||||
+17
-12
@@ -398,9 +398,10 @@ access the fixture function:
|
||||
.. code-block:: python
|
||||
|
||||
# content of conftest.py
|
||||
import pytest
|
||||
import smtplib
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def smtp_connection():
|
||||
@@ -609,10 +610,10 @@ Here's what that might look like:
|
||||
.. code-block:: python
|
||||
|
||||
# content of test_emaillib.py
|
||||
import pytest
|
||||
|
||||
from emaillib import Email, MailAdminClient
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mail_admin():
|
||||
@@ -630,6 +631,7 @@ Here's what that might look like:
|
||||
def receiving_user(mail_admin):
|
||||
user = mail_admin.create_user()
|
||||
yield user
|
||||
user.clear_mailbox()
|
||||
mail_admin.delete_user(user)
|
||||
|
||||
|
||||
@@ -683,10 +685,10 @@ Here's how the previous example would look using the ``addfinalizer`` method:
|
||||
.. code-block:: python
|
||||
|
||||
# content of test_emaillib.py
|
||||
import pytest
|
||||
|
||||
from emaillib import Email, MailAdminClient
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mail_admin():
|
||||
@@ -833,10 +835,10 @@ above):
|
||||
.. code-block:: python
|
||||
|
||||
# content of test_emaillib.py
|
||||
import pytest
|
||||
|
||||
from emaillib import Email, MailAdminClient
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup():
|
||||
@@ -1111,16 +1113,17 @@ read an optional server URL from the test module which uses our fixture:
|
||||
.. code-block:: python
|
||||
|
||||
# content of conftest.py
|
||||
import pytest
|
||||
import smtplib
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def smtp_connection(request):
|
||||
server = getattr(request.module, "smtpserver", "smtp.gmail.com")
|
||||
smtp_connection = smtplib.SMTP(server, 587, timeout=5)
|
||||
yield smtp_connection
|
||||
print("finalizing {} ({})".format(smtp_connection, server))
|
||||
print(f"finalizing {smtp_connection} ({server})")
|
||||
smtp_connection.close()
|
||||
|
||||
We use the ``request.module`` attribute to optionally obtain an
|
||||
@@ -1274,15 +1277,16 @@ through the special :py:class:`request <FixtureRequest>` object:
|
||||
.. code-block:: python
|
||||
|
||||
# content of conftest.py
|
||||
import pytest
|
||||
import smtplib
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["smtp.gmail.com", "mail.python.org"])
|
||||
def smtp_connection(request):
|
||||
smtp_connection = smtplib.SMTP(request.param, 587, timeout=5)
|
||||
yield smtp_connection
|
||||
print("finalizing {}".format(smtp_connection))
|
||||
print(f"finalizing {smtp_connection}")
|
||||
smtp_connection.close()
|
||||
|
||||
The main change is the declaration of ``params`` with
|
||||
@@ -1586,7 +1590,7 @@ to show the setup/teardown flow:
|
||||
|
||||
|
||||
def test_2(otherarg, modarg):
|
||||
print(" RUN test2 with otherarg {} and modarg {}".format(otherarg, modarg))
|
||||
print(f" RUN test2 with otherarg {otherarg} and modarg {modarg}")
|
||||
|
||||
|
||||
Let's run the tests in verbose mode and with looking at the print-output:
|
||||
@@ -1687,6 +1691,7 @@ and declare its use in a test module via a ``usefixtures`` marker:
|
||||
|
||||
# content of test_setenv.py
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
|
||||
@@ -55,6 +55,13 @@ These options can also be customized through ``pytest.ini`` file:
|
||||
log_format = %(asctime)s %(levelname)s %(message)s
|
||||
log_date_format = %Y-%m-%d %H:%M:%S
|
||||
|
||||
Specific loggers can be disabled via ``--log-disable={logger_name}``.
|
||||
This argument can be passed multiple times:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pytest --log-disable=main --log-disable=testing
|
||||
|
||||
Further it is possible to disable reporting of captured content (stdout,
|
||||
stderr and logs) on failed tests completely with:
|
||||
|
||||
@@ -73,7 +80,6 @@ messages. This is supported by the ``caplog`` fixture:
|
||||
|
||||
def test_foo(caplog):
|
||||
caplog.set_level(logging.INFO)
|
||||
pass
|
||||
|
||||
By default the level is set on the root logger,
|
||||
however as a convenience it is also possible to set the log level of any
|
||||
@@ -83,7 +89,6 @@ logger:
|
||||
|
||||
def test_foo(caplog):
|
||||
caplog.set_level(logging.CRITICAL, logger="root.baz")
|
||||
pass
|
||||
|
||||
The log levels set are restored automatically at the end of the test.
|
||||
|
||||
@@ -161,9 +166,7 @@ the records for the ``setup`` and ``call`` stages during teardown like so:
|
||||
x.message for x in caplog.get_records(when) if x.levelno == logging.WARNING
|
||||
]
|
||||
if messages:
|
||||
pytest.fail(
|
||||
"warning messages encountered during testing: {}".format(messages)
|
||||
)
|
||||
pytest.fail(f"warning messages encountered during testing: {messages}")
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@ How to run tests written for nose
|
||||
|
||||
``pytest`` has basic support for running tests written for nose_.
|
||||
|
||||
.. warning::
|
||||
This functionality has been deprecated and is likely to be removed in ``pytest 8.x``.
|
||||
|
||||
.. _nosestyle:
|
||||
|
||||
Usage
|
||||
|
||||
@@ -12,8 +12,9 @@ Examples for modifying traceback printing:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
pytest --showlocals # show local variables in tracebacks
|
||||
pytest -l # show local variables (shortcut)
|
||||
pytest --showlocals # show local variables in tracebacks
|
||||
pytest -l # show local variables (shortcut)
|
||||
pytest --no-showlocals # hide local variables (if addopts enables them)
|
||||
|
||||
pytest --tb=auto # (default) 'long' tracebacks for the first and last
|
||||
# entry, but 'short' style for the other entries
|
||||
@@ -348,8 +349,7 @@ Example:
|
||||
test_example.py:14: AssertionError
|
||||
========================= short test summary info ==========================
|
||||
SKIPPED [1] test_example.py:22: skipping this test
|
||||
XFAIL test_example.py::test_xfail
|
||||
reason: xfailing this test
|
||||
XFAIL test_example.py::test_xfail - reason: xfailing this test
|
||||
XPASS test_example.py::test_xpass always xfail
|
||||
ERROR test_example.py::test_error - assert 0
|
||||
FAILED test_example.py::test_fail - assert 0
|
||||
|
||||
@@ -69,6 +69,7 @@ It is also possible to skip the whole module using
|
||||
.. code-block:: python
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
if not sys.platform.startswith("win"):
|
||||
@@ -409,6 +410,7 @@ test instances when using parametrize:
|
||||
.. code-block:: python
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
|
||||
@@ -131,10 +131,13 @@ The default base temporary directory
|
||||
|
||||
Temporary directories are by default created as sub-directories of
|
||||
the system temporary directory. The base name will be ``pytest-NUM`` where
|
||||
``NUM`` will be incremented with each test run. Moreover, entries older
|
||||
than 3 temporary directories will be removed.
|
||||
``NUM`` will be incremented with each test run.
|
||||
By default, only the directories of failed tests will be kept.
|
||||
Also only the last 3 directries will remain at most.
|
||||
This behavior can be configured with :confval:`tmp_path_retention_count` and
|
||||
:confval:`tmp_path_retention_policy`.
|
||||
|
||||
The number of entries currently cannot be changed, but using the ``--basetemp``
|
||||
Using the ``--basetemp``
|
||||
option will remove the directory before every run, effectively meaning the temporary directories
|
||||
of only the most recent run will be kept.
|
||||
|
||||
|
||||
@@ -118,6 +118,7 @@ fixture definition:
|
||||
# content of test_unittest_db.py
|
||||
|
||||
import unittest
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -156,7 +157,7 @@ the ``self.db`` values in the traceback:
|
||||
E AssertionError: <conftest.db_class.<locals>.DummyDB object at 0xdeadbeef0001>
|
||||
E assert 0
|
||||
|
||||
test_unittest_db.py:10: AssertionError
|
||||
test_unittest_db.py:11: AssertionError
|
||||
___________________________ MyTest.test_method2 ____________________________
|
||||
|
||||
self = <test_unittest_db.MyTest testMethod=test_method2>
|
||||
@@ -166,7 +167,7 @@ the ``self.db`` values in the traceback:
|
||||
E AssertionError: <conftest.db_class.<locals>.DummyDB object at 0xdeadbeef0001>
|
||||
E assert 0
|
||||
|
||||
test_unittest_db.py:13: AssertionError
|
||||
test_unittest_db.py:14: AssertionError
|
||||
========================= short test summary info ==========================
|
||||
FAILED test_unittest_db.py::MyTest::test_method1 - AssertionError: <conft...
|
||||
FAILED test_unittest_db.py::MyTest::test_method2 - AssertionError: <conft...
|
||||
@@ -197,10 +198,10 @@ creation of a per-test temporary directory:
|
||||
.. code-block:: python
|
||||
|
||||
# content of test_unittest_cleandir.py
|
||||
import os
|
||||
import pytest
|
||||
import unittest
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class MyTest(unittest.TestCase):
|
||||
@pytest.fixture(autouse=True)
|
||||
|
||||
@@ -183,9 +183,10 @@ You can specify additional plugins to ``pytest.main``:
|
||||
.. code-block:: python
|
||||
|
||||
# content of myinvoke.py
|
||||
import pytest
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
class MyPlugin:
|
||||
def pytest_sessionfinish(self):
|
||||
|
||||
@@ -194,7 +194,7 @@ class or module can then be passed to the ``pluginmanager`` using the ``pytest_a
|
||||
.. code-block:: python
|
||||
|
||||
def pytest_addhooks(pluginmanager):
|
||||
""" This example assumes the hooks are grouped in the 'sample_hook' module. """
|
||||
"""This example assumes the hooks are grouped in the 'sample_hook' module."""
|
||||
from my_app.tests import sample_hook
|
||||
|
||||
pluginmanager.add_hookspecs(sample_hook)
|
||||
@@ -253,14 +253,14 @@ and use pytest_addoption as follows:
|
||||
# default value
|
||||
@hookspec(firstresult=True)
|
||||
def pytest_config_file_default_value():
|
||||
""" Return the default value for the config file command line option. """
|
||||
"""Return the default value for the config file command line option."""
|
||||
|
||||
|
||||
# contents of myplugin.py
|
||||
|
||||
|
||||
def pytest_addhooks(pluginmanager):
|
||||
""" This example assumes the hooks are grouped in the 'hooks' module. """
|
||||
"""This example assumes the hooks are grouped in the 'hooks' module."""
|
||||
from . import hooks
|
||||
|
||||
pluginmanager.add_hookspecs(hooks)
|
||||
|
||||
@@ -147,29 +147,37 @@ Making your plugin installable by others
|
||||
|
||||
If you want to make your plugin externally available, you
|
||||
may define a so-called entry point for your distribution so
|
||||
that ``pytest`` finds your plugin module. Entry points are
|
||||
a feature that is provided by :std:doc:`setuptools:index`. pytest looks up
|
||||
the ``pytest11`` entrypoint to discover its
|
||||
plugins and you can thus make your plugin available by defining
|
||||
it in your setuptools-invocation:
|
||||
that ``pytest`` finds your plugin module. Entry points are
|
||||
a feature that is provided by :std:doc:`setuptools <setuptools:index>`.
|
||||
|
||||
.. sourcecode:: python
|
||||
pytest looks up the ``pytest11`` entrypoint to discover its
|
||||
plugins, thus you can make your plugin available by defining
|
||||
it in your ``pyproject.toml`` file.
|
||||
|
||||
# sample ./setup.py file
|
||||
from setuptools import setup
|
||||
.. sourcecode:: toml
|
||||
|
||||
setup(
|
||||
name="myproject",
|
||||
packages=["myproject"],
|
||||
# the following makes a plugin available to pytest
|
||||
entry_points={"pytest11": ["name_of_plugin = myproject.pluginmodule"]},
|
||||
# custom PyPI classifier for pytest plugins
|
||||
classifiers=["Framework :: Pytest"],
|
||||
)
|
||||
# sample ./pyproject.toml file
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "myproject"
|
||||
classifiers = [
|
||||
"Framework :: Pytest",
|
||||
]
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["myproject"]
|
||||
|
||||
[project.entry_points]
|
||||
pytest11 = [
|
||||
"myproject = myproject.pluginmodule",
|
||||
]
|
||||
|
||||
If a package is installed this way, ``pytest`` will load
|
||||
``myproject.pluginmodule`` as a plugin which can define
|
||||
:ref:`hooks <hook-reference>`.
|
||||
:ref:`hooks <hook-reference>`. Confirm registration with ``pytest --trace-config``
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -367,7 +375,7 @@ string value of ``Hello World!`` if we do not supply a value or ``Hello
|
||||
def _hello(name=None):
|
||||
if not name:
|
||||
name = request.config.getoption("name")
|
||||
return "Hello {name}!".format(name=name)
|
||||
return f"Hello {name}!"
|
||||
|
||||
return _hello
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ which will usually be called once for all the functions:
|
||||
.. code-block:: python
|
||||
|
||||
def setup_module(module):
|
||||
""" setup any state specific to the execution of the given module."""
|
||||
"""setup any state specific to the execution of the given module."""
|
||||
|
||||
|
||||
def teardown_module(module):
|
||||
@@ -63,6 +63,8 @@ and after all test methods of the class are called:
|
||||
setup_class.
|
||||
"""
|
||||
|
||||
.. _xunit-method-setup:
|
||||
|
||||
Method and function level setup/teardown
|
||||
-----------------------------------------------
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
.. sidebar:: Next Open Trainings
|
||||
|
||||
- Professionelles Testen für Python mit pytest, part of `enterPy <https://www.enterpy.de/>`__ (German), `October 28th <https://www.enterpy.de/veranstaltung-15409-se-0-professionelles-testen-fuer-python-mit-pytest.html>`__ (sold out) and `November 4th <https://www.enterpy.de/veranstaltung-15557-se-0-professionelles-testen-fuer-python-mit-pytest-zusatztermin.html>`__, online
|
||||
- `Professional Testing with Python <https://python-academy.com/courses/python_course_testing.html>`_, via `Python Academy <https://www.python-academy.com/>`_, March 7th to 9th 2023 (3 day in-depth training), Remote and Leipzig, Germany
|
||||
|
||||
Also see :doc:`previous talks and blogposts <talks>`.
|
||||
|
||||
@@ -29,9 +29,11 @@ pytest.ini
|
||||
|
||||
``pytest.ini`` files take precedence over other files, even when empty.
|
||||
|
||||
Alternatively, the hidden version ``.pytest.ini`` can be used.
|
||||
|
||||
.. code-block:: ini
|
||||
|
||||
# pytest.ini
|
||||
# pytest.ini or .pytest.ini
|
||||
[pytest]
|
||||
minversion = 6.0
|
||||
addopts = -ra -q
|
||||
@@ -88,7 +90,7 @@ and can also be used to hold pytest configuration if they have a ``[pytest]`` se
|
||||
setup.cfg
|
||||
~~~~~~~~~
|
||||
|
||||
``setup.cfg`` files are general purpose configuration files, used originally by :doc:`distutils <distutils/configfile>`, and can also be used to hold pytest configuration
|
||||
``setup.cfg`` files are general purpose configuration files, used originally by :doc:`distutils <python:distutils/configfile>`, and can also be used to hold pytest configuration
|
||||
if they have a ``[tool:pytest]`` section.
|
||||
|
||||
.. code-block:: ini
|
||||
|
||||
+2761
-1377
File diff suppressed because it is too large
Load Diff
+305
-262
@@ -102,7 +102,7 @@ pytest.deprecated_call
|
||||
|
||||
**Tutorial**: :ref:`ensuring_function_triggers`
|
||||
|
||||
.. autofunction:: pytest.deprecated_call()
|
||||
.. autofunction:: pytest.deprecated_call([match])
|
||||
:with:
|
||||
|
||||
pytest.register_assert_rewrite
|
||||
@@ -290,7 +290,7 @@ Example for using multiple custom markers:
|
||||
def test_function():
|
||||
...
|
||||
|
||||
When :meth:`Node.iter_markers <_pytest.nodes.Node.iter_markers>` or :meth:`Node.iter_markers <_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(...)``.
|
||||
When :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(...)``.
|
||||
|
||||
.. _`fixtures-api`:
|
||||
|
||||
@@ -333,6 +333,68 @@ For more details, consult the full :ref:`fixtures docs <fixture>`.
|
||||
:decorator:
|
||||
|
||||
|
||||
.. fixture:: capfd
|
||||
|
||||
capfd
|
||||
~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`captures`
|
||||
|
||||
.. autofunction:: _pytest.capture.capfd()
|
||||
:no-auto-options:
|
||||
|
||||
|
||||
.. fixture:: capfdbinary
|
||||
|
||||
capfdbinary
|
||||
~~~~~~~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`captures`
|
||||
|
||||
.. autofunction:: _pytest.capture.capfdbinary()
|
||||
:no-auto-options:
|
||||
|
||||
|
||||
.. fixture:: caplog
|
||||
|
||||
caplog
|
||||
~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`logging`
|
||||
|
||||
.. autofunction:: _pytest.logging.caplog()
|
||||
:no-auto-options:
|
||||
|
||||
Returns a :class:`pytest.LogCaptureFixture` instance.
|
||||
|
||||
.. autoclass:: pytest.LogCaptureFixture()
|
||||
:members:
|
||||
|
||||
|
||||
.. fixture:: capsys
|
||||
|
||||
capsys
|
||||
~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`captures`
|
||||
|
||||
.. autofunction:: _pytest.capture.capsys()
|
||||
:no-auto-options:
|
||||
|
||||
.. autoclass:: pytest.CaptureFixture()
|
||||
:members:
|
||||
|
||||
.. fixture:: capsysbinary
|
||||
|
||||
capsysbinary
|
||||
~~~~~~~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`captures`
|
||||
|
||||
.. autofunction:: _pytest.capture.capsysbinary()
|
||||
:no-auto-options:
|
||||
|
||||
|
||||
.. fixture:: cache
|
||||
|
||||
config.cache
|
||||
@@ -353,51 +415,6 @@ Under the hood, the cache plugin uses the simple
|
||||
:members:
|
||||
|
||||
|
||||
.. fixture:: capsys
|
||||
|
||||
capsys
|
||||
~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`captures`
|
||||
|
||||
.. autofunction:: _pytest.capture.capsys()
|
||||
:no-auto-options:
|
||||
|
||||
.. autoclass:: pytest.CaptureFixture()
|
||||
:members:
|
||||
|
||||
|
||||
.. fixture:: capsysbinary
|
||||
|
||||
capsysbinary
|
||||
~~~~~~~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`captures`
|
||||
|
||||
.. autofunction:: _pytest.capture.capsysbinary()
|
||||
:no-auto-options:
|
||||
|
||||
.. fixture:: capfd
|
||||
|
||||
capfd
|
||||
~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`captures`
|
||||
|
||||
.. autofunction:: _pytest.capture.capfd()
|
||||
:no-auto-options:
|
||||
|
||||
.. fixture:: capfdbinary
|
||||
|
||||
capfdbinary
|
||||
~~~~~~~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`captures`
|
||||
|
||||
.. autofunction:: _pytest.capture.capfdbinary()
|
||||
:no-auto-options:
|
||||
|
||||
|
||||
.. fixture:: doctest_namespace
|
||||
|
||||
doctest_namespace
|
||||
@@ -408,63 +425,6 @@ doctest_namespace
|
||||
.. autofunction:: _pytest.doctest.doctest_namespace()
|
||||
|
||||
|
||||
.. fixture:: request
|
||||
|
||||
request
|
||||
~~~~~~~
|
||||
|
||||
**Example**: :ref:`request example`
|
||||
|
||||
The ``request`` fixture is a special fixture providing information of the requesting test function.
|
||||
|
||||
.. autoclass:: pytest.FixtureRequest()
|
||||
:members:
|
||||
|
||||
|
||||
.. fixture:: pytestconfig
|
||||
|
||||
pytestconfig
|
||||
~~~~~~~~~~~~
|
||||
|
||||
.. autofunction:: _pytest.fixtures.pytestconfig()
|
||||
|
||||
|
||||
.. fixture:: record_property
|
||||
|
||||
record_property
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`record_property example`
|
||||
|
||||
.. autofunction:: _pytest.junitxml.record_property()
|
||||
|
||||
|
||||
.. fixture:: record_testsuite_property
|
||||
|
||||
record_testsuite_property
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`record_testsuite_property example`
|
||||
|
||||
.. autofunction:: _pytest.junitxml.record_testsuite_property()
|
||||
|
||||
|
||||
.. fixture:: caplog
|
||||
|
||||
caplog
|
||||
~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`logging`
|
||||
|
||||
.. autofunction:: _pytest.logging.caplog()
|
||||
:no-auto-options:
|
||||
|
||||
Returns a :class:`pytest.LogCaptureFixture` instance.
|
||||
|
||||
.. autoclass:: pytest.LogCaptureFixture()
|
||||
:members:
|
||||
|
||||
|
||||
.. fixture:: monkeypatch
|
||||
|
||||
monkeypatch
|
||||
@@ -481,6 +441,14 @@ monkeypatch
|
||||
:members:
|
||||
|
||||
|
||||
.. fixture:: pytestconfig
|
||||
|
||||
pytestconfig
|
||||
~~~~~~~~~~~~
|
||||
|
||||
.. autofunction:: _pytest.fixtures.pytestconfig()
|
||||
|
||||
|
||||
.. fixture:: pytester
|
||||
|
||||
pytester
|
||||
@@ -517,18 +485,25 @@ To use it, include in your topmost ``conftest.py`` file:
|
||||
.. autoclass:: pytest.RecordedHookCall()
|
||||
:members:
|
||||
|
||||
.. fixture:: testdir
|
||||
|
||||
testdir
|
||||
~~~~~~~
|
||||
.. fixture:: record_property
|
||||
|
||||
Identical to :fixture:`pytester`, but provides an instance whose methods return
|
||||
legacy ``py.path.local`` objects instead when applicable.
|
||||
record_property
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
New code should avoid using :fixture:`testdir` in favor of :fixture:`pytester`.
|
||||
**Tutorial**: :ref:`record_property example`
|
||||
|
||||
.. autoclass:: pytest.Testdir()
|
||||
:members:
|
||||
.. autofunction:: _pytest.junitxml.record_property()
|
||||
|
||||
|
||||
.. fixture:: record_testsuite_property
|
||||
|
||||
record_testsuite_property
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
**Tutorial**: :ref:`record_testsuite_property example`
|
||||
|
||||
.. autofunction:: _pytest.junitxml.record_testsuite_property()
|
||||
|
||||
|
||||
.. fixture:: recwarn
|
||||
@@ -545,6 +520,34 @@ recwarn
|
||||
:members:
|
||||
|
||||
|
||||
.. fixture:: request
|
||||
|
||||
request
|
||||
~~~~~~~
|
||||
|
||||
**Example**: :ref:`request example`
|
||||
|
||||
The ``request`` fixture is a special fixture providing information of the requesting test function.
|
||||
|
||||
.. autoclass:: pytest.FixtureRequest()
|
||||
:members:
|
||||
|
||||
|
||||
.. fixture:: testdir
|
||||
|
||||
testdir
|
||||
~~~~~~~
|
||||
|
||||
Identical to :fixture:`pytester`, but provides an instance whose methods return
|
||||
legacy ``py.path.local`` objects instead when applicable.
|
||||
|
||||
New code should avoid using :fixture:`testdir` in favor of :fixture:`pytester`.
|
||||
|
||||
.. autoclass:: pytest.Testdir()
|
||||
:members:
|
||||
:noindex: TimeoutExpired
|
||||
|
||||
|
||||
.. fixture:: tmp_path
|
||||
|
||||
tmp_path
|
||||
@@ -1130,6 +1133,12 @@ Custom warnings generated in some situations such as improper usage or deprecate
|
||||
.. autoclass:: pytest.PytestExperimentalApiWarning
|
||||
:show-inheritance:
|
||||
|
||||
.. autoclass:: pytest.PytestReturnNotNoneWarning
|
||||
:show-inheritance:
|
||||
|
||||
.. autoclass:: pytest.PytestRemovedIn8Warning
|
||||
:show-inheritance:
|
||||
|
||||
.. autoclass:: pytest.PytestUnhandledCoroutineWarning
|
||||
:show-inheritance:
|
||||
|
||||
@@ -1151,9 +1160,10 @@ Consult the :ref:`internal-warnings` section in the documentation for more infor
|
||||
Configuration Options
|
||||
---------------------
|
||||
|
||||
Here is a list of builtin configuration options that may be written in a ``pytest.ini``, ``pyproject.toml``, ``tox.ini`` or ``setup.cfg``
|
||||
file, usually located at the root of your repository. To see each file format in details, see
|
||||
:ref:`config file formats`.
|
||||
Here is a list of builtin configuration options that may be written in a ``pytest.ini`` (or ``.pytest.ini``),
|
||||
``pyproject.toml``, ``tox.ini``, or ``setup.cfg`` file, usually located at the root of your repository.
|
||||
|
||||
To see each file format in details, see :ref:`config file formats`.
|
||||
|
||||
.. warning::
|
||||
Usage of ``setup.cfg`` is not recommended except for very simple use cases. ``.cfg``
|
||||
@@ -1699,6 +1709,8 @@ passed multiple times. The expected format is ``name=value``. For example::
|
||||
Sets list of directories that should be searched for tests when
|
||||
no specific directories, files or test ids are given in the command line when
|
||||
executing pytest from the :ref:`rootdir <rootdir>` directory.
|
||||
File system paths may use shell-style wildcards, including the recursive
|
||||
``**`` pattern.
|
||||
Useful when all project tests are in a known location to speed up
|
||||
test collection and to avoid picking up undesired tests by accident.
|
||||
|
||||
@@ -1711,6 +1723,40 @@ passed multiple times. The expected format is ``name=value``. For example::
|
||||
directories when executing from the root directory.
|
||||
|
||||
|
||||
.. confval:: tmp_path_retention_count
|
||||
|
||||
|
||||
|
||||
How many sessions should we keep the `tmp_path` directories,
|
||||
according to `tmp_path_retention_policy`.
|
||||
|
||||
.. code-block:: ini
|
||||
|
||||
[pytest]
|
||||
tmp_path_retention_count = 3
|
||||
|
||||
Default: 3
|
||||
|
||||
|
||||
.. confval:: tmp_path_retention_policy
|
||||
|
||||
|
||||
|
||||
Controls which directories created by the `tmp_path` fixture are kept around,
|
||||
based on test outcome.
|
||||
|
||||
* `all`: retains directories for all tests, regardless of the outcome.
|
||||
* `failed`: retains directories only for tests with outcome `error` or `failed`.
|
||||
* `none`: directories are always removed after each test ends, regardless of the outcome.
|
||||
|
||||
.. code-block:: ini
|
||||
|
||||
[pytest]
|
||||
tmp_path_retention_policy = "all"
|
||||
|
||||
Default: failed
|
||||
|
||||
|
||||
.. confval:: usefixtures
|
||||
|
||||
List of fixtures that will be applied to all test functions; this is semantically the same to apply
|
||||
@@ -1751,8 +1797,8 @@ All the command-line flags can be obtained by running ``pytest --help``::
|
||||
file_or_dir
|
||||
|
||||
general:
|
||||
-k EXPRESSION only run tests which match the given substring
|
||||
expression. An expression is a python evaluatable
|
||||
-k EXPRESSION Only run tests which match the given substring
|
||||
expression. An expression is a Python evaluatable
|
||||
expression where all names are substring-matched
|
||||
against test names and their parent classes.
|
||||
Example: -k 'test_method or test_other' matches all
|
||||
@@ -1766,93 +1812,93 @@ All the command-line flags can be obtained by running ``pytest --help``::
|
||||
'extra_keyword_matches' set, as well as functions
|
||||
which have names assigned directly to them. The
|
||||
matching is case-insensitive.
|
||||
-m MARKEXPR only run tests matching given mark expression.
|
||||
For example: -m 'mark1 and not mark2'.
|
||||
-m MARKEXPR Only run tests matching given mark expression. For
|
||||
example: -m 'mark1 and not mark2'.
|
||||
--markers show markers (builtin, plugin and per-project ones).
|
||||
-x, --exitfirst exit instantly on first error or failed test.
|
||||
-x, --exitfirst Exit instantly on first error or failed test
|
||||
--fixtures, --funcargs
|
||||
show available fixtures, sorted by plugin appearance
|
||||
Show available fixtures, sorted by plugin appearance
|
||||
(fixtures with leading '_' are only shown with '-v')
|
||||
--fixtures-per-test show fixtures per test
|
||||
--pdb start the interactive Python debugger on errors or
|
||||
KeyboardInterrupt.
|
||||
--fixtures-per-test Show fixtures per test
|
||||
--pdb Start the interactive Python debugger on errors or
|
||||
KeyboardInterrupt
|
||||
--pdbcls=modulename:classname
|
||||
specify a custom interactive Python debugger for use
|
||||
Specify a custom interactive Python debugger for use
|
||||
with --pdb.For example:
|
||||
--pdbcls=IPython.terminal.debugger:TerminalPdb
|
||||
--trace Immediately break when running each test.
|
||||
--capture=method per-test capturing method: one of fd|sys|no|tee-sys.
|
||||
-s shortcut for --capture=no.
|
||||
--runxfail report the results of xfail tests as if they were
|
||||
--trace Immediately break when running each test
|
||||
--capture=method Per-test capturing method: one of fd|sys|no|tee-sys
|
||||
-s Shortcut for --capture=no
|
||||
--runxfail Report the results of xfail tests as if they were
|
||||
not marked
|
||||
--lf, --last-failed rerun only the tests that failed at the last run (or
|
||||
--lf, --last-failed Rerun only the tests that failed at the last run (or
|
||||
all if none failed)
|
||||
--ff, --failed-first run all tests, but run the last failures first.
|
||||
This may re-order tests and thus lead to repeated
|
||||
fixture setup/teardown.
|
||||
--nf, --new-first run tests from new files first, then the rest of the
|
||||
--ff, --failed-first Run all tests, but run the last failures first. This
|
||||
may re-order tests and thus lead to repeated fixture
|
||||
setup/teardown.
|
||||
--nf, --new-first Run tests from new files first, then the rest of the
|
||||
tests sorted by file mtime
|
||||
--cache-show=[CACHESHOW]
|
||||
show cache contents, don't perform collection or
|
||||
Show cache contents, don't perform collection or
|
||||
tests. Optional argument: glob (default: '*').
|
||||
--cache-clear remove all cache contents at start of test run.
|
||||
--cache-clear Remove all cache contents at start of test run
|
||||
--lfnf={all,none}, --last-failed-no-failures={all,none}
|
||||
which tests to run with no previously (known)
|
||||
failures.
|
||||
--sw, --stepwise exit on test failure and continue from last failing
|
||||
Which tests to run with no previously (known)
|
||||
failures
|
||||
--sw, --stepwise Exit on test failure and continue from last failing
|
||||
test next time
|
||||
--sw-skip, --stepwise-skip
|
||||
ignore the first failing test but stop on the next
|
||||
failing test.
|
||||
implicitly enables --stepwise.
|
||||
Ignore the first failing test but stop on the next
|
||||
failing test. Implicitly enables --stepwise.
|
||||
|
||||
reporting:
|
||||
--durations=N show N slowest setup/test durations (N=0 for all).
|
||||
Reporting:
|
||||
--durations=N Show N slowest setup/test durations (N=0 for all)
|
||||
--durations-min=N Minimal duration in seconds for inclusion in slowest
|
||||
list. Default 0.005
|
||||
-v, --verbose increase verbosity.
|
||||
--no-header disable header
|
||||
--no-summary disable summary
|
||||
-q, --quiet decrease verbosity.
|
||||
--verbosity=VERBOSE set verbosity. Default is 0.
|
||||
-r chars show extra test summary info as specified by chars:
|
||||
list. Default: 0.005.
|
||||
-v, --verbose Increase verbosity
|
||||
--no-header Disable header
|
||||
--no-summary Disable summary
|
||||
-q, --quiet Decrease verbosity
|
||||
--verbosity=VERBOSE Set verbosity. Default: 0.
|
||||
-r chars Show extra test summary info as specified by chars:
|
||||
(f)ailed, (E)rror, (s)kipped, (x)failed, (X)passed,
|
||||
(p)assed, (P)assed with output, (a)ll except passed
|
||||
(p/P), or (A)ll. (w)arnings are enabled by default
|
||||
(see --disable-warnings), 'N' can be used to reset
|
||||
the list. (default: 'fE').
|
||||
--disable-warnings, --disable-pytest-warnings
|
||||
disable warnings summary
|
||||
-l, --showlocals show locals in tracebacks (disabled by default).
|
||||
--tb=style traceback print mode
|
||||
(auto/long/short/line/native/no).
|
||||
Disable warnings summary
|
||||
-l, --showlocals Show locals in tracebacks (disabled by default)
|
||||
--no-showlocals Hide locals in tracebacks (negate --showlocals
|
||||
passed through addopts)
|
||||
--tb=style Traceback print mode
|
||||
(auto/long/short/line/native/no)
|
||||
--show-capture={no,stdout,stderr,log,all}
|
||||
Controls how captured stdout/stderr/log is shown on
|
||||
failed tests. Default is 'all'.
|
||||
--full-trace don't cut any tracebacks (default is to cut).
|
||||
--color=color color terminal output (yes/no/auto).
|
||||
failed tests. Default: all.
|
||||
--full-trace Don't cut any tracebacks (default is to cut)
|
||||
--color=color Color terminal output (yes/no/auto)
|
||||
--code-highlight={yes,no}
|
||||
Whether code should be highlighted (only if --color
|
||||
is also enabled)
|
||||
--pastebin=mode send failed|all info to bpaste.net pastebin service.
|
||||
--junit-xml=path create junit-xml style report file at given path.
|
||||
--junit-prefix=str prepend prefix to classnames in junit-xml output
|
||||
is also enabled). Default: yes.
|
||||
--pastebin=mode Send failed|all info to bpaste.net pastebin service
|
||||
--junit-xml=path Create junit-xml style report file at given path
|
||||
--junit-prefix=str Prepend prefix to classnames in junit-xml output
|
||||
|
||||
pytest-warnings:
|
||||
-W PYTHONWARNINGS, --pythonwarnings=PYTHONWARNINGS
|
||||
set which warnings to report, see -W option of
|
||||
python itself.
|
||||
--maxfail=num exit after first num failures or errors.
|
||||
--strict-config any warnings encountered while parsing the `pytest`
|
||||
section of the configuration file raise errors.
|
||||
--strict-markers markers not registered in the `markers` section of
|
||||
the configuration file raise errors.
|
||||
--strict (deprecated) alias to --strict-markers.
|
||||
-c file load configuration from `file` instead of trying to
|
||||
locate one of the implicit configuration files.
|
||||
Set which warnings to report, see -W option of
|
||||
Python itself
|
||||
--maxfail=num Exit after first num failures or errors
|
||||
--strict-config Any warnings encountered while parsing the `pytest`
|
||||
section of the configuration file raise errors
|
||||
--strict-markers Markers not registered in the `markers` section of
|
||||
the configuration file raise errors
|
||||
--strict (Deprecated) alias to --strict-markers
|
||||
-c file Load configuration from `file` instead of trying to
|
||||
locate one of the implicit configuration files
|
||||
--continue-on-collection-errors
|
||||
Force test execution even if collection errors
|
||||
occur.
|
||||
Force test execution even if collection errors occur
|
||||
--rootdir=ROOTDIR Define root directory for tests. Can be relative
|
||||
path: 'root_dir', './root_dir',
|
||||
'root_dir/another_dir/'; absolute path:
|
||||
@@ -1860,123 +1906,120 @@ All the command-line flags can be obtained by running ``pytest --help``::
|
||||
'$HOME/root_dir'.
|
||||
|
||||
collection:
|
||||
--collect-only, --co only collect tests, don't execute them.
|
||||
--pyargs try to interpret all arguments as python packages.
|
||||
--ignore=path ignore path during collection (multi-allowed).
|
||||
--ignore-glob=path ignore path pattern during collection (multi-
|
||||
allowed).
|
||||
--collect-only, --co Only collect tests, don't execute them
|
||||
--pyargs Try to interpret all arguments as Python packages
|
||||
--ignore=path Ignore path during collection (multi-allowed)
|
||||
--ignore-glob=path Ignore path pattern during collection (multi-
|
||||
allowed)
|
||||
--deselect=nodeid_prefix
|
||||
deselect item (via node id prefix) during collection
|
||||
(multi-allowed).
|
||||
--confcutdir=dir only load conftest.py's relative to specified dir.
|
||||
--noconftest Don't load any conftest.py files.
|
||||
--keep-duplicates Keep duplicate tests.
|
||||
Deselect item (via node id prefix) during collection
|
||||
(multi-allowed)
|
||||
--confcutdir=dir Only load conftest.py's relative to specified dir
|
||||
--noconftest Don't load any conftest.py files
|
||||
--keep-duplicates Keep duplicate tests
|
||||
--collect-in-virtualenv
|
||||
Don't ignore tests in a local virtualenv directory
|
||||
--import-mode={prepend,append,importlib}
|
||||
prepend/append to sys.path when importing test
|
||||
modules and conftest files, default is to prepend.
|
||||
--doctest-modules run doctests in all .py modules
|
||||
Prepend/append to sys.path when importing test
|
||||
modules and conftest files. Default: prepend.
|
||||
--doctest-modules Run doctests in all .py modules
|
||||
--doctest-report={none,cdiff,ndiff,udiff,only_first_failure}
|
||||
choose another output format for diffs on doctest
|
||||
Choose another output format for diffs on doctest
|
||||
failure
|
||||
--doctest-glob=pat doctests file matching pattern, default: test*.txt
|
||||
--doctest-glob=pat Doctests file matching pattern, default: test*.txt
|
||||
--doctest-ignore-import-errors
|
||||
ignore doctest ImportErrors
|
||||
Ignore doctest ImportErrors
|
||||
--doctest-continue-on-failure
|
||||
for a given doctest, continue to run after the first
|
||||
For a given doctest, continue to run after the first
|
||||
failure
|
||||
|
||||
test session debugging and configuration:
|
||||
--basetemp=dir base temporary directory for this test run.(warning:
|
||||
this directory is removed if it exists)
|
||||
-V, --version display pytest version and information about
|
||||
--basetemp=dir Base temporary directory for this test run.
|
||||
(Warning: this directory is removed if it exists.)
|
||||
-V, --version Display pytest version and information about
|
||||
plugins. When given twice, also display information
|
||||
about plugins.
|
||||
-h, --help show help message and configuration info
|
||||
-p name early-load given plugin module name or entry point
|
||||
(multi-allowed).
|
||||
To avoid loading of plugins, use the `no:` prefix,
|
||||
e.g. `no:doctest`.
|
||||
--trace-config trace considerations of conftest.py files.
|
||||
-h, --help Show help message and configuration info
|
||||
-p name Early-load given plugin module name or entry point
|
||||
(multi-allowed). To avoid loading of plugins, use
|
||||
the `no:` prefix, e.g. `no:doctest`.
|
||||
--trace-config Trace considerations of conftest.py files
|
||||
--debug=[DEBUG_FILE_NAME]
|
||||
store internal tracing debug information in this log
|
||||
file.
|
||||
This file is opened with 'w' and truncated as a
|
||||
result, care advised.
|
||||
Defaults to 'pytestdebug.log'.
|
||||
Store internal tracing debug information in this log
|
||||
file. This file is opened with 'w' and truncated as
|
||||
a result, care advised. Default: pytestdebug.log.
|
||||
-o OVERRIDE_INI, --override-ini=OVERRIDE_INI
|
||||
override ini option with "option=value" style, e.g.
|
||||
Override ini option with "option=value" style, e.g.
|
||||
`-o xfail_strict=True -o cache_dir=cache`.
|
||||
--assert=MODE Control assertion debugging tools.
|
||||
'plain' performs no assertion debugging.
|
||||
'rewrite' (the default) rewrites assert statements
|
||||
in test modules on import to provide assert
|
||||
expression information.
|
||||
--setup-only only setup fixtures, do not execute tests.
|
||||
--setup-show show setup of fixtures while executing tests.
|
||||
--setup-plan show what fixtures and tests would be executed but
|
||||
don't execute anything.
|
||||
--setup-only Only setup fixtures, do not execute tests
|
||||
--setup-show Show setup of fixtures while executing tests
|
||||
--setup-plan Show what fixtures and tests would be executed but
|
||||
don't execute anything
|
||||
|
||||
logging:
|
||||
--log-level=LEVEL level of messages to catch/display.
|
||||
Not set by default, so it depends on the root/parent
|
||||
log handler's effective level, where it is "WARNING"
|
||||
by default.
|
||||
--log-level=LEVEL Level of messages to catch/display. Not set by
|
||||
default, so it depends on the root/parent log
|
||||
handler's effective level, where it is "WARNING" by
|
||||
default.
|
||||
--log-format=LOG_FORMAT
|
||||
log format as used by the logging module.
|
||||
Log format used by the logging module
|
||||
--log-date-format=LOG_DATE_FORMAT
|
||||
log date format as used by the logging module.
|
||||
Log date format used by the logging module
|
||||
--log-cli-level=LOG_CLI_LEVEL
|
||||
cli logging level.
|
||||
CLI logging level
|
||||
--log-cli-format=LOG_CLI_FORMAT
|
||||
log format as used by the logging module.
|
||||
Log format used by the logging module
|
||||
--log-cli-date-format=LOG_CLI_DATE_FORMAT
|
||||
log date format as used by the logging module.
|
||||
--log-file=LOG_FILE path to a file when logging will be written to.
|
||||
Log date format used by the logging module
|
||||
--log-file=LOG_FILE Path to a file when logging will be written to
|
||||
--log-file-level=LOG_FILE_LEVEL
|
||||
log file logging level.
|
||||
Log file logging level
|
||||
--log-file-format=LOG_FILE_FORMAT
|
||||
log format as used by the logging module.
|
||||
Log format used by the logging module
|
||||
--log-file-date-format=LOG_FILE_DATE_FORMAT
|
||||
log date format as used by the logging module.
|
||||
Log date format used by the logging module
|
||||
--log-auto-indent=LOG_AUTO_INDENT
|
||||
Auto-indent multiline messages passed to the logging
|
||||
module. Accepts true|on, false|off or an integer.
|
||||
|
||||
[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:
|
||||
|
||||
markers (linelist): markers for test functions
|
||||
markers (linelist): Markers for test functions
|
||||
empty_parameter_set_mark (string):
|
||||
default marker for empty parametersets
|
||||
norecursedirs (args): directory patterns to avoid for recursion
|
||||
testpaths (args): directories to search for tests when no files or
|
||||
directories are given in the command line.
|
||||
Default marker for empty parametersets
|
||||
norecursedirs (args): Directory patterns to avoid for recursion
|
||||
testpaths (args): Directories to search for tests when no files or
|
||||
directories are given on the command line
|
||||
filterwarnings (linelist):
|
||||
Each line specifies a pattern for
|
||||
warnings.filterwarnings. Processed after
|
||||
-W/--pythonwarnings.
|
||||
usefixtures (args): list of default fixtures to be used with this
|
||||
usefixtures (args): List of default fixtures to be used with this
|
||||
project
|
||||
python_files (args): glob-style file patterns for Python test module
|
||||
python_files (args): Glob-style file patterns for Python test module
|
||||
discovery
|
||||
python_classes (args):
|
||||
prefixes or glob names for Python test class
|
||||
Prefixes or glob names for Python test class
|
||||
discovery
|
||||
python_functions (args):
|
||||
prefixes or glob names for Python test function and
|
||||
Prefixes or glob names for Python test function and
|
||||
method discovery
|
||||
disable_test_id_escaping_and_forfeit_all_rights_to_community_support (bool):
|
||||
disable string escape non-ascii characters, might
|
||||
Disable string escape non-ASCII characters, might
|
||||
cause unwanted side effects(use at your own risk)
|
||||
console_output_style (string):
|
||||
console output: "classic", or with additional
|
||||
Console output: "classic", or with additional
|
||||
progress information ("progress" (percentage) |
|
||||
"count").
|
||||
xfail_strict (bool): default for the strict parameter of xfail markers
|
||||
"count")
|
||||
xfail_strict (bool): Default for the strict parameter of xfail markers
|
||||
when not given explicitly (default: False)
|
||||
enable_assertion_pass_hook (bool):
|
||||
Enables the pytest_assertion_pass hook.Make sure to
|
||||
Enables the pytest_assertion_pass hook. Make sure to
|
||||
delete any previously generated pyc cache files.
|
||||
junit_suite_name (string):
|
||||
Test suite name for JUnit report
|
||||
@@ -1991,45 +2034,45 @@ All the command-line flags can be obtained by running ``pytest --help``::
|
||||
junit_family (string):
|
||||
Emit XML for schema: one of legacy|xunit1|xunit2
|
||||
doctest_optionflags (args):
|
||||
option flags for doctests
|
||||
Option flags for doctests
|
||||
doctest_encoding (string):
|
||||
encoding used for doctest files
|
||||
cache_dir (string): cache directory path.
|
||||
log_level (string): default value for --log-level
|
||||
log_format (string): default value for --log-format
|
||||
Encoding used for doctest files
|
||||
cache_dir (string): Cache directory path
|
||||
log_level (string): Default value for --log-level
|
||||
log_format (string): Default value for --log-format
|
||||
log_date_format (string):
|
||||
default value for --log-date-format
|
||||
log_cli (bool): enable log display during test run (also known as
|
||||
"live logging").
|
||||
Default value for --log-date-format
|
||||
log_cli (bool): Enable log display during test run (also known as
|
||||
"live logging")
|
||||
log_cli_level (string):
|
||||
default value for --log-cli-level
|
||||
Default value for --log-cli-level
|
||||
log_cli_format (string):
|
||||
default value for --log-cli-format
|
||||
Default value for --log-cli-format
|
||||
log_cli_date_format (string):
|
||||
default value for --log-cli-date-format
|
||||
log_file (string): default value for --log-file
|
||||
Default value for --log-cli-date-format
|
||||
log_file (string): Default value for --log-file
|
||||
log_file_level (string):
|
||||
default value for --log-file-level
|
||||
Default value for --log-file-level
|
||||
log_file_format (string):
|
||||
default value for --log-file-format
|
||||
Default value for --log-file-format
|
||||
log_file_date_format (string):
|
||||
default value for --log-file-date-format
|
||||
Default value for --log-file-date-format
|
||||
log_auto_indent (string):
|
||||
default value for --log-auto-indent
|
||||
Default value for --log-auto-indent
|
||||
pythonpath (paths): Add paths to sys.path
|
||||
faulthandler_timeout (string):
|
||||
Dump the traceback of all threads if a test takes
|
||||
more than TIMEOUT seconds to finish.
|
||||
addopts (args): extra command line options
|
||||
minversion (string): minimally required pytest version
|
||||
more than TIMEOUT seconds to finish
|
||||
addopts (args): Extra command line options
|
||||
minversion (string): Minimally required pytest version
|
||||
required_plugins (args):
|
||||
plugins that must be present for pytest to run
|
||||
Plugins that must be present for pytest to run
|
||||
|
||||
environment variables:
|
||||
PYTEST_ADDOPTS extra command line options
|
||||
PYTEST_PLUGINS comma-separated plugins to load during startup
|
||||
PYTEST_DISABLE_PLUGIN_AUTOLOAD set to disable plugin auto-loading
|
||||
PYTEST_DEBUG set to enable debug tracing of pytest's internals
|
||||
Environment variables:
|
||||
PYTEST_ADDOPTS Extra command line options
|
||||
PYTEST_PLUGINS Comma-separated plugins to load during startup
|
||||
PYTEST_DISABLE_PLUGIN_AUTOLOAD Set to disable plugin auto-loading
|
||||
PYTEST_DEBUG Set to enable debug tracing of pytest's internals
|
||||
|
||||
|
||||
to see available markers type: pytest --markers
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
pallets-sphinx-themes
|
||||
pluggy>=1.0
|
||||
pygments-pytest>=2.2.0
|
||||
pygments-pytest>=2.3.0
|
||||
sphinx-removed-in>=0.2.0
|
||||
sphinx>=3.1,<4
|
||||
sphinx>=5,<6
|
||||
sphinxcontrib-trio
|
||||
sphinxcontrib-svg2pdfconverter
|
||||
|
||||
# XXX: sphinx<4 is broken with latest jinja2
|
||||
jinja2<3.1
|
||||
# Pin packaging because it no longer handles 'latest' version, which
|
||||
# is the version that is assigned to the docs.
|
||||
# See https://github.com/pytest-dev/pytest/pull/10578#issuecomment-1348249045.
|
||||
packaging <22
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
import sys
|
||||
|
||||
from distutils.core import setup
|
||||
|
||||
if __name__ == "__main__":
|
||||
if "sdist" not in sys.argv[1:]:
|
||||
raise ValueError("please use 'pytest' pypi package instead of 'py.test'")
|
||||
setup(
|
||||
name="py.test",
|
||||
version="0.0",
|
||||
description="please use 'pytest' for installation",
|
||||
)
|
||||
+3
-1
@@ -3,7 +3,6 @@ requires = [
|
||||
# sync with setup.py until we discard non-pep-517/518
|
||||
"setuptools>=45.0",
|
||||
"setuptools-scm[toml]>=6.2.3",
|
||||
"wheel",
|
||||
]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
@@ -38,6 +37,9 @@ filterwarnings = [
|
||||
# Those are caught/handled by pyupgrade, and not easy to filter with the
|
||||
# module being the filename (with .py removed).
|
||||
"default:invalid escape sequence:DeprecationWarning",
|
||||
# ignore not yet fixed warnings for hook markers
|
||||
"default:.*not marked using pytest.hook.*",
|
||||
"ignore:.*not marked using pytest.hook.*::xdist.*",
|
||||
# ignore use of unregistered marks, because we use many to test the implementation
|
||||
"ignore::_pytest.warning_types.PytestUnknownMarkWarning",
|
||||
# https://github.com/benjaminp/six/issues/341
|
||||
|
||||
@@ -78,11 +78,23 @@ def iter_plugins():
|
||||
requires = "N/A"
|
||||
if info["requires_dist"]:
|
||||
for requirement in info["requires_dist"]:
|
||||
if requirement == "pytest" or "pytest " in requirement:
|
||||
if re.match(r"pytest(?![-.\w])", requirement):
|
||||
requires = requirement
|
||||
break
|
||||
|
||||
def version_sort_key(version_string):
|
||||
"""
|
||||
Return the sort key for the given version string
|
||||
returned by the API.
|
||||
"""
|
||||
try:
|
||||
return packaging.version.parse(version_string)
|
||||
except packaging.version.InvalidVersion:
|
||||
# Use a hard-coded pre-release version.
|
||||
return packaging.version.Version("0.0.0alpha")
|
||||
|
||||
releases = response.json()["releases"]
|
||||
for release in sorted(releases, key=packaging.version.parse, reverse=True):
|
||||
for release in sorted(releases, key=version_sort_key, reverse=True):
|
||||
if releases[release]:
|
||||
release_date = datetime.date.fromisoformat(
|
||||
releases[release][-1]["upload_time_iso_8601"].split("T")[0]
|
||||
@@ -90,7 +102,9 @@ def iter_plugins():
|
||||
last_release = release_date.strftime("%b %d, %Y")
|
||||
break
|
||||
name = f':pypi:`{info["name"]}`'
|
||||
summary = escape_rst(info["summary"].replace("\n", ""))
|
||||
summary = ""
|
||||
if info["summary"]:
|
||||
summary = escape_rst(info["summary"].replace("\n", ""))
|
||||
yield {
|
||||
"name": name,
|
||||
"summary": summary.strip(),
|
||||
@@ -122,7 +136,7 @@ def main():
|
||||
reference_dir = pathlib.Path("doc", "en", "reference")
|
||||
|
||||
plugin_list = reference_dir / "plugin_list.rst"
|
||||
with plugin_list.open("w") as f:
|
||||
with plugin_list.open("w", encoding="UTF-8") as f:
|
||||
f.write(FILE_HEAD)
|
||||
f.write(f"This list contains {len(plugins)} plugins.\n\n")
|
||||
f.write(".. only:: not latex\n\n")
|
||||
|
||||
@@ -21,6 +21,7 @@ classifiers =
|
||||
Programming Language :: Python :: 3.8
|
||||
Programming Language :: Python :: 3.9
|
||||
Programming Language :: Python :: 3.10
|
||||
Programming Language :: Python :: 3.11
|
||||
Topic :: Software Development :: Libraries
|
||||
Topic :: Software Development :: Testing
|
||||
Topic :: Utilities
|
||||
@@ -36,20 +37,21 @@ packages =
|
||||
_pytest
|
||||
_pytest._code
|
||||
_pytest._io
|
||||
_pytest._py
|
||||
_pytest.assertion
|
||||
_pytest.config
|
||||
_pytest.mark
|
||||
pytest
|
||||
py_modules = py
|
||||
install_requires =
|
||||
attrs>=19.2.0
|
||||
iniconfig
|
||||
packaging
|
||||
pluggy>=0.12,<2.0
|
||||
py>=1.8.2
|
||||
tomli>=1.0.0
|
||||
colorama;sys_platform=="win32"
|
||||
exceptiongroup>=1.0.0rc8;python_version<"3.11"
|
||||
importlib-metadata>=0.12;python_version<"3.8"
|
||||
tomli>=1.0.0;python_version<"3.11"
|
||||
python_requires = >=3.7
|
||||
package_dir =
|
||||
=src
|
||||
@@ -94,7 +96,6 @@ mypy_path = src
|
||||
check_untyped_defs = True
|
||||
disallow_any_generics = True
|
||||
ignore_missing_imports = True
|
||||
no_implicit_optional = True
|
||||
show_error_codes = True
|
||||
strict_equality = True
|
||||
warn_redundant_casts = True
|
||||
|
||||
@@ -78,15 +78,15 @@ class FastFilesCompleter:
|
||||
|
||||
def __call__(self, prefix: str, **kwargs: Any) -> List[str]:
|
||||
# Only called on non option completions.
|
||||
if os.path.sep in prefix[1:]:
|
||||
prefix_dir = len(os.path.dirname(prefix) + os.path.sep)
|
||||
if os.sep in prefix[1:]:
|
||||
prefix_dir = len(os.path.dirname(prefix) + os.sep)
|
||||
else:
|
||||
prefix_dir = 0
|
||||
completion = []
|
||||
globbed = []
|
||||
if "*" not in prefix and "?" not in prefix:
|
||||
# We are on unix, otherwise no bash.
|
||||
if not prefix or prefix[-1] == os.path.sep:
|
||||
if not prefix or prefix[-1] == os.sep:
|
||||
globbed.extend(glob(prefix + ".*"))
|
||||
prefix += "*"
|
||||
globbed.extend(glob(prefix))
|
||||
|
||||
@@ -675,10 +675,11 @@ class ExceptionInfo(Generic[E]):
|
||||
If it matches `True` is returned, otherwise an `AssertionError` is raised.
|
||||
"""
|
||||
__tracebackhide__ = True
|
||||
msg = "Regex pattern {!r} does not match {!r}."
|
||||
if regexp == str(self.value):
|
||||
msg += " Did you mean to `re.escape()` the regex?"
|
||||
assert re.search(regexp, str(self.value)), msg.format(regexp, str(self.value))
|
||||
value = str(self.value)
|
||||
msg = f"Regex pattern did not match.\n Regex: {regexp!r}\n Input: {value!r}"
|
||||
if regexp == value:
|
||||
msg += "\n Did you mean to `re.escape()` the regex?"
|
||||
assert re.search(regexp, value), msg
|
||||
# Return True to allow for "assert excinfo.match()".
|
||||
return True
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ class SafeRepr(reprlib.Repr):
|
||||
information on exceptions raised during the call.
|
||||
"""
|
||||
|
||||
def __init__(self, maxsize: Optional[int]) -> None:
|
||||
def __init__(self, maxsize: Optional[int], use_ascii: bool = False) -> None:
|
||||
"""
|
||||
:param maxsize:
|
||||
If not None, will truncate the resulting repr to that specific size, using ellipsis
|
||||
@@ -54,10 +54,15 @@ class SafeRepr(reprlib.Repr):
|
||||
# truncation.
|
||||
self.maxstring = maxsize if maxsize is not None else 1_000_000_000
|
||||
self.maxsize = maxsize
|
||||
self.use_ascii = use_ascii
|
||||
|
||||
def repr(self, x: object) -> str:
|
||||
try:
|
||||
s = super().repr(x)
|
||||
if self.use_ascii:
|
||||
s = ascii(x)
|
||||
else:
|
||||
s = super().repr(x)
|
||||
|
||||
except (KeyboardInterrupt, SystemExit):
|
||||
raise
|
||||
except BaseException as exc:
|
||||
@@ -94,7 +99,9 @@ def safeformat(obj: object) -> str:
|
||||
DEFAULT_REPR_MAX_SIZE = 240
|
||||
|
||||
|
||||
def saferepr(obj: object, maxsize: Optional[int] = DEFAULT_REPR_MAX_SIZE) -> str:
|
||||
def saferepr(
|
||||
obj: object, maxsize: Optional[int] = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False
|
||||
) -> str:
|
||||
"""Return a size-limited safe repr-string for the given object.
|
||||
|
||||
Failing __repr__ functions of user instances will be represented
|
||||
@@ -104,7 +111,27 @@ def saferepr(obj: object, maxsize: Optional[int] = DEFAULT_REPR_MAX_SIZE) -> str
|
||||
This function is a wrapper around the Repr/reprlib functionality of the
|
||||
stdlib.
|
||||
"""
|
||||
return SafeRepr(maxsize).repr(obj)
|
||||
|
||||
return SafeRepr(maxsize, use_ascii).repr(obj)
|
||||
|
||||
|
||||
def saferepr_unlimited(obj: object, use_ascii: bool = True) -> str:
|
||||
"""Return an unlimited-size safe repr-string for the given object.
|
||||
|
||||
As with saferepr, failing __repr__ functions of user instances
|
||||
will be represented with a short exception info.
|
||||
|
||||
This function is a wrapper around simple repr.
|
||||
|
||||
Note: a cleaner solution would be to alter ``saferepr``this way
|
||||
when maxsize=None, but that might affect some other code.
|
||||
"""
|
||||
try:
|
||||
if use_ascii:
|
||||
return ascii(obj)
|
||||
return repr(obj)
|
||||
except Exception as exc:
|
||||
return _format_repr_exception(exc, obj)
|
||||
|
||||
|
||||
class AlwaysDispatchingPrettyPrinter(pprint.PrettyPrinter):
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""create errno-specific classes for IO or os calls."""
|
||||
from __future__ import annotations
|
||||
|
||||
import errno
|
||||
import os
|
||||
import sys
|
||||
from typing import Callable
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import TypeVar
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing_extensions import ParamSpec
|
||||
|
||||
P = ParamSpec("P")
|
||||
|
||||
R = TypeVar("R")
|
||||
|
||||
|
||||
class Error(EnvironmentError):
|
||||
def __repr__(self) -> str:
|
||||
return "{}.{} {!r}: {} ".format(
|
||||
self.__class__.__module__,
|
||||
self.__class__.__name__,
|
||||
self.__class__.__doc__,
|
||||
" ".join(map(str, self.args)),
|
||||
# repr(self.args)
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
s = "[{}]: {}".format(
|
||||
self.__class__.__doc__,
|
||||
" ".join(map(str, self.args)),
|
||||
)
|
||||
return s
|
||||
|
||||
|
||||
_winerrnomap = {
|
||||
2: errno.ENOENT,
|
||||
3: errno.ENOENT,
|
||||
17: errno.EEXIST,
|
||||
18: errno.EXDEV,
|
||||
13: errno.EBUSY, # empty cd drive, but ENOMEDIUM seems unavailiable
|
||||
22: errno.ENOTDIR,
|
||||
20: errno.ENOTDIR,
|
||||
267: errno.ENOTDIR,
|
||||
5: errno.EACCES, # anything better?
|
||||
}
|
||||
|
||||
|
||||
class ErrorMaker:
|
||||
"""lazily provides Exception classes for each possible POSIX errno
|
||||
(as defined per the 'errno' module). All such instances
|
||||
subclass EnvironmentError.
|
||||
"""
|
||||
|
||||
_errno2class: dict[int, type[Error]] = {}
|
||||
|
||||
def __getattr__(self, name: str) -> type[Error]:
|
||||
if name[0] == "_":
|
||||
raise AttributeError(name)
|
||||
eno = getattr(errno, name)
|
||||
cls = self._geterrnoclass(eno)
|
||||
setattr(self, name, cls)
|
||||
return cls
|
||||
|
||||
def _geterrnoclass(self, eno: int) -> type[Error]:
|
||||
try:
|
||||
return self._errno2class[eno]
|
||||
except KeyError:
|
||||
clsname = errno.errorcode.get(eno, "UnknownErrno%d" % (eno,))
|
||||
errorcls = type(
|
||||
clsname,
|
||||
(Error,),
|
||||
{"__module__": "py.error", "__doc__": os.strerror(eno)},
|
||||
)
|
||||
self._errno2class[eno] = errorcls
|
||||
return errorcls
|
||||
|
||||
def checked_call(
|
||||
self, func: Callable[P, R], *args: P.args, **kwargs: P.kwargs
|
||||
) -> R:
|
||||
"""Call a function and raise an errno-exception if applicable."""
|
||||
__tracebackhide__ = True
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except Error:
|
||||
raise
|
||||
except OSError as value:
|
||||
if not hasattr(value, "errno"):
|
||||
raise
|
||||
errno = value.errno
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
cls = self._geterrnoclass(_winerrnomap[errno])
|
||||
except KeyError:
|
||||
raise value
|
||||
else:
|
||||
# we are not on Windows, or we got a proper OSError
|
||||
cls = self._geterrnoclass(errno)
|
||||
|
||||
raise cls(f"{func.__name__}{args!r}")
|
||||
|
||||
|
||||
_error_maker = ErrorMaker()
|
||||
checked_call = _error_maker.checked_call
|
||||
|
||||
|
||||
def __getattr__(attr: str) -> type[Error]:
|
||||
return getattr(_error_maker, attr) # type: ignore[no-any-return]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -39,7 +39,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"enable_assertion_pass_hook",
|
||||
type="bool",
|
||||
default=False,
|
||||
help="Enables the pytest_assertion_pass hook."
|
||||
help="Enables the pytest_assertion_pass hook. "
|
||||
"Make sure to delete any previously generated pyc cache files.",
|
||||
)
|
||||
|
||||
@@ -53,7 +53,7 @@ def register_assert_rewrite(*names: str) -> None:
|
||||
actually imported, usually in your __init__.py if you are a plugin
|
||||
using a package.
|
||||
|
||||
:raises TypeError: If the given module names are not strings.
|
||||
:param names: The module names to register.
|
||||
"""
|
||||
for name in names:
|
||||
if not isinstance(name, str):
|
||||
|
||||
@@ -180,7 +180,7 @@ class AssertionRewritingHook(importlib.abc.MetaPathFinder, importlib.abc.Loader)
|
||||
for initial_path in self.session._initialpaths:
|
||||
# Make something as c:/projects/my_project/path.py ->
|
||||
# ['c:', 'projects', 'my_project', 'path.py']
|
||||
parts = str(initial_path).split(os.path.sep)
|
||||
parts = str(initial_path).split(os.sep)
|
||||
# add 'path' to basenames to be checked.
|
||||
self._basenames_to_check_rewrite.add(os.path.splitext(parts[-1])[0])
|
||||
|
||||
@@ -275,7 +275,12 @@ class AssertionRewritingHook(importlib.abc.MetaPathFinder, importlib.abc.Loader)
|
||||
|
||||
if sys.version_info >= (3, 10):
|
||||
|
||||
def get_resource_reader(self, name: str) -> importlib.abc.TraversableResources: # type: ignore
|
||||
if sys.version_info >= (3, 12):
|
||||
from importlib.resources.abc import TraversableResources
|
||||
else:
|
||||
from importlib.abc import TraversableResources
|
||||
|
||||
def get_resource_reader(self, name: str) -> TraversableResources: # type: ignore
|
||||
if sys.version_info < (3, 11):
|
||||
from importlib.readers import FileReader
|
||||
else:
|
||||
|
||||
@@ -38,9 +38,9 @@ def _truncate_explanation(
|
||||
"""Truncate given list of strings that makes up the assertion explanation.
|
||||
|
||||
Truncates to either 8 lines, or 640 characters - whichever the input reaches
|
||||
first. The remaining lines will be replaced by a usage message.
|
||||
first, taking the truncation explanation into account. The remaining lines
|
||||
will be replaced by a usage message.
|
||||
"""
|
||||
|
||||
if max_lines is None:
|
||||
max_lines = DEFAULT_MAX_LINES
|
||||
if max_chars is None:
|
||||
@@ -48,35 +48,56 @@ def _truncate_explanation(
|
||||
|
||||
# Check if truncation required
|
||||
input_char_count = len("".join(input_lines))
|
||||
if len(input_lines) <= max_lines and input_char_count <= max_chars:
|
||||
# The length of the truncation explanation depends on the number of lines
|
||||
# removed but is at least 68 characters:
|
||||
# The real value is
|
||||
# 64 (for the base message:
|
||||
# '...\n...Full output truncated (1 line hidden), use '-vv' to show")'
|
||||
# )
|
||||
# + 1 (for plural)
|
||||
# + int(math.log10(len(input_lines) - max_lines)) (number of hidden line, at least 1)
|
||||
# + 3 for the '...' added to the truncated line
|
||||
# But if there's more than 100 lines it's very likely that we're going to
|
||||
# truncate, so we don't need the exact value using log10.
|
||||
tolerable_max_chars = (
|
||||
max_chars + 70 # 64 + 1 (for plural) + 2 (for '99') + 3 for '...'
|
||||
)
|
||||
# The truncation explanation add two lines to the output
|
||||
tolerable_max_lines = max_lines + 2
|
||||
if (
|
||||
len(input_lines) <= tolerable_max_lines
|
||||
and input_char_count <= tolerable_max_chars
|
||||
):
|
||||
return input_lines
|
||||
|
||||
# Truncate first to max_lines, and then truncate to max_chars if max_chars
|
||||
# is exceeded.
|
||||
# Truncate first to max_lines, and then truncate to max_chars if necessary
|
||||
truncated_explanation = input_lines[:max_lines]
|
||||
truncated_explanation = _truncate_by_char_count(truncated_explanation, max_chars)
|
||||
|
||||
# Add ellipsis to final line
|
||||
truncated_explanation[-1] = truncated_explanation[-1] + "..."
|
||||
|
||||
# Append useful message to explanation
|
||||
truncated_line_count = len(input_lines) - len(truncated_explanation)
|
||||
truncated_line_count += 1 # Account for the part-truncated final line
|
||||
msg = "...Full output truncated"
|
||||
if truncated_line_count == 1:
|
||||
msg += f" ({truncated_line_count} line hidden)"
|
||||
truncated_char = True
|
||||
# We reevaluate the need to truncate chars following removal of some lines
|
||||
if len("".join(truncated_explanation)) > tolerable_max_chars:
|
||||
truncated_explanation = _truncate_by_char_count(
|
||||
truncated_explanation, max_chars
|
||||
)
|
||||
else:
|
||||
msg += f" ({truncated_line_count} lines hidden)"
|
||||
msg += f", {USAGE_MSG}"
|
||||
truncated_explanation.extend(["", str(msg)])
|
||||
return truncated_explanation
|
||||
truncated_char = False
|
||||
|
||||
truncated_line_count = len(input_lines) - len(truncated_explanation)
|
||||
if truncated_explanation[-1]:
|
||||
# Add ellipsis and take into account part-truncated final line
|
||||
truncated_explanation[-1] = truncated_explanation[-1] + "..."
|
||||
if truncated_char:
|
||||
# It's possible that we did not remove any char from this line
|
||||
truncated_line_count += 1
|
||||
else:
|
||||
# Add proper ellipsis when we were able to fit a full line exactly
|
||||
truncated_explanation[-1] = "..."
|
||||
return truncated_explanation + [
|
||||
"",
|
||||
f"...Full output truncated ({truncated_line_count} line"
|
||||
f"{'' if truncated_line_count == 1 else 's'} hidden), {USAGE_MSG}",
|
||||
]
|
||||
|
||||
|
||||
def _truncate_by_char_count(input_lines: List[str], max_chars: int) -> List[str]:
|
||||
# Check if truncation required
|
||||
if len("".join(input_lines)) <= max_chars:
|
||||
return input_lines
|
||||
|
||||
# Find point at which input length exceeds total allowed length
|
||||
iterated_char_count = 0
|
||||
for iterated_index, input_line in enumerate(input_lines):
|
||||
|
||||
@@ -10,12 +10,13 @@ from typing import List
|
||||
from typing import Mapping
|
||||
from typing import Optional
|
||||
from typing import Sequence
|
||||
from unicodedata import normalize
|
||||
|
||||
import _pytest._code
|
||||
from _pytest import outcomes
|
||||
from _pytest._io.saferepr import _pformat_dispatch
|
||||
from _pytest._io.saferepr import safeformat
|
||||
from _pytest._io.saferepr import saferepr
|
||||
from _pytest._io.saferepr import saferepr_unlimited
|
||||
from _pytest.config import Config
|
||||
|
||||
# The _reprcompare attribute on the util module is used by the new assertion
|
||||
@@ -156,20 +157,32 @@ def has_default_eq(
|
||||
return True
|
||||
|
||||
|
||||
def assertrepr_compare(config, op: str, left: Any, right: Any) -> Optional[List[str]]:
|
||||
def assertrepr_compare(
|
||||
config, op: str, left: Any, right: Any, use_ascii: bool = False
|
||||
) -> Optional[List[str]]:
|
||||
"""Return specialised explanations for some operators/operands."""
|
||||
verbose = config.getoption("verbose")
|
||||
|
||||
# Strings which normalize equal are often hard to distinguish when printed; use ascii() to make this easier.
|
||||
# See issue #3246.
|
||||
use_ascii = (
|
||||
isinstance(left, str)
|
||||
and isinstance(right, str)
|
||||
and normalize("NFD", left) == normalize("NFD", right)
|
||||
)
|
||||
|
||||
if verbose > 1:
|
||||
left_repr = safeformat(left)
|
||||
right_repr = safeformat(right)
|
||||
left_repr = saferepr_unlimited(left, use_ascii=use_ascii)
|
||||
right_repr = saferepr_unlimited(right, use_ascii=use_ascii)
|
||||
else:
|
||||
# XXX: "15 chars indentation" is wrong
|
||||
# ("E AssertionError: assert "); should use term width.
|
||||
maxsize = (
|
||||
80 - 15 - len(op) - 2
|
||||
) // 2 # 15 chars indentation, 1 space around op
|
||||
left_repr = saferepr(left, maxsize=maxsize)
|
||||
right_repr = saferepr(right, maxsize=maxsize)
|
||||
|
||||
left_repr = saferepr(left, maxsize=maxsize, use_ascii=use_ascii)
|
||||
right_repr = saferepr(right, maxsize=maxsize, use_ascii=use_ascii)
|
||||
|
||||
summary = f"{left_repr} {op} {right_repr}"
|
||||
|
||||
|
||||
@@ -157,7 +157,7 @@ class Cache:
|
||||
"""
|
||||
path = self._getvaluepath(key)
|
||||
try:
|
||||
with path.open("r") as f:
|
||||
with path.open("r", encoding="UTF-8") as f:
|
||||
return json.load(f)
|
||||
except (ValueError, OSError):
|
||||
return default
|
||||
@@ -184,9 +184,9 @@ class Cache:
|
||||
return
|
||||
if not cache_dir_exists_already:
|
||||
self._ensure_supporting_files()
|
||||
data = json.dumps(value, indent=2)
|
||||
data = json.dumps(value, ensure_ascii=False, indent=2)
|
||||
try:
|
||||
f = path.open("w")
|
||||
f = path.open("w", encoding="UTF-8")
|
||||
except OSError:
|
||||
self.warn("cache could not write path {path}", path=path, _ispytest=True)
|
||||
else:
|
||||
@@ -196,7 +196,7 @@ class Cache:
|
||||
def _ensure_supporting_files(self) -> None:
|
||||
"""Create supporting files in the cache dir that are not really part of the cache."""
|
||||
readme_path = self._cachedir / "README.md"
|
||||
readme_path.write_text(README_CONTENT)
|
||||
readme_path.write_text(README_CONTENT, encoding="UTF-8")
|
||||
|
||||
gitignore_path = self._cachedir.joinpath(".gitignore")
|
||||
msg = "# Created by pytest automatically.\n*\n"
|
||||
@@ -440,7 +440,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--last-failed",
|
||||
action="store_true",
|
||||
dest="lf",
|
||||
help="rerun only the tests that failed "
|
||||
help="Rerun only the tests that failed "
|
||||
"at the last run (or all if none failed)",
|
||||
)
|
||||
group.addoption(
|
||||
@@ -448,7 +448,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--failed-first",
|
||||
action="store_true",
|
||||
dest="failedfirst",
|
||||
help="run all tests, but run the last failures first.\n"
|
||||
help="Run all tests, but run the last failures first. "
|
||||
"This may re-order tests and thus lead to "
|
||||
"repeated fixture setup/teardown.",
|
||||
)
|
||||
@@ -457,7 +457,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--new-first",
|
||||
action="store_true",
|
||||
dest="newfirst",
|
||||
help="run tests from new files first, then the rest of the tests "
|
||||
help="Run tests from new files first, then the rest of the tests "
|
||||
"sorted by file mtime",
|
||||
)
|
||||
group.addoption(
|
||||
@@ -466,7 +466,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
nargs="?",
|
||||
dest="cacheshow",
|
||||
help=(
|
||||
"show cache contents, don't perform collection or tests. "
|
||||
"Show cache contents, don't perform collection or tests. "
|
||||
"Optional argument: glob (default: '*')."
|
||||
),
|
||||
)
|
||||
@@ -474,12 +474,12 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--cache-clear",
|
||||
action="store_true",
|
||||
dest="cacheclear",
|
||||
help="remove all cache contents at start of test run.",
|
||||
help="Remove all cache contents at start of test run",
|
||||
)
|
||||
cache_dir_default = ".pytest_cache"
|
||||
if "TOX_ENV_DIR" in os.environ:
|
||||
cache_dir_default = os.path.join(os.environ["TOX_ENV_DIR"], cache_dir_default)
|
||||
parser.addini("cache_dir", default=cache_dir_default, help="cache directory path.")
|
||||
parser.addini("cache_dir", default=cache_dir_default, help="Cache directory path")
|
||||
group.addoption(
|
||||
"--lfnf",
|
||||
"--last-failed-no-failures",
|
||||
@@ -487,7 +487,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
dest="last_failed_no_failures",
|
||||
choices=("all", "none"),
|
||||
default="all",
|
||||
help="which tests to run with no previously (known) failures.",
|
||||
help="Which tests to run with no previously (known) failures",
|
||||
)
|
||||
|
||||
|
||||
|
||||
+30
-3
@@ -42,14 +42,14 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
default="fd",
|
||||
metavar="method",
|
||||
choices=["fd", "sys", "no", "tee-sys"],
|
||||
help="per-test capturing method: one of fd|sys|no|tee-sys.",
|
||||
help="Per-test capturing method: one of fd|sys|no|tee-sys",
|
||||
)
|
||||
group._addoption(
|
||||
"-s",
|
||||
action="store_const",
|
||||
const="no",
|
||||
dest="capture",
|
||||
help="shortcut for --capture=no.",
|
||||
help="Shortcut for --capture=no",
|
||||
)
|
||||
|
||||
|
||||
@@ -203,12 +203,39 @@ class DontReadFromInput:
|
||||
def fileno(self) -> int:
|
||||
raise UnsupportedOperation("redirected stdin is pseudofile, has no fileno()")
|
||||
|
||||
def flush(self) -> None:
|
||||
raise UnsupportedOperation("redirected stdin is pseudofile, has no flush()")
|
||||
|
||||
def isatty(self) -> bool:
|
||||
return False
|
||||
|
||||
def close(self) -> None:
|
||||
pass
|
||||
|
||||
def readable(self) -> bool:
|
||||
return False
|
||||
|
||||
def seek(self, offset: int) -> int:
|
||||
raise UnsupportedOperation("redirected stdin is pseudofile, has no seek(int)")
|
||||
|
||||
def seekable(self) -> bool:
|
||||
return False
|
||||
|
||||
def tell(self) -> int:
|
||||
raise UnsupportedOperation("redirected stdin is pseudofile, has no tell()")
|
||||
|
||||
def truncate(self, size: int) -> None:
|
||||
raise UnsupportedOperation("cannont truncate stdin")
|
||||
|
||||
def write(self, *args) -> None:
|
||||
raise UnsupportedOperation("cannot write to stdin")
|
||||
|
||||
def writelines(self, *args) -> None:
|
||||
raise UnsupportedOperation("Cannot write to stdin")
|
||||
|
||||
def writable(self) -> bool:
|
||||
return False
|
||||
|
||||
@property
|
||||
def buffer(self):
|
||||
return self
|
||||
@@ -354,7 +381,7 @@ class FDCaptureBinary:
|
||||
self.targetfd_save = os.dup(targetfd)
|
||||
|
||||
if targetfd == 0:
|
||||
self.tmpfile = open(os.devnull)
|
||||
self.tmpfile = open(os.devnull, encoding="utf-8")
|
||||
self.syscapture = SysCapture(targetfd)
|
||||
else:
|
||||
self.tmpfile = EncodedFile(
|
||||
|
||||
+17
-5
@@ -10,6 +10,7 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
from typing import Callable
|
||||
from typing import Generic
|
||||
from typing import NoReturn
|
||||
from typing import Optional
|
||||
from typing import Tuple
|
||||
from typing import TYPE_CHECKING
|
||||
@@ -17,10 +18,20 @@ from typing import TypeVar
|
||||
from typing import Union
|
||||
|
||||
import attr
|
||||
|
||||
import py
|
||||
|
||||
# fmt: off
|
||||
# Workaround for https://github.com/sphinx-doc/sphinx/issues/10351.
|
||||
# If `overload` is imported from `compat` instead of from `typing`,
|
||||
# Sphinx doesn't recognize it as `overload` and the API docs for
|
||||
# overloaded functions look good again. But type checkers handle
|
||||
# it fine.
|
||||
# fmt: on
|
||||
if True:
|
||||
from typing import overload as overload
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import NoReturn
|
||||
from typing_extensions import Final
|
||||
|
||||
|
||||
@@ -50,9 +61,11 @@ NOTSET: "Final" = NotSetType.token # noqa: E305
|
||||
# fmt: on
|
||||
|
||||
if sys.version_info >= (3, 8):
|
||||
from importlib import metadata as importlib_metadata
|
||||
import importlib.metadata
|
||||
|
||||
importlib_metadata = importlib.metadata
|
||||
else:
|
||||
import importlib_metadata # noqa: F401
|
||||
import importlib_metadata as importlib_metadata # noqa: F401
|
||||
|
||||
|
||||
def _format_args(func: Callable[..., Any]) -> str:
|
||||
@@ -343,7 +356,6 @@ else:
|
||||
if sys.version_info >= (3, 8):
|
||||
from functools import cached_property as cached_property
|
||||
else:
|
||||
from typing import overload
|
||||
from typing import Type
|
||||
|
||||
class cached_property(Generic[_S, _T]):
|
||||
@@ -401,5 +413,5 @@ else:
|
||||
# previously.
|
||||
#
|
||||
# This also work for Enums (if you use `is` to compare) and Literals.
|
||||
def assert_never(value: "NoReturn") -> "NoReturn":
|
||||
def assert_never(value: NoReturn) -> NoReturn:
|
||||
assert False, f"Unhandled value: {value} ({type(value).__name__})"
|
||||
|
||||
@@ -3,6 +3,7 @@ import argparse
|
||||
import collections.abc
|
||||
import copy
|
||||
import enum
|
||||
import glob
|
||||
import inspect
|
||||
import os
|
||||
import re
|
||||
@@ -13,6 +14,7 @@ import warnings
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from textwrap import dedent
|
||||
from types import FunctionType
|
||||
from types import TracebackType
|
||||
from typing import Any
|
||||
from typing import Callable
|
||||
@@ -57,6 +59,7 @@ from _pytest.pathlib import ImportMode
|
||||
from _pytest.pathlib import resolve_package_path
|
||||
from _pytest.stash import Stash
|
||||
from _pytest.warning_types import PytestConfigWarning
|
||||
from _pytest.warning_types import warn_explicit_for
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
@@ -309,7 +312,9 @@ def _prepareconfig(
|
||||
elif isinstance(args, os.PathLike):
|
||||
args = [os.fspath(args)]
|
||||
elif not isinstance(args, list):
|
||||
msg = "`args` parameter expected to be a list of strings, got: {!r} (type: {})"
|
||||
msg = ( # type:ignore[unreachable]
|
||||
"`args` parameter expected to be a list of strings, got: {!r} (type: {})"
|
||||
)
|
||||
raise TypeError(msg.format(args, type(args)))
|
||||
|
||||
config = get_config(args, plugins)
|
||||
@@ -338,6 +343,38 @@ def _get_directory(path: Path) -> Path:
|
||||
return path
|
||||
|
||||
|
||||
def _get_legacy_hook_marks(
|
||||
method: Any,
|
||||
hook_type: str,
|
||||
opt_names: Tuple[str, ...],
|
||||
) -> Dict[str, bool]:
|
||||
if TYPE_CHECKING:
|
||||
# abuse typeguard from importlib to avoid massive method type union thats lacking a alias
|
||||
assert inspect.isroutine(method)
|
||||
known_marks: set[str] = {m.name for m in getattr(method, "pytestmark", [])}
|
||||
must_warn: list[str] = []
|
||||
opts: dict[str, bool] = {}
|
||||
for opt_name in opt_names:
|
||||
opt_attr = getattr(method, opt_name, AttributeError)
|
||||
if opt_attr is not AttributeError:
|
||||
must_warn.append(f"{opt_name}={opt_attr}")
|
||||
opts[opt_name] = True
|
||||
elif opt_name in known_marks:
|
||||
must_warn.append(f"{opt_name}=True")
|
||||
opts[opt_name] = True
|
||||
else:
|
||||
opts[opt_name] = False
|
||||
if must_warn:
|
||||
hook_opts = ", ".join(must_warn)
|
||||
message = _pytest.deprecated.HOOK_LEGACY_MARKING.format(
|
||||
type=hook_type,
|
||||
fullname=method.__qualname__,
|
||||
hook_opts=hook_opts,
|
||||
)
|
||||
warn_explicit_for(cast(FunctionType, method), message)
|
||||
return opts
|
||||
|
||||
|
||||
@final
|
||||
class PytestPluginManager(PluginManager):
|
||||
"""A :py:class:`pluggy.PluginManager <pluggy.PluginManager>` with
|
||||
@@ -411,40 +448,29 @@ class PytestPluginManager(PluginManager):
|
||||
if name == "pytest_plugins":
|
||||
return
|
||||
|
||||
method = getattr(plugin, name)
|
||||
opts = super().parse_hookimpl_opts(plugin, name)
|
||||
if opts is not None:
|
||||
return opts
|
||||
|
||||
method = getattr(plugin, name)
|
||||
# Consider only actual functions for hooks (#3775).
|
||||
if not inspect.isroutine(method):
|
||||
return
|
||||
|
||||
# Collect unmarked hooks as long as they have the `pytest_' prefix.
|
||||
if opts is None and name.startswith("pytest_"):
|
||||
opts = {}
|
||||
if opts is not None:
|
||||
# TODO: DeprecationWarning, people should use hookimpl
|
||||
# https://github.com/pytest-dev/pytest/issues/4562
|
||||
known_marks = {m.name for m in getattr(method, "pytestmark", [])}
|
||||
|
||||
for name in ("tryfirst", "trylast", "optionalhook", "hookwrapper"):
|
||||
opts.setdefault(name, hasattr(method, name) or name in known_marks)
|
||||
return opts
|
||||
return _get_legacy_hook_marks(
|
||||
method, "impl", ("tryfirst", "trylast", "optionalhook", "hookwrapper")
|
||||
)
|
||||
|
||||
def parse_hookspec_opts(self, module_or_class, name: str):
|
||||
opts = super().parse_hookspec_opts(module_or_class, name)
|
||||
if opts is None:
|
||||
method = getattr(module_or_class, name)
|
||||
|
||||
if name.startswith("pytest_"):
|
||||
# todo: deprecate hookspec hacks
|
||||
# https://github.com/pytest-dev/pytest/issues/4562
|
||||
known_marks = {m.name for m in getattr(method, "pytestmark", [])}
|
||||
opts = {
|
||||
"firstresult": hasattr(method, "firstresult")
|
||||
or "firstresult" in known_marks,
|
||||
"historic": hasattr(method, "historic")
|
||||
or "historic" in known_marks,
|
||||
}
|
||||
opts = _get_legacy_hook_marks(
|
||||
method,
|
||||
"spec",
|
||||
("firstresult", "historic"),
|
||||
)
|
||||
return opts
|
||||
|
||||
def register(
|
||||
@@ -486,12 +512,14 @@ class PytestPluginManager(PluginManager):
|
||||
config.addinivalue_line(
|
||||
"markers",
|
||||
"tryfirst: mark a hook implementation function such that the "
|
||||
"plugin machinery will try to call it first/as early as possible.",
|
||||
"plugin machinery will try to call it first/as early as possible. "
|
||||
"DEPRECATED, use @pytest.hookimpl(tryfirst=True) instead.",
|
||||
)
|
||||
config.addinivalue_line(
|
||||
"markers",
|
||||
"trylast: mark a hook implementation function such that the "
|
||||
"plugin machinery will try to call it last/as late as possible.",
|
||||
"plugin machinery will try to call it last/as late as possible. "
|
||||
"DEPRECATED, use @pytest.hookimpl(trylast=True) instead.",
|
||||
)
|
||||
self._configured = True
|
||||
|
||||
@@ -898,6 +926,19 @@ class Config:
|
||||
dir: Path
|
||||
"""The directory from which :func:`pytest.main` was invoked."""
|
||||
|
||||
class ArgsSource(enum.Enum):
|
||||
"""Indicates the source of the test arguments.
|
||||
|
||||
.. versionadded:: 7.2
|
||||
"""
|
||||
|
||||
#: Command line arguments.
|
||||
ARGS = enum.auto()
|
||||
#: Invocation directory.
|
||||
INCOVATION_DIR = enum.auto()
|
||||
#: 'testpaths' configuration value.
|
||||
TESTPATHS = enum.auto()
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pluginmanager: PytestPluginManager,
|
||||
@@ -1100,11 +1141,11 @@ class Config:
|
||||
self.inicfg = inicfg
|
||||
self._parser.extra_info["rootdir"] = str(self.rootpath)
|
||||
self._parser.extra_info["inifile"] = str(self.inipath)
|
||||
self._parser.addini("addopts", "extra command line options", "args")
|
||||
self._parser.addini("minversion", "minimally required pytest version")
|
||||
self._parser.addini("addopts", "Extra command line options", "args")
|
||||
self._parser.addini("minversion", "Minimally required pytest version")
|
||||
self._parser.addini(
|
||||
"required_plugins",
|
||||
"plugins that must be present for pytest to run",
|
||||
"Plugins that must be present for pytest to run",
|
||||
type="args",
|
||||
default=[],
|
||||
)
|
||||
@@ -1307,15 +1348,25 @@ class Config:
|
||||
self.hook.pytest_cmdline_preparse(config=self, args=args)
|
||||
self._parser.after_preparse = True # type: ignore
|
||||
try:
|
||||
source = Config.ArgsSource.ARGS
|
||||
args = self._parser.parse_setoption(
|
||||
args, self.option, namespace=self.option
|
||||
)
|
||||
if not args:
|
||||
if self.invocation_params.dir == self.rootpath:
|
||||
args = self.getini("testpaths")
|
||||
source = Config.ArgsSource.TESTPATHS
|
||||
testpaths: List[str] = self.getini("testpaths")
|
||||
if self.known_args_namespace.pyargs:
|
||||
args = testpaths
|
||||
else:
|
||||
args = []
|
||||
for path in testpaths:
|
||||
args.extend(sorted(glob.iglob(path, recursive=True)))
|
||||
if not args:
|
||||
source = Config.ArgsSource.INCOVATION_DIR
|
||||
args = [str(self.invocation_params.dir)]
|
||||
self.args = args
|
||||
self.args_source = source
|
||||
except PrintHelp:
|
||||
pass
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ from typing import cast
|
||||
from typing import Dict
|
||||
from typing import List
|
||||
from typing import Mapping
|
||||
from typing import NoReturn
|
||||
from typing import Optional
|
||||
from typing import Sequence
|
||||
from typing import Tuple
|
||||
@@ -24,7 +25,6 @@ from _pytest.deprecated import ARGUMENT_TYPE_STR_CHOICE
|
||||
from _pytest.deprecated import check_ispytest
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import NoReturn
|
||||
from typing_extensions import Literal
|
||||
|
||||
FILE_OR_DIR = "file_or_dir"
|
||||
@@ -48,7 +48,7 @@ class Parser:
|
||||
_ispytest: bool = False,
|
||||
) -> None:
|
||||
check_ispytest(_ispytest)
|
||||
self._anonymous = OptionGroup("custom options", parser=self, _ispytest=True)
|
||||
self._anonymous = OptionGroup("Custom options", parser=self, _ispytest=True)
|
||||
self._groups: List[OptionGroup] = []
|
||||
self._processopt = processopt
|
||||
self._usage = usage
|
||||
@@ -66,14 +66,15 @@ class Parser:
|
||||
) -> "OptionGroup":
|
||||
"""Get (or create) a named option Group.
|
||||
|
||||
:name: Name of the option group.
|
||||
:description: Long description for --help output.
|
||||
:after: Name of another group, used for ordering --help output.
|
||||
:param name: Name of the option group.
|
||||
:param description: Long description for --help output.
|
||||
:param after: Name of another group, used for ordering --help output.
|
||||
:returns: The option group.
|
||||
|
||||
The returned group object has an ``addoption`` method with the same
|
||||
signature as :func:`parser.addoption <pytest.Parser.addoption>` but
|
||||
will be shown in the respective group in the output of
|
||||
``pytest. --help``.
|
||||
``pytest --help``.
|
||||
"""
|
||||
for group in self._groups:
|
||||
if group.name == name:
|
||||
@@ -89,10 +90,11 @@ class Parser:
|
||||
def addoption(self, *opts: str, **attrs: Any) -> None:
|
||||
"""Register a command line option.
|
||||
|
||||
:opts: Option names, can be short or long options.
|
||||
:attrs: Same attributes which the ``add_argument()`` function of the
|
||||
`argparse library <https://docs.python.org/library/argparse.html>`_
|
||||
accepts.
|
||||
:param opts:
|
||||
Option names, can be short or long options.
|
||||
:param attrs:
|
||||
Same attributes as the argparse library's :py:func:`add_argument()
|
||||
<argparse.ArgumentParser.add_argument>` function accepts.
|
||||
|
||||
After command line parsing, options are available on the pytest config
|
||||
object via ``config.option.NAME`` where ``NAME`` is usually set
|
||||
@@ -148,7 +150,10 @@ class Parser:
|
||||
args: Sequence[Union[str, "os.PathLike[str]"]],
|
||||
namespace: Optional[argparse.Namespace] = None,
|
||||
) -> argparse.Namespace:
|
||||
"""Parse and return a namespace object with known arguments at this point."""
|
||||
"""Parse the known arguments at this point.
|
||||
|
||||
:returns: An argparse namespace object.
|
||||
"""
|
||||
return self.parse_known_and_unknown_args(args, namespace=namespace)[0]
|
||||
|
||||
def parse_known_and_unknown_args(
|
||||
@@ -156,8 +161,13 @@ class Parser:
|
||||
args: Sequence[Union[str, "os.PathLike[str]"]],
|
||||
namespace: Optional[argparse.Namespace] = None,
|
||||
) -> Tuple[argparse.Namespace, List[str]]:
|
||||
"""Parse and return a namespace object with known arguments, and
|
||||
the remaining arguments unknown at this point."""
|
||||
"""Parse the known arguments at this point, and also return the
|
||||
remaining unknown arguments.
|
||||
|
||||
:returns:
|
||||
A tuple containing an argparse namespace object for the known
|
||||
arguments, and a list of the unknown arguments.
|
||||
"""
|
||||
optparser = self._getparser()
|
||||
strargs = [os.fspath(x) for x in args]
|
||||
return optparser.parse_known_args(strargs, namespace=namespace)
|
||||
@@ -169,13 +179,13 @@ class Parser:
|
||||
type: Optional[
|
||||
"Literal['string', 'paths', 'pathlist', 'args', 'linelist', 'bool']"
|
||||
] = None,
|
||||
default=None,
|
||||
default: Any = None,
|
||||
) -> None:
|
||||
"""Register an ini-file option.
|
||||
|
||||
:name:
|
||||
:param name:
|
||||
Name of the ini-variable.
|
||||
:type:
|
||||
:param type:
|
||||
Type of the variable. Can be:
|
||||
|
||||
* ``string``: a string
|
||||
@@ -189,7 +199,7 @@ class Parser:
|
||||
The ``paths`` variable type.
|
||||
|
||||
Defaults to ``string`` if ``None`` or not passed.
|
||||
:default:
|
||||
:param default:
|
||||
Default value if no ini-file option exists but is queried.
|
||||
|
||||
The value of ini-variables can be retrieved via a call to
|
||||
@@ -227,7 +237,7 @@ class Argument:
|
||||
_typ_map = {"int": int, "string": str, "float": float, "complex": complex}
|
||||
|
||||
def __init__(self, *names: str, **attrs: Any) -> None:
|
||||
"""Store parms in private vars for use in add_argument."""
|
||||
"""Store params in private vars for use in add_argument."""
|
||||
self._attrs = attrs
|
||||
self._short_opts: List[str] = []
|
||||
self._long_opts: List[str] = []
|
||||
@@ -354,24 +364,30 @@ class OptionGroup:
|
||||
self.options: List[Argument] = []
|
||||
self.parser = parser
|
||||
|
||||
def addoption(self, *optnames: str, **attrs: Any) -> None:
|
||||
def addoption(self, *opts: str, **attrs: Any) -> None:
|
||||
"""Add an option to this group.
|
||||
|
||||
If a shortened version of a long option is specified, it will
|
||||
be suppressed in the help. ``addoption('--twowords', '--two-words')``
|
||||
results in help showing ``--two-words`` only, but ``--twowords`` gets
|
||||
accepted **and** the automatic destination is in ``args.twowords``.
|
||||
|
||||
:param opts:
|
||||
Option names, can be short or long options.
|
||||
:param attrs:
|
||||
Same attributes as the argparse library's :py:func:`add_argument()
|
||||
<argparse.ArgumentParser.add_argument>` function accepts.
|
||||
"""
|
||||
conflict = set(optnames).intersection(
|
||||
conflict = set(opts).intersection(
|
||||
name for opt in self.options for name in opt.names()
|
||||
)
|
||||
if conflict:
|
||||
raise ValueError("option names %s already added" % conflict)
|
||||
option = Argument(*optnames, **attrs)
|
||||
option = Argument(*opts, **attrs)
|
||||
self._addoption_instance(option, shortupper=False)
|
||||
|
||||
def _addoption(self, *optnames: str, **attrs: Any) -> None:
|
||||
option = Argument(*optnames, **attrs)
|
||||
def _addoption(self, *opts: str, **attrs: Any) -> None:
|
||||
option = Argument(*opts, **attrs)
|
||||
self._addoption_instance(option, shortupper=True)
|
||||
|
||||
def _addoption_instance(self, option: "Argument", shortupper: bool = False) -> None:
|
||||
@@ -403,7 +419,7 @@ class MyOptionParser(argparse.ArgumentParser):
|
||||
# an usage error to provide more contextual information to the user.
|
||||
self.extra_info = extra_info if extra_info else {}
|
||||
|
||||
def error(self, message: str) -> "NoReturn":
|
||||
def error(self, message: str) -> NoReturn:
|
||||
"""Transform argparse error message into UsageError."""
|
||||
msg = f"{self.prog}: error: {message}"
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Dict
|
||||
from typing import Iterable
|
||||
@@ -64,12 +65,15 @@ def load_config_dict_from_file(
|
||||
|
||||
# '.toml' files are considered if they contain a [tool.pytest.ini_options] table.
|
||||
elif filepath.suffix == ".toml":
|
||||
import tomli
|
||||
if sys.version_info >= (3, 11):
|
||||
import tomllib
|
||||
else:
|
||||
import tomli as tomllib
|
||||
|
||||
toml_text = filepath.read_text(encoding="utf-8")
|
||||
try:
|
||||
config = tomli.loads(toml_text)
|
||||
except tomli.TOMLDecodeError as exc:
|
||||
config = tomllib.loads(toml_text)
|
||||
except tomllib.TOMLDecodeError as exc:
|
||||
raise UsageError(f"{filepath}: {exc}") from exc
|
||||
|
||||
result = config.get("tool", {}).get("pytest", {}).get("ini_options", None)
|
||||
@@ -92,6 +96,7 @@ def locate_config(
|
||||
and return a tuple of (rootdir, inifile, cfg-dict)."""
|
||||
config_names = [
|
||||
"pytest.ini",
|
||||
".pytest.ini",
|
||||
"pyproject.toml",
|
||||
"tox.ini",
|
||||
"setup.cfg",
|
||||
@@ -198,8 +203,7 @@ def determine_setup(
|
||||
else:
|
||||
cwd = Path.cwd()
|
||||
rootdir = get_common_ancestor([cwd, ancestor])
|
||||
is_fs_root = os.path.splitdrive(str(rootdir))[1] == "/"
|
||||
if is_fs_root:
|
||||
if is_fs_root(rootdir):
|
||||
rootdir = ancestor
|
||||
if rootdir_cmd_arg:
|
||||
rootdir = absolutepath(os.path.expandvars(rootdir_cmd_arg))
|
||||
@@ -211,3 +215,11 @@ def determine_setup(
|
||||
)
|
||||
assert rootdir is not None
|
||||
return rootdir, inipath, inicfg or {}
|
||||
|
||||
|
||||
def is_fs_root(p: Path) -> bool:
|
||||
r"""
|
||||
Return True if the given path is pointing to the root of the
|
||||
file system ("/" on Unix and "C:\\" on Windows for example).
|
||||
"""
|
||||
return os.path.splitdrive(str(p))[1] == os.sep
|
||||
|
||||
@@ -3,6 +3,7 @@ import argparse
|
||||
import functools
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from typing import Any
|
||||
from typing import Callable
|
||||
from typing import Generator
|
||||
@@ -46,21 +47,21 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--pdb",
|
||||
dest="usepdb",
|
||||
action="store_true",
|
||||
help="start the interactive Python debugger on errors or KeyboardInterrupt.",
|
||||
help="Start the interactive Python debugger on errors or KeyboardInterrupt",
|
||||
)
|
||||
group._addoption(
|
||||
"--pdbcls",
|
||||
dest="usepdb_cls",
|
||||
metavar="modulename:classname",
|
||||
type=_validate_usepdb_cls,
|
||||
help="specify a custom interactive Python debugger for use with --pdb."
|
||||
help="Specify a custom interactive Python debugger for use with --pdb."
|
||||
"For example: --pdbcls=IPython.terminal.debugger:TerminalPdb",
|
||||
)
|
||||
group._addoption(
|
||||
"--trace",
|
||||
dest="trace",
|
||||
action="store_true",
|
||||
help="Immediately break when running each test.",
|
||||
help="Immediately break when running each test",
|
||||
)
|
||||
|
||||
|
||||
@@ -293,7 +294,9 @@ class PdbInvoke:
|
||||
sys.stdout.write(out)
|
||||
sys.stdout.write(err)
|
||||
assert call.excinfo is not None
|
||||
_enter_pdb(node, call.excinfo, report)
|
||||
|
||||
if not isinstance(call.excinfo.value, unittest.SkipTest):
|
||||
_enter_pdb(node, call.excinfo, report)
|
||||
|
||||
def pytest_internalerror(self, excinfo: ExceptionInfo[BaseException]) -> None:
|
||||
tb = _postmortem_traceback(excinfo)
|
||||
|
||||
@@ -22,6 +22,21 @@ DEPRECATED_EXTERNAL_PLUGINS = {
|
||||
"pytest_faulthandler",
|
||||
}
|
||||
|
||||
NOSE_SUPPORT = UnformattedWarning(
|
||||
PytestRemovedIn8Warning,
|
||||
"Support for nose tests is deprecated and will be removed in a future release.\n"
|
||||
"{nodeid} is using nose method: `{method}` ({stage})\n"
|
||||
"See docs: https://docs.pytest.org/en/stable/deprecations.html#support-for-tests-written-for-nose",
|
||||
)
|
||||
|
||||
NOSE_SUPPORT_METHOD = UnformattedWarning(
|
||||
PytestRemovedIn8Warning,
|
||||
"Support for nose tests is deprecated and will be removed in a future release.\n"
|
||||
"{nodeid} is using nose-specific method: `{method}(self)`\n"
|
||||
"To remove this warning, rename it to `{method}_method(self)`\n"
|
||||
"See docs: https://docs.pytest.org/en/stable/deprecations.html#support-for-tests-written-for-nose",
|
||||
)
|
||||
|
||||
|
||||
# This can be* removed pytest 8, but it's harmless and common, so no rush to remove.
|
||||
# * If you're in the future: "could have been".
|
||||
@@ -98,6 +113,14 @@ INSTANCE_COLLECTOR = PytestRemovedIn8Warning(
|
||||
"The pytest.Instance collector type is deprecated and is no longer used. "
|
||||
"See https://docs.pytest.org/en/latest/deprecations.html#the-pytest-instance-collector",
|
||||
)
|
||||
HOOK_LEGACY_MARKING = UnformattedWarning(
|
||||
PytestDeprecationWarning,
|
||||
"The hook{type} {fullname} uses old-style configuration options (marks or attributes).\n"
|
||||
"Please use the pytest.hook{type}({hook_opts}) decorator instead\n"
|
||||
" to configure the hooks.\n"
|
||||
" See https://docs.pytest.org/en/latest/deprecations.html"
|
||||
"#configuring-hook-specs-impls-using-markers",
|
||||
)
|
||||
|
||||
# You want to make some `__init__` or function "private".
|
||||
#
|
||||
|
||||
+17
-14
@@ -23,7 +23,6 @@ from typing import Type
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import Union
|
||||
|
||||
import pytest
|
||||
from _pytest import outcomes
|
||||
from _pytest._code.code import ExceptionInfo
|
||||
from _pytest._code.code import ReprFileLocation
|
||||
@@ -32,11 +31,15 @@ from _pytest._io import TerminalWriter
|
||||
from _pytest.compat import safe_getattr
|
||||
from _pytest.config import Config
|
||||
from _pytest.config.argparsing import Parser
|
||||
from _pytest.fixtures import fixture
|
||||
from _pytest.fixtures import FixtureRequest
|
||||
from _pytest.nodes import Collector
|
||||
from _pytest.nodes import Item
|
||||
from _pytest.outcomes import OutcomeException
|
||||
from _pytest.outcomes import skip
|
||||
from _pytest.pathlib import fnmatch_ex
|
||||
from _pytest.pathlib import import_path
|
||||
from _pytest.python import Module
|
||||
from _pytest.python_api import approx
|
||||
from _pytest.warning_types import PytestWarning
|
||||
|
||||
@@ -66,26 +69,26 @@ CHECKER_CLASS: Optional[Type["doctest.OutputChecker"]] = None
|
||||
def pytest_addoption(parser: Parser) -> None:
|
||||
parser.addini(
|
||||
"doctest_optionflags",
|
||||
"option flags for doctests",
|
||||
"Option flags for doctests",
|
||||
type="args",
|
||||
default=["ELLIPSIS"],
|
||||
)
|
||||
parser.addini(
|
||||
"doctest_encoding", "encoding used for doctest files", default="utf-8"
|
||||
"doctest_encoding", "Encoding used for doctest files", default="utf-8"
|
||||
)
|
||||
group = parser.getgroup("collect")
|
||||
group.addoption(
|
||||
"--doctest-modules",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="run doctests in all .py modules",
|
||||
help="Run doctests in all .py modules",
|
||||
dest="doctestmodules",
|
||||
)
|
||||
group.addoption(
|
||||
"--doctest-report",
|
||||
type=str.lower,
|
||||
default="udiff",
|
||||
help="choose another output format for diffs on doctest failure",
|
||||
help="Choose another output format for diffs on doctest failure",
|
||||
choices=DOCTEST_REPORT_CHOICES,
|
||||
dest="doctestreport",
|
||||
)
|
||||
@@ -94,21 +97,21 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
action="append",
|
||||
default=[],
|
||||
metavar="pat",
|
||||
help="doctests file matching pattern, default: test*.txt",
|
||||
help="Doctests file matching pattern, default: test*.txt",
|
||||
dest="doctestglob",
|
||||
)
|
||||
group.addoption(
|
||||
"--doctest-ignore-import-errors",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="ignore doctest ImportErrors",
|
||||
help="Ignore doctest ImportErrors",
|
||||
dest="doctest_ignore_import_errors",
|
||||
)
|
||||
group.addoption(
|
||||
"--doctest-continue-on-failure",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="for a given doctest, continue to run after the first failure",
|
||||
help="For a given doctest, continue to run after the first failure",
|
||||
dest="doctest_continue_on_failure",
|
||||
)
|
||||
|
||||
@@ -246,7 +249,7 @@ def _get_runner(
|
||||
)
|
||||
|
||||
|
||||
class DoctestItem(pytest.Item):
|
||||
class DoctestItem(Item):
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
@@ -411,7 +414,7 @@ def _get_continue_on_failure(config):
|
||||
return continue_on_failure
|
||||
|
||||
|
||||
class DoctestTextfile(pytest.Module):
|
||||
class DoctestTextfile(Module):
|
||||
obj = None
|
||||
|
||||
def collect(self) -> Iterable[DoctestItem]:
|
||||
@@ -449,7 +452,7 @@ def _check_all_skipped(test: "doctest.DocTest") -> None:
|
||||
|
||||
all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
|
||||
if all_skipped:
|
||||
pytest.skip("all tests skipped by +SKIP option")
|
||||
skip("all tests skipped by +SKIP option")
|
||||
|
||||
|
||||
def _is_mocked(obj: object) -> bool:
|
||||
@@ -491,7 +494,7 @@ def _patch_unwrap_mock_aware() -> Generator[None, None, None]:
|
||||
inspect.unwrap = real_unwrap
|
||||
|
||||
|
||||
class DoctestModule(pytest.Module):
|
||||
class DoctestModule(Module):
|
||||
def collect(self) -> Iterable[DoctestItem]:
|
||||
import doctest
|
||||
|
||||
@@ -549,7 +552,7 @@ class DoctestModule(pytest.Module):
|
||||
)
|
||||
except ImportError:
|
||||
if self.config.getvalue("doctest_ignore_import_errors"):
|
||||
pytest.skip("unable to import module %r" % self.path)
|
||||
skip("unable to import module %r" % self.path)
|
||||
else:
|
||||
raise
|
||||
# Uses internal doctest module parsing mechanism.
|
||||
@@ -731,7 +734,7 @@ def _get_report_choice(key: str) -> int:
|
||||
}[key]
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
@fixture(scope="session")
|
||||
def doctest_namespace() -> Dict[str, Any]:
|
||||
"""Fixture that returns a :py:class:`dict` that will be injected into the
|
||||
namespace of doctests.
|
||||
|
||||
@@ -18,7 +18,7 @@ fault_handler_originally_enabled_key = StashKey[bool]()
|
||||
def pytest_addoption(parser: Parser) -> None:
|
||||
help = (
|
||||
"Dump the traceback of all threads if a test takes "
|
||||
"more than TIMEOUT seconds to finish."
|
||||
"more than TIMEOUT seconds to finish"
|
||||
)
|
||||
parser.addini("faulthandler_timeout", help, default=0.0)
|
||||
|
||||
|
||||
+36
-24
@@ -18,8 +18,8 @@ from typing import Iterable
|
||||
from typing import Iterator
|
||||
from typing import List
|
||||
from typing import MutableMapping
|
||||
from typing import NoReturn
|
||||
from typing import Optional
|
||||
from typing import overload
|
||||
from typing import Sequence
|
||||
from typing import Set
|
||||
from typing import Tuple
|
||||
@@ -47,6 +47,7 @@ from _pytest.compat import getimfunc
|
||||
from _pytest.compat import getlocation
|
||||
from _pytest.compat import is_generator
|
||||
from _pytest.compat import NOTSET
|
||||
from _pytest.compat import overload
|
||||
from _pytest.compat import safe_getattr
|
||||
from _pytest.config import _PluggyPlugin
|
||||
from _pytest.config import Config
|
||||
@@ -57,6 +58,7 @@ from _pytest.mark import Mark
|
||||
from _pytest.mark import ParameterSet
|
||||
from _pytest.mark.structures import MarkDecorator
|
||||
from _pytest.outcomes import fail
|
||||
from _pytest.outcomes import skip
|
||||
from _pytest.outcomes import TEST_OUTCOME
|
||||
from _pytest.pathlib import absolutepath
|
||||
from _pytest.pathlib import bestrelpath
|
||||
@@ -67,7 +69,6 @@ from _pytest.stash import StashKey
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import Deque
|
||||
from typing import NoReturn
|
||||
|
||||
from _pytest.scope import _ScopeName
|
||||
from _pytest.main import Session
|
||||
@@ -223,15 +224,10 @@ def add_funcarg_pseudo_fixture_def(
|
||||
def getfixturemarker(obj: object) -> Optional["FixtureFunctionMarker"]:
|
||||
"""Return fixturemarker or None if it doesn't exist or raised
|
||||
exceptions."""
|
||||
try:
|
||||
fixturemarker: Optional[FixtureFunctionMarker] = getattr(
|
||||
obj, "_pytestfixturefunction", None
|
||||
)
|
||||
except TEST_OUTCOME:
|
||||
# some objects raise errors like request (from flask import request)
|
||||
# we don't expect them to be fixture functions
|
||||
return None
|
||||
return fixturemarker
|
||||
return cast(
|
||||
Optional[FixtureFunctionMarker],
|
||||
safe_getattr(obj, "_pytestfixturefunction", None),
|
||||
)
|
||||
|
||||
|
||||
# Parametrized fixture key, helper alias for code below.
|
||||
@@ -518,8 +514,8 @@ class FixtureRequest:
|
||||
return self._pyfuncitem.session # type: ignore[no-any-return]
|
||||
|
||||
def addfinalizer(self, finalizer: Callable[[], object]) -> None:
|
||||
"""Add finalizer/teardown function to be called after the last test
|
||||
within the requesting test context finished execution."""
|
||||
"""Add finalizer/teardown function to be called without arguments after
|
||||
the last test within the requesting test context finished execution."""
|
||||
# XXX usually this method is shadowed by fixturedef specific ones.
|
||||
self._addfinalizer(finalizer, scope=self.scope)
|
||||
|
||||
@@ -534,13 +530,16 @@ class FixtureRequest:
|
||||
on all function invocations.
|
||||
|
||||
:param marker:
|
||||
A :class:`pytest.MarkDecorator` object created by a call
|
||||
to ``pytest.mark.NAME(...)``.
|
||||
An object created by a call to ``pytest.mark.NAME(...)``.
|
||||
"""
|
||||
self.node.add_marker(marker)
|
||||
|
||||
def raiseerror(self, msg: Optional[str]) -> "NoReturn":
|
||||
"""Raise a FixtureLookupError with the given message."""
|
||||
def raiseerror(self, msg: Optional[str]) -> NoReturn:
|
||||
"""Raise a FixtureLookupError exception.
|
||||
|
||||
:param msg:
|
||||
An optional custom error message.
|
||||
"""
|
||||
raise self._fixturemanager.FixtureLookupError(None, self, msg)
|
||||
|
||||
def _fillfixtures(self) -> None:
|
||||
@@ -558,11 +557,20 @@ class FixtureRequest:
|
||||
setup time, you may use this function to retrieve it inside a fixture
|
||||
or test function body.
|
||||
|
||||
This method can be used during the test setup phase or the test run
|
||||
phase, but during the test teardown phase a fixture's value may not
|
||||
be available.
|
||||
|
||||
:param argname:
|
||||
The fixture name.
|
||||
:raises pytest.FixtureLookupError:
|
||||
If the given fixture could not be found.
|
||||
"""
|
||||
fixturedef = self._get_active_fixturedef(argname)
|
||||
assert fixturedef.cached_result is not None
|
||||
assert fixturedef.cached_result is not None, (
|
||||
f'The fixture value for "{argname}" is not available. '
|
||||
"This can happen when the fixture has already been torn down."
|
||||
)
|
||||
return fixturedef.cached_result[0]
|
||||
|
||||
def _get_active_fixturedef(
|
||||
@@ -766,8 +774,8 @@ class SubRequest(FixtureRequest):
|
||||
return f"<SubRequest {self.fixturename!r} for {self._pyfuncitem!r}>"
|
||||
|
||||
def addfinalizer(self, finalizer: Callable[[], object]) -> None:
|
||||
"""Add finalizer/teardown function to be called after the last test
|
||||
within the requesting test context finished execution."""
|
||||
"""Add finalizer/teardown function to be called without arguments after
|
||||
the last test within the requesting test context finished execution."""
|
||||
self._fixturedef.addfinalizer(finalizer)
|
||||
|
||||
def _schedule_finalizers(
|
||||
@@ -874,7 +882,7 @@ class FixtureLookupErrorRepr(TerminalRepr):
|
||||
tw.line("%s:%d" % (os.fspath(self.filename), self.firstlineno + 1))
|
||||
|
||||
|
||||
def fail_fixturefunc(fixturefunc, msg: str) -> "NoReturn":
|
||||
def fail_fixturefunc(fixturefunc, msg: str) -> NoReturn:
|
||||
fs, lineno = getfslineno(fixturefunc)
|
||||
location = f"{fs}:{lineno + 1}"
|
||||
source = _pytest._code.Source(fixturefunc)
|
||||
@@ -1122,6 +1130,10 @@ def pytest_fixture_setup(
|
||||
except TEST_OUTCOME:
|
||||
exc_info = sys.exc_info()
|
||||
assert exc_info[0] is not None
|
||||
if isinstance(
|
||||
exc_info[1], skip.Exception
|
||||
) and not fixturefunc.__name__.startswith("xunit_setup"):
|
||||
exc_info[1]._use_item_location = True # type: ignore[attr-defined]
|
||||
fixturedef.cached_result = (None, my_cache_key, exc_info)
|
||||
raise
|
||||
fixturedef.cached_result = (result, my_cache_key, None)
|
||||
@@ -1224,7 +1236,7 @@ def fixture(
|
||||
|
||||
|
||||
@overload
|
||||
def fixture(
|
||||
def fixture( # noqa: F811
|
||||
fixture_function: None = ...,
|
||||
*,
|
||||
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = ...,
|
||||
@@ -1238,7 +1250,7 @@ def fixture(
|
||||
...
|
||||
|
||||
|
||||
def fixture(
|
||||
def fixture( # noqa: F811
|
||||
fixture_function: Optional[FixtureFunction] = None,
|
||||
*,
|
||||
scope: "Union[_ScopeName, Callable[[str, Config], _ScopeName]]" = "function",
|
||||
@@ -1360,7 +1372,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"usefixtures",
|
||||
type="args",
|
||||
default=[],
|
||||
help="list of default fixtures to be used with this project",
|
||||
help="List of default fixtures to be used with this project",
|
||||
)
|
||||
|
||||
|
||||
|
||||
+14
-13
@@ -49,7 +49,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
action="count",
|
||||
default=0,
|
||||
dest="version",
|
||||
help="display pytest version and information about plugins. "
|
||||
help="Display pytest version and information about plugins. "
|
||||
"When given twice, also display information about plugins.",
|
||||
)
|
||||
group._addoption(
|
||||
@@ -57,7 +57,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--help",
|
||||
action=HelpAction,
|
||||
dest="help",
|
||||
help="show help message and configuration info",
|
||||
help="Show help message and configuration info",
|
||||
)
|
||||
group._addoption(
|
||||
"-p",
|
||||
@@ -65,7 +65,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
dest="plugins",
|
||||
default=[],
|
||||
metavar="name",
|
||||
help="early-load given plugin module name or entry point (multi-allowed).\n"
|
||||
help="Early-load given plugin module name or entry point (multi-allowed). "
|
||||
"To avoid loading of plugins, use the `no:` prefix, e.g. "
|
||||
"`no:doctest`.",
|
||||
)
|
||||
@@ -74,7 +74,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--trace-config",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="trace considerations of conftest.py files.",
|
||||
help="Trace considerations of conftest.py files",
|
||||
)
|
||||
group.addoption(
|
||||
"--debug",
|
||||
@@ -83,16 +83,17 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
const="pytestdebug.log",
|
||||
dest="debug",
|
||||
metavar="DEBUG_FILE_NAME",
|
||||
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"
|
||||
"Defaults to 'pytestdebug.log'.",
|
||||
help="Store internal tracing debug information in this log file. "
|
||||
"This file is opened with 'w' and truncated as a result, care advised. "
|
||||
"Default: pytestdebug.log.",
|
||||
)
|
||||
group._addoption(
|
||||
"-o",
|
||||
"--override-ini",
|
||||
dest="override_ini",
|
||||
action="append",
|
||||
help='override ini option with "option=value" style, e.g. `-o xfail_strict=True -o cache_dir=cache`.',
|
||||
help='Override ini option with "option=value" style, '
|
||||
"e.g. `-o xfail_strict=True -o cache_dir=cache`.",
|
||||
)
|
||||
|
||||
|
||||
@@ -203,12 +204,12 @@ def showhelp(config: Config) -> None:
|
||||
tw.line(indent + line)
|
||||
|
||||
tw.line()
|
||||
tw.line("environment variables:")
|
||||
tw.line("Environment variables:")
|
||||
vars = [
|
||||
("PYTEST_ADDOPTS", "extra command line options"),
|
||||
("PYTEST_PLUGINS", "comma-separated plugins to load during startup"),
|
||||
("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "set to disable plugin auto-loading"),
|
||||
("PYTEST_DEBUG", "set to enable debug tracing of pytest's internals"),
|
||||
("PYTEST_ADDOPTS", "Extra command line options"),
|
||||
("PYTEST_PLUGINS", "Comma-separated plugins to load during startup"),
|
||||
("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "Set to disable plugin auto-loading"),
|
||||
("PYTEST_DEBUG", "Set to enable debug tracing of pytest's internals"),
|
||||
]
|
||||
for name, help in vars:
|
||||
tw.line(f" {name:<24} {help}")
|
||||
|
||||
+150
-68
@@ -143,7 +143,7 @@ def pytest_configure(config: "Config") -> None:
|
||||
def pytest_cmdline_parse(
|
||||
pluginmanager: "PytestPluginManager", args: List[str]
|
||||
) -> Optional["Config"]:
|
||||
"""Return an initialized config object, parsing the specified args.
|
||||
"""Return an initialized :class:`~pytest.Config`, parsing the specified args.
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
|
||||
@@ -152,8 +152,9 @@ def pytest_cmdline_parse(
|
||||
``plugins`` arg when using `pytest.main`_ to perform an in-process
|
||||
test run.
|
||||
|
||||
:param pytest.PytestPluginManager pluginmanager: The pytest plugin manager.
|
||||
:param List[str] args: List of arguments passed on the command line.
|
||||
:param pluginmanager: The pytest plugin manager.
|
||||
:param args: List of arguments passed on the command line.
|
||||
:returns: A pytest config object.
|
||||
"""
|
||||
|
||||
|
||||
@@ -167,8 +168,8 @@ def pytest_cmdline_preparse(config: "Config", args: List[str]) -> None:
|
||||
.. note::
|
||||
This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
|
||||
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param List[str] args: Arguments passed on the command line.
|
||||
:param config: The pytest config object.
|
||||
:param args: Arguments passed on the command line.
|
||||
"""
|
||||
|
||||
|
||||
@@ -179,7 +180,8 @@ def pytest_cmdline_main(config: "Config") -> Optional[Union["ExitCode", int]]:
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param config: The pytest config object.
|
||||
:returns: The exit code.
|
||||
"""
|
||||
|
||||
|
||||
@@ -192,9 +194,9 @@ def pytest_load_initial_conftests(
|
||||
.. note::
|
||||
This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
|
||||
|
||||
:param pytest.Config early_config: The pytest config object.
|
||||
:param List[str] args: Arguments passed on the command line.
|
||||
:param pytest.Parser parser: To add command line options.
|
||||
:param early_config: The pytest config object.
|
||||
:param args: Arguments passed on the command line.
|
||||
:param parser: To add command line options.
|
||||
"""
|
||||
|
||||
|
||||
@@ -236,7 +238,7 @@ def pytest_collection(session: "Session") -> Optional[object]:
|
||||
for example the terminal plugin uses it to start displaying the collection
|
||||
counter (and returns `None`).
|
||||
|
||||
:param pytest.Session session: The pytest session object.
|
||||
:param session: The pytest session object.
|
||||
"""
|
||||
|
||||
|
||||
@@ -246,16 +248,16 @@ def pytest_collection_modifyitems(
|
||||
"""Called after collection has been performed. May filter or re-order
|
||||
the items in-place.
|
||||
|
||||
:param pytest.Session session: The pytest session object.
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param List[pytest.Item] items: List of item objects.
|
||||
:param session: The pytest session object.
|
||||
:param config: The pytest config object.
|
||||
:param items: List of item objects.
|
||||
"""
|
||||
|
||||
|
||||
def pytest_collection_finish(session: "Session") -> None:
|
||||
"""Called after collection has been performed and modified.
|
||||
|
||||
:param pytest.Session session: The pytest session object.
|
||||
:param session: The pytest session object.
|
||||
"""
|
||||
|
||||
|
||||
@@ -270,9 +272,9 @@ def pytest_ignore_collect(
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
|
||||
:param pathlib.Path collection_path : The path to analyze.
|
||||
:param LEGACY_PATH path: The path to analyze (deprecated).
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param collection_path: The path to analyze.
|
||||
:param path: The path to analyze (deprecated).
|
||||
:param config: The pytest config object.
|
||||
|
||||
.. versionchanged:: 7.0.0
|
||||
The ``collection_path`` parameter was added as a :class:`pathlib.Path`
|
||||
@@ -284,12 +286,12 @@ def pytest_ignore_collect(
|
||||
def pytest_collect_file(
|
||||
file_path: Path, path: "LEGACY_PATH", parent: "Collector"
|
||||
) -> "Optional[Collector]":
|
||||
"""Create a Collector for the given path, or None if not relevant.
|
||||
"""Create a :class:`~pytest.Collector` for the given path, or None if not relevant.
|
||||
|
||||
The new node needs to have the specified ``parent`` as a parent.
|
||||
|
||||
:param pathlib.Path file_path: The path to analyze.
|
||||
:param LEGACY_PATH path: The path to collect (deprecated).
|
||||
:param file_path: The path to analyze.
|
||||
:param path: The path to collect (deprecated).
|
||||
|
||||
.. versionchanged:: 7.0.0
|
||||
The ``file_path`` parameter was added as a :class:`pathlib.Path`
|
||||
@@ -302,21 +304,36 @@ def pytest_collect_file(
|
||||
|
||||
|
||||
def pytest_collectstart(collector: "Collector") -> None:
|
||||
"""Collector starts collecting."""
|
||||
"""Collector starts collecting.
|
||||
|
||||
:param collector:
|
||||
The collector.
|
||||
"""
|
||||
|
||||
|
||||
def pytest_itemcollected(item: "Item") -> None:
|
||||
"""We just collected a test item."""
|
||||
"""We just collected a test item.
|
||||
|
||||
:param item:
|
||||
The item.
|
||||
"""
|
||||
|
||||
|
||||
def pytest_collectreport(report: "CollectReport") -> None:
|
||||
"""Collector finished collecting."""
|
||||
"""Collector finished collecting.
|
||||
|
||||
:param report:
|
||||
The collect report.
|
||||
"""
|
||||
|
||||
|
||||
def pytest_deselected(items: Sequence["Item"]) -> None:
|
||||
"""Called for deselected test items, e.g. by keyword.
|
||||
|
||||
May be called multiple times.
|
||||
|
||||
:param items:
|
||||
The items.
|
||||
"""
|
||||
|
||||
|
||||
@@ -326,6 +343,9 @@ def pytest_make_collect_report(collector: "Collector") -> "Optional[CollectRepor
|
||||
a :class:`~pytest.CollectReport`.
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
|
||||
:param collector:
|
||||
The collector.
|
||||
"""
|
||||
|
||||
|
||||
@@ -338,16 +358,16 @@ def pytest_make_collect_report(collector: "Collector") -> "Optional[CollectRepor
|
||||
def pytest_pycollect_makemodule(
|
||||
module_path: Path, path: "LEGACY_PATH", parent
|
||||
) -> Optional["Module"]:
|
||||
"""Return a Module collector or None for the given path.
|
||||
"""Return a :class:`pytest.Module` collector or None for the given path.
|
||||
|
||||
This hook will be called for each matching test module path.
|
||||
The pytest_collect_file hook needs to be used if you want to
|
||||
The :hook:`pytest_collect_file` hook needs to be used if you want to
|
||||
create test modules for files that do not match as a test module.
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
|
||||
:param pathlib.Path module_path: The path of the module to collect.
|
||||
:param LEGACY_PATH path: The path of the module to collect (deprecated).
|
||||
:param module_path: The path of the module to collect.
|
||||
:param path: The path of the module to collect (deprecated).
|
||||
|
||||
.. versionchanged:: 7.0.0
|
||||
The ``module_path`` parameter was added as a :class:`pathlib.Path`
|
||||
@@ -364,6 +384,15 @@ def pytest_pycollect_makeitem(
|
||||
"""Return a custom item/collector for a Python object in a module, or None.
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
|
||||
:param collector:
|
||||
The module/class collector.
|
||||
:param name:
|
||||
The name of the object in the module/class.
|
||||
:param obj:
|
||||
The object.
|
||||
:returns:
|
||||
The created items/collectors.
|
||||
"""
|
||||
|
||||
|
||||
@@ -372,11 +401,18 @@ def pytest_pyfunc_call(pyfuncitem: "Function") -> Optional[object]:
|
||||
"""Call underlying test function.
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
|
||||
:param pyfuncitem:
|
||||
The function item.
|
||||
"""
|
||||
|
||||
|
||||
def pytest_generate_tests(metafunc: "Metafunc") -> None:
|
||||
"""Generate (multiple) parametrized calls to a test function."""
|
||||
"""Generate (multiple) parametrized calls to a test function.
|
||||
|
||||
:param metafunc:
|
||||
The :class:`~pytest.Metafunc` helper for the test function.
|
||||
"""
|
||||
|
||||
|
||||
@hookspec(firstresult=True)
|
||||
@@ -391,7 +427,7 @@ def pytest_make_parametrize_id(
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param config: The pytest config object.
|
||||
:param val: The parametrized value.
|
||||
:param str argname: The automatic parameter name produced by pytest.
|
||||
"""
|
||||
@@ -416,7 +452,7 @@ def pytest_runtestloop(session: "Session") -> Optional[object]:
|
||||
If at any point ``session.shouldfail`` or ``session.shouldstop`` are set, the
|
||||
loop is terminated after the runtest protocol for the current item is finished.
|
||||
|
||||
:param pytest.Session session: The pytest session object.
|
||||
:param session: The pytest session object.
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
The return value is not used, but only stops further processing.
|
||||
@@ -468,7 +504,7 @@ def pytest_runtest_logstart(
|
||||
|
||||
See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
|
||||
|
||||
:param str nodeid: Full node ID of the item.
|
||||
:param nodeid: Full node ID of the item.
|
||||
:param location: A tuple of ``(filename, lineno, testname)``.
|
||||
"""
|
||||
|
||||
@@ -480,7 +516,7 @@ def pytest_runtest_logfinish(
|
||||
|
||||
See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
|
||||
|
||||
:param str nodeid: Full node ID of the item.
|
||||
:param nodeid: Full node ID of the item.
|
||||
:param location: A tuple of ``(filename, lineno, testname)``.
|
||||
"""
|
||||
|
||||
@@ -492,6 +528,9 @@ def pytest_runtest_setup(item: "Item") -> None:
|
||||
parents (which haven't been setup yet). This includes obtaining the
|
||||
values of fixtures required by the item (which haven't been obtained
|
||||
yet).
|
||||
|
||||
:param item:
|
||||
The item.
|
||||
"""
|
||||
|
||||
|
||||
@@ -499,6 +538,9 @@ def pytest_runtest_call(item: "Item") -> None:
|
||||
"""Called to run the test for test item (the call phase).
|
||||
|
||||
The default implementation calls ``item.runtest()``.
|
||||
|
||||
:param item:
|
||||
The item.
|
||||
"""
|
||||
|
||||
|
||||
@@ -510,6 +552,8 @@ def pytest_runtest_teardown(item: "Item", nextitem: Optional["Item"]) -> None:
|
||||
includes running the teardown phase of fixtures required by the item (if
|
||||
they go out of scope).
|
||||
|
||||
:param item:
|
||||
The item.
|
||||
:param nextitem:
|
||||
The scheduled-to-be-next test item (None if no further test item is
|
||||
scheduled). This argument is used to perform exact teardowns, i.e.
|
||||
@@ -527,6 +571,7 @@ def pytest_runtest_makereport(
|
||||
|
||||
See :hook:`pytest_runtest_protocol` for a description of the runtest protocol.
|
||||
|
||||
:param item: The item.
|
||||
:param call: The :class:`~pytest.CallInfo` for the phase.
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
@@ -547,7 +592,11 @@ def pytest_report_to_serializable(
|
||||
report: Union["CollectReport", "TestReport"],
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
"""Serialize the given report object into a data structure suitable for
|
||||
sending over the wire, e.g. converted to JSON."""
|
||||
sending over the wire, e.g. converted to JSON.
|
||||
|
||||
:param config: The pytest config object.
|
||||
:param report: The report.
|
||||
"""
|
||||
|
||||
|
||||
@hookspec(firstresult=True)
|
||||
@@ -556,7 +605,10 @@ def pytest_report_from_serializable(
|
||||
data: Dict[str, Any],
|
||||
) -> Optional[Union["CollectReport", "TestReport"]]:
|
||||
"""Restore a report object previously serialized with
|
||||
:hook:`pytest_report_to_serializable`."""
|
||||
:hook:`pytest_report_to_serializable`.
|
||||
|
||||
:param config: The pytest config object.
|
||||
"""
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
@@ -570,7 +622,12 @@ def pytest_fixture_setup(
|
||||
) -> Optional[object]:
|
||||
"""Perform fixture setup execution.
|
||||
|
||||
:returns: The return value of the call to the fixture function.
|
||||
:param fixturdef:
|
||||
The fixture definition object.
|
||||
:param request:
|
||||
The fixture request object.
|
||||
:returns:
|
||||
The return value of the call to the fixture function.
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
|
||||
@@ -586,7 +643,13 @@ def pytest_fixture_post_finalizer(
|
||||
) -> None:
|
||||
"""Called after fixture teardown, but before the cache is cleared, so
|
||||
the fixture result ``fixturedef.cached_result`` is still available (not
|
||||
``None``)."""
|
||||
``None``).
|
||||
|
||||
:param fixturdef:
|
||||
The fixture definition object.
|
||||
:param request:
|
||||
The fixture request object.
|
||||
"""
|
||||
|
||||
|
||||
# -------------------------------------------------------------------------
|
||||
@@ -598,7 +661,7 @@ def pytest_sessionstart(session: "Session") -> None:
|
||||
"""Called after the ``Session`` object has been created and before performing collection
|
||||
and entering the run test loop.
|
||||
|
||||
:param pytest.Session session: The pytest session object.
|
||||
:param session: The pytest session object.
|
||||
"""
|
||||
|
||||
|
||||
@@ -608,15 +671,15 @@ def pytest_sessionfinish(
|
||||
) -> None:
|
||||
"""Called after whole test run finished, right before returning the exit status to the system.
|
||||
|
||||
:param pytest.Session session: The pytest session object.
|
||||
:param int exitstatus: The status which pytest will return to the system.
|
||||
:param session: The pytest session object.
|
||||
:param exitstatus: The status which pytest will return to the system.
|
||||
"""
|
||||
|
||||
|
||||
def pytest_unconfigure(config: "Config") -> None:
|
||||
"""Called before test process is exited.
|
||||
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param config: The pytest config object.
|
||||
"""
|
||||
|
||||
|
||||
@@ -635,7 +698,10 @@ def pytest_assertrepr_compare(
|
||||
*in* a string will be escaped. Note that all but the first line will
|
||||
be indented slightly, the intention is for the first line to be a summary.
|
||||
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param config: The pytest config object.
|
||||
:param op: The operator, e.g. `"=="`, `"!="`, `"not in"`.
|
||||
:param left: The left operand.
|
||||
:param right: The right operand.
|
||||
"""
|
||||
|
||||
|
||||
@@ -660,10 +726,10 @@ def pytest_assertion_pass(item: "Item", lineno: int, orig: str, expl: str) -> No
|
||||
You need to **clean the .pyc** files in your project directory and interpreter libraries
|
||||
when enabling this option, as assertions will require to be re-written.
|
||||
|
||||
:param pytest.Item item: pytest item object of current test.
|
||||
:param int lineno: Line number of the assert statement.
|
||||
:param str orig: String with the original assertion.
|
||||
:param str expl: String with the assert explanation.
|
||||
:param item: pytest item object of current test.
|
||||
:param lineno: Line number of the assert statement.
|
||||
:param orig: String with the original assertion.
|
||||
:param expl: String with the assert explanation.
|
||||
"""
|
||||
|
||||
|
||||
@@ -672,14 +738,14 @@ def pytest_assertion_pass(item: "Item", lineno: int, orig: str, expl: str) -> No
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def pytest_report_header(
|
||||
def pytest_report_header( # type:ignore[empty-body]
|
||||
config: "Config", start_path: Path, startdir: "LEGACY_PATH"
|
||||
) -> Union[str, List[str]]:
|
||||
"""Return a string or list of strings to be displayed as header info for terminal reporting.
|
||||
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param Path start_path: The starting dir.
|
||||
:param LEGACY_PATH startdir: The starting dir (deprecated).
|
||||
:param config: The pytest config object.
|
||||
:param start_path: The starting dir.
|
||||
:param startdir: The starting dir (deprecated).
|
||||
|
||||
.. note::
|
||||
|
||||
@@ -701,7 +767,7 @@ def pytest_report_header(
|
||||
"""
|
||||
|
||||
|
||||
def pytest_report_collectionfinish(
|
||||
def pytest_report_collectionfinish( # type:ignore[empty-body]
|
||||
config: "Config",
|
||||
start_path: Path,
|
||||
startdir: "LEGACY_PATH",
|
||||
@@ -714,9 +780,9 @@ def pytest_report_collectionfinish(
|
||||
|
||||
.. versionadded:: 3.2
|
||||
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param Path start_path: The starting dir.
|
||||
:param LEGACY_PATH startdir: The starting dir (deprecated).
|
||||
:param config: The pytest config object.
|
||||
:param start_path: The starting dir.
|
||||
:param startdir: The starting dir (deprecated).
|
||||
:param items: List of pytest items that are going to be executed; this list should not be modified.
|
||||
|
||||
.. note::
|
||||
@@ -734,7 +800,7 @@ def pytest_report_collectionfinish(
|
||||
|
||||
|
||||
@hookspec(firstresult=True)
|
||||
def pytest_report_teststatus(
|
||||
def pytest_report_teststatus( # type:ignore[empty-body]
|
||||
report: Union["CollectReport", "TestReport"], config: "Config"
|
||||
) -> Tuple[str, str, Union[str, Mapping[str, bool]]]:
|
||||
"""Return result-category, shortletter and verbose word for status
|
||||
@@ -755,6 +821,7 @@ def pytest_report_teststatus(
|
||||
|
||||
:param report: The report object whose status is to be returned.
|
||||
:param config: The pytest config object.
|
||||
:returns: The test status.
|
||||
|
||||
Stops at first non-None result, see :ref:`firstresult`.
|
||||
"""
|
||||
@@ -767,9 +834,9 @@ def pytest_terminal_summary(
|
||||
) -> None:
|
||||
"""Add a section to terminal summary reporting.
|
||||
|
||||
:param _pytest.terminal.TerminalReporter terminalreporter: The internal terminal reporter object.
|
||||
:param int exitstatus: The exit status that will be reported back to the OS.
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param terminalreporter: The internal terminal reporter object.
|
||||
:param exitstatus: The exit status that will be reported back to the OS.
|
||||
:param config: The pytest config object.
|
||||
|
||||
.. versionadded:: 4.2
|
||||
The ``config`` parameter.
|
||||
@@ -785,21 +852,21 @@ def pytest_warning_recorded(
|
||||
) -> None:
|
||||
"""Process a warning captured by the internal pytest warnings plugin.
|
||||
|
||||
:param warnings.WarningMessage warning_message:
|
||||
:param warning_message:
|
||||
The captured warning. This is the same object produced by :py:func:`warnings.catch_warnings`, and contains
|
||||
the same attributes as the parameters of :py:func:`warnings.showwarning`.
|
||||
|
||||
:param str when:
|
||||
:param when:
|
||||
Indicates when the warning was captured. Possible values:
|
||||
|
||||
* ``"config"``: during pytest configuration/initialization stage.
|
||||
* ``"collect"``: during test collection.
|
||||
* ``"runtest"``: during test execution.
|
||||
|
||||
:param str nodeid:
|
||||
:param nodeid:
|
||||
Full id of the item.
|
||||
|
||||
:param tuple|None location:
|
||||
:param location:
|
||||
When available, holds information about the execution context of the captured
|
||||
warning (filename, linenumber, function). ``function`` evaluates to <module>
|
||||
when the execution context is at the module level.
|
||||
@@ -813,7 +880,9 @@ def pytest_warning_recorded(
|
||||
# -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def pytest_markeval_namespace(config: "Config") -> Dict[str, Any]:
|
||||
def pytest_markeval_namespace( # type:ignore[empty-body]
|
||||
config: "Config",
|
||||
) -> Dict[str, Any]:
|
||||
"""Called when constructing the globals dictionary used for
|
||||
evaluating string conditions in xfail/skipif markers.
|
||||
|
||||
@@ -824,7 +893,7 @@ def pytest_markeval_namespace(config: "Config") -> Dict[str, Any]:
|
||||
|
||||
.. versionadded:: 6.2
|
||||
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param config: The pytest config object.
|
||||
:returns: A dictionary of additional globals to add.
|
||||
"""
|
||||
|
||||
@@ -842,13 +911,19 @@ def pytest_internalerror(
|
||||
|
||||
Return True to suppress the fallback handling of printing an
|
||||
INTERNALERROR message directly to sys.stderr.
|
||||
|
||||
:param excrepr: The exception repr object.
|
||||
:param excinfo: The exception info.
|
||||
"""
|
||||
|
||||
|
||||
def pytest_keyboard_interrupt(
|
||||
excinfo: "ExceptionInfo[Union[KeyboardInterrupt, Exit]]",
|
||||
) -> None:
|
||||
"""Called for keyboard interrupt."""
|
||||
"""Called for keyboard interrupt.
|
||||
|
||||
:param excinfo: The exception info.
|
||||
"""
|
||||
|
||||
|
||||
def pytest_exception_interact(
|
||||
@@ -867,6 +942,13 @@ def pytest_exception_interact(
|
||||
|
||||
This hook is not called if the exception that was raised is an internal
|
||||
exception like ``skip.Exception``.
|
||||
|
||||
:param node:
|
||||
The item or collector.
|
||||
:param call:
|
||||
The call information. Contains the exception.
|
||||
:param report:
|
||||
The collection or test report.
|
||||
"""
|
||||
|
||||
|
||||
@@ -876,8 +958,8 @@ def pytest_enter_pdb(config: "Config", pdb: "pdb.Pdb") -> None:
|
||||
Can be used by plugins to take special action just before the python
|
||||
debugger enters interactive mode.
|
||||
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param pdb.Pdb pdb: The Pdb instance.
|
||||
:param config: The pytest config object.
|
||||
:param pdb: The Pdb instance.
|
||||
"""
|
||||
|
||||
|
||||
@@ -887,6 +969,6 @@ def pytest_leave_pdb(config: "Config", pdb: "pdb.Pdb") -> None:
|
||||
Can be used by plugins to take special action just after the python
|
||||
debugger leaves interactive mode.
|
||||
|
||||
:param pytest.Config config: The pytest config object.
|
||||
:param pdb.Pdb pdb: The Pdb instance.
|
||||
:param config: The pytest config object.
|
||||
:param pdb: The Pdb instance.
|
||||
"""
|
||||
|
||||
@@ -354,7 +354,10 @@ def record_testsuite_property(request: FixtureRequest) -> Callable[[str, object]
|
||||
record_testsuite_property("ARCH", "PPC")
|
||||
record_testsuite_property("STORAGE_TYPE", "CEPH")
|
||||
|
||||
``name`` must be a string, ``value`` will be converted to a string and properly xml-escaped.
|
||||
:param name:
|
||||
The property name.
|
||||
:param value:
|
||||
The property value. Will be converted to a string.
|
||||
|
||||
.. warning::
|
||||
|
||||
@@ -386,7 +389,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
metavar="path",
|
||||
type=functools.partial(filename_arg, optname="--junitxml"),
|
||||
default=None,
|
||||
help="create junit-xml style report file at given path.",
|
||||
help="Create junit-xml style report file at given path",
|
||||
)
|
||||
group.addoption(
|
||||
"--junitprefix",
|
||||
@@ -394,7 +397,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
action="store",
|
||||
metavar="str",
|
||||
default=None,
|
||||
help="prepend prefix to classnames in junit-xml output",
|
||||
help="Prepend prefix to classnames in junit-xml output",
|
||||
)
|
||||
parser.addini(
|
||||
"junit_suite_name", "Test suite name for JUnit report", default="pytest"
|
||||
|
||||
+47
-27
@@ -37,10 +37,11 @@ from _pytest.terminal import TerminalReporter
|
||||
|
||||
if TYPE_CHECKING:
|
||||
logging_StreamHandler = logging.StreamHandler[StringIO]
|
||||
|
||||
from typing_extensions import Literal
|
||||
else:
|
||||
logging_StreamHandler = logging.StreamHandler
|
||||
|
||||
|
||||
DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s"
|
||||
DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
|
||||
_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m")
|
||||
@@ -218,7 +219,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
|
||||
def add_option_ini(option, dest, default=None, type=None, **kwargs):
|
||||
parser.addini(
|
||||
dest, default=default, type=type, help="default value for " + option
|
||||
dest, default=default, type=type, help="Default value for " + option
|
||||
)
|
||||
group.addoption(option, dest=dest, **kwargs)
|
||||
|
||||
@@ -228,8 +229,8 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
default=None,
|
||||
metavar="LEVEL",
|
||||
help=(
|
||||
"level of messages to catch/display.\n"
|
||||
"Not set by default, so it depends on the root/parent log handler's"
|
||||
"Level of messages to catch/display."
|
||||
" Not set by default, so it depends on the root/parent log handler's"
|
||||
' effective level, where it is "WARNING" by default.'
|
||||
),
|
||||
)
|
||||
@@ -237,58 +238,58 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--log-format",
|
||||
dest="log_format",
|
||||
default=DEFAULT_LOG_FORMAT,
|
||||
help="log format as used by the logging module.",
|
||||
help="Log format used by the logging module",
|
||||
)
|
||||
add_option_ini(
|
||||
"--log-date-format",
|
||||
dest="log_date_format",
|
||||
default=DEFAULT_LOG_DATE_FORMAT,
|
||||
help="log date format as used by the logging module.",
|
||||
help="Log date format used by the logging module",
|
||||
)
|
||||
parser.addini(
|
||||
"log_cli",
|
||||
default=False,
|
||||
type="bool",
|
||||
help='enable log display during test run (also known as "live logging").',
|
||||
help='Enable log display during test run (also known as "live logging")',
|
||||
)
|
||||
add_option_ini(
|
||||
"--log-cli-level", dest="log_cli_level", default=None, help="cli logging level."
|
||||
"--log-cli-level", dest="log_cli_level", default=None, help="CLI logging level"
|
||||
)
|
||||
add_option_ini(
|
||||
"--log-cli-format",
|
||||
dest="log_cli_format",
|
||||
default=None,
|
||||
help="log format as used by the logging module.",
|
||||
help="Log format used by the logging module",
|
||||
)
|
||||
add_option_ini(
|
||||
"--log-cli-date-format",
|
||||
dest="log_cli_date_format",
|
||||
default=None,
|
||||
help="log date format as used by the logging module.",
|
||||
help="Log date format used by the logging module",
|
||||
)
|
||||
add_option_ini(
|
||||
"--log-file",
|
||||
dest="log_file",
|
||||
default=None,
|
||||
help="path to a file when logging will be written to.",
|
||||
help="Path to a file when logging will be written to",
|
||||
)
|
||||
add_option_ini(
|
||||
"--log-file-level",
|
||||
dest="log_file_level",
|
||||
default=None,
|
||||
help="log file logging level.",
|
||||
help="Log file logging level",
|
||||
)
|
||||
add_option_ini(
|
||||
"--log-file-format",
|
||||
dest="log_file_format",
|
||||
default=DEFAULT_LOG_FORMAT,
|
||||
help="log format as used by the logging module.",
|
||||
help="Log format used by the logging module",
|
||||
)
|
||||
add_option_ini(
|
||||
"--log-file-date-format",
|
||||
dest="log_file_date_format",
|
||||
default=DEFAULT_LOG_DATE_FORMAT,
|
||||
help="log date format as used by the logging module.",
|
||||
help="Log date format used by the logging module",
|
||||
)
|
||||
add_option_ini(
|
||||
"--log-auto-indent",
|
||||
@@ -296,6 +297,13 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
default=None,
|
||||
help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.",
|
||||
)
|
||||
group.addoption(
|
||||
"--log-disable",
|
||||
action="append",
|
||||
default=[],
|
||||
dest="logger_disable",
|
||||
help="Disable a logger by name. Can be passed multipe times.",
|
||||
)
|
||||
|
||||
|
||||
_HandlerType = TypeVar("_HandlerType", bound=logging.Handler)
|
||||
@@ -345,6 +353,10 @@ class LogCaptureHandler(logging_StreamHandler):
|
||||
self.records = []
|
||||
self.stream = StringIO()
|
||||
|
||||
def clear(self) -> None:
|
||||
self.records.clear()
|
||||
self.stream = StringIO()
|
||||
|
||||
def handleError(self, record: logging.LogRecord) -> None:
|
||||
if logging.raiseExceptions:
|
||||
# Fail the test if the log message is bad (emit failed).
|
||||
@@ -379,20 +391,19 @@ class LogCaptureFixture:
|
||||
|
||||
@property
|
||||
def handler(self) -> LogCaptureHandler:
|
||||
"""Get the logging handler used by the fixture.
|
||||
|
||||
:rtype: LogCaptureHandler
|
||||
"""
|
||||
"""Get the logging handler used by the fixture."""
|
||||
return self._item.stash[caplog_handler_key]
|
||||
|
||||
def get_records(self, when: str) -> List[logging.LogRecord]:
|
||||
def get_records(
|
||||
self, when: "Literal['setup', 'call', 'teardown']"
|
||||
) -> List[logging.LogRecord]:
|
||||
"""Get the logging records for one of the possible test phases.
|
||||
|
||||
:param str when:
|
||||
Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown".
|
||||
:param when:
|
||||
Which test phase to obtain the records from.
|
||||
Valid values are: "setup", "call" and "teardown".
|
||||
|
||||
:returns: The list of captured records at the given stage.
|
||||
:rtype: List[logging.LogRecord]
|
||||
|
||||
.. versionadded:: 3.4
|
||||
"""
|
||||
@@ -440,7 +451,7 @@ class LogCaptureFixture:
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Reset the list of log records and the captured log text."""
|
||||
self.handler.reset()
|
||||
self.handler.clear()
|
||||
|
||||
def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None:
|
||||
"""Set the level of a logger for the duration of a test.
|
||||
@@ -449,8 +460,8 @@ class LogCaptureFixture:
|
||||
The levels of the loggers changed by this function will be
|
||||
restored to their initial values at the end of the test.
|
||||
|
||||
:param int level: The level.
|
||||
:param str logger: The logger to update. If not given, the root logger.
|
||||
:param level: The level.
|
||||
:param logger: The logger to update. If not given, the root logger.
|
||||
"""
|
||||
logger_obj = logging.getLogger(logger)
|
||||
# Save the original log-level to restore it during teardown.
|
||||
@@ -468,8 +479,8 @@ class LogCaptureFixture:
|
||||
the end of the 'with' statement the level is restored to its original
|
||||
value.
|
||||
|
||||
:param int level: The level.
|
||||
:param str logger: The logger to update. If not given, the root logger.
|
||||
:param level: The level.
|
||||
:param logger: The logger to update. If not given, the root logger.
|
||||
"""
|
||||
logger_obj = logging.getLogger(logger)
|
||||
orig_level = logger_obj.level
|
||||
@@ -590,6 +601,15 @@ class LoggingPlugin:
|
||||
get_option_ini(config, "log_auto_indent"),
|
||||
)
|
||||
self.log_cli_handler.setFormatter(log_cli_formatter)
|
||||
self._disable_loggers(loggers_to_disable=config.option.logger_disable)
|
||||
|
||||
def _disable_loggers(self, loggers_to_disable: List[str]) -> None:
|
||||
if not loggers_to_disable:
|
||||
return
|
||||
|
||||
for name in loggers_to_disable:
|
||||
logger = logging.getLogger(name)
|
||||
logger.disabled = True
|
||||
|
||||
def _create_formatter(self, log_format, log_date_format, auto_indent):
|
||||
# Color option doesn't exist if terminal plugin is disabled.
|
||||
|
||||
+38
-31
@@ -12,7 +12,6 @@ from typing import FrozenSet
|
||||
from typing import Iterator
|
||||
from typing import List
|
||||
from typing import Optional
|
||||
from typing import overload
|
||||
from typing import Sequence
|
||||
from typing import Set
|
||||
from typing import Tuple
|
||||
@@ -25,6 +24,7 @@ import attr
|
||||
import _pytest._code
|
||||
from _pytest import nodes
|
||||
from _pytest.compat import final
|
||||
from _pytest.compat import overload
|
||||
from _pytest.config import Config
|
||||
from _pytest.config import directory_arg
|
||||
from _pytest.config import ExitCode
|
||||
@@ -51,7 +51,7 @@ if TYPE_CHECKING:
|
||||
def pytest_addoption(parser: Parser) -> None:
|
||||
parser.addini(
|
||||
"norecursedirs",
|
||||
"directory patterns to avoid for recursion",
|
||||
"Directory patterns to avoid for recursion",
|
||||
type="args",
|
||||
default=[
|
||||
"*.egg",
|
||||
@@ -67,26 +67,26 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
)
|
||||
parser.addini(
|
||||
"testpaths",
|
||||
"directories to search for tests when no files or directories are given in the "
|
||||
"command line.",
|
||||
"Directories to search for tests when no files or directories are given on the "
|
||||
"command line",
|
||||
type="args",
|
||||
default=[],
|
||||
)
|
||||
group = parser.getgroup("general", "running and selection options")
|
||||
group = parser.getgroup("general", "Running and selection options")
|
||||
group._addoption(
|
||||
"-x",
|
||||
"--exitfirst",
|
||||
action="store_const",
|
||||
dest="maxfail",
|
||||
const=1,
|
||||
help="exit instantly on first error or failed test.",
|
||||
help="Exit instantly on first error or failed test",
|
||||
)
|
||||
group = parser.getgroup("pytest-warnings")
|
||||
group.addoption(
|
||||
"-W",
|
||||
"--pythonwarnings",
|
||||
action="append",
|
||||
help="set which warnings to report, see -W option of python itself.",
|
||||
help="Set which warnings to report, see -W option of Python itself",
|
||||
)
|
||||
parser.addini(
|
||||
"filterwarnings",
|
||||
@@ -102,37 +102,39 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
type=int,
|
||||
dest="maxfail",
|
||||
default=0,
|
||||
help="exit after first num failures or errors.",
|
||||
help="Exit after first num failures or errors",
|
||||
)
|
||||
group._addoption(
|
||||
"--strict-config",
|
||||
action="store_true",
|
||||
help="any warnings encountered while parsing the `pytest` section of the configuration file raise errors.",
|
||||
help="Any warnings encountered while parsing the `pytest` section of the "
|
||||
"configuration file raise errors",
|
||||
)
|
||||
group._addoption(
|
||||
"--strict-markers",
|
||||
action="store_true",
|
||||
help="markers not registered in the `markers` section of the configuration file raise errors.",
|
||||
help="Markers not registered in the `markers` section of the configuration "
|
||||
"file raise errors",
|
||||
)
|
||||
group._addoption(
|
||||
"--strict",
|
||||
action="store_true",
|
||||
help="(deprecated) alias to --strict-markers.",
|
||||
help="(Deprecated) alias to --strict-markers",
|
||||
)
|
||||
group._addoption(
|
||||
"-c",
|
||||
metavar="file",
|
||||
type=str,
|
||||
dest="inifilename",
|
||||
help="load configuration from `file` instead of trying to locate one of the implicit "
|
||||
"configuration files.",
|
||||
help="Load configuration from `file` instead of trying to locate one of the "
|
||||
"implicit configuration files",
|
||||
)
|
||||
group._addoption(
|
||||
"--continue-on-collection-errors",
|
||||
action="store_true",
|
||||
default=False,
|
||||
dest="continue_on_collection_errors",
|
||||
help="Force test execution even if collection errors occur.",
|
||||
help="Force test execution even if collection errors occur",
|
||||
)
|
||||
group._addoption(
|
||||
"--rootdir",
|
||||
@@ -149,30 +151,30 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--collect-only",
|
||||
"--co",
|
||||
action="store_true",
|
||||
help="only collect tests, don't execute them.",
|
||||
help="Only collect tests, don't execute them",
|
||||
)
|
||||
group.addoption(
|
||||
"--pyargs",
|
||||
action="store_true",
|
||||
help="try to interpret all arguments as python packages.",
|
||||
help="Try to interpret all arguments as Python packages",
|
||||
)
|
||||
group.addoption(
|
||||
"--ignore",
|
||||
action="append",
|
||||
metavar="path",
|
||||
help="ignore path during collection (multi-allowed).",
|
||||
help="Ignore path during collection (multi-allowed)",
|
||||
)
|
||||
group.addoption(
|
||||
"--ignore-glob",
|
||||
action="append",
|
||||
metavar="path",
|
||||
help="ignore path pattern during collection (multi-allowed).",
|
||||
help="Ignore path pattern during collection (multi-allowed)",
|
||||
)
|
||||
group.addoption(
|
||||
"--deselect",
|
||||
action="append",
|
||||
metavar="nodeid_prefix",
|
||||
help="deselect item (via node id prefix) during collection (multi-allowed).",
|
||||
help="Deselect item (via node id prefix) during collection (multi-allowed)",
|
||||
)
|
||||
group.addoption(
|
||||
"--confcutdir",
|
||||
@@ -180,14 +182,14 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
default=None,
|
||||
metavar="dir",
|
||||
type=functools.partial(directory_arg, optname="--confcutdir"),
|
||||
help="only load conftest.py's relative to specified dir.",
|
||||
help="Only load conftest.py's relative to specified dir",
|
||||
)
|
||||
group.addoption(
|
||||
"--noconftest",
|
||||
action="store_true",
|
||||
dest="noconftest",
|
||||
default=False,
|
||||
help="Don't load any conftest.py files.",
|
||||
help="Don't load any conftest.py files",
|
||||
)
|
||||
group.addoption(
|
||||
"--keepduplicates",
|
||||
@@ -195,7 +197,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
action="store_true",
|
||||
dest="keepduplicates",
|
||||
default=False,
|
||||
help="Keep duplicate tests.",
|
||||
help="Keep duplicate tests",
|
||||
)
|
||||
group.addoption(
|
||||
"--collect-in-virtualenv",
|
||||
@@ -209,8 +211,8 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
default="prepend",
|
||||
choices=["prepend", "append", "importlib"],
|
||||
dest="importmode",
|
||||
help="prepend/append to sys.path when importing test modules and conftest files, "
|
||||
"default is to prepend.",
|
||||
help="Prepend/append to sys.path when importing test modules and conftest "
|
||||
"files. Default: prepend.",
|
||||
)
|
||||
|
||||
group = parser.getgroup("debugconfig", "test session debugging and configuration")
|
||||
@@ -221,8 +223,8 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
type=validate_basetemp,
|
||||
metavar="dir",
|
||||
help=(
|
||||
"base temporary directory for this test run."
|
||||
"(warning: this directory is removed if it exists)"
|
||||
"Base temporary directory for this test run. "
|
||||
"(Warning: this directory is removed if it exists.)"
|
||||
),
|
||||
)
|
||||
|
||||
@@ -595,12 +597,12 @@ class Session(nodes.FSCollector):
|
||||
...
|
||||
|
||||
@overload
|
||||
def perform_collect(
|
||||
def perform_collect( # noqa: F811
|
||||
self, args: Optional[Sequence[str]] = ..., genitems: bool = ...
|
||||
) -> Sequence[Union[nodes.Item, nodes.Collector]]:
|
||||
...
|
||||
|
||||
def perform_collect(
|
||||
def perform_collect( # noqa: F811
|
||||
self, args: Optional[Sequence[str]] = None, genitems: bool = True
|
||||
) -> Sequence[Union[nodes.Item, nodes.Collector]]:
|
||||
"""Perform the collection phase for this session.
|
||||
@@ -645,9 +647,14 @@ class Session(nodes.FSCollector):
|
||||
self.trace.root.indent -= 1
|
||||
if self._notfound:
|
||||
errors = []
|
||||
for arg, cols in self._notfound:
|
||||
line = f"(no name {arg!r} in any of {cols!r})"
|
||||
errors.append(f"not found: {arg}\n{line}")
|
||||
for arg, collectors in self._notfound:
|
||||
if collectors:
|
||||
errors.append(
|
||||
f"not found: {arg}\n(no name {arg!r} in any of {collectors!r})"
|
||||
)
|
||||
else:
|
||||
errors.append(f"found no collectors for {arg}")
|
||||
|
||||
raise UsageError(*errors)
|
||||
if not genitems:
|
||||
items = rep.result
|
||||
|
||||
@@ -62,8 +62,8 @@ def param(
|
||||
assert eval(test_input) == expected
|
||||
|
||||
:param values: Variable args of the values of the parameter set, in order.
|
||||
:keyword marks: A single mark or a list of marks to be applied to this parameter set.
|
||||
:keyword str id: The id to attribute to this parameter set.
|
||||
:param marks: A single mark or a list of marks to be applied to this parameter set.
|
||||
:param id: The id to attribute to this parameter set.
|
||||
"""
|
||||
return ParameterSet.param(*values, marks=marks, id=id)
|
||||
|
||||
@@ -76,8 +76,8 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
dest="keyword",
|
||||
default="",
|
||||
metavar="EXPRESSION",
|
||||
help="only run tests which match the given substring expression. "
|
||||
"An expression is a python evaluatable expression "
|
||||
help="Only run tests which match the given substring expression. "
|
||||
"An expression is a Python evaluatable expression "
|
||||
"where all names are substring-matched against test names "
|
||||
"and their parent classes. Example: -k 'test_method or test_"
|
||||
"other' matches all test functions and classes whose name "
|
||||
@@ -96,7 +96,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
dest="markexpr",
|
||||
default="",
|
||||
metavar="MARKEXPR",
|
||||
help="only run tests matching given mark expression.\n"
|
||||
help="Only run tests matching given mark expression. "
|
||||
"For example: -m 'mark1 and not mark2'.",
|
||||
)
|
||||
|
||||
@@ -106,8 +106,8 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
help="show markers (builtin, plugin and per-project ones).",
|
||||
)
|
||||
|
||||
parser.addini("markers", "markers for test functions", "linelist")
|
||||
parser.addini(EMPTY_PARAMETERSET_OPTION, "default marker for empty parametersets")
|
||||
parser.addini("markers", "Markers for test functions", "linelist")
|
||||
parser.addini(EMPTY_PARAMETERSET_OPTION, "Default marker for empty parametersets")
|
||||
|
||||
|
||||
@hookimpl(tryfirst=True)
|
||||
|
||||
@@ -21,15 +21,12 @@ import types
|
||||
from typing import Callable
|
||||
from typing import Iterator
|
||||
from typing import Mapping
|
||||
from typing import NoReturn
|
||||
from typing import Optional
|
||||
from typing import Sequence
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import attr
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import NoReturn
|
||||
|
||||
|
||||
__all__ = [
|
||||
"Expression",
|
||||
@@ -117,7 +114,7 @@ class Scanner:
|
||||
self.reject((type,))
|
||||
return None
|
||||
|
||||
def reject(self, expected: Sequence[TokenType]) -> "NoReturn":
|
||||
def reject(self, expected: Sequence[TokenType]) -> NoReturn:
|
||||
raise ParseError(
|
||||
self.current.pos + 1,
|
||||
"expected {}; got {}".format(
|
||||
|
||||
@@ -126,12 +126,12 @@ class ParameterSet(NamedTuple):
|
||||
|
||||
@staticmethod
|
||||
def _parse_parametrize_args(
|
||||
argnames: Union[str, List[str], Tuple[str, ...]],
|
||||
argnames: Union[str, Sequence[str]],
|
||||
argvalues: Iterable[Union["ParameterSet", Sequence[object], object]],
|
||||
*args,
|
||||
**kwargs,
|
||||
) -> Tuple[Union[List[str], Tuple[str, ...]], bool]:
|
||||
if not isinstance(argnames, (tuple, list)):
|
||||
) -> Tuple[Sequence[str], bool]:
|
||||
if isinstance(argnames, str):
|
||||
argnames = [x.strip() for x in argnames.split(",") if x.strip()]
|
||||
force_tuple = len(argnames) == 1
|
||||
else:
|
||||
@@ -150,12 +150,12 @@ class ParameterSet(NamedTuple):
|
||||
@classmethod
|
||||
def _for_parametrize(
|
||||
cls,
|
||||
argnames: Union[str, List[str], Tuple[str, ...]],
|
||||
argnames: Union[str, Sequence[str]],
|
||||
argvalues: Iterable[Union["ParameterSet", Sequence[object], object]],
|
||||
func,
|
||||
config: Config,
|
||||
nodeid: str,
|
||||
) -> Tuple[Union[List[str], Tuple[str, ...]], List["ParameterSet"]]:
|
||||
) -> Tuple[Sequence[str], List["ParameterSet"]]:
|
||||
argnames, force_tuple = cls._parse_parametrize_args(argnames, argvalues)
|
||||
parameters = cls._parse_parametrize_parameters(argvalues, force_tuple)
|
||||
del argvalues
|
||||
@@ -355,12 +355,35 @@ class MarkDecorator:
|
||||
return self.with_args(*args, **kwargs)
|
||||
|
||||
|
||||
def get_unpacked_marks(obj: object) -> Iterable[Mark]:
|
||||
"""Obtain the unpacked marks that are stored on an object."""
|
||||
mark_list = getattr(obj, "pytestmark", [])
|
||||
if not isinstance(mark_list, list):
|
||||
mark_list = [mark_list]
|
||||
return normalize_mark_list(mark_list)
|
||||
def get_unpacked_marks(
|
||||
obj: Union[object, type],
|
||||
*,
|
||||
consider_mro: bool = True,
|
||||
) -> List[Mark]:
|
||||
"""Obtain the unpacked marks that are stored on an object.
|
||||
|
||||
If obj is a class and consider_mro is true, return marks applied to
|
||||
this class and all of its super-classes in MRO order. If consider_mro
|
||||
is false, only return marks applied directly to this class.
|
||||
"""
|
||||
if isinstance(obj, type):
|
||||
if not consider_mro:
|
||||
mark_lists = [obj.__dict__.get("pytestmark", [])]
|
||||
else:
|
||||
mark_lists = [x.__dict__.get("pytestmark", []) for x in obj.__mro__]
|
||||
mark_list = []
|
||||
for item in mark_lists:
|
||||
if isinstance(item, list):
|
||||
mark_list.extend(item)
|
||||
else:
|
||||
mark_list.append(item)
|
||||
else:
|
||||
mark_attribute = getattr(obj, "pytestmark", [])
|
||||
if isinstance(mark_attribute, list):
|
||||
mark_list = mark_attribute
|
||||
else:
|
||||
mark_list = [mark_attribute]
|
||||
return list(normalize_mark_list(mark_list))
|
||||
|
||||
|
||||
def normalize_mark_list(
|
||||
@@ -388,7 +411,7 @@ def store_mark(obj, mark: Mark) -> None:
|
||||
assert isinstance(mark, Mark), mark
|
||||
# Always reassign name to avoid updating pytestmark in a reference that
|
||||
# was only borrowed.
|
||||
obj.pytestmark = [*get_unpacked_marks(obj), mark]
|
||||
obj.pytestmark = [*get_unpacked_marks(obj, consider_mro=False), mark]
|
||||
|
||||
|
||||
# Typing for builtin pytest marks. This is cheating; it gives builtin marks
|
||||
@@ -397,7 +420,7 @@ if TYPE_CHECKING:
|
||||
from _pytest.scope import _ScopeName
|
||||
|
||||
class _SkipMarkDecorator(MarkDecorator):
|
||||
@overload # type: ignore[override,misc]
|
||||
@overload # type: ignore[override,misc,no-overload-impl]
|
||||
def __call__(self, arg: Markable) -> Markable:
|
||||
...
|
||||
|
||||
@@ -415,7 +438,7 @@ if TYPE_CHECKING:
|
||||
...
|
||||
|
||||
class _XfailMarkDecorator(MarkDecorator):
|
||||
@overload # type: ignore[override,misc]
|
||||
@overload # type: ignore[override,misc,no-overload-impl]
|
||||
def __call__(self, arg: Markable) -> Markable:
|
||||
...
|
||||
|
||||
@@ -434,7 +457,7 @@ if TYPE_CHECKING:
|
||||
class _ParametrizeMarkDecorator(MarkDecorator):
|
||||
def __call__( # type: ignore[override]
|
||||
self,
|
||||
argnames: Union[str, List[str], Tuple[str, ...]],
|
||||
argnames: Union[str, Sequence[str]],
|
||||
argvalues: Iterable[Union[ParameterSet, Sequence[object], object]],
|
||||
*,
|
||||
indirect: Union[bool, Sequence[str]] = ...,
|
||||
|
||||
@@ -120,7 +120,7 @@ class MonkeyPatch:
|
||||
|
||||
Returned by the :fixture:`monkeypatch` fixture.
|
||||
|
||||
:versionchanged:: 6.2
|
||||
.. versionchanged:: 6.2
|
||||
Can now also be used directly as `pytest.MonkeyPatch()`, for when
|
||||
the fixture is not available. In this case, use
|
||||
:meth:`with MonkeyPatch.context() as mp: <context>` or remember to call
|
||||
@@ -367,7 +367,8 @@ class MonkeyPatch:
|
||||
def chdir(self, path: Union[str, "os.PathLike[str]"]) -> None:
|
||||
"""Change the current working directory to the specified path.
|
||||
|
||||
Path can be a string or a path object.
|
||||
:param path:
|
||||
The path to change into.
|
||||
"""
|
||||
if self._cwd is None:
|
||||
self._cwd = os.getcwd()
|
||||
|
||||
+17
-8
@@ -193,7 +193,7 @@ class Node(metaclass=NodeMeta):
|
||||
nodeid: Optional[str] = None,
|
||||
) -> None:
|
||||
#: A unique name within the scope of the parent node.
|
||||
self.name = name
|
||||
self.name: str = name
|
||||
|
||||
#: The parent collector node.
|
||||
self.parent = parent
|
||||
@@ -208,7 +208,7 @@ class Node(metaclass=NodeMeta):
|
||||
|
||||
if session:
|
||||
#: The pytest session this node is part of.
|
||||
self.session = session
|
||||
self.session: Session = session
|
||||
else:
|
||||
if not parent:
|
||||
raise TypeError("session or parent must be provided")
|
||||
@@ -239,9 +239,7 @@ class Node(metaclass=NodeMeta):
|
||||
|
||||
#: A place where plugins can store information on the node for their
|
||||
#: own use.
|
||||
#:
|
||||
#: :type: Stash
|
||||
self.stash = Stash()
|
||||
self.stash: Stash = Stash()
|
||||
# Deprecated alias. Was never public. Can be removed in a few releases.
|
||||
self._store = self.stash
|
||||
|
||||
@@ -326,7 +324,10 @@ class Node(metaclass=NodeMeta):
|
||||
|
||||
def listchain(self) -> List["Node"]:
|
||||
"""Return list of all parent collectors up to self, starting from
|
||||
the root of collection tree."""
|
||||
the root of collection tree.
|
||||
|
||||
:returns: The nodes.
|
||||
"""
|
||||
chain = []
|
||||
item: Optional[Node] = self
|
||||
while item is not None:
|
||||
@@ -340,6 +341,8 @@ class Node(metaclass=NodeMeta):
|
||||
) -> None:
|
||||
"""Dynamically add a marker object to the node.
|
||||
|
||||
:param marker:
|
||||
The marker.
|
||||
:param append:
|
||||
Whether to append the marker, or prepend it.
|
||||
"""
|
||||
@@ -361,6 +364,7 @@ class Node(metaclass=NodeMeta):
|
||||
"""Iterate over all markers of the node.
|
||||
|
||||
:param name: If given, filter the results by the name attribute.
|
||||
:returns: An iterator of the markers of the node.
|
||||
"""
|
||||
return (x[1] for x in self.iter_markers_with_node(name=name))
|
||||
|
||||
@@ -407,7 +411,8 @@ class Node(metaclass=NodeMeta):
|
||||
return [x.name for x in self.listchain()]
|
||||
|
||||
def addfinalizer(self, fin: Callable[[], object]) -> None:
|
||||
"""Register a function to be called when this node is finalized.
|
||||
"""Register a function to be called without arguments when this node is
|
||||
finalized.
|
||||
|
||||
This method can only be called when this node is active
|
||||
in a setup chain, for example during self.setup().
|
||||
@@ -416,7 +421,11 @@ class Node(metaclass=NodeMeta):
|
||||
|
||||
def getparent(self, cls: Type[_NodeType]) -> Optional[_NodeType]:
|
||||
"""Get the next parent node (including self) which is an instance of
|
||||
the given class."""
|
||||
the given class.
|
||||
|
||||
:param cls: The node class to search for.
|
||||
:returns: The node, if found.
|
||||
"""
|
||||
current: Optional[Node] = self
|
||||
while current and not isinstance(current, cls):
|
||||
current = current.parent
|
||||
|
||||
+11
-3
@@ -1,5 +1,8 @@
|
||||
"""Run testsuites written for nose."""
|
||||
import warnings
|
||||
|
||||
from _pytest.config import hookimpl
|
||||
from _pytest.deprecated import NOSE_SUPPORT
|
||||
from _pytest.fixtures import getfixturemarker
|
||||
from _pytest.nodes import Item
|
||||
from _pytest.python import Function
|
||||
@@ -18,8 +21,8 @@ def pytest_runtest_setup(item: Item) -> None:
|
||||
# see https://github.com/python/mypy/issues/2608
|
||||
func = item
|
||||
|
||||
call_optional(func.obj, "setup")
|
||||
func.addfinalizer(lambda: call_optional(func.obj, "teardown"))
|
||||
call_optional(func.obj, "setup", func.nodeid)
|
||||
func.addfinalizer(lambda: call_optional(func.obj, "teardown", func.nodeid))
|
||||
|
||||
# NOTE: Module- and class-level fixtures are handled in python.py
|
||||
# with `pluginmanager.has_plugin("nose")` checks.
|
||||
@@ -27,7 +30,7 @@ def pytest_runtest_setup(item: Item) -> None:
|
||||
# it's not straightforward.
|
||||
|
||||
|
||||
def call_optional(obj: object, name: str) -> bool:
|
||||
def call_optional(obj: object, name: str, nodeid: str) -> bool:
|
||||
method = getattr(obj, name, None)
|
||||
if method is None:
|
||||
return False
|
||||
@@ -36,6 +39,11 @@ def call_optional(obj: object, name: str) -> bool:
|
||||
return False
|
||||
if not callable(method):
|
||||
return False
|
||||
# Warn about deprecation of this plugin.
|
||||
method_name = getattr(method, "__name__", str(method))
|
||||
warnings.warn(
|
||||
NOSE_SUPPORT.format(nodeid=nodeid, method=method_name, stage=name), stacklevel=2
|
||||
)
|
||||
# If there are any problems allow the exception to raise rather than
|
||||
# silently ignoring it.
|
||||
method()
|
||||
|
||||
+11
-10
@@ -5,6 +5,7 @@ import warnings
|
||||
from typing import Any
|
||||
from typing import Callable
|
||||
from typing import cast
|
||||
from typing import NoReturn
|
||||
from typing import Optional
|
||||
from typing import Type
|
||||
from typing import TypeVar
|
||||
@@ -14,7 +15,6 @@ from _pytest.deprecated import KEYWORD_MSG_ARG
|
||||
TYPE_CHECKING = False # Avoid circular import through compat.
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import NoReturn
|
||||
from typing_extensions import Protocol
|
||||
else:
|
||||
# typing.Protocol is only available starting from Python 3.8. It is also
|
||||
@@ -115,7 +115,7 @@ def _with_exception(exception_type: _ET) -> Callable[[_F], _WithException[_F, _E
|
||||
@_with_exception(Exit)
|
||||
def exit(
|
||||
reason: str = "", returncode: Optional[int] = None, *, msg: Optional[str] = None
|
||||
) -> "NoReturn":
|
||||
) -> NoReturn:
|
||||
"""Exit testing process.
|
||||
|
||||
:param reason:
|
||||
@@ -146,7 +146,7 @@ def exit(
|
||||
@_with_exception(Skipped)
|
||||
def skip(
|
||||
reason: str = "", *, allow_module_level: bool = False, msg: Optional[str] = None
|
||||
) -> "NoReturn":
|
||||
) -> NoReturn:
|
||||
"""Skip an executing test with the given message.
|
||||
|
||||
This function should be called only during testing (setup, call or teardown) or
|
||||
@@ -176,9 +176,7 @@ def skip(
|
||||
|
||||
|
||||
@_with_exception(Failed)
|
||||
def fail(
|
||||
reason: str = "", pytrace: bool = True, msg: Optional[str] = None
|
||||
) -> "NoReturn":
|
||||
def fail(reason: str = "", pytrace: bool = True, msg: Optional[str] = None) -> NoReturn:
|
||||
"""Explicitly fail an executing test with the given message.
|
||||
|
||||
:param reason:
|
||||
@@ -238,11 +236,14 @@ class XFailed(Failed):
|
||||
|
||||
|
||||
@_with_exception(XFailed)
|
||||
def xfail(reason: str = "") -> "NoReturn":
|
||||
def xfail(reason: str = "") -> NoReturn:
|
||||
"""Imperatively xfail an executing test or setup function with the given reason.
|
||||
|
||||
This function should be called only during testing (setup, call or teardown).
|
||||
|
||||
:param reason:
|
||||
The message to show the user as reason for the xfail.
|
||||
|
||||
.. note::
|
||||
It is better to use the :ref:`pytest.mark.xfail ref` marker when
|
||||
possible to declare a test to be xfailed under certain conditions
|
||||
@@ -258,12 +259,12 @@ def importorskip(
|
||||
"""Import and return the requested module ``modname``, or skip the
|
||||
current test if the module cannot be imported.
|
||||
|
||||
:param str modname:
|
||||
:param modname:
|
||||
The name of the module to import.
|
||||
:param str minversion:
|
||||
:param minversion:
|
||||
If given, the imported module's ``__version__`` attribute must be at
|
||||
least this minimal version, otherwise the test is still skipped.
|
||||
:param str reason:
|
||||
:param reason:
|
||||
If given, this reason is shown as the message when the module cannot
|
||||
be imported.
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
dest="pastebin",
|
||||
default=None,
|
||||
choices=["failed", "all"],
|
||||
help="send failed|all info to bpaste.net pastebin service.",
|
||||
help="Send failed|all info to bpaste.net pastebin service",
|
||||
)
|
||||
|
||||
|
||||
|
||||
+17
-4
@@ -335,15 +335,26 @@ def cleanup_candidates(root: Path, prefix: str, keep: int) -> Iterator[Path]:
|
||||
yield path
|
||||
|
||||
|
||||
def cleanup_dead_symlink(root: Path):
|
||||
for left_dir in root.iterdir():
|
||||
if left_dir.is_symlink():
|
||||
if not left_dir.resolve().exists():
|
||||
left_dir.unlink()
|
||||
|
||||
|
||||
def cleanup_numbered_dir(
|
||||
root: Path, prefix: str, keep: int, consider_lock_dead_if_created_before: float
|
||||
) -> None:
|
||||
"""Cleanup for lock driven numbered directories."""
|
||||
if not root.exists():
|
||||
return
|
||||
for path in cleanup_candidates(root, prefix, keep):
|
||||
try_cleanup(path, consider_lock_dead_if_created_before)
|
||||
for path in root.glob("garbage-*"):
|
||||
try_cleanup(path, consider_lock_dead_if_created_before)
|
||||
|
||||
cleanup_dead_symlink(root)
|
||||
|
||||
|
||||
def make_numbered_dir_with_cleanup(
|
||||
root: Path,
|
||||
@@ -357,8 +368,10 @@ def make_numbered_dir_with_cleanup(
|
||||
for i in range(10):
|
||||
try:
|
||||
p = make_numbered_dir(root, prefix, mode)
|
||||
lock_path = create_cleanup_lock(p)
|
||||
register_cleanup_lock_removal(lock_path)
|
||||
# Only lock the current dir when keep is not 0
|
||||
if keep != 0:
|
||||
lock_path = create_cleanup_lock(p)
|
||||
register_cleanup_lock_removal(lock_path)
|
||||
except Exception as exc:
|
||||
e = exc
|
||||
else:
|
||||
@@ -544,8 +557,8 @@ def import_path(
|
||||
|
||||
if module_file.endswith((".pyc", ".pyo")):
|
||||
module_file = module_file[:-1]
|
||||
if module_file.endswith(os.path.sep + "__init__.py"):
|
||||
module_file = module_file[: -(len(os.path.sep + "__init__.py"))]
|
||||
if module_file.endswith(os.sep + "__init__.py"):
|
||||
module_file = module_file[: -(len(os.sep + "__init__.py"))]
|
||||
|
||||
try:
|
||||
is_same = _is_same(str(path), module_file)
|
||||
|
||||
+80
-43
@@ -89,7 +89,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
action="store_true",
|
||||
dest="lsof",
|
||||
default=False,
|
||||
help="run FD checks if lsof is available",
|
||||
help="Run FD checks if lsof is available",
|
||||
)
|
||||
|
||||
parser.addoption(
|
||||
@@ -98,13 +98,13 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
dest="runpytest",
|
||||
choices=("inprocess", "subprocess"),
|
||||
help=(
|
||||
"run pytest sub runs in tests using an 'inprocess' "
|
||||
"Run pytest sub runs in tests using an 'inprocess' "
|
||||
"or 'subprocess' (python -m main) method"
|
||||
),
|
||||
)
|
||||
|
||||
parser.addini(
|
||||
"pytester_example_dir", help="directory to take the pytester example files from"
|
||||
"pytester_example_dir", help="Directory to take the pytester example files from"
|
||||
)
|
||||
|
||||
|
||||
@@ -661,17 +661,7 @@ class Pytester:
|
||||
against expected output, perfect for black-box testing of pytest plugins.
|
||||
|
||||
It attempts to isolate the test run from external factors as much as possible, modifying
|
||||
the current working directory to ``path`` and environment variables during initialization.
|
||||
|
||||
Attributes:
|
||||
|
||||
:ivar Path path: temporary directory path used to create files/run tests from, etc.
|
||||
|
||||
:ivar plugins:
|
||||
A list of plugins to use with :py:meth:`parseconfig` and
|
||||
:py:meth:`runpytest`. Initially this is an empty list but plugins can
|
||||
be added to the list. The type of items to add to the list depends on
|
||||
the method using them so refer to them for details.
|
||||
the current working directory to :attr:`path` and environment variables during initialization.
|
||||
"""
|
||||
|
||||
__test__ = False
|
||||
@@ -700,6 +690,10 @@ class Pytester:
|
||||
name = request.node.name
|
||||
self._name = name
|
||||
self._path: Path = tmp_path_factory.mktemp(name, numbered=True)
|
||||
#: A list of plugins to use with :py:meth:`parseconfig` and
|
||||
#: :py:meth:`runpytest`. Initially this is an empty list but plugins can
|
||||
#: be added to the list. The type of items to add to the list depends on
|
||||
#: the method using them so refer to them for details.
|
||||
self.plugins: List[Union[str, _PluggyPlugin]] = []
|
||||
self._cwd_snapshot = CwdSnapshot()
|
||||
self._sys_path_snapshot = SysPathsSnapshot()
|
||||
@@ -724,7 +718,7 @@ class Pytester:
|
||||
|
||||
@property
|
||||
def path(self) -> Path:
|
||||
"""Temporary directory where files are created and pytest is executed."""
|
||||
"""Temporary directory path used to create files/run tests from, etc."""
|
||||
return self._path
|
||||
|
||||
def __repr__(self) -> str:
|
||||
@@ -755,7 +749,7 @@ class Pytester:
|
||||
return SysModulesSnapshot(preserve=preserve_module)
|
||||
|
||||
def make_hook_recorder(self, pluginmanager: PytestPluginManager) -> HookRecorder:
|
||||
"""Create a new :py:class:`HookRecorder` for a PluginManager."""
|
||||
"""Create a new :class:`HookRecorder` for a :class:`PytestPluginManager`."""
|
||||
pluginmanager.reprec = reprec = HookRecorder(pluginmanager, _ispytest=True)
|
||||
self._request.addfinalizer(reprec.finish_recording)
|
||||
return reprec
|
||||
@@ -804,7 +798,7 @@ class Pytester:
|
||||
def makefile(self, ext: str, *args: str, **kwargs: str) -> Path:
|
||||
r"""Create new text file(s) in the test directory.
|
||||
|
||||
:param str ext:
|
||||
:param ext:
|
||||
The extension the file(s) should use, including the dot, e.g. `.py`.
|
||||
:param args:
|
||||
All args are treated as strings and joined using newlines.
|
||||
@@ -813,6 +807,8 @@ class Pytester:
|
||||
:param kwargs:
|
||||
Each keyword is the name of a file, while the value of it will
|
||||
be written as contents of the file.
|
||||
:returns:
|
||||
The first created file.
|
||||
|
||||
Examples:
|
||||
|
||||
@@ -832,11 +828,19 @@ class Pytester:
|
||||
return self._makefile(ext, args, kwargs)
|
||||
|
||||
def makeconftest(self, source: str) -> Path:
|
||||
"""Write a contest.py file with 'source' as contents."""
|
||||
"""Write a contest.py file.
|
||||
|
||||
:param source: The contents.
|
||||
:returns: The conftest.py file.
|
||||
"""
|
||||
return self.makepyfile(conftest=source)
|
||||
|
||||
def makeini(self, source: str) -> Path:
|
||||
"""Write a tox.ini file with 'source' as contents."""
|
||||
"""Write a tox.ini file.
|
||||
|
||||
:param source: The contents.
|
||||
:returns: The tox.ini file.
|
||||
"""
|
||||
return self.makefile(".ini", tox=source)
|
||||
|
||||
def getinicfg(self, source: str) -> SectionWrapper:
|
||||
@@ -845,7 +849,10 @@ class Pytester:
|
||||
return IniConfig(str(p))["pytest"]
|
||||
|
||||
def makepyprojecttoml(self, source: str) -> Path:
|
||||
"""Write a pyproject.toml file with 'source' as contents.
|
||||
"""Write a pyproject.toml file.
|
||||
|
||||
:param source: The contents.
|
||||
:returns: The pyproject.ini file.
|
||||
|
||||
.. versionadded:: 6.0
|
||||
"""
|
||||
@@ -898,19 +905,28 @@ class Pytester:
|
||||
|
||||
This is undone automatically when this object dies at the end of each
|
||||
test.
|
||||
|
||||
:param path:
|
||||
The path.
|
||||
"""
|
||||
if path is None:
|
||||
path = self.path
|
||||
|
||||
self._monkeypatch.syspath_prepend(str(path))
|
||||
|
||||
def mkdir(self, name: str) -> Path:
|
||||
"""Create a new (sub)directory."""
|
||||
def mkdir(self, name: Union[str, "os.PathLike[str]"]) -> Path:
|
||||
"""Create a new (sub)directory.
|
||||
|
||||
:param name:
|
||||
The name of the directory, relative to the pytester path.
|
||||
:returns:
|
||||
The created directory.
|
||||
"""
|
||||
p = self.path / name
|
||||
p.mkdir()
|
||||
return p
|
||||
|
||||
def mkpydir(self, name: str) -> Path:
|
||||
def mkpydir(self, name: Union[str, "os.PathLike[str]"]) -> Path:
|
||||
"""Create a new python package.
|
||||
|
||||
This creates a (sub)directory with an empty ``__init__.py`` file so it
|
||||
@@ -924,14 +940,15 @@ class Pytester:
|
||||
def copy_example(self, name: Optional[str] = None) -> Path:
|
||||
"""Copy file from project's directory into the testdir.
|
||||
|
||||
:param str name: The name of the file to copy.
|
||||
:return: path to the copied directory (inside ``self.path``).
|
||||
|
||||
:param name:
|
||||
The name of the file to copy.
|
||||
:return:
|
||||
Path to the copied directory (inside ``self.path``).
|
||||
"""
|
||||
example_dir = self._request.config.getini("pytester_example_dir")
|
||||
if example_dir is None:
|
||||
example_dir_ = self._request.config.getini("pytester_example_dir")
|
||||
if example_dir_ is None:
|
||||
raise ValueError("pytester_example_dir is unset, can't copy examples")
|
||||
example_dir = self._request.config.rootpath / example_dir
|
||||
example_dir: Path = self._request.config.rootpath / example_dir_
|
||||
|
||||
for extra_element in self._request.node.iter_markers("pytester_example_path"):
|
||||
assert extra_element.args
|
||||
@@ -967,14 +984,16 @@ class Pytester:
|
||||
|
||||
def getnode(
|
||||
self, config: Config, arg: Union[str, "os.PathLike[str]"]
|
||||
) -> Optional[Union[Collector, Item]]:
|
||||
"""Return the collection node of a file.
|
||||
) -> Union[Collector, Item]:
|
||||
"""Get the collection node of a file.
|
||||
|
||||
:param pytest.Config config:
|
||||
:param config:
|
||||
A pytest config.
|
||||
See :py:meth:`parseconfig` and :py:meth:`parseconfigure` for creating it.
|
||||
:param os.PathLike[str] arg:
|
||||
:param arg:
|
||||
Path to the file.
|
||||
:returns:
|
||||
The node.
|
||||
"""
|
||||
session = Session.from_config(config)
|
||||
assert "::" not in str(arg)
|
||||
@@ -984,13 +1003,18 @@ class Pytester:
|
||||
config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)
|
||||
return res
|
||||
|
||||
def getpathnode(self, path: Union[str, "os.PathLike[str]"]):
|
||||
def getpathnode(
|
||||
self, path: Union[str, "os.PathLike[str]"]
|
||||
) -> Union[Collector, Item]:
|
||||
"""Return the collection node of a file.
|
||||
|
||||
This is like :py:meth:`getnode` but uses :py:meth:`parseconfigure` to
|
||||
create the (configured) pytest Config instance.
|
||||
|
||||
:param os.PathLike[str] path: Path to the file.
|
||||
:param path:
|
||||
Path to the file.
|
||||
:returns:
|
||||
The node.
|
||||
"""
|
||||
path = Path(path)
|
||||
config = self.parseconfigure(path)
|
||||
@@ -1006,6 +1030,11 @@ class Pytester:
|
||||
|
||||
This recurses into the collection node and returns a list of all the
|
||||
test items contained within.
|
||||
|
||||
:param colitems:
|
||||
The collection nodes.
|
||||
:returns:
|
||||
The collected items.
|
||||
"""
|
||||
session = colitems[0].session
|
||||
result: List[Item] = []
|
||||
@@ -1192,15 +1221,16 @@ class Pytester:
|
||||
return new_args
|
||||
|
||||
def parseconfig(self, *args: Union[str, "os.PathLike[str]"]) -> Config:
|
||||
"""Return a new pytest Config instance from given commandline args.
|
||||
"""Return a new pytest :class:`pytest.Config` instance from given
|
||||
commandline args.
|
||||
|
||||
This invokes the pytest bootstrapping code in _pytest.config to create
|
||||
a new :py:class:`_pytest.core.PluginManager` and call the
|
||||
pytest_cmdline_parse hook to create a new
|
||||
:py:class:`pytest.Config` instance.
|
||||
This invokes the pytest bootstrapping code in _pytest.config to create a
|
||||
new :py:class:`pytest.PytestPluginManager` and call the
|
||||
:hook:`pytest_cmdline_parse` hook to create a new :class:`pytest.Config`
|
||||
instance.
|
||||
|
||||
If :py:attr:`plugins` has been populated they should be plugin modules
|
||||
to be registered with the PluginManager.
|
||||
If :attr:`plugins` has been populated they should be plugin modules
|
||||
to be registered with the plugin manager.
|
||||
"""
|
||||
import _pytest.config
|
||||
|
||||
@@ -1218,7 +1248,8 @@ class Pytester:
|
||||
"""Return a new pytest configured Config instance.
|
||||
|
||||
Returns a new :py:class:`pytest.Config` instance like
|
||||
:py:meth:`parseconfig`, but also calls the pytest_configure hook.
|
||||
:py:meth:`parseconfig`, but also calls the :hook:`pytest_configure`
|
||||
hook.
|
||||
"""
|
||||
config = self.parseconfig(*args)
|
||||
config._do_configure()
|
||||
@@ -1237,6 +1268,8 @@ class Pytester:
|
||||
The module source.
|
||||
:param funcname:
|
||||
The name of the test function for which to return a test item.
|
||||
:returns:
|
||||
The test item.
|
||||
"""
|
||||
items = self.getitems(source)
|
||||
for item in items:
|
||||
@@ -1377,6 +1410,8 @@ class Pytester:
|
||||
- Otherwise, it is passed through to :py:class:`subprocess.Popen`.
|
||||
For further information in this case, consult the document of the
|
||||
``stdin`` parameter in :py:class:`subprocess.Popen`.
|
||||
:returns:
|
||||
The result.
|
||||
"""
|
||||
__tracebackhide__ = True
|
||||
|
||||
@@ -1463,6 +1498,8 @@ class Pytester:
|
||||
:param timeout:
|
||||
The period in seconds after which to timeout and raise
|
||||
:py:class:`Pytester.TimeoutExpired`.
|
||||
:returns:
|
||||
The result.
|
||||
"""
|
||||
__tracebackhide__ = True
|
||||
p = make_numbered_dir(root=self.path, prefix="runpytest-", mode=0o700)
|
||||
|
||||
+38
-10
@@ -59,6 +59,7 @@ from _pytest.config.argparsing import Parser
|
||||
from _pytest.deprecated import check_ispytest
|
||||
from _pytest.deprecated import FSCOLLECTOR_GETHOOKPROXY_ISINITPATH
|
||||
from _pytest.deprecated import INSTANCE_COLLECTOR
|
||||
from _pytest.deprecated import NOSE_SUPPORT_METHOD
|
||||
from _pytest.fixtures import FuncFixtureInfo
|
||||
from _pytest.main import Session
|
||||
from _pytest.mark import MARK_GEN
|
||||
@@ -77,10 +78,12 @@ from _pytest.pathlib import parts
|
||||
from _pytest.pathlib import visit
|
||||
from _pytest.scope import Scope
|
||||
from _pytest.warning_types import PytestCollectionWarning
|
||||
from _pytest.warning_types import PytestReturnNotNoneWarning
|
||||
from _pytest.warning_types import PytestUnhandledCoroutineWarning
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing_extensions import Literal
|
||||
|
||||
from _pytest.scope import _ScopeName
|
||||
|
||||
|
||||
@@ -95,7 +98,7 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
action="store_true",
|
||||
dest="showfixtures",
|
||||
default=False,
|
||||
help="show available fixtures, sorted by plugin appearance "
|
||||
help="Show available fixtures, sorted by plugin appearance "
|
||||
"(fixtures with leading '_' are only shown with '-v')",
|
||||
)
|
||||
group.addoption(
|
||||
@@ -103,32 +106,32 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
action="store_true",
|
||||
dest="show_fixtures_per_test",
|
||||
default=False,
|
||||
help="show fixtures per test",
|
||||
help="Show fixtures per test",
|
||||
)
|
||||
parser.addini(
|
||||
"python_files",
|
||||
type="args",
|
||||
# NOTE: default is also used in AssertionRewritingHook.
|
||||
default=["test_*.py", "*_test.py"],
|
||||
help="glob-style file patterns for Python test module discovery",
|
||||
help="Glob-style file patterns for Python test module discovery",
|
||||
)
|
||||
parser.addini(
|
||||
"python_classes",
|
||||
type="args",
|
||||
default=["Test"],
|
||||
help="prefixes or glob names for Python test class discovery",
|
||||
help="Prefixes or glob names for Python test class discovery",
|
||||
)
|
||||
parser.addini(
|
||||
"python_functions",
|
||||
type="args",
|
||||
default=["test"],
|
||||
help="prefixes or glob names for Python test function and method discovery",
|
||||
help="Prefixes or glob names for Python test function and method discovery",
|
||||
)
|
||||
parser.addini(
|
||||
"disable_test_id_escaping_and_forfeit_all_rights_to_community_support",
|
||||
type="bool",
|
||||
default=False,
|
||||
help="disable string escape non-ascii characters, might cause unwanted "
|
||||
help="Disable string escape non-ASCII characters, might cause unwanted "
|
||||
"side effects(use at your own risk)",
|
||||
)
|
||||
|
||||
@@ -192,6 +195,13 @@ def pytest_pyfunc_call(pyfuncitem: "Function") -> Optional[object]:
|
||||
result = testfunction(**testargs)
|
||||
if hasattr(result, "__await__") or hasattr(result, "__aiter__"):
|
||||
async_warn_and_skip(pyfuncitem.nodeid)
|
||||
elif result is not None:
|
||||
warnings.warn(
|
||||
PytestReturnNotNoneWarning(
|
||||
f"Expected None, but {pyfuncitem.nodeid} returned {result!r}, which will be an error in a "
|
||||
"future version of pytest. Did you mean to use `assert` instead of `return`?"
|
||||
)
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
@@ -393,8 +403,8 @@ class PyCollector(PyobjMixin, nodes.Collector):
|
||||
|
||||
def istestfunction(self, obj: object, name: str) -> bool:
|
||||
if self.funcnamefilter(name) or self.isnosetest(obj):
|
||||
if isinstance(obj, staticmethod):
|
||||
# staticmethods need to be unwrapped.
|
||||
if isinstance(obj, (staticmethod, classmethod)):
|
||||
# staticmethods and classmethods need to be unwrapped.
|
||||
obj = safe_getattr(obj, "__func__", False)
|
||||
return callable(obj) and fixtures.getfixturemarker(obj) is None
|
||||
else:
|
||||
@@ -863,19 +873,23 @@ class Class(PyCollector):
|
||||
"""Inject a hidden autouse, function scoped fixture into the collected class object
|
||||
that invokes setup_method/teardown_method if either or both are available.
|
||||
|
||||
Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with
|
||||
Using a fixture to invoke these methods ensures we play nicely and unsurprisingly with
|
||||
other fixtures (#517).
|
||||
"""
|
||||
has_nose = self.config.pluginmanager.has_plugin("nose")
|
||||
setup_name = "setup_method"
|
||||
setup_method = _get_first_non_fixture_func(self.obj, (setup_name,))
|
||||
emit_nose_setup_warning = False
|
||||
if setup_method is None and has_nose:
|
||||
setup_name = "setup"
|
||||
emit_nose_setup_warning = True
|
||||
setup_method = _get_first_non_fixture_func(self.obj, (setup_name,))
|
||||
teardown_name = "teardown_method"
|
||||
teardown_method = getattr(self.obj, teardown_name, None)
|
||||
emit_nose_teardown_warning = False
|
||||
if teardown_method is None and has_nose:
|
||||
teardown_name = "teardown"
|
||||
emit_nose_teardown_warning = True
|
||||
teardown_method = getattr(self.obj, teardown_name, None)
|
||||
if setup_method is None and teardown_method is None:
|
||||
return
|
||||
@@ -891,10 +905,24 @@ class Class(PyCollector):
|
||||
if setup_method is not None:
|
||||
func = getattr(self, setup_name)
|
||||
_call_with_optional_argument(func, method)
|
||||
if emit_nose_setup_warning:
|
||||
warnings.warn(
|
||||
NOSE_SUPPORT_METHOD.format(
|
||||
nodeid=request.node.nodeid, method="setup"
|
||||
),
|
||||
stacklevel=2,
|
||||
)
|
||||
yield
|
||||
if teardown_method is not None:
|
||||
func = getattr(self, teardown_name)
|
||||
_call_with_optional_argument(func, method)
|
||||
if emit_nose_teardown_warning:
|
||||
warnings.warn(
|
||||
NOSE_SUPPORT_METHOD.format(
|
||||
nodeid=request.node.nodeid, method="teardown"
|
||||
),
|
||||
stacklevel=2,
|
||||
)
|
||||
|
||||
self.obj.__pytest_setup_method = xunit_setup_method_fixture
|
||||
|
||||
@@ -1198,7 +1226,7 @@ class Metafunc:
|
||||
|
||||
def parametrize(
|
||||
self,
|
||||
argnames: Union[str, List[str], Tuple[str, ...]],
|
||||
argnames: Union[str, Sequence[str]],
|
||||
argvalues: Iterable[Union[ParameterSet, Sequence[object], object]],
|
||||
indirect: Union[bool, Sequence[str]] = False,
|
||||
ids: Optional[
|
||||
|
||||
+25
-11
@@ -12,7 +12,6 @@ from typing import Generic
|
||||
from typing import List
|
||||
from typing import Mapping
|
||||
from typing import Optional
|
||||
from typing import overload
|
||||
from typing import Pattern
|
||||
from typing import Sequence
|
||||
from typing import Tuple
|
||||
@@ -28,6 +27,7 @@ if TYPE_CHECKING:
|
||||
import _pytest._code
|
||||
from _pytest.compat import final
|
||||
from _pytest.compat import STRING_TYPES
|
||||
from _pytest.compat import overload
|
||||
from _pytest.outcomes import fail
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ class ApproxBase:
|
||||
|
||||
|
||||
def _recursive_sequence_map(f, x):
|
||||
"""Recursively map a function over a sequence of arbitary depth"""
|
||||
"""Recursively map a function over a sequence of arbitrary depth"""
|
||||
if isinstance(x, (list, tuple)):
|
||||
seq_type = type(x)
|
||||
return seq_type(_recursive_sequence_map(f, xi) for xi in x)
|
||||
@@ -521,7 +521,7 @@ def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
|
||||
"""Assert that two numbers (or two ordered sequences of numbers) are equal to each other
|
||||
within some tolerance.
|
||||
|
||||
Due to the :std:doc:`tutorial/floatingpoint`, numbers that we
|
||||
Due to the :doc:`python:tutorial/floatingpoint`, numbers that we
|
||||
would intuitively expect to be equal are not always so::
|
||||
|
||||
>>> 0.1 + 0.2 == 0.3
|
||||
@@ -670,6 +670,11 @@ def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
|
||||
specialised test helpers in :std:doc:`numpy:reference/routines.testing`
|
||||
if you need support for comparisons, NaNs, or ULP-based tolerances.
|
||||
|
||||
To match strings using regex, you can use
|
||||
`Matches <https://github.com/asottile/re-assert#re_assertmatchespattern-str-args-kwargs>`_
|
||||
from the
|
||||
`re_assert package <https://github.com/asottile/re-assert>`_.
|
||||
|
||||
.. warning::
|
||||
|
||||
.. versionchanged:: 3.2
|
||||
@@ -781,7 +786,7 @@ def raises(
|
||||
|
||||
|
||||
@overload
|
||||
def raises(
|
||||
def raises( # noqa: F811
|
||||
expected_exception: Union[Type[E], Tuple[Type[E], ...]],
|
||||
func: Callable[..., Any],
|
||||
*args: Any,
|
||||
@@ -790,18 +795,21 @@ def raises(
|
||||
...
|
||||
|
||||
|
||||
def raises(
|
||||
def raises( # noqa: F811
|
||||
expected_exception: Union[Type[E], Tuple[Type[E], ...]], *args: Any, **kwargs: Any
|
||||
) -> Union["RaisesContext[E]", _pytest._code.ExceptionInfo[E]]:
|
||||
r"""Assert that a code block/function call raises ``expected_exception``
|
||||
or raise a failure exception otherwise.
|
||||
r"""Assert that a code block/function call raises an exception.
|
||||
|
||||
:kwparam match:
|
||||
:param typing.Type[E] | typing.Tuple[typing.Type[E], ...] expected_exception:
|
||||
The expected exception type, or a tuple if one of multiple possible
|
||||
exception types are excepted.
|
||||
:kwparam str | typing.Pattern[str] | None match:
|
||||
If specified, a string containing a regular expression,
|
||||
or a regular expression object, that is tested against the string
|
||||
representation of the exception using :py:func:`re.search`. To match a literal
|
||||
string that may contain :std:ref:`special characters <re-syntax>`, the pattern can
|
||||
first be escaped with :py:func:`re.escape`.
|
||||
representation of the exception using :func:`re.search`.
|
||||
|
||||
To match a literal string that may contain :ref:`special characters
|
||||
<re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
|
||||
|
||||
(This is only used when :py:func:`pytest.raises` is used as a context manager,
|
||||
and passed through to the function otherwise.
|
||||
@@ -903,6 +911,12 @@ def raises(
|
||||
"""
|
||||
__tracebackhide__ = True
|
||||
|
||||
if not expected_exception:
|
||||
raise ValueError(
|
||||
f"Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. "
|
||||
f"Raising exceptions is already understood as failing the test, so you don't need "
|
||||
f"any special code to say 'this should never raise an exception'."
|
||||
)
|
||||
if isinstance(expected_exception, type):
|
||||
excepted_exceptions: Tuple[Type[E], ...] = (expected_exception,)
|
||||
else:
|
||||
|
||||
+41
-31
@@ -1,6 +1,7 @@
|
||||
"""Record warnings during test function execution."""
|
||||
import re
|
||||
import warnings
|
||||
from pprint import pformat
|
||||
from types import TracebackType
|
||||
from typing import Any
|
||||
from typing import Callable
|
||||
@@ -8,7 +9,6 @@ from typing import Generator
|
||||
from typing import Iterator
|
||||
from typing import List
|
||||
from typing import Optional
|
||||
from typing import overload
|
||||
from typing import Pattern
|
||||
from typing import Tuple
|
||||
from typing import Type
|
||||
@@ -16,6 +16,7 @@ from typing import TypeVar
|
||||
from typing import Union
|
||||
|
||||
from _pytest.compat import final
|
||||
from _pytest.compat import overload
|
||||
from _pytest.deprecated import check_ispytest
|
||||
from _pytest.deprecated import WARNS_NONE_ARG
|
||||
from _pytest.fixtures import fixture
|
||||
@@ -46,11 +47,13 @@ def deprecated_call(
|
||||
|
||||
|
||||
@overload
|
||||
def deprecated_call(func: Callable[..., T], *args: Any, **kwargs: Any) -> T:
|
||||
def deprecated_call( # noqa: F811
|
||||
func: Callable[..., T], *args: Any, **kwargs: Any
|
||||
) -> T:
|
||||
...
|
||||
|
||||
|
||||
def deprecated_call(
|
||||
def deprecated_call( # noqa: F811
|
||||
func: Optional[Callable[..., Any]] = None, *args: Any, **kwargs: Any
|
||||
) -> Union["WarningsRecorder", Any]:
|
||||
"""Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning``.
|
||||
@@ -92,7 +95,7 @@ def warns(
|
||||
|
||||
|
||||
@overload
|
||||
def warns(
|
||||
def warns( # noqa: F811
|
||||
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]],
|
||||
func: Callable[..., T],
|
||||
*args: Any,
|
||||
@@ -101,7 +104,7 @@ def warns(
|
||||
...
|
||||
|
||||
|
||||
def warns(
|
||||
def warns( # noqa: F811
|
||||
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = Warning,
|
||||
*args: Any,
|
||||
match: Optional[Union[str, Pattern[str]]] = None,
|
||||
@@ -109,15 +112,15 @@ def warns(
|
||||
) -> Union["WarningsChecker", Any]:
|
||||
r"""Assert that code raises a particular class of warning.
|
||||
|
||||
Specifically, the parameter ``expected_warning`` can be a warning class or
|
||||
sequence of warning classes, and the inside the ``with`` block must issue a warning of that class or
|
||||
classes.
|
||||
Specifically, the parameter ``expected_warning`` can be a warning class or sequence
|
||||
of warning classes, and the code inside the ``with`` block must issue at least one
|
||||
warning of that class or classes.
|
||||
|
||||
This helper produces a list of :class:`warnings.WarningMessage` objects,
|
||||
one for each warning raised.
|
||||
This helper produces a list of :class:`warnings.WarningMessage` objects, one for
|
||||
each warning raised (regardless of whether it is an ``expected_warning`` or not).
|
||||
|
||||
This function can be used as a context manager, or any of the other ways
|
||||
:func:`pytest.raises` can be used::
|
||||
This function can be used as a context manager, which will capture all the raised
|
||||
warnings inside it::
|
||||
|
||||
>>> import pytest
|
||||
>>> with pytest.warns(RuntimeWarning):
|
||||
@@ -138,14 +141,23 @@ def warns(
|
||||
...
|
||||
Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...
|
||||
|
||||
**Using with** ``pytest.mark.parametrize``
|
||||
|
||||
When using :ref:`pytest.mark.parametrize ref` it is possible to parametrize tests
|
||||
such that some runs raise a warning and others do not.
|
||||
|
||||
This could be achieved in the same way as with exceptions, see
|
||||
:ref:`parametrizing_conditional_raising` for an example.
|
||||
|
||||
"""
|
||||
__tracebackhide__ = True
|
||||
if not args:
|
||||
if kwargs:
|
||||
msg = "Unexpected keyword arguments passed to pytest.warns: "
|
||||
msg += ", ".join(sorted(kwargs))
|
||||
msg += "\nUse context-manager form instead?"
|
||||
raise TypeError(msg)
|
||||
argnames = ", ".join(sorted(kwargs))
|
||||
raise TypeError(
|
||||
f"Unexpected keyword arguments passed to pytest.warns: {argnames}"
|
||||
"\nUse context-manager form instead?"
|
||||
)
|
||||
return WarningsChecker(expected_warning, match_expr=match, _ispytest=True)
|
||||
else:
|
||||
func = args[0]
|
||||
@@ -155,7 +167,7 @@ def warns(
|
||||
return func(*args[1:], **kwargs)
|
||||
|
||||
|
||||
class WarningsRecorder(warnings.catch_warnings):
|
||||
class WarningsRecorder(warnings.catch_warnings): # type:ignore[type-arg]
|
||||
"""A context manager to record raised warnings.
|
||||
|
||||
Each recorded warning is an instance of :class:`warnings.WarningMessage`.
|
||||
@@ -198,7 +210,7 @@ class WarningsRecorder(warnings.catch_warnings):
|
||||
if issubclass(w.category, cls):
|
||||
return self._list.pop(i)
|
||||
__tracebackhide__ = True
|
||||
raise AssertionError("%r not found in warning list" % cls)
|
||||
raise AssertionError(f"{cls!r} not found in warning list")
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clear the list of recorded warnings."""
|
||||
@@ -209,7 +221,7 @@ class WarningsRecorder(warnings.catch_warnings):
|
||||
def __enter__(self) -> "WarningsRecorder": # type: ignore
|
||||
if self._entered:
|
||||
__tracebackhide__ = True
|
||||
raise RuntimeError("Cannot enter %r twice" % self)
|
||||
raise RuntimeError(f"Cannot enter {self!r} twice")
|
||||
_list = super().__enter__()
|
||||
# record=True means it's None.
|
||||
assert _list is not None
|
||||
@@ -225,7 +237,7 @@ class WarningsRecorder(warnings.catch_warnings):
|
||||
) -> None:
|
||||
if not self._entered:
|
||||
__tracebackhide__ = True
|
||||
raise RuntimeError("Cannot exit %r without entering first" % self)
|
||||
raise RuntimeError(f"Cannot exit {self!r} without entering first")
|
||||
|
||||
super().__exit__(exc_type, exc_val, exc_tb)
|
||||
|
||||
@@ -275,16 +287,17 @@ class WarningsChecker(WarningsRecorder):
|
||||
|
||||
__tracebackhide__ = True
|
||||
|
||||
def found_str():
|
||||
return pformat([record.message for record in self], indent=2)
|
||||
|
||||
# only check if we're not currently handling an exception
|
||||
if exc_type is None and exc_val is None and exc_tb is None:
|
||||
if self.expected_warning is not None:
|
||||
if not any(issubclass(r.category, self.expected_warning) for r in self):
|
||||
__tracebackhide__ = True
|
||||
fail(
|
||||
"DID NOT WARN. No warnings of type {} were emitted. "
|
||||
"The list of emitted warnings is: {}.".format(
|
||||
self.expected_warning, [each.message for each in self]
|
||||
)
|
||||
f"DID NOT WARN. No warnings of type {self.expected_warning} were emitted.\n"
|
||||
f"The list of emitted warnings is: {found_str()}."
|
||||
)
|
||||
elif self.match_expr is not None:
|
||||
for r in self:
|
||||
@@ -293,11 +306,8 @@ class WarningsChecker(WarningsRecorder):
|
||||
break
|
||||
else:
|
||||
fail(
|
||||
"DID NOT WARN. No warnings of type {} matching"
|
||||
" ('{}') were emitted. The list of emitted warnings"
|
||||
" is: {}.".format(
|
||||
self.expected_warning,
|
||||
self.match_expr,
|
||||
[each.message for each in self],
|
||||
)
|
||||
f"""\
|
||||
DID NOT WARN. No warnings of type {self.expected_warning} matching the regex were emitted.
|
||||
Regex: {self.match_expr}
|
||||
Emitted warnings: {found_str()}"""
|
||||
)
|
||||
|
||||
+12
-8
@@ -8,6 +8,7 @@ from typing import Iterable
|
||||
from typing import Iterator
|
||||
from typing import List
|
||||
from typing import Mapping
|
||||
from typing import NoReturn
|
||||
from typing import Optional
|
||||
from typing import Tuple
|
||||
from typing import Type
|
||||
@@ -36,7 +37,6 @@ from _pytest.nodes import Item
|
||||
from _pytest.outcomes import skip
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import NoReturn
|
||||
from typing_extensions import Literal
|
||||
|
||||
from _pytest.runner import CallInfo
|
||||
@@ -229,7 +229,7 @@ class BaseReport:
|
||||
|
||||
def _report_unserialization_failure(
|
||||
type_name: str, report_class: Type[BaseReport], reportdict
|
||||
) -> "NoReturn":
|
||||
) -> NoReturn:
|
||||
url = "https://github.com/pytest-dev/pytest/issues"
|
||||
stream = StringIO()
|
||||
pprint("-" * 100, stream=stream)
|
||||
@@ -276,7 +276,7 @@ class TestReport(BaseReport):
|
||||
|
||||
#: A name -> value dictionary containing all keywords and
|
||||
#: markers associated with a test invocation.
|
||||
self.keywords = keywords
|
||||
self.keywords: Mapping[str, Any] = keywords
|
||||
|
||||
#: Test outcome, always one of "passed", "failed", "skipped".
|
||||
self.outcome = outcome
|
||||
@@ -298,7 +298,7 @@ class TestReport(BaseReport):
|
||||
self.sections = list(sections)
|
||||
|
||||
#: Time it took to run just the test.
|
||||
self.duration = duration
|
||||
self.duration: float = duration
|
||||
|
||||
self.__dict__.update(extra)
|
||||
|
||||
@@ -309,7 +309,11 @@ class TestReport(BaseReport):
|
||||
|
||||
@classmethod
|
||||
def from_item_and_call(cls, item: Item, call: "CallInfo[None]") -> "TestReport":
|
||||
"""Create and fill a TestReport with standard item and call info."""
|
||||
"""Create and fill a TestReport with standard item and call info.
|
||||
|
||||
:param item: The item.
|
||||
:param call: The call info.
|
||||
"""
|
||||
when = call.when
|
||||
# Remove "collect" from the Literal type -- only for collection calls.
|
||||
assert when != "collect"
|
||||
@@ -455,7 +459,7 @@ def _report_to_json(report: BaseReport) -> Dict[str, Any]:
|
||||
def serialize_repr_entry(
|
||||
entry: Union[ReprEntry, ReprEntryNative]
|
||||
) -> Dict[str, Any]:
|
||||
data = attr.asdict(entry) # type:ignore[arg-type]
|
||||
data = attr.asdict(entry)
|
||||
for key, value in data.items():
|
||||
if hasattr(value, "__dict__"):
|
||||
data[key] = attr.asdict(value)
|
||||
@@ -463,7 +467,7 @@ def _report_to_json(report: BaseReport) -> Dict[str, Any]:
|
||||
return entry_data
|
||||
|
||||
def serialize_repr_traceback(reprtraceback: ReprTraceback) -> Dict[str, Any]:
|
||||
result = attr.asdict(reprtraceback) # type:ignore[arg-type]
|
||||
result = attr.asdict(reprtraceback)
|
||||
result["reprentries"] = [
|
||||
serialize_repr_entry(x) for x in reprtraceback.reprentries
|
||||
]
|
||||
@@ -473,7 +477,7 @@ def _report_to_json(report: BaseReport) -> Dict[str, Any]:
|
||||
reprcrash: Optional[ReprFileLocation],
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if reprcrash is not None:
|
||||
return attr.asdict(reprcrash) # type:ignore[arg-type]
|
||||
return attr.asdict(reprcrash)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
+21
-10
@@ -35,6 +35,9 @@ from _pytest.outcomes import OutcomeException
|
||||
from _pytest.outcomes import Skipped
|
||||
from _pytest.outcomes import TEST_OUTCOME
|
||||
|
||||
if sys.version_info[:2] < (3, 11):
|
||||
from exceptiongroup import BaseExceptionGroup
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing_extensions import Literal
|
||||
|
||||
@@ -46,14 +49,14 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
def pytest_addoption(parser: Parser) -> None:
|
||||
group = parser.getgroup("terminal reporting", "reporting", after="general")
|
||||
group = parser.getgroup("terminal reporting", "Reporting", after="general")
|
||||
group.addoption(
|
||||
"--durations",
|
||||
action="store",
|
||||
type=int,
|
||||
default=None,
|
||||
metavar="N",
|
||||
help="show N slowest setup/test durations (N=0 for all).",
|
||||
help="Show N slowest setup/test durations (N=0 for all)",
|
||||
)
|
||||
group.addoption(
|
||||
"--durations-min",
|
||||
@@ -61,7 +64,8 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
type=float,
|
||||
default=0.005,
|
||||
metavar="N",
|
||||
help="Minimal duration in seconds for inclusion in slowest list. Default 0.005",
|
||||
help="Minimal duration in seconds for inclusion in slowest list. "
|
||||
"Default: 0.005.",
|
||||
)
|
||||
|
||||
|
||||
@@ -511,22 +515,29 @@ class SetupState:
|
||||
stack is torn down.
|
||||
"""
|
||||
needed_collectors = nextitem and nextitem.listchain() or []
|
||||
exc = None
|
||||
exceptions: List[BaseException] = []
|
||||
while self.stack:
|
||||
if list(self.stack.keys()) == needed_collectors[: len(self.stack)]:
|
||||
break
|
||||
node, (finalizers, _) = self.stack.popitem()
|
||||
these_exceptions = []
|
||||
while finalizers:
|
||||
fin = finalizers.pop()
|
||||
try:
|
||||
fin()
|
||||
except TEST_OUTCOME as e:
|
||||
# XXX Only first exception will be seen by user,
|
||||
# ideally all should be reported.
|
||||
if exc is None:
|
||||
exc = e
|
||||
if exc:
|
||||
raise exc
|
||||
these_exceptions.append(e)
|
||||
|
||||
if len(these_exceptions) == 1:
|
||||
exceptions.extend(these_exceptions)
|
||||
elif these_exceptions:
|
||||
msg = f"errors while tearing down {node!r}"
|
||||
exceptions.append(BaseExceptionGroup(msg, these_exceptions[::-1]))
|
||||
|
||||
if len(exceptions) == 1:
|
||||
raise exceptions[0]
|
||||
elif exceptions:
|
||||
raise BaseExceptionGroup("errors during test teardown", exceptions[::-1])
|
||||
if nextitem is None:
|
||||
assert not self.stack
|
||||
|
||||
|
||||
@@ -18,13 +18,13 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--setuponly",
|
||||
"--setup-only",
|
||||
action="store_true",
|
||||
help="only setup fixtures, do not execute tests.",
|
||||
help="Only setup fixtures, do not execute tests",
|
||||
)
|
||||
group.addoption(
|
||||
"--setupshow",
|
||||
"--setup-show",
|
||||
action="store_true",
|
||||
help="show setup of fixtures while executing tests.",
|
||||
help="Show setup of fixtures while executing tests",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -15,8 +15,8 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
"--setupplan",
|
||||
"--setup-plan",
|
||||
action="store_true",
|
||||
help="show what fixtures and tests would be executed but "
|
||||
"don't execute anything.",
|
||||
help="Show what fixtures and tests would be executed but "
|
||||
"don't execute anything",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -31,12 +31,12 @@ def pytest_addoption(parser: Parser) -> None:
|
||||
action="store_true",
|
||||
dest="runxfail",
|
||||
default=False,
|
||||
help="report the results of xfail tests as if they were not marked",
|
||||
help="Report the results of xfail tests as if they were not marked",
|
||||
)
|
||||
|
||||
parser.addini(
|
||||
"xfail_strict",
|
||||
"default for the strict parameter of xfail "
|
||||
"Default for the strict parameter of xfail "
|
||||
"markers when not given explicitly (default: False)",
|
||||
default=False,
|
||||
type="bool",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user