Compare commits

...

1222 Commits
4.3.1 ... 5.2.0

Author SHA1 Message Date
Bruno Oliveira
068ef90b92 Preparing release version 5.2.0 2019-09-28 21:18:37 -04:00
Bruno Oliveira
065773aa97 Use 'python3' instead of 'python3.6' on tox
This allows us to use python3.7+ to use tox
2019-09-28 21:16:20 -04:00
Anthony Sottile
b62276826c Merge pull request #5886 from nicoddemus/setup-plan-custom-items-5884
Fix --setup-only and --setup-show for custom pytest items
2019-09-28 18:08:36 -07:00
Bruno Oliveira
7bdfba3578 Fix --setup-only and --setup-show for custom pytest items
Fix #5884
2019-09-28 11:52:09 -03:00
Daniel Hahler
6bfd30d169 Merge pull request #5878 from blueyed/codecov-retry-6
ci: codecov: use 6 retries with curl
2019-09-24 10:30:23 +02:00
Daniel Hahler
7731e45615 ci: codecov: use 6 retries with curl
This should result in retries of 1+2+4+8+16+32 = 63s.

Ref: https://github.com/pytest-dev/pytest/pull/5869#issuecomment-534235437
2019-09-23 20:58:52 +02:00
Anthony Sottile
8806b1f531 Merge pull request #5875 from asottile/patch-1
Make sure to quote `sys.executable` as we're running a shell
2019-09-23 18:55:33 +02:00
Anthony Sottile
19c9e53604 Make sure to quote sys.executable as we're running a shell 2019-09-23 08:58:56 -07:00
Bruno Oliveira
c28b63135f Merge master into features (#5874)
Merge master into features
2019-09-23 12:44:20 -03:00
Bruno Oliveira
7c64d5d882 Do not call python directly but use sys.executable. Fixes #5872 (#5873)
Do not call python directly but use sys.executable. Fixes #5872
2019-09-23 12:28:00 -03:00
Bruno Oliveira
d3d9f9f668 Merge remote-tracking branch 'upstream/master' into mm 2019-09-23 12:09:01 -03:00
Bruno Oliveira
018edf2a0e Change report-coverage.sh in attempt to fix Azure (#5869)
Change report-coverage.sh in attempt to fix Azure
2019-09-23 12:01:19 -03:00
Tomáš Chvátal
04c01fb606 test_argcomplete do not call python directly #5872
Use sys.executable to detect which python we should actually be testing.
2019-09-23 16:38:15 +02:00
Daniel Hahler
ea0c7e43b6 Remove unneeded codecov options (implied with "-f") 2019-09-23 02:26:53 +02:00
Bruno Oliveira
de8fdab7a9 Change report-coverage.sh in attempt to fix Azure
Recently sometimes Azure has failed with:

++ curl -s https://codecov.io/bash
bash: /dev/fd/63: No such file or directory

This attempts to fix this by modifying report-coverage.sh slightly.
2019-09-21 16:02:48 -03:00
Daniel Hahler
c1361b48f8 Merge pull request #5868 from blueyed/mm
Merge master into features
2019-09-21 16:29:49 +02:00
Bruno Oliveira
1b4ad7774b Fix logging doc: change x.level to x.levelno (#5866)
Fix logging doc: change x.level to x.levelno
2019-09-21 11:28:40 -03:00
Daniel Hahler
409cc2946a Merge master into features 2019-09-21 16:22:48 +02:00
Bruno Oliveira
3114be9181 Revert "Show banner/full page for the Digital Climate Strike (#… (#5867)
Revert "Show banner/full page for the Digital Climate Strike (#5861)"
2019-09-21 11:09:34 -03:00
Bruno Oliveira
e4103cb02c Release version 5.1.3 (#5859)
Release version 5.1.3
2019-09-21 10:56:16 -03:00
Bruno Oliveira
217605c217 Revert "Show banner/full page for the Digital Climate Strike (#5861)"
This reverts commit c8cf748c49, reversing
changes made to 702acdba46.
2019-09-21 10:38:10 -03:00
James Cooke
2fcf21a6c7 Fix logging doc: change x.level to x.levelno 2019-09-20 18:38:47 +01:00
Bruno Oliveira
c8cf748c49 Show banner/full page for the Digital Climate Strike (#5861)
Show banner/full page for the Digital Climate Strike
2019-09-19 10:49:10 -03:00
Bruno Oliveira
249b53e623 Show banner/full page for the Ditigal Climate Strike
As discussed in the mailing list, pytest will join the
digital strike for the climate on Sep 20th. This will show
a closable banner on the docs until the date, and when the date
comes the banner will become a (closable) full page.

I will also pin an issue saying that the developers won't be
available on Sep 20th.
2019-09-19 08:26:25 -03:00
Bruno Oliveira
9669413b1f Merge pull request #5776 from aklajnert/1682-dynamic-scope
Implemented the dynamic scope feature.
2019-09-19 08:22:45 -03:00
Andrzej Klajnert
e2382e96ed Minor cleanup in tests. 2019-09-19 11:13:22 +02:00
Bruno Oliveira
1a9f4a51cb Preparing release version 5.1.3 2019-09-18 10:11:59 -03:00
Bruno Oliveira
892bdd59dc Normalize all summary durations, including quiet ones 2019-09-18 10:10:25 -03:00
Bruno Oliveira
df46afc96d Change fixture argument handling tests to unit-tests 2019-09-18 07:50:35 -03:00
Bruno Oliveira
6918d07560 Merge remote-tracking branch 'upstream/features' into aklajnert/1682-dynamic-scope 2019-09-18 07:44:18 -03:00
Daniel Hahler
c997c32004 Merge pull request #5856 from blueyed/mm
Merge master into features
2019-09-17 21:47:40 +02:00
Daniel Hahler
450409d123 Merge master into features
Conflicts:
	src/_pytest/reports.py
        (via 7259c453d, moved the type annotation; setting it to `None`
        was removed in 3c82b1cb9 already)
2019-09-17 12:46:36 +02:00
Daniel Hahler
702acdba46 Merge pull request #5811 from blueyed/fulltrace-pytest-raises
Handle --fulltrace with pytest.raises
2019-09-14 02:09:36 +02:00
Daniel Hahler
f832ac3316 Handle --fulltrace with pytest.raises
This changes `_repr_failure_py` to use `tbfilter=False` always.
2019-09-14 01:41:43 +02:00
Bruno Oliveira
9422e10322 Fix regression due to different cases on Windows (#5840)
Fix regression due to different cases on Windows
2019-09-13 18:11:12 -03:00
Bruno Oliveira
5c3b4a6f52 Add CHANGELOG entry for #5792 2019-09-12 08:05:50 -03:00
Christian Neumüller
05850d73bd Re-introduce Christian Neumüller to AUTHORS
The introduction was reverted by cd29d56
2019-09-12 08:05:50 -03:00
Bruno Oliveira
b48f51eb03 Use Path() objects to store conftest files
Using Path().resolve() is better than py.path.realpath because
it resolves to the correct path/drive in case-insensitive file systems (#5792):

>>> from py.path import local
>>> from pathlib import Path
>>>
>>> local('d:\\projects').realpath()
local('d:\\projects')
>>> Path('d:\\projects').resolve()
WindowsPath('D:/projects')

Fix #5819
2019-09-12 08:05:50 -03:00
Bruno Oliveira
cf5b544db3 Revert "Merge pull request #5792 from dynatrace-oss-contrib/bugfix/badcase"
This reverts commit 955e542210, reversing
changes made to 0215bcd84e.

Will attempt a simpler approach
2019-09-12 08:05:43 -03:00
Bruno Oliveira
73c5b7f4b1 Clarify docs by showing tox.ini considered before setup.cfg (#5839)
Clarify docs by showing tox.ini considered before setup.cfg
2019-09-11 22:14:31 -03:00
Anthony Sottile
8f2f51be6d Clarify docs by showing tox.ini considered before setup.cfg 2019-09-11 14:07:06 -07:00
Andrzej Klajnert
f2f3ced508 Fixed the fixture function signature. 2019-09-10 16:20:44 +02:00
Bruno Oliveira
23102a7d84 Update doc regarding pytest.raises (#5834)
Update doc regarding pytest.raises
2019-09-09 16:18:58 -03:00
Gene Wood
f0d538329c Update doc regarding pytest.raises
Remove reference to the `message` argument in the docs as it was deprecated in #4539
2019-09-09 12:14:09 -07:00
Bruno Oliveira
6c8bcf601c Fix pypy3.6 on windows (#5828)
Fix pypy3.6 on windows
2019-09-08 12:11:28 -03:00
Anthony Sottile
9d7b919c7d Fix pypy3.6 on windows 2019-09-07 16:49:05 -07:00
Bruno Oliveira
333e9d5c10 Merge pull request #5824 from blueyed/revert-py350
ci: Travis: do not test with 3.5.0
2019-09-06 08:05:51 -03:00
Daniel Hahler
f1b605c95e ci: Travis: do not test with 3.5.0
This causes flaky test failures (crashes).

Closes https://github.com/pytest-dev/pytest/issues/5795.
2019-09-06 12:29:17 +02:00
Bruno Oliveira
2bb8d93001 Fix for Python 4: replace unsafe PY3 with PY2 (#5820)
Fix for Python 4: replace unsafe PY3 with PY2
2019-09-05 12:39:06 -03:00
Hugo
d049b35397 Fix for Python 4: replace unsafe PY3 with PY2 2019-09-05 18:06:47 +03:00
Bruno Oliveira
8ee557f7ae Fix pythonpath anchor (#5817)
Fix pythonpath anchor
2019-09-04 22:19:57 -03:00
Gene Wood
ca3884d9bb Add Gene Wood to authors 2019-09-04 09:21:10 -07:00
Gene Wood
bc163605ab Fix anchor link from Good Practices to Pythonpath doc 2019-09-04 09:18:10 -07:00
Bruno Oliveira
1675048b35 Merge pull request #5808 from goerz/pastebin
Fix "lexer" being used when uploading to bpaste.net
2019-08-31 16:11:39 -03:00
aklajnert
10bf6aac76 Implemented the dynamic scope feature. 2019-08-31 18:12:24 +02:00
Michael Goerz
f8dd6349c1 Fix "lexer" being used when uploading to bpaste.net
Closes #5806.
2019-08-30 15:34:03 -04:00
Bruno Oliveira
8c8809e1aa Merge pull request #5805 from nicoddemus/release-5.1.2
Release 5.1.2
2019-08-30 16:05:14 -03:00
Bruno Oliveira
e56544cb58 Preparing release version 5.1.2 2019-08-30 12:43:47 -03:00
Bruno Oliveira
f9cc704b1a Replace session duration to a fix value in regendoc 2019-08-30 12:42:14 -03:00
Bruno Oliveira
bd57307a39 Merge pull request #5768 from robholt/fixture-class-instance
Fix self reference in function scoped fixtures
2019-08-30 12:31:16 -03:00
Bruno Oliveira
667c6463ab Merge pull request #5803 from nicoddemus/flaky-5795
Mark flaky test as xfail on Python 3.5.0
2019-08-30 12:30:11 -03:00
Bruno Oliveira
4e594552eb Merge pull request #5798 from aklajnert/570-indirect-fixtures
Fix the scope behavior with indirect fixtures
2019-08-30 12:29:03 -03:00
Bruno Oliveira
955dc6d18a Merge remote-tracking branch 'upstream/master' into robholt/fixture-class-instance 2019-08-30 11:21:33 -03:00
Bruno Oliveira
3ddbc7fb2a Improve CHANGELOG and add some comments
Ref: #5768
2019-08-30 11:20:19 -03:00
Bruno Oliveira
bb60736a6f Run py35 without xdist on Travis
Due to the flaky tests in 3.5.0, drop running
py35 with xdist for now in the hope we get better error
messages.

Ref: #5795
2019-08-30 10:59:50 -03:00
Bruno Oliveira
35b3b1097f Improve CHANGELOG and make test easier to understand for #570 2019-08-30 10:54:58 -03:00
Bruno Oliveira
01082fea12 Serialize/deserialize chained exceptions (#5787)
Serialize/deserialize chained exceptions
2019-08-30 07:29:48 -03:00
Bruno Oliveira
404cf0c872 Merge pull request #5764 from goerz/pastebin
Gracefully handle HTTP errors from pastebin
2019-08-30 07:29:14 -03:00
Bruno Oliveira
a511b98da9 Serialize/deserialize chained exceptions
Fix #5786
2019-08-29 20:23:44 -03:00
Andrzej Klajnert
487659d8b1 Fix the scope behavior with indirect fixtures. 2019-08-29 07:23:08 +02:00
Bruno Oliveira
955e542210 Merge pull request #5792 from dynatrace-oss-contrib/bugfix/badcase
Fix pytest with mixed up filename casing.
2019-08-28 08:44:16 -03:00
Christian Neumüller
29bb0eda27 Move _uniquepath to pathlib as unique_path.
Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2019-08-28 12:29:41 +02:00
Christian Neumüller
a98270eac0 Document the bugfix. 2019-08-27 16:36:40 +02:00
Christian Neumüller
1aac64573f black formatting. 2019-08-27 16:16:45 +02:00
Michael Goerz
d47b9d04d4 Gracefully handle HTTP errors from pastebin
We find that the --pastebin option to pytest sometimes fails with "HTTP
Error 400: Bad Request". We're still investigating the exact cause of
these errors, but in the meantime, a failure to upload to the pastebin
service should probably not crash pytest and cause a test failure in the
continuous-integration.

This patch catches exceptions like HTTPError that may be thrown while
trying to communicate with the pastebin service, and reports them as a
"bad response", without crashing with a backtrace or failing the entire
test suite.
2019-08-26 23:50:46 -04:00
Anthony Sottile
5bf9f9a711 Merge pull request #5788 from nicoddemus/mm
Merge master into features
2019-08-26 18:20:07 -07:00
Bruno Oliveira
c28e428249 Merge remote-tracking branch 'upstream/master' into mm 2019-08-26 20:00:30 -03:00
Christian Neumüller
505c3340bf Fix pytest with mixed up filename casing. 2019-08-26 17:18:46 +02:00
Bruno Oliveira
7a69365486 Move TWMock class to a fixture
Using a relative import like before was not very nice
2019-08-26 11:32:57 -03:00
Bruno Oliveira
3c82b1cb97 Refactor report serialization/deserialization code
Refactoring this in order to support chained exceptions
more easily.

Related to #5786
2019-08-26 10:54:25 -03:00
Bruno Oliveira
0215bcd84e update doc (#5784)
update doc
2019-08-25 13:41:17 -03:00
linchiwei123
01b9774e3b update doc 2019-08-25 23:50:41 +08:00
Bruno Oliveira
9859d37cf6 Merge pull request #5782 from linchiwei123/patch-1
Fix TypeError
2019-08-24 15:40:49 -03:00
Bruno Oliveira
1c7aeb670a Fix linting 2019-08-24 15:01:48 -03:00
Bruno Oliveira
691c706fcc Add test for #5782 2019-08-24 14:41:06 -03:00
linchiwei123
a4adf511fc Fix TypeError
can only concatenate str (not "bytes") to str
2019-08-24 23:10:17 +08:00
Anthony Sottile
4265ab3a41 Merge pull request #5773 from asottile/release-5.1.1
Preparing release version 5.1.1
2019-08-20 14:45:46 -07:00
Anthony Sottile
b135f5af8d Preparing release version 5.1.1 2019-08-20 11:30:36 -07:00
Anthony Sottile
daff9066c0 Merge pull request #5752 from bluetech/typing-py350-fix
Fix TypeError when importing pytest on Python 3.5.0 and 3.5.1
2019-08-20 08:04:58 -07:00
Ran Benita
c2f762460f Merge pull request #5673 from bluetech/type-annotations-3
1/X Fix check_untyped_defs = True mypy errors
2019-08-20 17:20:40 +03:00
Ran Benita
43eab917a1 Fix coverage 2019-08-20 15:41:32 +03:00
Ronny Pfannschmidt
0e569faca2 Merge pull request #5769 from The-Compiler/remove-training
Remove cancelled training
2019-08-20 11:48:36 +02:00
Ran Benita
a7c235732a Pypy doesn't have sys.getrefcount(), so go back to gc 2019-08-20 11:47:22 +03:00
Ran Benita
cec2183aeb Add workaround for test_raises_cyclic_reference in Python 3.5.{0,1} 2019-08-20 11:19:25 +03:00
Florian Bruhin
c049fd85ab Remove cancelled training 2019-08-19 22:07:53 +02:00
Robert Holt
62381125e7 Fix self reference in function scoped fixtures 2019-08-19 15:57:39 -04:00
Anthony Sottile
a7ede64f42 Move @overload to compat 2019-08-18 14:54:52 -07:00
Bruno Oliveira
307652202c Merge pull request #5762 from pytest-dev/hugovk-patch-1
Docs: update tense
2019-08-18 10:20:45 -03:00
Hugo van Kemenade
a287aea00e Docs: update tense
pytest 4.6.0 was released in June 2019

https://pypi.org/project/pytest/#history
2019-08-18 13:34:59 +03:00
Anthony Sottile
6bf6265c59 Merge pull request #5760 from blueyed/F401
minor: make noqa comment more specific
2019-08-17 19:54:04 -07:00
Daniel Hahler
7c26a65865 minor: make noqa comment more specific 2019-08-17 23:48:55 +02:00
Daniel Hahler
1e3205e7cf ci: Travis: use 3.5.0
Ref: https://github.com/pytest-dev/pytest/pull/5752#issuecomment-522241225
2019-08-17 23:10:01 +02:00
Daniel Hahler
32dac18f38 Merge pull request #5755 from blueyed/fix-assert-location-with-coverage
Fix wrong location of assertion error with Coverage.py .

Reverts using-constant part from 39ba996.

Fixes https://github.com/pytest-dev/pytest/issues/5754.
2019-08-17 22:49:00 +02:00
Daniel Hahler
f05ca74d27 Merge pull request #5056 from blueyed/argparsing-width
Inject width via pylib to argparse formatter
2019-08-17 21:46:02 +02:00
Daniel Hahler
e5f4c47cd5 test_assertion: minor cleanup 2019-08-17 21:38:52 +02:00
Daniel Hahler
05bfe73cf9 Fix wrong location of assertion error with coverage.py
Reverts using-constant part from 39ba99613.

Fixes https://github.com/pytest-dev/pytest/issues/5754.
2019-08-17 21:34:13 +02:00
Daniel Hahler
2a6a1ca07d Inject width via pylib to argparse formatter
`argparse.HelpFormatter` looks at `$COLUMNS` only, falling back to a
default of 80.

`py.io.get_terminal_width()` is smarter there, and could even work
better with https://github.com/pytest-dev/py/pull/219.

This ensures to use a consistent value for formatting the ini values etc.
2019-08-17 16:51:02 +02:00
Ran Benita
9f3bfe82cf Fix TypeError when importing pytest on Python 3.5.0 and 3.5.1
The typing module on these versions have these issues:

- `typing.Pattern` cannot appear in a Union since it is not considered a
  class.

- `@overload` is not supported in runtime. (On the other hand, mypy
  doesn't support putting it under `if False`, so we need some runtime
  hack).

Refs #5751.
2019-08-17 15:41:59 +03:00
Bruno Oliveira
c3a8e609f9 Merge pull request #5750 from nicoddemus/fix-gh-publish-notes
Forward $TRAVIS_REPO_SLUG for GH publish notes
2019-08-16 15:57:01 -03:00
Ran Benita
7259c453d6 Fix some check_untyped_defs = True mypy warnings 2019-08-16 10:41:57 +03:00
Ran Benita
28761c8da1 Have AssertionRewritingHook derive from importlib.abc.MetaPathFinder
This is nice for self-documentation, and is the type required by mypy
for adding to sys.meta_path.
2019-08-16 10:41:52 +03:00
Bruno Oliveira
d9c4e646c4 Forward TRAVIS_REPO_SLUG env var for GH publish notes
Fix #5749
2019-08-15 22:50:55 -03:00
Bruno Oliveira
8ccc0177c8 Release 5.1.0 (#5748)
Release 5.1.0
2019-08-15 22:35:59 -03:00
Bruno Oliveira
eaf7ce9a99 Preparing release version 5.1.0 2019-08-15 20:00:09 -04:00
Anthony Sottile
ac3056c5a2 Merge pull request #5747 from blueyed/coveragerc-report
.coveragerc: add report section
2019-08-15 16:52:43 -07:00
Bruno Oliveira
409d61b972 Merge remote-tracking branch 'upstream/master' into release-5.1.0 2019-08-15 19:46:46 -04:00
Daniel Hahler
6ead01aacd testing/python/fixtures.py: use NotImplementedError pattern 2019-08-16 01:14:19 +02:00
Daniel Hahler
4c37dca011 .coveragerc: add report section
This will allow for "raise NotImplementedError" to indicate code not to
be covered in tests etc.
2019-08-16 01:14:19 +02:00
Daniel Hahler
44c10dbd5f Merge pull request #5746 from blueyed/codecov-comment-off
ci: add codecov.yml to turn comments off
2019-08-16 01:13:19 +02:00
Bruno Oliveira
0f11a7a73d Merge master into features (#5744)
Merge master into features
2019-08-15 19:12:37 -03:00
Daniel Hahler
d50198a3ff ci: add codecov.yml to turn comments off
The only benefit for me is to get notified about finished builds, but
that might happen to early anyway.  Apart from that they are rather big
and distract from actual comments.
2019-08-15 23:54:03 +02:00
Bruno Oliveira
ac052a98ad reword a parametrize example sentence (#5745)
reword a parametrize example sentence
2019-08-15 14:00:30 -03:00
mei-li
f4a84a8dfd reword a parametrize example sentence 2019-08-15 18:12:18 +02:00
Bruno Oliveira
1049a38cee Fix wording as suggested in review of #5741 2019-08-15 10:05:42 -03:00
Bruno Oliveira
d7f082519a Merge remote-tracking branch 'upstream/master' into mm
Conflicts:
	src/_pytest/outcomes.py
2019-08-15 10:03:52 -03:00
Bruno Oliveira
2d613a03b3 Async result warn (#5742)
Async result warn
2019-08-15 09:47:56 -03:00
Bruno Oliveira
28c6c5bb71 check that tests that are partial staticmethods are supported (#5701)
check that tests that are partial staticmethods are supported
2019-08-15 09:12:01 -03:00
Thomas Grainger
6b9d729ed3 also warn on awaitable or async iterable test results 2019-08-15 12:30:44 +01:00
Bruno Oliveira
0ba774a7c3 warn for async generator functions (#5734)
warn for async generator functions
2019-08-15 08:17:12 -03:00
Bruno Oliveira
0a62c4ac04 Merge pull request #5729 from Stranger6667/issue-5115
Do not treat warnings as errors during ``pytest_configure``.
2019-08-15 08:05:15 -03:00
Thomas Grainger
137255816e Fix collection of staticmethods defined with functools.partial
Related to #5701
2019-08-15 08:04:05 -03:00
Thomas Grainger
2f1b192fe6 Issue a warning for async gen functions
Co-Authored-By: Bruno Oliveira <nicoddemus@gmail.com>
2019-08-15 07:54:10 -03:00
dmitry.dygalo
7183335e62 Capture warnings during `pytest_configure`
Fix #5115
2019-08-15 07:50:27 -03:00
Bruno Oliveira
0822a1e53a Merge pull request #5740 from nicoddemus/use-repo-env-var
Use TRAVIS_REPO_SLUG instead of hard-coding pytest-dev/pytest
2019-08-14 21:46:57 -03:00
Bruno Oliveira
cb94fd31c8 Use TRAVIS_REPO_SLUG instead of hard-coding pytest-dev/pytest
I was doing final tests on the script today, and forgot to change
the hardecoded "pytest-dev/pytest", which ended up publishing a
`4.99.10` release to the main repository by mistake, as my token
has access to both my fork and main repository.

I deleted the tag immeditely just a few seconds later, so hopefully
this won't cause major problems.

This change makes it safer to test this in the future, never publishing
to the main repository by mistake (as long as the tags are pushed to the
right repositories of course).
2019-08-14 20:29:16 -03:00
Bruno Oliveira
fa75d818cf pytester: spawn: skip without pexpect.spawn (#5736)
pytester: spawn: skip without pexpect.spawn
2019-08-14 18:06:06 -03:00
Daniel Hahler
1434b66c35 pytester: spawn: skip without pexpect.spawn
"pexpect" can be imported on Windows, but does not have "pexpect.spawn"
then.

Ref: https://github.com/pexpect/pexpect/blob/a803933ed53/pexpect/__init__.py#L73-L76
2019-08-13 17:54:40 +02:00
Bruno Oliveira
a24132ddc5 Publish GitHub release notes after deployment (#5723)
Publish GitHub release notes after deployment
2019-08-12 13:20:16 -03:00
Daniel Hahler
ed2425119f Merge pull request #5731 from blueyed/assert-compare-maxsize
assertrepr_compare: prefer same maxsize
2019-08-12 16:02:41 +02:00
Bruno Oliveira
a295a3ddaf test_non_ascii_paste_text: mock call to urlopen (#5728)
test_non_ascii_paste_text: mock call to urlopen
2019-08-12 10:56:38 -03:00
Bruno Oliveira
3b3ce0e799 remove %s formatting from docs (#5733)
remove %s formatting from docs
2019-08-12 10:21:31 -03:00
Bruno Oliveira
1a61265b1e Publish GitHub release notes after deployment
Fix #2933
2019-08-12 10:18:43 -03:00
Ran Benita
67ac878ccf Merge pull request #5732 from blueyed/drop-py2
assertion.rewrite: use ast.NameConstant(None) directly
2019-08-12 12:19:40 +03:00
boris
3eb4973065 remove %s formatting from docs 2019-08-12 00:09:53 -06:00
Daniel Hahler
39ba996133 assertion.rewrite: use ast.NameConstant(None) directly
`ast.parse("None")` was added/used in 3e6f1fa2d for differences between
Python 2/3, but we do not support py2 anymore.
2019-08-12 07:50:52 +02:00
Daniel Hahler
cb481a354a assertrepr_compare: prefer same maxsize
Previously it would say:

    > assert '123456789012...901234567890A' == '1234567890123...901234567890B'"

This makes it look like the "3" might be different already.

This is clearer, and it is OK to have potentially one less char in the
right one:

    > assert '123456789012...901234567890A' == '123456789012...901234567890B'"
2019-08-12 03:41:14 +02:00
Bruno Oliveira
300f78556f Show session duration in human-readable format (#5721)
Show session duration in human-readable format
2019-08-10 23:05:34 -03:00
Daniel Hahler
0db9dade65 test_non_ascii_paste_text: mock call to urlopen
Likely to fix flaky coverage due to requests failing sometimes.
Ref: f7e81dab9a...83a1f4bd66/changes
2019-08-10 23:30:49 +02:00
Daniel Hahler
a77c83a4c3 Merge pull request #5726 from jdufresne/black
Update URL: python/black → psf/black
2019-08-10 22:25:38 +02:00
Jon Dufresne
0767f080a4 Update URL: python/black → psf/black 2019-08-10 12:38:13 -07:00
Bruno Oliveira
2498aeaaa5 Merge master into features (#5717)
Merge master into features
2019-08-10 11:16:40 -03:00
Bruno Oliveira
345df99db7 Show session duration in human-readable format
Fix #5707
2019-08-10 10:45:53 -03:00
Anthony Sottile
8665f5652a Merge pull request #5722 from nicoddemus/improvements-changelog
Add new 'improvement' changelog category
2019-08-10 06:31:39 -07:00
Bruno Oliveira
beb457c75e Add new 'improvement' changelog category
This creates a separate section from 'features' for small changes which
don't usually require user intervention, such as:

* Human readable session duration
* New junitxml fields
* Improved colors in terminal
* etc.

The idea is to better match user expectations about new actual
features in the "Features" section of the changelog.
2019-08-10 09:33:51 -03:00
Bruno Oliveira
f7e81dab9a 5669: pytester: add docstrings for Testdir.copy_example (#5719)
5669: pytester: add docstrings for Testdir.copy_example
2019-08-10 09:00:42 -03:00
Ilya Stepin
ee936b27a8 pytester: fix docstrings
Co-Authored-By: Bruno Oliveira <nicoddemus@gmail.com>
2019-08-10 09:12:04 +03:00
martbln
e0ce8b79d5 pytester: add docstrings for Testdir.copy_example 2019-08-10 00:59:14 +03:00
Bruno Oliveira
8ffa3aa65d Improve docs of pytest.importorskip (#5718)
Improve docs of pytest.importorskip
2019-08-09 18:28:44 -03:00
Tim Hoffmann
b095e0de47 Improve docs of pytest.importorskip 2019-08-09 21:35:03 +02:00
Bruno Oliveira
2f065a555f Merge remote-tracking branch 'upstream/master' into release-5.1.0 2019-08-09 12:36:19 -03:00
Bruno Oliveira
ec76f70d71 Remove unused function CallSpec2.setall (#5716)
Remove unused function CallSpec2.setall
2019-08-09 12:35:07 -03:00
Bruno Oliveira
65e6038111 Validate xunit2 files against the schema (#5605)
Validate xunit2 files against the schema
2019-08-09 12:34:21 -03:00
Daniel Hahler
9f6da8cbeb Remove unused function CallSpec2.setall
Fixes https://github.com/pytest-dev/pytest/issues/5253.
2019-08-09 16:34:48 +02:00
Bruno Oliveira
ba72b480b9 Remove xfail marker from test_runs_twice_xdist
Apperently it does not hang, let's see how it fares on CI
2019-08-09 10:55:06 -03:00
Bruno Oliveira
ba76080b59 Validate xunit2 files against the schema
Fix #5095
2019-08-09 10:55:06 -03:00
Bruno Oliveira
5ecac3c861 Add a code of conduct (#5711)
Add a code of conduct
2019-08-08 12:37:14 -03:00
Florian Bruhin
0a19439677 Add a code of conduct
See #5709 and the mails linked from there
2019-08-08 14:01:29 +02:00
Bruno Oliveira
e772bb6480 trivial doc change (#5708)
trivial doc change
2019-08-08 08:10:36 -03:00
boris
7560a7b808 trivial doc change 2019-08-07 21:49:30 -06:00
Bruno Oliveira
6c8d8a99f4 pyupgrade docs to Python 3 (#5705)
pyupgrade docs to Python 3
2019-08-07 07:27:34 -03:00
boris
78de9d4677 replace implicit code tag with colon .replace("::\n\n.. code-block", ":\n\n.. code-block") 2019-08-06 16:20:06 -07:00
boris
23a0b532db Revert "remove implicit code tags .replace("::\n\n.. code-block", "\n\n.. code-block")"
This reverts commit 9fce0bdd88.
2019-08-06 16:18:06 -07:00
boris
9fce0bdd88 remove implicit code tags .replace("::\n\n.. code-block", "\n\n.. code-block") 2019-08-06 15:46:57 -07:00
Bruno Oliveira
28fabc52bd fix grammar in test_collect_functools_partial docstr (#5703)
fix grammar in test_collect_functools_partial docstr
2019-08-06 19:24:24 -03:00
boris
5f95dce956 ran blacken-docs 2019-08-06 13:34:58 -07:00
boris
75d0b899bb ran pyupgrade-docs again 2019-08-06 13:33:21 -07:00
boris
7f90e74e02 label code blocks 2019-08-06 13:25:54 -07:00
boris
cf7761f91f ran pyupgrade-docs 2019-08-06 12:40:27 -07:00
Thomas Grainger
ef0915e1db fix grammar in test_collect_functools_partial docstr 2019-08-06 15:27:36 +01:00
Bruno Oliveira
68c486a25f Add CHANGELOG for 4.6.5 (#5696) (#5699)
Add CHANGELOG for 4.6.5 (#5696)
2019-08-05 16:25:24 -03:00
Bruno Oliveira
f5fab2bfa1 Merge master into features (#5698)
Merge master into features
2019-08-05 15:20:54 -03:00
Bruno Oliveira
f43b54aaeb Add CHANGELOG for 4.6.5 (#5696) 2019-08-05 15:09:31 -03:00
Daniel Hahler
aa06e6c8f3 Merge master into features 2019-08-05 19:12:32 +02:00
Daniel Hahler
bf3aa72a29 Merge pull request #5697 from blueyed/fix-collect-pkg-init
Fix RuntimeError when trying to collect package with "__init__.py" only
2019-08-05 18:20:28 +02:00
Daniel Hahler
198fcd8a6f Fix RuntimeError when trying to collect package with "__init__.py" only
Fixes https://github.com/pytest-dev/pytest/issues/4344.
2019-08-05 17:52:21 +02:00
Bruno Oliveira
f7e925dcc1 Add hostname and timestamp to JUnit XML testsuite tag (#5692)
Add hostname and timestamp to JUnit XML testsuite tag
2019-08-05 10:19:15 -03:00
Bruno Oliveira
cf6632a57a Rename 5471.trivial.rst to 5471.feature.rst 2019-08-05 10:19:05 -03:00
Anthony Sottile
1a66a503b6 Merge pull request #5690 from nicoddemus/custom-exit-code-docs
Mention pytest-custom_exit_code in the docs
2019-08-04 19:10:36 -07:00
Anthony Sottile
82763a293a Merge pull request #5684 from nicoddemus/errno-nomore
Use OSError subclasses instead of handling errno
2019-08-04 14:50:12 -07:00
Anthony Sottile
73e0bf92f7 Merge pull request #5694 from yashtodi94/public_access_to_exitcode_doc_change
Added info to access exitcodes directly
2019-08-04 14:48:23 -07:00
Yash Todi
0d5ed57b40 Added info to access exitcodes directly 2019-08-04 22:35:51 +05:30
Samuel Searles-Bryant
1ce45a6f67 Add hostname and timestamp to JUnit XML testsuite tag
Fix #5471
2019-08-03 15:54:39 +01:00
Bruno Oliveira
8db6642515 Mention pytest-custom_exit_code in the docs
Related to #5689
2019-08-03 10:15:56 -03:00
Daniel Hahler
29e336bd9b Merge pull request #5687 from blueyed/merge-master
Merge master into features
2019-08-03 14:12:02 +02:00
Bruno Oliveira
d3e1907899 Use OSError subclasses instead of handling errno 2019-08-02 14:17:46 -03:00
Daniel Hahler
b5b710b3ae Merge master into features
Several conflicts, mostly due to 2c402f4bd.

Conflicts:
	.pre-commit-config.yaml
	src/_pytest/outcomes.py
	src/_pytest/python_api.py
	tox.ini
2019-08-02 16:52:51 +02:00
Bruno Oliveira
0d3958e8de Handle only known functions in rm_rf (#5627)
Handle only known functions in rm_rf
2019-08-02 10:23:12 -03:00
Daniel Hahler
9064eea216 Improve rm_rf to handle only known functions
Warnings are emitted if we cannot safely remove
paths.

Fix #5626
2019-08-02 08:18:11 -03:00
Bruno Oliveira
dc6e7b9fcf Cache splitnode results to improve tests collection time (#5681)
Cache splitnode results to improve tests collection time
2019-08-01 22:32:19 -03:00
Alexey Zankevich
b43ebb7d65 Cache split nodes results to reduce long tests collection time on large test suites 2019-08-01 20:46:27 -04:00
Anthony Sottile
8a5e72c936 Merge pull request #5682 from nicoddemus/disable-shallow-copy
Disable shallow cloning because of setuptools-scm
2019-08-01 09:28:26 -07:00
Bruno Oliveira
cd924b66ca Disable shallow cloning because of setuptools-scm
setuptools-scm needs all tags to guess the version correctly
2019-08-01 12:29:39 -03:00
Anthony Sottile
1076a7e61d Merge pull request #5680 from ss18/ss18/pr0
Fix some typos
2019-08-01 08:18:48 -07:00
Bruno Oliveira
cff58457dd Fix the confusing different names of fulltrace (#5668)
Fix the confusing different names of `fulltrace`
2019-08-01 10:30:17 -03:00
Semen Zhydenko
b3f4398d64 surpressing -> suppressing 2019-08-01 15:11:38 +02:00
Semen Zhydenko
2ca47cb3f5 programatically -> programmatically 2019-08-01 15:11:26 +02:00
Semen Zhydenko
d19fe3c410 didnt -> didn't 2019-08-01 15:10:39 +02:00
Semen Zhydenko
2de145f372 wasnt -> wasn't 2019-08-01 15:10:06 +02:00
Semen Zhydenko
942fd91995 shouldnt -> shouldn't 2019-08-01 15:09:14 +02:00
Florian Bruhin
cb15e7c700 Merge pull request #5674 from helloocc/master
Doc fix: remove redundant parentheses.
2019-07-30 10:46:29 +02:00
Xixi Zhao
2959fb3198 Doc fix: remove redundant parentheses. 2019-07-30 16:18:22 +08:00
Kaiqi
aa13c625da Change the warning message 2019-07-27 21:06:29 +02:00
Kaiqi
958374addb Remove name from author 2019-07-27 17:26:52 +02:00
Kaiqi
6c2f673daf Have same name for fulltrace 2019-07-27 17:25:23 +02:00
Anthony Sottile
fd2fb36eac Merge pull request #5665 from hroncok/i5664
In test_xfail_handling, only remove __pycache__ if it exists
2019-07-25 18:35:35 -07:00
Miro Hrončok
ab39502c98 In test_xfail_handling, only remove __pycache__ if it exists
Previously, the test failed when the directory was not present,
which could have been caused for example by invoking the tests
with PYTHONDONTWRITEBYTECODE=1.

Fixes https://github.com/pytest-dev/pytest/issues/5664
2019-07-26 02:23:14 +02:00
Bruno Oliveira
50c7b5d2b5 fix setenv prepend docs (#5658)
fix setenv prepend docs
2019-07-24 20:11:05 -03:00
Thomas Grainger
3bdcd6b4f3 Update doc/en/monkeypatch.rst 2019-07-24 20:49:31 +01:00
Bruno Oliveira
d89c88478d Merge pull request #5657 from helloocc/master
Doc fix: delete useless.
2019-07-24 15:22:58 -03:00
Thomas Grainger
635916052c fix setenv prepend docs 2019-07-24 17:23:48 +01:00
Bruno Oliveira
bd34bd872a fix docs about syspath_prepend (#5656)
fix docs about syspath_prepend
2019-07-24 13:19:05 -03:00
helloocc
1d8f668e10 Add author. 2019-07-24 23:44:37 +08:00
helloocc
28343bdcbd Merge remote-tracking branch 'upstream/master' 2019-07-24 23:35:22 +08:00
Thomas Grainger
ebfe8eabf5 Update doc/en/monkeypatch.rst 2019-07-24 14:27:51 +01:00
Thomas Grainger
829cc5a242 fix docs about syspath_prepend
eg it does not modify $PATH
2019-07-24 14:27:05 +01:00
Bruno Oliveira
7fa27485df Merge pull request #5648 from nicoddemus/improve-exc-info-changelog
Make ExceptionInfo.repr change more prominent
2019-07-23 21:24:48 -03:00
Bruno Oliveira
b2839c4084 Merge pull request #5646 from nicoddemus/mark-info-docs
Update MarkDecorator docs
2019-07-23 16:42:11 -03:00
Bruno Oliveira
880e368607 Merge pull request #5653 from blueyed/fix-test
Followup: unittest: handle outcomes.Exit
2019-07-23 15:09:24 -03:00
Daniel Hahler
b9111fe677 Fix changelog 2019-07-23 19:38:33 +02:00
Daniel Hahler
401c3d1109 tests: unittest: fix/harden "test_exit_outcome"
Ref: https://github.com/pytest-dev/pytest/pull/5634#pullrequestreview-265565917
2019-07-23 19:35:51 +02:00
Bruno Oliveira
2a724a1c81 Fix fixture example and regendocs (#5651)
Fix fixture example and regendocs
2019-07-23 11:53:13 -03:00
Bruno Oliveira
52ad5a1591 Improve output when parsing an ini configuration fails (#5650)
Improve output when parsing an ini configuration fails
2019-07-23 11:17:42 -03:00
Bruno Oliveira
4abf95ba4f Merge pull request #5644 from blueyed/rm-_orig_args
Replace internal config._origargs with invocation_params.args
2019-07-23 11:03:52 -03:00
Bruno Oliveira
f163b37f6a Run regen 2019-07-23 10:00:35 -04:00
Bruno Oliveira
a82dd2f064 Fix linting 2019-07-23 10:55:22 -03:00
Bruno Oliveira
1873dc6a8a Fix fixture example in docs 2019-07-23 09:48:22 -04:00
Florian Bruhin
8c47db724c Improve output when parsing an ini configuration fails 2019-07-23 15:27:27 +02:00
Bruno Oliveira
693e9d0733 Merge pull request #5634 from blueyed/fix-unittest-exit
unittest: handle outcomes.Exit
2019-07-23 10:08:43 -03:00
Bruno Oliveira
5c09cc16f2 Add changelog entry for #5634 2019-07-23 08:55:14 -03:00
Bruno Oliveira
0824789459 Improve test for pytest.exit handling 2019-07-23 08:53:38 -03:00
Bruno Oliveira
ec4ca59bf0 Merge pull request #5631 from RonnyPfannschmidt/fix-5606
use identity checks for the mock sentinels
2019-07-23 08:48:58 -03:00
Bruno Oliveira
3c94f32e77 Make ExceptionInfo.repr change more prominent
Related to #5579
2019-07-23 08:42:03 -03:00
Bruno Oliveira
d66b6c8371 Update MarkDecorator docs
The MarkInfo class no longer exists
2019-07-23 08:07:38 -03:00
Xixi Zhao
6e687c4354 Doc fix: m1 isn't a dependency of f1.
According to the file in `example/fixtures/test_fixtures_order.py`, m1 isn't a dependency of f1.
2019-07-23 15:09:32 +08:00
William Woodall
13d8577451 README: fix typo
Closes https://github.com/pytest-dev/pytest/pull/5643.
2019-07-23 06:50:51 +02:00
Daniel Hahler
3c7438969a Replace internal config._origargs with invocation_params.args
Added in https://github.com/pytest-dev/pytest/pull/5564.
2019-07-23 06:46:56 +02:00
Xixi Zhao
66cfc66d63 Update index.rst 2019-07-22 16:01:56 +08:00
Anthony Sottile
13c4b7d212 Merge pull request #5636 from asottile/fixup_sysmodules_test
Fix ordering of sys modules snapshot
2019-07-20 12:30:18 -07:00
Ronny Pfannschmidt
8c7d9124ba switch num_mock_patch_args to do identity checks for the sentinels 2019-07-20 20:21:27 +02:00
Bruno Oliveira
240d314f36 copy test and changelog from #5607 by @niccodemus 2019-07-20 20:21:27 +02:00
Anthony Sottile
27c9d80a7e Fix ordering of sys modules snapshot 2019-07-20 11:17:30 -07:00
Bruno Oliveira
cb828ebe70 tox.ini: clean up filterwarnings (#5633)
tox.ini: clean up filterwarnings
2019-07-20 11:59:23 -03:00
Daniel Hahler
d35d09f82d unittest: handle outcomes.Exit
This is required for pytest to stop when using "quit" in pdb, and should
get honored/handled in general.
2019-07-20 07:11:49 +02:00
Daniel Hahler
f0feb6c83a fixup! tox.ini: clean up filterwarnings 2019-07-20 01:54:04 +02:00
Daniel Hahler
dcbb9c1f5a tox.ini: clean up filterwarnings
- path.local/path.readlines is not used anymore
- enhance doc for "invalid escape sequence" filter
2019-07-20 01:24:04 +02:00
Anthony Sottile
c05fcc8641 Merge pull request #5615 from bluetech/type-annotations-2
Improve mypy setup + a few minor type fixes and removals
2019-07-19 06:48:24 -07:00
Florian Bruhin
c98e7aed94 Merge pull request #5628 from pytest-dev/leipzig-training-info-1
Add info about open training in Leipzig
2019-07-19 14:57:47 +02:00
Oliver Bestwalter
c0231ae780 Add info about open training in Leipzig 2019-07-18 21:06:53 +02:00
Ran Benita
675e9507d8 Don't accept bytes message in pytest.{fail,xfail,skip}
It seems to have been added in #1439 to fix #1178.

This was only relevant for Python 2 where it was tempting to use str (==
bytes) literals instead of unicode literals. In Python 3, it is unlikely
that anyone passes bytes to these functions.
2019-07-17 22:39:10 +03:00
Ran Benita
0b532fda76 Remove unnecessary checks from SetupState
Since 4622c28ffd, _finalizers cannot
contain Nones or tuples, so these checks are not longer needed.
2019-07-17 22:39:10 +03:00
Ran Benita
7d1c697c30 Remove a no-longer-needed check if enum is available
Not needed since 4d49ba6529.
2019-07-17 22:39:10 +03:00
Ran Benita
65aee1e0c8 Allow bytes for OutcomeException(msg=...)
It's __repr__ explicitly handles it so allow it.
2019-07-17 22:39:10 +03:00
Ran Benita
8d413c1926 Allow tuple of exceptions in ExceptionInfo.errisinstance
isinstance() accepts it and some code does pass a tuple.

Fixup for commit 55a570e513.
2019-07-17 22:39:10 +03:00
Ran Benita
104f8fc836 Update mypy from 0.711 to 0.720
Release notes: http://mypy-lang.blogspot.com/2019/07/mypy-0720-released.html
2019-07-17 22:39:10 +03:00
Bruno Oliveira
157515f3c5 Fix/Remove broken links (#5613)
Fix/Remove broken links
2019-07-17 13:52:05 -03:00
Bruno Oliveira
183750fa86 CSS changes to the API reference (#5609)
CSS changes to the API reference
2019-07-17 06:24:31 -03:00
Ran Benita
fd8f92d0e7 Run mypy on src/ and testing/ together
This makes testing/ actually pick up the pytest imports -- otherwise
they are opaque and we don't actually test the types.

A single run is also a bit faster and simpler. The original reason why
we split it is no longer relevant (we fixed the problems).
2019-07-16 23:29:02 +03:00
Steffen Schroeder
1e34734f8f Fixed link to Python Classifiers 2019-07-16 21:56:04 +02:00
Steffen Schroeder
7c2e843358 Fixed link to correct anchor of Python's -w postion 2019-07-16 21:56:04 +02:00
Steffen Schroeder
79414164c2 Fixed broken links in adopt.rst 2019-07-16 21:56:03 +02:00
Steffen Schroeder
0cca7f831a Fixed broken links and non-existing anchors in release announcements 2019-07-16 21:56:03 +02:00
Steffen Schroeder
1f4ae789b8 Change link to "Where do Google's flaky tests come from?"
Although it's available, linkchecker complained about it.
It was changed to the permanent redirect.
2019-07-16 21:56:03 +02:00
Steffen Schroeder
3f46315a9d Remove link to non-existing anchor 2019-07-16 21:56:03 +02:00
Steffen Schroeder
e03b8b9e95 Update/Fix links to using projects 2019-07-16 21:56:03 +02:00
Steffen Schroeder
eb7f950e20 Fixed broken link to virtualenv 2019-07-16 21:56:03 +02:00
Steffen Schroeder
848b735a06 Fixed links to non existing GitHub users and py 2019-07-16 21:56:03 +02:00
Steffen Schroeder
7337cce332 Fixed links were content was from 'writing_plugins' to 'reference' 2019-07-16 21:56:02 +02:00
Steffen Schroeder
7a5c0a01bc Fixed links were content was moved to 'historical' 2019-07-16 21:56:02 +02:00
Ran Benita
faf222f8fb Merge pull request #5593 from bluetech/type-annotations-1
Type-annotate pytest.{exit,skip,fail,xfail,importorskip,warns,raises}
2019-07-16 22:38:20 +03:00
Ran Benita
9258fd1296 Merge pull request #5603 from bluetech/saferepr-simplify
Simplify SafeRepr a bit
2019-07-16 22:37:02 +03:00
Thomas Grainger
7440cece59 Merge pull request #5589 from graingert/fixture-yield-exit-stack
de-emphasize request.addfinalizer Fixes #5587
2019-07-16 18:33:59 +01:00
Anthony Sottile
f1332872a6 Merge pull request #5611 from mxr/patch-1
Remove language_version specification in black hooks
2019-07-16 10:15:28 -07:00
Bruno Oliveira
ac12245f5f Merge pull request #5612 from The-Compiler/new-trainings-2
Remove Europython training
2019-07-16 14:00:04 -03:00
Florian Bruhin
d9eab12ee0 Remove Europython training 2019-07-16 15:03:54 +02:00
Max R
2e756d698b Remove language_version specification in black hooks
Resolves #3840
2019-07-16 08:32:24 -04:00
Bruno Oliveira
15e235c63e Remove obsolete "importorskip('unittest.mock')" calls (#5608)
Remove obsolete "importorskip('unittest.mock')" calls
2019-07-16 04:41:58 -03:00
Bruno Oliveira
65c23017c7 Update test_getfuncargnames_patching to work with modern mock 2019-07-15 12:23:59 -03:00
Tim Hoffmann
bb7608c56f Change section titles in docs 2019-07-15 16:25:33 +02:00
Bruno Oliveira
8a3f40996a Remove obsolete "importorskip('unittest.mock')" calls 2019-07-15 11:18:05 -03:00
Tim Hoffmann
6f1d358a0c Fix some ReST indentation issues in docstrings 2019-07-15 16:16:44 +02:00
Tim Hoffmann
3ad315bcee Improve CSS layout of API reference 2019-07-15 16:15:59 +02:00
Ran Benita
129600d698 saferepr: Avoid indirect function calls
The DRY savings they provide are rather small, while they make it harder
to type-check, and IMO harder to understand.
2019-07-15 17:07:58 +03:00
Thomas Grainger
a96710dd8a demonstrate ExitStack assuming connect returns a context manager 2019-07-15 14:05:19 +01:00
Bruno Oliveira
54e08b729f More CSS fine-tuning (#5604)
More CSS fine-tuning
2019-07-15 09:42:18 -03:00
Tim Hoffmann
01606315aa More CSS fine-tuning 2019-07-15 13:40:30 +02:00
Bruno Oliveira
8f2f3bb1fa Improve CSS layout (#5602)
Improve CSS layout
2019-07-14 19:02:58 -03:00
Bruno Oliveira
499fda2349 Various cleanups in src/_pytest/python.py (#5599)
Various cleanups in src/_pytest/python.py
2019-07-14 19:00:35 -03:00
Ran Benita
c7aacc96bb saferepr: Remove unused setting of max_other
max_other is used by the superclass repr_instance, but we override it
and use maxsize instead.
2019-07-14 22:50:14 +03:00
Ran Benita
0394ebffee saferepr: Use an __init__ instead of setting attributes after construction
This will be easier to type-check, and also somewhat clearer.
2019-07-14 22:50:14 +03:00
Ran Benita
0225be53a2 saferepr: Remove dead SafeRepr.repr_unicode
This function is not called anywhere directly, and cannot be called by
the dynamic `repr_<type>()` dispatch mechanism because unicode is no
longer a type in Python 3.
2019-07-14 22:13:57 +03:00
Tim Hoffmann
da5add1294 Improve CSS layout 2019-07-14 18:58:07 +02:00
Ran Benita
11f1f79222 Allow creating ExceptionInfo from existing exc_info for better typing
This way the ExceptionInfo generic parameter can be inferred from the
passed-in exc_info. See for example the replaced cast().
2019-07-14 14:28:24 +03:00
Ran Benita
3f1fb62584 Rework ExceptionInfo to not require manual __init__ call
Mypy doesn't like calling __init__() in this way.
2019-07-14 14:28:24 +03:00
Ran Benita
14bf4cdf44 Make ExceptionInfo generic in the exception type
This way, in

    with pytest.raises(ValueError) as cm:
        ...

cm.value is a ValueError and not a BaseException.
2019-07-14 14:28:24 +03:00
Ran Benita
56dcc9e1f8 Type-annotate pytest.raises 2019-07-14 14:28:24 +03:00
Ran Benita
55a570e513 Type-annotate ExceptionInfo 2019-07-14 14:28:24 +03:00
Ran Benita
2dca68b863 Type-annotate pytest.warns 2019-07-14 14:28:24 +03:00
Ran Benita
d7ee3dac2c Type-annotate pytest.{exit,skip,fail,xfail,importorskip} 2019-07-14 14:28:24 +03:00
Ran Benita
866904ab80 Revert "Let context-managers for raises and warns handle unknown keyword arguments"
This reverts commit dfe54cd82f.

The idea in the commit was to simplify the code by removing the check
and instead letting it TypeError which has the same effect.

However this type error is caught by mypy, and rather than ignoring the
error we think it's better and clearer to go back to the previous
explicit check.
2019-07-14 14:28:21 +03:00
Ran Benita
35a57a0dfb Use flake8's extend-ignore instead of ignore
extend-ignore adds ignores in addition to flake8's existing ignores.

The default ignores currently are:
E121,E123,E126,E226,E24,E704,W503,W504
2019-07-14 11:12:47 +03:00
Florian Bruhin
6afbac29a3 Merge pull request #5600 from wojtekerbetowski/issues/3404
Add autouse fixture order information (#3404).
2019-07-13 03:22:15 -07:00
Wojtek Erbetowski
d23fbab188 Add autouse fixture order information (#3404).
A case with a fixture use both as an autouse and explititly
was raised. This case sounds too narrow to add to documentation
(and could be misleading for people learning pytest with explicitely
using an autouse fixture). At the same time there was no documentation
on the autouse vs regular fixture order, therefore this commit adds
such an information. Code sample grew and it was extracted to the file.
2019-07-13 11:43:47 +02:00
Ronny Pfannschmidt
374c4325a8 refactor finding xunit setup/teardown functions
s/_get_non_fixture_func(obj, name: str)/_get_first_non_fixture_func(obj, names: List[str])/
2019-07-13 08:13:46 +02:00
Ronny Pfannschmidt
2c071a060e refactor resolve_arg_value_types
* more explicit type checks
* expand from list+tuple to sequence
2019-07-13 08:13:46 +02:00
Bruno Oliveira
0f8b462677 Include <testsuites> root tag in generated XML (#5550)
Include <testsuites> root tag in generated XML
2019-07-12 14:35:34 -03:00
Ronny Pfannschmidt
898028cb22 remove unused _get_xunit_setup_teardown 2019-07-12 17:45:23 +02:00
Ronny Pfannschmidt
4480d3e518 generate_tests: always use call_extra
- its a noop addition in the methods is empty list
2019-07-12 17:44:17 +02:00
Bruno Oliveira
4868d0d97a Drop unittest2 support (#5565)
Drop unittest2 support
2019-07-12 11:13:51 -03:00
Bruno Oliveira
8052c7c5c6 Fix typos in a docstring (#5598)
Fix typos in a docstring
2019-07-12 07:37:50 -03:00
Ronny Pfannschmidt
13d750db20 simplify the expression which transfers mark names to keywords 2019-07-12 06:16:06 +02:00
Ronny Pfannschmidt
e98627223f remove the noop init of PyobjMixin 2019-07-12 06:14:36 +02:00
Albert Tugushev
c89e379f49 Fix typos 2019-07-12 02:35:44 +03:00
Bruno Oliveira
24a66db8d3 Remove support code for unittest 2
Also moved a pytest_runtest_makereport hook implemented in
nose.py, but nowadays makes more sense to be implemented in
unittest.py
2019-07-11 20:11:06 -03:00
Bruno Oliveira
4027254a4b Fix rmtree to remove directories with read-only files (#5588)
Fix rmtree to remove directories with read-only files
2019-07-11 18:57:03 -03:00
Bruno Oliveira
37c37963c4 Fix rmtree to remove directories with read-only files
Fix #5524
2019-07-11 18:24:53 -03:00
Bruno Oliveira
666acc9b7a doctest: Add +NUMBER option to ignore irrelevant floating-point… (#5576)
doctest: Add +NUMBER option to ignore irrelevant floating-point differences
2019-07-11 07:25:37 -03:00
David Röthlisberger
a740ef2036 docs: Document doctest +NUMBER limitation with strings
Also added an "xfail" testcase for the same.
2019-07-11 10:06:57 +01:00
David Röthlisberger
4c590e002f Fix test_doctest.test_number_non_matches
These doctests were expected to fail, but they were failing because of a
silly bug (I forgot to replace "{expression}" with the actual expression
to be tested), not because of the thing they were meant to be testing.

Then I had to fix one of the testcases because it was actually matching:

    >>> 3.0 #doctest: +NUMBER
    2.99

The doctest is saying that the actual output should match to 2 decimal
places, i.e. within 0.01 -- which it is, so it passes. I changed the
expected output to 2.98 and now it doesn't match (as we expect).
2019-07-11 09:57:44 +01:00
Anthony Sottile
26b06bdb45 Merge pull request #5595 from blueyed/typos
doc: fix typos in OPENCOLLECTIVE.rst  [ci skip]
2019-07-10 14:01:16 -07:00
Daniel Hahler
d5f1d7aebe doc: fix typos in OPENCOLLECTIVE.rst [ci skip] 2019-07-10 20:15:22 +02:00
Ran Benita
f7747f5dd6 Remove references to old-style classes in a couple error messages
These don't exist in Python 3.
2019-07-10 20:25:45 +03:00
Thomas Grainger
c224c4f1d6 de-emphasize request.addfinalizer 2019-07-10 14:52:40 +01:00
Bruno Oliveira
2c402f4bd9 [cherry-pick to master] Add rudimentary mypy type checking (#5583)
[cherry-pick to master] Add rudimentary mypy type checking
2019-07-10 07:52:32 -03:00
Bruno Oliveira
602cd5e21f Introduce Config.invocation_params (#5564)
Introduce Config.invocation_params
2019-07-10 07:46:34 -03:00
Bruno Oliveira
57e5bd0664 Improve type-checking in OutcomeException (#5580)
Improve type-checking in OutcomeException
2019-07-09 19:12:05 -03:00
Bruno Oliveira
31738155b5 Remove deprecated features (#5529)
Remove deprecated features
2019-07-09 19:04:06 -03:00
Bruno Oliveira
9db1823707 Improve type-checking in OutcomeException
Fix #5578
2019-07-09 18:26:57 -03:00
Ran Benita
89dfde9535 Add rudimentary mypy type checking
Add a very lax mypy configuration, add it to tox -e linting, and
fix/ignore the few errors that come up. The idea is to get it running
before diving in too much.

This enables:

- Progressively adding type annotations and enabling more strict
  options, which will improve the codebase (IMO).

- Annotating the public API in-line, and eventually exposing it to
  library users who use type checkers (with a py.typed file).

Though, none of this is done yet.

Refs https://github.com/pytest-dev/pytest/issues/3342.
2019-07-09 12:12:07 -07:00
Anthony Sottile
39a43dbae1 Merge pull request #5575 from bluetech/mypy-initial
Add rudimentary mypy type checking
2019-07-09 08:05:14 -07:00
Ran Benita
c1167ac552 Add rudimentary mypy type checking
Add a very lax mypy configuration, add it to tox -e linting, and
fix/ignore the few errors that come up. The idea is to get it running
before diving in too much.

This enables:

- Progressively adding type annotations and enabling more strict
  options, which will improve the codebase (IMO).

- Annotating the public API in-line, and eventually exposing it to
  library users who use type checkers (with a py.typed file).

Though, none of this is done yet.

Refs https://github.com/pytest-dev/pytest/issues/3342.
2019-07-09 10:49:17 +03:00
Bruno Oliveira
628ff4d619 Improve docs sidebar layout (#5568)
Improve docs sidebar layout
2019-07-08 19:24:48 -03:00
Bruno Oliveira
add912ff68 Update doc footer/copyright (#5569)
Update doc footer/copyright
2019-07-08 19:21:38 -03:00
Bruno Oliveira
b77c876481 Merge pull request #5563 from nicoddemus/sort-fix
Sort parametrize params to test_external_plugins_integrated
2019-07-08 19:10:45 -03:00
Bruno Oliveira
9b78a216a2 Remove unused import 2019-07-08 19:08:09 -03:00
Bruno Oliveira
7aff51ee83 Show warning about importing abcs from collections once
This is being raised by `unittest2.compatibility`:

DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
2019-07-08 17:30:15 -03:00
Bruno Oliveira
e33736c791 Merge master into features (#5559)
Merge master into features
2019-07-08 17:26:49 -03:00
David Röthlisberger
d5cc0f2a62 changelog for new NUMBERS doctest option 2019-07-08 17:16:35 +01:00
David Röthlisberger
2a23fdab9f docs: Tidy up doctest options section
* Move the parts about "how to configure it" (pytest.ini vs. inline
  comment) together.
* Move `--doctest-continue-on-failure` into its own sub-heading, as it
  isn't related to the doctest optionflags.
2019-07-08 17:07:58 +01:00
David Röthlisberger
aaa7e837cc doctest: Add +NUMBER option to ignore irrelevant floating-point differences
When enabled, floating-point numbers only need to match as far as the
precision you have written in the expected doctest output. This avoids
false positives caused by limited floating-point precision, like this:

    Expected:
        0.233
    Got:
        0.23300000000000001

This is inspired by Sébastien Boisgérault's [numtest] but the
implementation is a bit different:

* This implementation edits the literals that are in the "got"
  string (the actual output from the expression being tested), and then
  proceeds to compare the strings literally. This is similar to pytest's
  existing ALLOW_UNICODE and ALLOW_BYTES implementation.

* This implementation only compares floats against floats, not ints
  against floats. That is, the following doctest will fail with pytest
  whereas it would pass with numtest:

      >>> math.py  # doctest: +NUMBER
      3

  This behaviour should be less surprising (less false negatives) when
  you enable NUMBER globally in pytest.ini.

Advantages of this implementation compared to numtest:

* Doesn't require `import numtest` at the top level of the file.
* Works with pytest (if you try to use pytest & numtest together, pytest
  raises "TypeError: unbound method check_output() must be called with
  NumTestOutputChecker instance as first argument (got
  LiteralsOutputChecker instance instead)").
* Works with Python 3.

[numtest]: https://github.com/boisgera/numtest
2019-07-08 17:07:58 +01:00
Tim Hoffmann
71c8ca7d3d Improve sidebar layout 2019-07-07 20:32:09 +02:00
Tim Hoffmann
56a0dd7658 Update doc footer/copyright 2019-07-07 20:23:56 +02:00
Bruno Oliveira
7a82285b03 Update CHANGELOG 2019-07-06 17:29:35 -03:00
Bruno Oliveira
4cda7093f6 Add note about PYTEST_ADDOPTS 2019-07-06 17:27:54 -03:00
Bruno Oliveira
6a9bf2852a Apply review suggestions: use a simple struct for invocation params 2019-07-06 12:22:19 -03:00
Bruno Oliveira
3e669a262a Introduce Config.invocation_args and Config.invocation_plugins
These attributes can be used to access the unchanged arguments passed
to pytest.main().

The intention is to use these attributes to initialize workers in
the same manner as the master node is initialized in pytest-xdist.
2019-07-05 19:45:23 -03:00
Bruno Oliveira
f1b8431d99 Sort parametrize params to test_external_plugins_integrated
This might cause problems during collection with pytest-xdist; we
didn't see any so far mostly by luck I think.

Shame on me for letting that slip in.
2019-07-05 19:05:55 -03:00
Bruno Oliveira
a43ba78d3b Include <testsuites> root tag in generated XML
Fix #5477
2019-07-05 11:29:35 -03:00
Bruno Oliveira
2180d9ef6d Fix comment in stepwise (follow up to #5555) [skip ci] (#5560)
Fix comment in stepwise (follow up to #5555) [skip ci]
2019-07-05 10:26:37 -03:00
Bruno Oliveira
0371a3023a Fix comment in stepwise (follow up to #5555) [skip ci] 2019-07-05 09:57:10 -03:00
Bruno Oliveira
d7588b8d40 Merge remote-tracking branch 'upstream/master' into merge-master-into-features 2019-07-05 08:14:18 -03:00
Bruno Oliveira
b62b549f5f Preparing release version 5.0.1 (#5557)
Preparing release version 5.0.1
2019-07-05 08:13:37 -03:00
Bruno Oliveira
60a358fa2d Replace importlib_metadata with importlib.metadata on Python 3.… (#5539)
Replace importlib_metadata with importlib.metadata on Python 3.8+
2019-07-04 21:46:43 -03:00
Bruno Oliveira
bb29f31d22 Preparing release version 5.0.1 2019-07-04 20:01:16 -04:00
Bruno Oliveira
b1928f878d Handle xfail(strict=True) properly in --step-wise mode (#5555)
Handle xfail(strict=True) properly in --step-wise mode
2019-07-04 20:50:33 -03:00
Bruno Oliveira
8651d880a0 Handle xfail(strict=True) properly in --step-wise mode
Fix #5547
2019-07-04 20:28:37 -03:00
Bruno Oliveira
95824c588a Improve quoting in raises match failure message (#5553)
Improve quoting in raises match failure message
2019-07-04 10:25:27 -03:00
Miro Hrončok
c54cbd63c8 Replace importlib_metadata with importlib.metadata on Python 3.8+
Fixes https://github.com/pytest-dev/pytest/issues/5537
2019-07-04 15:00:10 +02:00
Bruno Oliveira
1db132290f Apply workaround for multiple short options for Python <= 3.8
Hopefully by Python 3.9 this will be fixed upstream, if not we will
need to bump the version again.

Fix #5523
2019-07-04 14:59:40 +02:00
Anthony Sottile
caa08ebd45 Improve quoting in raises match failure message 2019-07-04 05:55:26 -07:00
Bruno Oliveira
b08ae4449b Add docs about Tidelift and OpenCollective (#5527)
Add docs about Tidelift and OpenCollective
2019-07-04 07:38:17 -03:00
Anthony Sottile
776a632170 Merge pull request #5540 from bazcrown/yml2yaml
Substituted 'yml' to '.yaml' in relevant files
2019-07-03 18:47:26 -04:00
Bruno Oliveira
d74a975f82 remove documentation about setuptools integration Refs #5534 Fi… (#5546)
remove documentation about setuptools integration Refs #5534 Fixes #3814
2019-07-03 16:01:30 -03:00
Bruno Oliveira
dfe54cd82f Let context-managers for raises and warns handle unknown keyword arguments
As suggested during review
2019-07-03 13:57:28 -03:00
Thomas Grainger
2b9522e9da remove documentation about setuptools integration Refs #5534
integrating with `python setup.py test` is not good practice!
2019-07-03 16:42:53 +01:00
Bruno Oliveira
528ee3e1c5 Add upcoming trainings (#5544)
Add upcoming trainings
2019-07-03 10:45:14 -03:00
Florian Bruhin
9677099acf Add upcoming trainings 2019-07-03 14:50:32 +02:00
Michael Moore
1b0e8d73d5 Substituted 'yml' to '.yaml' in relevant files 2019-07-02 23:49:06 -07:00
Bruno Oliveira
50b846e9d3 Merge pull request #5538 from avallbona/patch-2
Added talk about pytest in PyBCN June 2019
2019-07-02 19:46:10 -03:00
Andreu Vallbona Plazas
fa9791127a Added talk about pytest in PyBCN June 2019
Added talk about pytest in PyBCN June 2019
2019-07-02 23:18:52 +02:00
Bruno Oliveira
2d9b432613 Add docs about Tidelift and OpenCollective
Give an overview of how we as an organization will use the donated money,
as well as show this information more prominently in the docs.
2019-06-30 14:13:30 -03:00
Bruno Oliveira
5d8da88e9e Merge pull request #5530 from AmirElkess/patch-1
update CONTRIBUTING.rst
2019-06-30 14:07:27 -03:00
Bruno Oliveira
0da690c8e9 Update AUTHORS (#5531)
Update AUTHORS
2019-06-30 14:07:10 -03:00
AmirElkess
e32c903fb6 Update AUTHORS 2019-06-30 18:32:07 +02:00
Bruno Oliveira
0ed7aa2db6 Make 'request' a reserved name for fixtures 2019-06-30 13:31:39 -03:00
Bruno Oliveira
85cc12e328 Move FIXTURE_FUNCTION_CALL constant to the point of error
This is no longer a deprecation so it makes sense to move it
to the place where it is needed instead of leaving it in deprecated.py
2019-06-30 13:31:39 -03:00
Bruno Oliveira
c470ade0a5 Remove 'RemovedInPytest4Warning' 2019-06-30 13:31:39 -03:00
AmirElkess
9972c78cfa update CONTRIBUTING.rst
The following edits are for the "Preparing pull requests" section only.
1. remove Python2-related commands.
2. clarifying some details for beginners. Such as that pre-commit must to be installed as admin to function properly.
3. Added "You may not create a changelog entry if the change doesn't affect the documented behaviour of Pytest." on line 270.
2019-06-30 18:29:37 +02:00
Bruno Oliveira
3a17c1b30b Remove 'pytest_logwarning' hook 2019-06-30 13:18:07 -03:00
Bruno Oliveira
7b35405033 Remove YIELD_TESTS from deprecated module as it is now an error 2019-06-30 13:18:07 -03:00
Bruno Oliveira
aa1955de72 Remove 'tmpdir_factory.ensuretemp' 2019-06-30 13:18:07 -03:00
Bruno Oliveira
7e58defc15 Remove 'pytest.config' 2019-06-30 13:18:07 -03:00
Bruno Oliveira
f2b7809d5d Move setup.cfg error message and tests to an appropriate location
Those are not really deprecated anymore and are part of the normal
code for config
2019-06-30 13:18:07 -03:00
Bruno Oliveira
647d89c444 Move code about 'pytest_plugins' error to a more appropriate place
It is no longer deprecated, but part of the normal code for 'config'
2019-06-30 13:18:07 -03:00
Bruno Oliveira
683b2632b4 Remove explicit kwargs handling from raises, warns and ParameterSet.param 2019-06-30 13:18:06 -03:00
Bruno Oliveira
13f7f27fd2 Remove 'message' parameter from pytest.raises 2019-06-30 13:18:06 -03:00
Bruno Oliveira
279733a30b Remove support for 'code as string' from pytest.raises and pytest.warns 2019-06-30 11:40:24 -03:00
Bruno Oliveira
be91c4d932 Remove Request.getfuncargvalue 2019-06-30 11:02:46 -03:00
Bruno Oliveira
497cd87fdd Apply workaround for multiple short options for Python <= 3.8 (#5526)
Apply workaround for multiple short options for Python <= 3.8
2019-06-29 12:33:00 -03:00
Bruno Oliveira
94a05e513e Run py38-xdist as part of the build instead of cron 2019-06-29 11:19:50 -03:00
Bruno Oliveira
9021194efd Apply workaround for multiple short options for Python <= 3.8
Hopefully by Python 3.9 this will be fixed upstream, if not we will
need to bump the version again.

Fix #5523
2019-06-29 11:15:28 -03:00
Bruno Oliveira
d4a76a0b99 doc(plugin_hooks): Improve documentation for writing plugin hoo… (#5517)
doc(plugin_hooks): Improve documentation for writing plugin hooks.
2019-06-29 09:39:49 -03:00
Bruno Oliveira
789a3662ce Fix linting 2019-06-29 09:11:09 -03:00
Niklas Meinzer
93a68cdfb4 doc(plugin_hooks): Improve documentation for writing plugin hooks. 2019-06-29 14:02:53 +02:00
Anthony Sottile
4f9bf028f5 Merge pull request #5522 from nicoddemus/merge-master-into-features
Merge master into features
2019-06-28 20:22:56 -07:00
Anthony Sottile
4bc0415720 Merge pull request #5521 from asottile/cherry-pick-maintenance-release
4.6.4 changelog notes
2019-06-28 19:28:44 -07:00
Anthony Sottile
844d660d5c Merge pull request #5520 from asottile/release-4.6.4
Preparing release version 4.6.4
2019-06-28 19:09:10 -07:00
Anthony Sottile
2c6453c72d Merge pull request #5509 from asottile/release-5.0.0
Preparing release version 5.0.0
2019-06-28 18:12:16 -07:00
Bruno Oliveira
e6ffa78e59 Refactoring doctests (#5518)
Refactoring doctests
2019-06-28 19:15:02 -03:00
Anthony Sottile
58bfc7736f Use shutil.which to avoid distutils+imp warning 2019-06-28 14:44:49 -07:00
Anthony Sottile
97f0a20ca9 Add notice about py35+ and move ExitCode changelog entry 2019-06-28 14:40:10 -07:00
Anthony Sottile
55d2fe076f Use importlib instead of imp in demo 2019-06-28 14:40:10 -07:00
Anthony Sottile
5e39eb91bb Correct Zac-HD's name in changelogs 2019-06-28 14:40:10 -07:00
Anthony Sottile
fd2f320485 Preparing release version 5.0.0 2019-06-28 14:39:53 -07:00
Bruno Oliveira
73d918db55 Remove astor and reproduce the original assertion expression (#5512)
Remove astor and reproduce the original assertion expression
2019-06-28 18:36:11 -03:00
Anthony Sottile
7ee244476a Remove astor and reproduce the original assertion expression 2019-06-28 13:38:52 -07:00
AmirElkess
bf39e89946 Refactoring doctests 2019-06-28 21:16:17 +02:00
Bruno Oliveira
3c9b46f781 Remove stray comment from tox.ini (#5507)
Remove stray comment from tox.ini
2019-06-27 15:12:57 -03:00
Anthony Sottile
f7bfbb557e Merge pull request #5506 from asottile/fix_no_terminal
Fix crash when discovery fails while using `-p no:terminal`
2019-06-27 10:46:43 -07:00
Anthony Sottile
45af361a67 Remove stray comment from tox.ini 2019-06-27 10:46:08 -07:00
Anthony Sottile
4e723d6750 Fix crash when discovery fails while using -p no:terminal 2019-06-27 10:24:29 -07:00
Bruno Oliveira
65fbdf2568 Don't crash with --pyargs and a filename that looks like a modu… (#5503)
Don't crash with --pyargs and a filename that looks like a module
2019-06-27 13:53:02 -03:00
Bruno Oliveira
5ef507982c Add Open Collective to FUNDING.yml (#5504)
Add Open Collective to FUNDING.yml
2019-06-27 13:49:58 -03:00
Florian Bruhin
2479a91e92 Add Open Collective to FUNDING.yml 2019-06-27 17:53:03 +02:00
Anthony Sottile
3e0e31a364 Don't crash with --pyargs and a filename that looks like a module 2019-06-27 08:32:32 -07:00
Anthony Sottile
c9923a3a5c Merge pull request #5499 from nicoddemus/cleanup-py35-rewrite
Remove py<35 compatibility code from rewrite.py
2019-06-26 21:31:54 -07:00
Bruno Oliveira
1be49e713a Remove py<35 compatibility code from rewrite.py 2019-06-26 21:44:10 -03:00
Bruno Oliveira
37fb50a3ed Features assertion pass hook (#3479)
Features assertion pass hook
2019-06-26 21:14:19 -03:00
Bruno Oliveira
790806e865 Merge pull request #5494 from Zac-HD/funcargnames-to-fixturenames
Deprecate funcargnames alias for fixturenames
2019-06-26 21:13:59 -03:00
Bruno Oliveira
2ea22218ff Cover assertions with messages when enable_assertion_pass_hook is enabled 2019-06-26 20:46:31 -03:00
Bruno Oliveira
629eb3ec6a Move formatting variables under the "has impls" if
Small optimization, move the generation of the intermediate
formatting variables inside the 'if _check_if_assertion_pass_impl():'
block.
2019-06-26 19:26:12 -03:00
Bruno Oliveira
8edf68f3c0 Add a trivial note about astor 2019-06-26 19:21:12 -03:00
Bruno Oliveira
3afee36ebb Improve docs and reference 2019-06-26 19:15:00 -03:00
Bruno Oliveira
fcbe66feba Restore proper handling of '%' in assertion messages 2019-06-26 18:51:27 -03:00
Bruno Oliveira
eb90f3d1c8 Fix default value of 'enable_assertion_pass_hook' 2019-06-26 17:54:24 -03:00
Victor Maryama
6854ff2acc Fixed import order pep8. 2019-06-26 19:05:17 +02:00
Victor Maryama
53234bf613 Added config back to AssertionWriter and fixed typo in check_if_assertion_pass_impl function call. 2019-06-26 19:00:31 +02:00
Victor Maryama
6f851e6cbb Merge remote-tracking branch 'upstream/master' into features-assertion-pass-hook-master
# Conflicts:
#	src/_pytest/assertion/rewrite.py
2019-06-26 18:12:56 +02:00
Victor Maryama
9a34d88c8d Explanation variables only defined if failed or passed with plugins implementing the hook. 2019-06-26 18:10:16 +02:00
Victor Maryama
d91a5d3cd7 Further reverting changes. 2019-06-26 18:10:16 +02:00
Victor Maryama
f755ff6af1 Black formatting. 2019-06-26 18:10:16 +02:00
Victor Maryama
d638da5821 Using ini-file option instead of cmd option. 2019-06-26 18:10:16 +02:00
Victor Maryama
0fb52416b1 Reverted changes. 2019-06-26 18:10:15 +02:00
Bruno Oliveira
6a2d844c5d Fix typo replace circuting with circuiting. (#5497)
Fix typo replace `circuting` with `circuiting`.
2019-06-26 11:09:22 -03:00
Bruno Oliveira
a48feb3261 Delete 5497.trivial.rst
Just a typo, no need for a changelog entry. :)
2019-06-26 11:09:04 -03:00
Anthony Sottile
6cf8e71dca Merge pull request #5496 from pytest-dev/stray_comment
Delete stray comment
2019-06-26 05:59:38 -07:00
Tim Gates
994c32235c Fix rst support 2019-06-26 20:46:09 +10:00
Tim Gates
d81f758285 Update changelog with trivial as per ./CONTRIBUTING.rst 2019-06-26 20:31:45 +10:00
Tim Gates
fdb6e35b1b Fix typo replace circuting with circuiting. 2019-06-26 20:23:35 +10:00
Victor Maryama
7efdd5063b Update src/_pytest/assertion/rewrite.py
Co-Authored-By: Bruno Oliveira <nicoddemus@gmail.com>
2019-06-26 10:50:27 +02:00
Anthony Sottile
bfba33ec9e Delete stray comment 2019-06-25 20:24:13 -07:00
Anthony Sottile
3f3f3e7a29 Merge pull request #5495 from nicoddemus/blueyed/cmp-bytes
Improve comparison of byte strings (supersedes #5267)
2019-06-25 19:16:24 -07:00
Bruno Oliveira
aaf40314d1 Do not attempt to rewrite non-source files (#5490)
Do not attempt to rewrite non-source files
2019-06-25 20:43:23 -03:00
Bruno Oliveira
3f2344e8f7 Show bytes ascii representation instead of numeric value 2019-06-25 20:40:25 -03:00
Daniel Hahler
8c7eb82363 Fix/improve comparison of byte strings
Fixes https://github.com/pytest-dev/pytest/issues/5260.
2019-06-25 20:15:45 -03:00
Bruno Oliveira
1aefb24b37 Merge features into master (#5491)
Merge features into master
2019-06-25 20:02:02 -03:00
Zac Hatfield-Dodds
ed85c83154 Deprecate funcargnames alias 2019-06-26 08:53:17 +10:00
Anthony Sottile
bd647fdd8b Revert allow_abbrev=False in helper scripts 2019-06-25 14:50:07 -07:00
Victor Maryama
80ac910a24 Added msg to docstring for cleaning pyc. 2019-06-25 19:49:57 +02:00
Victor Maryama
4db5488ed8 Now dependent on command line option. 2019-06-25 19:49:05 +02:00
Victor Maryama
cfbfa53f2b Using pytester subprocess to avoid keeping references in the HookRecorder. 2019-06-25 17:46:56 +02:00
Victor Maryama
db50a975fd Reverted leak fixture test. 2019-06-25 17:23:14 +02:00
Bruno Oliveira
019455298b Merge remote-tracking branch 'upstream/features' into merge-features-into-master 2019-06-25 12:07:54 -03:00
Bruno Oliveira
64a6365227 Include pytest version in the cached pyc tags (#5484)
Include pytest version in the cached pyc tags
2019-06-25 12:07:01 -03:00
Anthony Sottile
b991810f32 Do not attempt to rewrite non-source files 2019-06-25 08:00:20 -07:00
Zac Hatfield-Dodds
4d5780facf Merge pull request #5469 from Zac-HD/disallow-abbrev
Disallow abbreviated command-line options
2019-06-25 22:38:52 +10:00
Victor Maryama
81e3f3cf95 Black formatting 2019-06-25 10:41:11 +02:00
Victor Maryama
2280f28596 Black formatting. 2019-06-25 10:36:01 +02:00
Victor Maryama
f8c9a7b86d Formatting and removed py2 support. 2019-06-25 10:35:42 +02:00
Victor Maryama
98b212cbfb Added "experimental" note. 2019-06-25 10:35:09 +02:00
Zac Hatfield-Dodds
d72fb73fa0 Do not allow abbreviated arguments 2019-06-25 13:51:33 +10:00
Bruno Oliveira
a54e2e19f5 Clarify changelog entries should be rst files (#5485)
Clarify changelog entries should be rst files
2019-06-24 22:33:40 -03:00
Bruno Oliveira
37fce6c6e5 Pickup addition positional args passed to _parse_parametrize_ar… (#5483)
Pickup addition positional args passed to _parse_parametrize_args
2019-06-24 22:05:19 -03:00
Kevin J. Foley
23aa3bb0ae Clarify changelog entries should be rst files 2019-06-24 20:55:51 -04:00
Kevin J. Foley
95714436a1 Pickup additional positional args passed to _parse_parametrize_args 2019-06-24 20:43:52 -04:00
Bruno Oliveira
f43fb13179 Include pytest version in the cached pyc tags
Fix #1671
2019-06-24 20:37:07 -03:00
Bruno Oliveira
3f5b078462 Merge pull request #5441 from nicoddemus/faulthandler-5440
Integrate pytest-faulthandler into the core
2019-06-24 20:01:15 -03:00
Bruno Oliveira
63c4802be0 minor: clarify help with reportchars (#5475)
minor: clarify help with reportchars
2019-06-24 19:59:15 -03:00
Anthony Sottile
a24933b0a6 Merge pull request #5481 from asottile/minor_py3_cleanup
Use new raise syntax in one case
2019-06-24 12:06:53 -07:00
Anthony Sottile
380ca8f880 Use new raise syntax in one case 2019-06-24 11:24:03 -07:00
Anthony Sottile
61dcb84f0d Merge pull request #5468 from asottile/switch_importlib_to_imp
Switch from deprecated imp to importlib
2019-06-24 11:22:01 -07:00
Anthony Sottile
4cd08f9b52 Switch from deprecated imp to importlib 2019-06-24 09:48:38 -07:00
Victor Maryama
52e695b329 Removed debug code. 2019-06-24 17:47:48 +02:00
Victor Maryama
9a89783fbb Assertion passed hook 2019-06-24 16:09:39 +02:00
Daniel Hahler
01a094cc43 minor: clarify help with reportchars
`-ra` / `-rA` will include "w" also.  This does not explicitly mention
it (allowing for change the behavior), but makes it a) clearer that "w"
is a recognized reportchar, and b) less confusing that `-ra
--disable-warnings` still displays them.
2019-06-24 06:07:52 +02:00
Bruno Oliveira
3ce31b6370 Change pytest-faulthandler for simplification
* The --no-faulthandler option is not necessary given that we can use
  `-p no:faulthandler`.

* The `--faulthandler-timeout` command-line option has become an ini
  option, for the reasons described in
  https://github.com/pytest-dev/pytest-faulthandler/issues/34 and
  users can still set it from the command-line.

Fix pytest-dev/pytest-faulthandler#34
2019-06-22 19:22:43 -03:00
Bruno Oliveira
3d01dd3adf Update cache.rst (#5465)
Update cache.rst
2019-06-21 21:12:30 -03:00
Bruno Oliveira
a37b902afe Integrate pytest-faulthandler into the core
* Add pytest-faulthandler files unchanged
* Adapt imports and tests
* Add code to skip registration of the external `pytest_faulthandler`
  to avoid conflicts

Fix #5440
2019-06-21 21:02:24 -03:00
curiousjazz77
12b76b6261 Update cache.rst 2019-06-21 15:48:59 -07:00
Bruno Oliveira
b713460cc7 fix typos in the resolution of #5125 (#5458)
fix typos in the resolution of #5125
2019-06-17 16:55:26 -03:00
Ronny Pfannschmidt
0627d92df2 fix typos in the resolution of #5125 2019-06-17 20:35:23 +02:00
Bruno Oliveira
b38a4e8e11 Fix stepwise crash when first collected module fails (#5446)
Fix stepwise crash when first collected module fails
2019-06-16 10:43:18 -03:00
Bruno Oliveira
689ce112e7 Small cleanups on _pytest.compat (#5451)
Small cleanups on _pytest.compat
2019-06-16 10:42:07 -03:00
Bruno Oliveira
87fc5a5455 Make pytest warnings show as from 'pytest' module instead of '_pytest.warning_types' (#5452)
Make pytest warnings show as from 'pytest' module instead of '_pytest.warning_types'
2019-06-16 10:41:40 -03:00
Bruno Oliveira
bbfc8d1501 conversion of exit codes to enum + exposure (#5420)
conversion of exit codes to enum  + exposure
2019-06-16 10:41:18 -03:00
Bruno Oliveira
ab6ed381ac Improve ExitCode docstring 2019-06-15 20:53:46 -03:00
Ronny Pfannschmidt
1cfea5f1b3 add ExitCode reference in usage 2019-06-15 21:41:55 +02:00
Daniel Hahler
cf27af734e Merge pull request #5404 from Zac-HD/helpful-mock-unwrapper
Emit warning for broken object
2019-06-15 18:54:03 +02:00
Ronny Pfannschmidt
8b3b10b14b pre-commit 2019-06-15 17:41:13 +02:00
Ronny Pfannschmidt
103d6146b0 document exitcode members 2019-06-15 17:18:21 +02:00
Ronny Pfannschmidt
065fa17124 update cangelog to fit review suggestion 2019-06-15 17:03:40 +02:00
Bruno Oliveira
43e8576ca3 Make pytest warnings show as from 'pytest' module instead of '_pytest.warning_types'
When we configure warnings as errors, users see error messages like this:

        def test():
    >       warnings.warn(pytest.PytestWarning("some warning"))
    E       _pytest.warning_types.PytestWarning: some warning

This is a problem because suggests the user should use `_pytest.warning_types.PytestWarning` to configure
their warning filters, which is not nice.

This commit changes the message to:

        def test():
    >       warnings.warn(pytest.PytestWarning("some warning"))
    E       pytest.PytestWarning: some warning
2019-06-15 11:48:34 -03:00
Bruno Oliveira
d8fa434d39 Remove Python 2-only workaround 2019-06-15 10:45:16 -03:00
Bruno Oliveira
177af032d2 Remove unused/unneeded code 2019-06-15 10:45:16 -03:00
Bruno Oliveira
355eb5adfb Small cleanups on _pytest.compat
Small improvements and cleanups
2019-06-15 10:06:37 -03:00
Ronny Pfannschmidt
2bd619ecb0 add changelog 2019-06-15 07:05:18 +02:00
Ronny Pfannschmidt
2b92fee1c3 initial conversion of exit codes to enum 2019-06-15 06:48:00 +02:00
Anthony Sottile
240828d912 Merge pull request #5448 from nicoddemus/add-hooks
Remove broken/unused PytestPluginManager.addhooks
2019-06-14 21:45:11 -07:00
Bruno Oliveira
c94e9b6145 Fix test docstring 2019-06-13 23:10:13 -03:00
Bruno Oliveira
7513d87b15 Remove broken/unused PytestPluginManager.addhooks
The function has been deprecated for ages and
the PLUGIN_MANAGER_ADDHOOKS constant doesn't even exist since 3.0.

Because the function is clearly broken, this change doesn't even
require a CHANGELOG.
2019-06-13 19:55:13 -03:00
Bruno Oliveira
bc345ac980 Remove handling of collection errors by --sw
Since then pytest itself adopted the behavior of interrupting
the test session on collection errors, so --sw no longer needs
to handle this.

The --sw behavior seems have been implemented when pytest
would continue execution even if there were collection errors.
2019-06-13 17:19:36 -03:00
Bruno Oliveira
4cc05a657d Fix --sw crash when first file in cmdline fails to collect
Fix #5444
2019-06-13 16:47:01 -03:00
Thomas Grainger
ad15efc7ea add test for stepwise attribute error Refs: #5444 2019-06-13 12:39:49 +01:00
Bruno Oliveira
e3dcf1f39d Merge pull request #5442 from patriksevallius/master
Add missing 'e' to test_mod(e).
2019-06-13 08:23:53 -03:00
patriksevallius
701d0351a6 Add missing 'e' to test_mod(e). 2019-06-13 06:01:30 +02:00
Bruno Oliveira
bad7ab721a Minor: tox: coverage: use -m with coverage-report (#5427)
Minor:  tox: coverage: use -m with coverage-report
2019-06-12 19:44:15 -03:00
Anthony Sottile
ede8b87560 Merge pull request #5438 from nicoddemus/result-log-deprecation
Postpone removal of --result-log to pytest 6.0
2019-06-12 10:45:02 -07:00
Bruno Oliveira
52780f39ce Postpone removal of --result-log to pytest 6.0
As we did not provide an alternative yet, it is better to postpone
the actual removal until we have provided a suitable and stable
alternative.

Related to #4488
2019-06-12 08:26:11 -03:00
Bruno Oliveira
d637d1b2ac Merge pull request #5435 from asottile/release-4.6.3 (#5436)
Merge pull request #5435 from asottile/release-4.6.3
2019-06-11 21:24:45 -03:00
Anthony Sottile
47447963b7 Merge pull request #5437 from asottile/reenable_pypy3
re-enable pypy3
2019-06-11 12:21:53 -07:00
Anthony Sottile
f586d627b3 re-enable pypy3 now that importlib-metadata 0.18 is released 2019-06-11 10:54:16 -07:00
Anthony Sottile
108fad1ac0 Revert "ci: Travis: remove pypy3 job for now"
This reverts commit 47022b36cb.
2019-06-11 10:53:32 -07:00
Anthony Sottile
18c2ff6625 Merge pull request #5435 from asottile/release-4.6.3
Preparing release version 4.6.3
2019-06-11 09:59:05 -07:00
Zac-HD
c5a549b5bb Emit warning for broken object 2019-06-09 22:17:40 +10:00
Daniel Hahler
75cda6de53 tox: coverage: use -m with coverage-report 2019-06-09 12:51:32 +02:00
Daniel Hahler
e868bb647d remove commented code 2019-06-09 12:51:32 +02:00
Daniel Hahler
40c5a9d9f2 Merge pull request #5409 from blueyed/twisted
ci: optimize twisted/numpy related jobs
2019-06-09 12:49:41 +02:00
Anthony Sottile
83d18096d4 Merge pull request #5421 from nicoddemus/raises-warning-message
Link deprecation docs pytest.raises 'message' warning
2019-06-08 12:44:40 -07:00
Daniel Hahler
28aa38ece6 ci: optimize twisted/pexpect related jobs
- tox: use twisted as dep only
- Azure: move twisted/numpy to main py37 job
- Travis: move twisted to main py37 build
2019-06-08 19:21:56 +02:00
Bruno Oliveira
f0cee593f2 Link deprecation docs pytest.raises 'message' warning
As commented in https://github.com/pytest-dev/pytest/issues/3974#issuecomment-499870914
2019-06-07 14:14:46 -03:00
Daniel Hahler
4f597f011d Merge pull request #5419 from blueyed/remove-pypy3
ci: Travis: remove pypy3 job for now
2019-06-07 18:05:59 +02:00
Bruno Oliveira
9f5c356784 Remove ExceptionInfo.__str__, falling back to __repr__ (#5413)
Remove ExceptionInfo.__str__, falling back to __repr__
2019-06-07 08:48:03 -03:00
Daniel Hahler
47022b36cb ci: Travis: remove pypy3 job for now
Ref: https://github.com/pytest-dev/pytest/issues/5317#issuecomment-499019928
2019-06-07 11:01:23 +02:00
Bruno Oliveira
042a10f2e2 Add slow marker in run/skip option example. (#5416)
Add `slow` marker in run/skip option example.
2019-06-06 15:00:04 -03:00
Anthony Sottile
0405697a78 Merge pull request #5415 from asottile/small_mypy_fixes
small mypy fixes
2019-06-06 10:47:58 -07:00
Ralph Giles
918268774b Add slow marker in run/skip option example.
The example implementation of a `--runslow` option results in
a `PytestUnknownMarkWarning`. Include registering the custom
mark in the example, based on the documentation in markers.rst.
2019-06-06 10:15:43 -07:00
Anthony Sottile
ccd87f9e80 small mypy fixes 2019-06-06 09:13:02 -07:00
Bruno Oliveira
65c2a81924 Remove ExceptionInfo.__str__, falling back to __repr__
Fix #5412
2019-06-06 12:20:32 -03:00
Bruno Oliveira
450d264623 ci: move coverage reporting to shared script (#5403)
ci: move coverage reporting to shared script
2019-06-06 12:04:32 -03:00
Daniel Hahler
0fd1f3038c ci: move coverage reporting to shared script 2019-06-06 16:31:39 +02:00
Bruno Oliveira
9f8b566ea9 Turn PytestDeprecationWarning into error (#5410)
Turn PytestDeprecationWarning into error
2019-06-05 22:20:14 -03:00
Bruno Oliveira
3656885d0d Fix verbosity bug in --collect-only (#5391)
Fix verbosity bug in --collect-only
2019-06-05 20:47:59 -03:00
Thomas Hisch
577b0dffe7 Fix verbosity bug in --collect-only 2019-06-05 20:10:16 -03:00
Bruno Oliveira
8f5cb461a8 Turn PytestDeprecationWarning into error
Fix #5402
2019-06-05 19:02:52 -03:00
Daniel Hahler
be84ba8a33 Merge pull request #5396 from blueyed/travis-py37-nocov
Revert "Enable coverage for 'py37' environment"
2019-06-05 12:40:46 +02:00
Daniel Hahler
d9eafbdee3 Revert "Enable coverage for 'py37' environment"
This reverts commit 6d393c5dc8.

It should not be necessary, because we have it via other jobs already.
2019-06-05 12:12:58 +02:00
Daniel Hahler
190456aeda Merge pull request #5406 from blueyed/restore-tracing
tests: restore tracing function
2019-06-05 11:50:56 +02:00
Daniel Hahler
aab5687093 tests: restore tracing function
Without this, `testing/test_pdb.py` (already without pexpect) will cause
missing test coverage afterwards (for the same process).
2019-06-05 11:26:48 +02:00
Anthony Sottile
5fdc2d7744 Merge pull request #5400 from asottile/prefixes
Clean up u' prefixes and py2 bytes conversions
2019-06-04 19:03:12 -07:00
Anthony Sottile
25cef55e4a Merge pull request #5398 from nicoddemus/kwargs-refactoring
Use keyword-only arguments in a few places
2019-06-04 18:21:44 -07:00
Anthony Sottile
be2be040f9 Clean up u' prefixes and py2 bytes conversions 2019-06-04 17:50:34 -07:00
Anthony Sottile
0f4992c223 Merge pull request #5393 from nicoddemus/unittest-self-5390
item.obj is again a bound method on TestCase function items
2019-06-04 17:48:48 -07:00
Bruno Oliveira
23cd68b667 Use keyword-only arguments in a few places 2019-06-04 21:10:59 -03:00
Bruno Oliveira
79ef04888e Merge pull request #5389 from dirk-thomas/patch-1
fix logic if importlib_metadata.PathDistribution.files is None [breaks pytest 4.6.0|1|2]
2019-06-04 20:25:21 -03:00
Bruno Oliveira
1f8fd421c4 item.obj is again a bound method on TestCase function items
Fix #5390
2019-06-04 20:22:49 -03:00
Bruno Oliveira
76d50801fd Allow pypy3 failures again (#5394)
Allow pypy3 failures again
2019-06-04 20:22:25 -03:00
Bruno Oliveira
9349c72cac Allow pypy3 failures again
Related to #5317
2019-06-04 20:17:51 -03:00
Bruno Oliveira
883db6a216 Add test for packages with broken metadata
Related to #5389
2019-06-04 17:04:15 -03:00
Dirk Thomas
898e869bcd add changelog file for #5389 2019-06-04 10:55:38 -07:00
Dirk Thomas
0a91e181af fix logic if importlib_metadata.PathDistribution.files is None 2019-06-04 10:41:58 -07:00
Bruno Oliveira
6a6b6d8195 Remove --recreate from .travis.yml (#5384)
Remove --recreate from .travis.yml
2019-06-03 22:18:17 -03:00
Anthony Sottile
b95bb29fc2 Remove --recreate from .travis.yml
Looks like this has been in the history since the beginning of time, but we should always get a blank slate anyway

Noticed this in https://github.com/crsmithdev/arrow/pull/597
2019-06-03 16:31:06 -07:00
Bruno Oliveira
2a3d643bdf Documentation: expansion of Monkeypatch to include mocked classes and dictionaries (#5315)
Documentation: expansion of Monkeypatch to include mocked classes and dictionaries
2019-06-03 19:30:29 -03:00
Bruno Oliveira
2cfd9c259f Revert "ci: Travis: add pypy3 to allowed failures temporarily" (#5378)
Revert "ci: Travis: add pypy3 to allowed failures temporarily"
2019-06-03 17:59:24 -03:00
Bruno Oliveira
927e95c65a [release notes] Merge pull request #5379 from asottile/release-4.6.2 (#5380)
[release notes] Merge pull request #5379 from asottile/release-4.6.2
2019-06-03 16:35:21 -03:00
Anthony Sottile
9657166a22 Merge pull request #5379 from asottile/release-4.6.2
Preparing release version 4.6.2
2019-06-03 12:19:42 -07:00
Bruno Oliveira
f223d26111 Add a new Exceptions section in documentation and document UsageError (#5231)
Add a new Exceptions section in documentation and document UsageError
2019-06-03 14:41:04 -03:00
Pulkit Goyal
1d6bbab2b0 Add a new Exceptions section in documentation and document UsageError 2019-06-03 14:23:56 -03:00
Daniel Hahler
606d728697 Revert "Revert "Revert "ci: Travis: add pypy3 to allowed failures temporarily""" 2019-06-03 18:54:40 +02:00
Daniel Hahler
3a8b08275d Merge pull request #5377 from blueyed/pypy3
Revert "Revert "ci: Travis: add pypy3 to allowed failures temporarily""
2019-06-03 18:33:57 +02:00
Daniel Hahler
e770db4c91 Revert "Revert "ci: Travis: add pypy3 to allowed failures temporarily""
This reverts commit a6dc283133.
2019-06-03 18:30:50 +02:00
Anthony Sottile
63099bc282 Merge pull request #5373 from asottile/revert_all_handling
Revert unrolling of `all()`
2019-06-03 09:18:47 -07:00
Bruno Oliveira
4f57d40a43 Merge master into features (#5374)
Merge master into features
2019-06-03 13:14:31 -03:00
Anthony Sottile
230f736fcd Add changelog entries for reverting all() handling 2019-06-03 08:42:03 -07:00
Anthony Sottile
1b381d5277 Revert "Unroll calls to any #5062 (#5103)"
This reverts commit 2b9ca34280, reversing
changes made to 0a57124063.
2019-06-03 08:42:03 -07:00
Anthony Sottile
2125d04501 Revert "Fix all() unroll for non-generators/non-list comprehensions (#5360)"
This reverts commit 733f43b02e, reversing
changes made to e4fe41ebb7.
2019-06-03 08:42:03 -07:00
Anthony Sottile
5976f36240 Merge pull request #5368 from asottile/pyupgrade
Automated / semi-automated python3 upgrades
2019-06-03 08:41:37 -07:00
Bruno Oliveira
ce78c9adef Fix linting 2019-06-03 12:08:50 -03:00
Bruno Oliveira
6d393c5dc8 Enable coverage for 'py37' environment 2019-06-03 12:08:02 -03:00
Anthony Sottile
8292644015 Allow multiple positions for the SyntaxError in pypy3.6 2019-06-03 12:08:02 -03:00
Anthony Sottile
96fd44e040 Update line number for warning 2019-06-03 12:08:02 -03:00
Anthony Sottile
5dcf85c17e manual: remove dependence on six 2019-06-03 12:08:02 -03:00
Anthony Sottile
ca1efd57bd git rm src/_pytest/_code/_py2traceback.py 2019-06-03 12:08:02 -03:00
Anthony Sottile
c63320cc31 codecs.open / io.open 2019-06-03 12:08:02 -03:00
Anthony Sottile
4df529e5b9 Clean up __future__ and coding: in tests 2019-06-03 12:08:02 -03:00
Anthony Sottile
a91fe1fedd pre-commit run pyupgrade --all-files 2019-06-03 12:08:02 -03:00
Anthony Sottile
3f1ec520fc pre-commit run reorder-python-imports --all-files 2019-06-03 12:08:01 -03:00
Anthony Sottile
5034399d7a pre-commit run fix-encoding-pragma --all-files 2019-06-03 12:08:01 -03:00
Anthony Sottile
99057555e1 manual changes to .pre-commit-config.yaml 2019-06-03 12:08:01 -03:00
Thomas Hisch
b8781ff868 Merge pull request #5335 from thisch/fmtregex
logging: Extend LEVELNAME_FMT_REGEX
2019-06-03 05:55:36 +02:00
Thomas Hisch
ef053193b5 logging: Extend LEVELNAME_FMT_REGEX 2019-06-03 05:53:19 +02:00
Bruno Oliveira
28ac469eaa Merge pull request #5367 from apollovy/master
Fix typo about interpreters count in doc/en/example/parametrize.html
2019-06-02 20:43:53 -03:00
Bruno Oliveira
5999782768 Use python 3 interpreters in example 2019-06-02 19:20:00 -03:00
Bruno Oliveira
6e68532bb3 Merge pull request #5362 from asottile/release-4.6.1 (#5365)
Merge pull request #5362 from asottile/release-4.6.1
2019-06-02 19:17:29 -03:00
Bruno Oliveira
602a290fcc Drop py27 and py34 support (#5318)
Drop py27 and py34 support
2019-06-02 19:14:54 -03:00
Bruno Oliveira
876df87672 Update release instructions for 4.6-maintenance (#5363)
Update release instructions for 4.6-maintenance
2019-06-02 19:14:26 -03:00
Bruno Oliveira
b7f8f53127 Revert "ci: Travis: add pypy3 to allowed failures temporarily" (#5364)
Revert "ci: Travis: add pypy3 to allowed failures temporarily"
2019-06-02 19:12:39 -03:00
Yuri Apollov
5c016d1021 Fix typo about interpreters count in doc/en/example/parametrize.html 2019-06-02 23:57:22 +03:00
Anthony Sottile
25e728c78b Update release instructions for 4.6-maintenance 2019-06-02 11:50:07 -07:00
Anthony Sottile
642ef6dc1b Merge pull request #5362 from asottile/release-4.6.1
Preparing release version 4.6.1
2019-06-02 11:47:26 -07:00
Daniel Hahler
a6dc283133 Revert "ci: Travis: add pypy3 to allowed failures temporarily"
This reverts commit 5ac498ea96.

The idea is that maybe https://github.com/pytest-dev/pytest/pull/5360
fixes the failures here also.
2019-06-02 20:19:34 +02:00
Bruno Oliveira
4d49ba6529 Drop Python 2.7 and 3.4 support
* Update setup.py requires and classifiers
* Drop Python 2.7 and 3.4 from CI
* Update docs dropping 2.7 and 3.4 support
* Fix mock imports and remove tests related to pypi's mock module
* Add py27 and 34 support docs to the sidebar
* Remove usage of six from tmpdir
* Remove six.PY* code blocks
* Remove sys.version_info related code
* Cleanup compat
* Remove obsolete safe_str
* Remove obsolete __unicode__ methods
* Remove compat.PY35 and compat.PY36: not really needed anymore
* Remove unused UNICODE_TYPES
* Remove Jython specific code
* Remove some Python 2 references from docs

Related to #5275
2019-06-02 14:39:11 -03:00
Bruno Oliveira
733f43b02e Fix all() unroll for non-generators/non-list comprehensions (#5360)
Fix all() unroll for non-generators/non-list comprehensions
2019-06-02 12:51:43 -03:00
Bruno Oliveira
acdf30a523 Fix all() unroll for non-generators/non-list comprehensions
Fix #5358
2019-06-02 12:12:14 -03:00
Anthony Sottile
e4fe41ebb7 Merge pull request #5356 from asottile/fix_parametrize_iterator
Fix `pytest.mark.parametrize` when the argvalue is an iterator
2019-06-01 15:09:43 -07:00
Anthony Sottile
cafb13c95f Fix pytest.mark.parametrize when the argvalue is an iterator 2019-06-01 15:09:17 -07:00
Bruno Oliveira
a8f4e56d8c Docs: Fix link anchor (#5355)
Docs: Fix link anchor
2019-06-01 19:09:04 -03:00
Hugo
e2ac4b782a Fix link anchor 2019-06-01 23:27:20 +03:00
Anthony Sottile
917195ea8e Merge pull request #5350 from asottile/release-4.6.0
Release 4.6.0
2019-06-01 11:10:57 -07:00
Anthony Sottile
e7cd00ac92 Preparing release version 4.6.0 2019-05-31 23:12:57 -07:00
Daniel Hahler
693c3b7f61 Merge pull request #5349 from asottile/mm
Merge master into features
2019-05-31 06:35:00 +02:00
Anthony Sottile
fb3ae5eaa9 Merge remote-tracking branch 'origin/master' into mm 2019-05-30 20:23:38 -07:00
Bruno Oliveira
c8d23c206b logging: Improve formatting of multiline message (#5312)
logging: Improve formatting of multiline message
2019-05-30 21:42:41 -03:00
Bruno Oliveira
c5de8e8c50 ci: Travis: add pypy3 to allowed failures temporarily (#5340)
ci: Travis: add pypy3 to allowed failures temporarily
2019-05-30 21:37:55 -03:00
Bruno Oliveira
f360147758 Avoiding looking upwards for parameter argnames when generating fixtu… (#5254)
Avoiding looking upwards for parameter argnames when generating fixtu…
2019-05-30 21:08:15 -03:00
Victor Maryama
65bd1b8a93 Avoiding looking upwards for parameter argnames when generating fixtureinfo. 2019-05-30 23:42:04 +02:00
Daniel Hahler
882f3a4cd7 Merge pull request #5306 from blueyed/spawn-home
pytester: use temporary HOME with spawn
2019-05-30 20:46:17 +02:00
Anthony Sottile
56e430f74e Merge pull request #5338 from nicoddemus/junit_log_passing_tests-ref-docs
Add missing junitxml ini options to the reference docs
2019-05-30 10:29:56 -07:00
Anthony Sottile
654d8da9f7 Merge pull request #5346 from nicoddemus/improve-collect-warn-message
Show test module in the PytestCollectionWarning message
2019-05-30 10:27:52 -07:00
Daniel Hahler
ace3a02cd4 pytester: factor out testdir._env_run_update 2019-05-30 17:39:44 +02:00
Daniel Hahler
f013a5e8c1 pytester: use temporary HOME with spawn
Followup to https://github.com/pytest-dev/pytest/issues/4956.
2019-05-30 17:39:44 +02:00
Bruno Oliveira
fbd8ff9502 Merge master into features (#5339)
Merge master into features
2019-05-30 12:21:51 -03:00
Daniel Hahler
737a1bf947 Merge pull request #5341 from blueyed/auto-slow
tests: conftest: auto-add slow marker
2019-05-30 17:01:43 +02:00
Bruno Oliveira
843ca03770 Merge pull request #5343 from blueyed/remove-winpymap
pytester: remove unused winpymap
2019-05-30 09:21:51 -03:00
Bruno Oliveira
5cbc06a453 Show test module in the PytestCollectionWarning message
Related to #5330
2019-05-30 08:18:28 -03:00
Daniel Hahler
da23aa3419 pytester: remove unused winpymap
Follow-up to c86d2daf8.
2019-05-30 08:09:49 +02:00
Daniel Hahler
28bf3816e7 tests: conftest: auto-add slow marker 2019-05-30 06:55:38 +02:00
Daniel Hahler
d6ce2e5858 Merge pull request #5322 from blueyed/pdb-wrapper
pdb: move/refactor initialization of PytestPdbWrapper
2019-05-30 06:39:25 +02:00
Daniel Hahler
5ac498ea96 ci: Travis: add pypy3 to allowed failures temporarily
Ref: https://github.com/pytest-dev/pytest/pull/5334
Ref: https://github.com/pytest-dev/pytest/issues/5317
2019-05-30 06:37:53 +02:00
Daniel Hahler
6765aca0d1 Merge master into features 2019-05-30 06:33:04 +02:00
Daniel Hahler
72fc43952b Merge pull request #5336 from blueyed/fix-pexpect
Fix pexpect tests on MacOS
2019-05-30 06:31:11 +02:00
Daniel Hahler
6896dbc5ca tox: pexpect: use "-m uses_pexpect" 2019-05-30 03:52:41 +02:00
Daniel Hahler
49c6aebbc7 ci: Travis: test with pexpect on macos
Uses `PYTEST_COVERAGE=1` already, which will come in via dropping
Python 2 soon anyway.
2019-05-30 03:51:33 +02:00
Daniel Hahler
fb12d2a612 test_enter_leave_pdb_hooks_are_called: remove child.sendeof() 2019-05-30 03:09:36 +02:00
Daniel Hahler
8e51563384 tests: pdb: flush also on MacOS, but read() before
Ref: https://github.com/pytest-dev/pytest/issues/2022
2019-05-30 03:09:36 +02:00
Daniel Hahler
61dfd0a94f pdb: move/refactor initialization of PytestPdbWrapper 2019-05-30 03:00:07 +02:00
Bruno Oliveira
f9cafd1c94 Add missing junitxml ini options to the reference docs 2019-05-29 21:13:16 -03:00
Bruno Oliveira
b10f28949d Add the junit_log_passing_tests ini flag to skip logging output for passing tests. (#5052)
Add the junit_log_passing_tests ini flag to skip logging output for passing tests.
2019-05-29 20:56:13 -03:00
Bruno Oliveira
b0f090890c Merge master into features (#5332)
Merge master into features
2019-05-29 20:39:27 -03:00
Daniel Hahler
f0a4a13e48 Merge pull request #5333 from blueyed/fix-lf
Fix regression with --lf and non-selected failures
2019-05-30 01:24:07 +02:00
Daniel Hahler
ff80464b47 last-failed: display skipped-files msg always 2019-05-29 23:32:52 +02:00
Daniel Hahler
480dd9e6d6 last_failed_paths: improve caching 2019-05-29 23:28:58 +02:00
Daniel Hahler
ceb4f3f701 fixup! Fix regression with --lf and non-selected failures 2019-05-29 23:24:52 +02:00
Thomas Hisch
ea3ebec117 logging: Improve formatting of multiline message 2019-05-29 23:21:14 +02:00
Daniel Hahler
bf3b26b3f7 Fix regression with --lf and non-selected failures 2019-05-29 22:44:43 +02:00
Thomas Hisch
84569ca4da Merge pull request #5311 from thisch/coloredcaplog
Use same code for setting up cli/non-cli formatter
2019-05-29 22:18:43 +02:00
Daniel Hahler
af21e6b45c Merge master into features
(dropping the temporary pinning of pluggy (2e2e895b4))
2019-05-29 22:15:25 +02:00
Daniel Hahler
5c5966f62d Merge pull request #5331 from blueyed/conftest
tests: conftest: fix collection of slow/slowest items
2019-05-29 22:13:52 +02:00
Thomas Hisch
31b1c4ca0c Update changelog/5311.feature.rst
Co-Authored-By: Daniel Hahler <github@thequod.de>
2019-05-29 22:00:34 +02:00
Daniel Hahler
61b76c7f5f tests: conftest: fix collection of slow/slowest items 2019-05-29 21:35:05 +02:00
Bruno Oliveira
c35544a0f7 conftest: add uses_pexpect mark (#5314)
conftest: add uses_pexpect mark
2019-05-28 20:00:36 -03:00
Bruno Oliveira
5bc3ad8e27 minor: getbasetemp: dedent, improve assert (#5327)
minor: getbasetemp: dedent, improve assert
2019-05-28 19:59:43 -03:00
Bruno Oliveira
a930ca0b45 Remove _pytest.compat.NoneType (#5326)
Remove _pytest.compat.NoneType
2019-05-28 19:58:17 -03:00
Thomas Hisch
d4b85da8c7 Use same code for setting up cli/non-cli formatter
A method _create_formatter was introduced that is used for both the
log_cli_formatter and the log_formatter.

Consequences of this commit are:
* Captured logs that are output for each failing test are formatted
  using the ColoredLevelFromatter.
* The formatter used for writing to a file still uses the non-colored
  logging.Formatter class.
2019-05-28 21:30:34 +02:00
Daniel Hahler
0025e4408f conftest: add uses_pexpect mark 2019-05-28 18:41:01 +02:00
Anthony Sottile
81cc73103a Merge pull request #5325 from asottile/temporary
Temporarily pin pluggy on master
2019-05-28 09:37:04 -07:00
Daniel Hahler
97d8e9fbec minor: getbasetemp: dedent, improve assert 2019-05-28 18:26:10 +02:00
Daniel Hahler
220a2a1bc9 Remove _pytest.compat.NoneType 2019-05-28 18:16:18 +02:00
Anthony Sottile
2e2e895b4b Temporarily pin pluggy on master 2019-05-28 09:02:23 -07:00
Bruno Oliveira
bce45052a6 Correct some tiny typos in changelog (#5323)
Correct some tiny typos in changelog
2019-05-28 12:41:05 -03:00
Anthony Sottile
2f48ae4e66 Correct some tiny typos in changelog 2019-05-28 08:11:18 -07:00
Evan Kepner
2dfbed11b4 fix path expansion example 2019-05-27 23:23:18 -04:00
Evan Kepner
24c95c78e7 add updated monkeypatch examples 2019-05-27 20:55:15 -04:00
Daniel Hahler
6061ecf95a Merge master into features (#5319) 2019-05-28 02:15:15 +02:00
Daniel Hahler
e032904413 Merge master into features 2019-05-28 01:46:16 +02:00
Bruno Oliveira
ece774f0eb pdb: import pdbcls lazily (#5307)
pdb: import pdbcls lazily
2019-05-27 20:23:39 -03:00
Bruno Oliveira
bc49d6ff99 Update docs about py27 and py34 support plans (#5316)
Update docs about py27 and py34 support plans
2019-05-27 20:22:31 -03:00
Bruno Oliveira
2b9ca34280 Unroll calls to any #5062 (#5103)
Unroll calls to any #5062
2019-05-27 20:17:44 -03:00
Bruno Oliveira
e38561037d Update docs about py27 and py34 support plans
As discussed in #5275
2019-05-27 19:28:27 -03:00
Anthony Sottile
0a57124063 Merge pull request #5063 from asottile/importlib_metadata_v2
Switch to importlib-metadata
2019-05-27 15:00:12 -07:00
Anthony Sottile
13f02af97d Switch to importlib-metadata 2019-05-27 13:24:08 -07:00
Daniel Hahler
f2ed796c41 pdb: import pdbcls lazily
Fixes https://github.com/pytest-dev/pytest/issues/2064.
2019-05-26 15:56:38 +02:00
Anthony Sottile
b3f8fabac8 Merge pull request #5308 from blueyed/minor
Minor fixes
2019-05-25 21:58:39 -07:00
Tomer Keren
22d91a3c3a Unroll calls to all on python 2 2019-05-25 19:34:08 +03:00
Tomer Keren
322a0f0a33 Fix mention of issue #5062 in docstrings 2019-05-25 19:34:08 +03:00
Tomer Keren
58149459a5 Mark visit_all as a private method 2019-05-25 19:34:08 +03:00
Tomer Keren
852fb6a4ae Change basic test case to be consistent with existing assertion rewriting
The code
```
x = 0
assert x == 1
```
will give the failure message 0 == 1, so it shouldn't be different as
part of an unroll
2019-05-25 19:34:08 +03:00
Tomer Keren
437d6452c1 Expand list comprehensions as well 2019-05-25 19:34:08 +03:00
Tomer Keren
e37ff3042e Check calls to all only if it's a name and not an attribute 2019-05-25 19:34:08 +03:00
Tomer Keren
ecd2de25a1 Revert "Displaying pip list command's packages and versions #5062"
This reverts commit 043fdb7c40.
These tests were part of the PR #5155 but weren't relevant to #5602
2019-05-25 19:34:08 +03:00
danielx123
c607697400 Fixed test case 2019-05-25 19:34:08 +03:00
danielx123
0996f3dbc5 Displaying pip list command's packages and versions #5062 2019-05-25 19:34:08 +03:00
danielx123
a0dbf2ab99 Adding test cases for unrolling an iterable #5062 2019-05-25 19:34:08 +03:00
Tomer Keren
ddbe733666 Add changelog entry for 5062 2019-05-25 19:34:08 +03:00
Tomer Keren
470e686a70 Rewrite unrolled assertion with a new rewriter,correctly append the unrolled for loop 2019-05-25 19:34:08 +03:00
Tomer Keren
765f75a8f1 Replace asserts of any with an assert in a for 2019-05-25 19:34:08 +03:00
Tomer Keren
6b5152ae13 Sanity tests for loop unrolling 2019-05-25 19:34:08 +03:00
Daniel Hahler
10ca84ffc5 Merge pull request #5119 from blueyed/reportopts-A-order
reportopts: A: put "Pp" in front
2019-05-24 18:28:43 +02:00
Bruno Oliveira
e393a73890 Small change to test if pushing directly to master is disabled 2019-05-24 12:11:15 -03:00
Thomas Hisch
bed3918cbc Revert "logging: Simple impl of multline pretty printing"
This reverts commit 31dfbb4668.
2019-05-24 09:11:03 +02:00
Thomas Hisch
31dfbb4668 logging: Simple impl of multline pretty printing 2019-05-24 09:09:09 +02:00
Bruno Oliveira
b4d75ad31d Merge pull request #5091 from blueyed/showhelp-ini-options
Improve output of ini options in --help
2019-05-23 21:10:43 -03:00
Daniel Hahler
ec6d0fa4d7 Merge pull request #5268 from blueyed/harden-test
tests: harden test_nonascii_text
2019-05-24 01:51:35 +02:00
Daniel Hahler
fa8a658458 Merge pull request #4908 from blueyed/pdb-pm-enter-hook
pdb: trigger pytest_enter_pdb hook with post-mortem
2019-05-24 01:50:24 +02:00
Bruno Oliveira
66f20b6f5e Fix invalid Python file encoding "utf8" (#5252)
Fix invalid Python file encoding "utf8"
2019-05-23 20:24:23 -03:00
Bruno Oliveira
6ba5e3c071 tests: fix test_trace_after_runpytest (#5245)
tests: fix test_trace_after_runpytest
2019-05-23 19:58:33 -03:00
Bruno Oliveira
b900b4155f importorskip: display/include ImportError (#5269)
importorskip: display/include ImportError
2019-05-23 19:25:34 -03:00
Bruno Oliveira
364ae5d723 changelog: Fix typo (#5304)
changelog: Fix typo
2019-05-23 14:16:49 -03:00
David Röthlisberger
84c7fef836 changelog: Fix typo 2019-05-23 16:48:39 +01:00
Bruno Oliveira
aaea4e52ef Fix whitespace in FUNDING.yml 2019-05-23 12:44:55 -03:00
Bruno Oliveira
0cacdadc97 Create FUNDING.yml
Following instructions from:

* https://tidelift.com/subscription/how-to-connect-tidelift-with-github
* https://help.github.com/en/articles/displaying-a-sponsor-button-in-your-repository#displaying-a-sponsor-button-in-your-repository
2019-05-23 12:36:46 -03:00
Daniel Hahler
6c56070df1 Merge pull request #5278 from blueyed/disable-python-plugin
Allow disabling of python plugin
2019-05-23 15:52:19 +02:00
Daniel Hahler
f9f41e69a8 reportopts: A: put "Pp" in front 2019-05-23 09:40:16 +02:00
Daniel Hahler
b2ce6f3200 Improve output of ini options in --help
Do not cut long help texts, but wrap them the same way as argparse wraps
the other help items.
2019-05-23 09:33:07 +02:00
Daniel Hahler
e0b584d048 CaptureFixture: do not crash in _suspend when not started
This happened in test_pdb_with_caplog_on_pdb_invocation.
2019-05-23 09:09:53 +02:00
Daniel Hahler
a0ff5deabf pdb: trigger pytest_enter_pdb hook with post-mortem
This is required for pytest-pdb to be called with `--pdb`.

TODO:

- [ ] test
- [ ] pass mode to hook, e.g. "post_mortem" in this case?
2019-05-23 09:09:53 +02:00
Daniel Hahler
97b85a17ae changelog [ci skip] 2019-05-23 08:38:54 +02:00
Anthony Sottile
de7ba5958b Merge pull request #5294 from akiomik/fix-disable_test_id_escaping-option
Fix `disable_test_id_escaping_and_forfeit_all_rights_to_community_support` option when using a list of test IDs
2019-05-21 15:14:45 -07:00
Akiomi Kamakura
8a498700da Add tests for #5286 2019-05-22 03:56:52 +09:00
Anthony Sottile
45c894b73f Merge pull request #5297 from nicoddemus/tidelift-contents
Add link to tidelift to the main docs
2019-05-21 08:18:07 -07:00
Bruno Oliveira
65342db7a4 Update fixture.rst (#5295)
Update fixture.rst
2019-05-21 11:57:15 -03:00
Bruno Oliveira
d391274f39 Add link to tidelift to the main docs
As commented in:

https://github.com/pytest-dev/pytest/pull/5240#issuecomment-494175451
2019-05-21 11:12:07 -03:00
oleg-yegorov
c5fa1d1c3e Update fixture.rst
add a missing import
2019-05-21 09:40:31 +03:00
Akiomi Kamakura
a304dbb519 Fix disable_test_id_escaping_and_forfeit_all_rights_to_community_support option when using a list of test IDs 2019-05-21 09:48:22 +09:00
Daniel Hahler
d19df5efa2 importorskip: display/include ImportError
This can provide useful information, e.g.

> could not import 'pyrepl.readline': curses library not found
2019-05-20 14:13:33 +02:00
Bruno Oliveira
6663cb054c Fix documentation of pytest.raises(match=...) (#5288)
Fix documentation of pytest.raises(match=...)
2019-05-19 12:29:02 -03:00
Tim Hoffmann
b27e40cbf1 Fix documentation of pytest.raises(match=...) 2019-05-19 16:01:48 +02:00
Anthony Sottile
ee52a8a5f8 Merge pull request #5287 from clickthisnick/chore-fix-misspellings
Fix one misspelling in changelog
2019-05-18 15:30:35 -07:00
MyComputer
8f04bd003c Fix misspellings 2019-05-18 17:11:23 -04:00
Daniel Hahler
93fd9debe3 Allow disabling of python plugin
Fixes https://github.com/pytest-dev/pytest/issues/5277.
2019-05-17 18:17:14 +02:00
Daniel Hahler
ff428bfee1 tests: harden test_nonascii_text 2019-05-17 18:06:32 +02:00
Daniel Hahler
0f7c7a99bf Merge pull request #5281 from nicoddemus/merge-master-into-features
Merge master into features (make CI green again)
2019-05-17 16:58:16 +02:00
Bruno Oliveira
041ea3704b Merge remote-tracking branch 'upstream/master' into merge-master-into-features 2019-05-16 20:10:44 -03:00
Anthony Sottile
d94b4b031f Merge pull request #5271 from nicoddemus/lone-surrogate-jython-5256
Handle lone surrogate unicode character not being representable in Jython
2019-05-16 15:02:08 -07:00
Bruno Oliveira
e253029ad0 Handle lone surrogate unicode character not being representable in Jython
No tests for this because we don't test with Jython currently.

Fix #5256
2019-05-16 17:59:31 -03:00
Bruno Oliveira
43617a8c47 Disable PyPy on Azure (#5274)
Disable PyPy on Azure
2019-05-16 17:57:32 -03:00
Bruno Oliveira
56bf7446f6 Disable pypy2 and pypy3 on Azure [travis skip]
Related to #5279
2019-05-16 12:20:17 -03:00
Bruno Oliveira
8e42c5b7db Make it clear that small typos in docs don't require a CHANGELOG entry (#5276)
Make it clear that small typos in docs don't require a CHANGELOG entry
2019-05-16 12:15:15 -03:00
Bruno Oliveira
0571e1ee8e Make it clear that small typos in docs don't require a CHANGELOG entry
From: https://github.com/pytest-dev/pytest/pull/5273#issuecomment-493076587
2019-05-16 10:54:50 -03:00
Bruno Oliveira
b0a6161d41 Fixed double be word on monkeypatch docs page. (#5273)
Fixed double `be` word on monkeypatch docs page.
2019-05-16 10:53:08 -03:00
Bruno Oliveira
06fa2bc0b8 Re-enable pypy3 to see how it fares on Azure 2019-05-16 08:10:53 -03:00
Bruno Oliveira
8abd4aec6e Remove customization of (python.exe) from Azure [skip travis]
This is no longer needed it seems
2019-05-16 08:07:59 -03:00
Nikita Krokosh
858010e214 Fixed double be word on monkeypatch docs page. 2019-05-16 18:22:41 +10:00
Bruno Oliveira
96424272a1 Improve mark docs (#5265)
Improve mark docs
2019-05-15 20:52:21 -03:00
Bruno Oliveira
e44a2ef653 Apply suggestions from code review
Co-Authored-By: Daniel Hahler <github@thequod.de>
2019-05-15 20:45:22 -03:00
Bruno Oliveira
c6e3ff3ce5 Mention "-m" in the main mark docs 2019-05-15 20:45:22 -03:00
Bruno Oliveira
a31098a74e Move section about mark revamp and iteration to historical notes
This has been in place for a long time now, since 3.6.
2019-05-15 20:45:22 -03:00
Bruno Oliveira
7e8044f9b8 Revamp the mark section in the docs
Add an introductory section about how to register marks,
including doing so programatically (#5255).
2019-05-15 20:45:22 -03:00
Anthony Sottile
b81173ea0c Upgrade pre-commit/pre-commit-hooks 2019-05-15 10:19:12 -07:00
Daniel Hahler
c8f7e50c47 Merge pull request #5262 from asottile/mode_non_binary
Remove 'b' from sys.stdout.mode
2019-05-15 10:56:36 +02:00
Daniel Hahler
c0e53a61e6 Merge pull request #5263 from blueyed/mm
Merge master to fix CI
2019-05-15 10:55:54 +02:00
Bruno Oliveira
494ac28a32 Merge pull request #5250 from EvanKepner/master
Documentation: add setenv/delenv examples to monkeypatch docs
2019-05-14 23:10:58 -03:00
Anthony Sottile
dc75b6af47 Use fix-encoding-pragma pre-commit hook 2019-05-14 15:56:31 -07:00
Bruno Oliveira
7573747cda Normalize all source encoding declarations 2019-05-14 19:42:44 -03:00
Daniel Hahler
2db05b6582 Merge master into features 2019-05-15 00:11:37 +02:00
Anthony Sottile
4318698bae Remove 'b' from sys.stdout.mode 2019-05-14 15:00:59 -07:00
Bruno Oliveira
e668aaf885 Fix indentation and use code-block directives
The code-block directives are required by our blacken-docs hook
2019-05-14 18:59:27 -03:00
Daniel Hahler
58e6a09db4 Merge pull request #5261 from blueyed/fix-py37-freeze-remove-no-use-pep517
ci: tox: fix py37-freeze
2019-05-14 23:57:09 +02:00
Daniel Hahler
6718a2f028 ci: tox: fix py37-freeze
Remove ``--no-use-pep517``, which appears to not be supported anymore,
and PyInstaller works without it by now.
2019-05-14 23:49:57 +02:00
Daniel Hahler
c081c01eb1 minor: s/no covers/no cover/ 2019-05-14 06:51:49 +02:00
Daniel Hahler
f8e1d58e8f minor: settrace != set_trace 2019-05-14 06:51:30 +02:00
Raul Tambre
18024467ff Fix invalid Python file encoding "utf8"
Since Python 3 it must be "utf-8", which is the official name.
This is backwards compatible with Python 2.
2019-05-12 19:14:06 +03:00
Evan Kepner
2ad36b1402 add #5250 changelog entry 2019-05-12 10:08:46 -04:00
Evan Kepner
6ca3e1e425 add @EvanKepner to authors 2019-05-12 10:04:24 -04:00
Evan Kepner
ecd072ea94 add env example to monkeypatch docs 2019-05-12 09:52:22 -04:00
Daniel Hahler
dda21935a7 tests: fix test_trace_after_runpytest
It was not really testing what it was supposed to test (e.g. the inner
test was not run in the first place).
2019-05-12 09:33:34 +02:00
Bruno Oliveira
cc464f6b96 Merge master into features (#5248)
Merge master into features
2019-05-11 22:33:44 -03:00
Bruno Oliveira
6a43c8cd94 Release 4.5.0 (#5246)
Release 4.5.0
2019-05-11 21:40:27 -03:00
Bruno Oliveira
63fe547d9f Preparing release version 4.5.0 2019-05-11 16:35:32 +00:00
Bruno Oliveira
b709e61892 Merge remote-tracking branch 'upstream/master' into release-4.5.0 2019-05-11 16:30:23 +00:00
Bruno Oliveira
465b2d998a Further "unknown marks warning" improvements (#5178)
Further "unknown marks warning" improvements
2019-05-11 13:28:10 -03:00
Bruno Oliveira
184ef92f0b Introduce record_testsuite_property fixture (#5205)
Introduce record_testsuite_property fixture
2019-05-11 13:27:14 -03:00
Bruno Oliveira
73bbff2b74 Introduce record_testsuite_property fixture
This exposes the functionality introduced in fa6acdc as a session-scoped fixture.

Plugins that want to remain compatible with the `xunit2`
standard should use this fixture instead of `record_property`.

Fix #5202
2019-05-10 19:44:27 -03:00
Floris Bruynooghe
4ccaa987d4 Merge pull request #5240 from nicoddemus/tidelift
Add Tidelift management docs and blurb on README, as discussed in the ML
2019-05-10 13:27:57 +02:00
Bruno Oliveira
3a4a815c41 Merge master into features (#5233)
Merge master into features
2019-05-09 20:13:01 -03:00
Bruno Oliveira
dae455e8a3 Add Tidelift management docs and blurb on README, as discussed in the ML 2019-05-09 20:10:30 -03:00
Bruno Oliveira
0594dba5ce Remove unused markers and enable --strict-markers 2019-05-09 19:36:39 -03:00
Bruno Oliveira
f1183c2422 Remove the 'issue' marker from test suite
It doesn't seem to add much value (why would one execute tests
based on that marker?), plus using the docstring for that
encourages one to write a more descriptive message about the test
2019-05-09 19:36:38 -03:00
Bruno Oliveira
685ca96c71 Change `--strict to --strict-markers`, preserving the old one
Fix #5023
2019-05-09 19:36:38 -03:00
Bruno Oliveira
ccf6c3cb46 Merge remote-tracking branch 'upstream/master' into merge-master-into-features 2019-05-09 19:22:40 -03:00
Daniel Hahler
ceca35b94a Merge pull request #5236 from blueyed/pdb-eoferror-quit
pdb: only use outcomes.exit via do_quit
2019-05-09 17:10:36 +02:00
Bruno Oliveira
803d68847b Pin pluggy to <1.0 (#5239)
Pin pluggy to <1.0
2019-05-09 11:03:36 -03:00
Bruno Oliveira
0bd02cd1bc Ignore PytestUnknownMark warning when generating docs (#5234)
Ignore PytestUnknownMark warning when generating docs
2019-05-09 11:03:20 -03:00
Daniel Hahler
0b8b006db4 minor: improve formatting 2019-05-09 15:36:49 +02:00
Daniel Hahler
73b74c74c9 pdb: only use outcomes.exit via do_quit
Fixes https://github.com/pytest-dev/pytest/issues/5235.
2019-05-09 14:55:55 +02:00
Bruno Oliveira
4d782dc13f Add CHANGELOG for #5239 2019-05-09 09:00:39 -03:00
Bruno Oliveira
e1756fc631 Pin pluggy to <1.0
Make sure we don't update to pluggy 1.0 automatically, as there are planned breaking
changes in the 1.0 release.
2019-05-09 08:47:01 -03:00
Bruno Oliveira
5d7686951c Run regendoc 2019-05-08 21:50:08 +00:00
Bruno Oliveira
80c5f6e609 Ignore PytestUnknownMark warnings when regen docs
A lot of our examples use custom markers to make a point and showcase
features, which generates a lot of warnings
2019-05-08 21:46:26 +00:00
Bruno Oliveira
0b47e51d08 Release version 4.4.2 (#5230)
Release version 4.4.2
2019-05-08 18:07:05 -03:00
Daniel Hahler
5eeb5ee960 Merge pull request #5013 from blueyed/short-summary-message
Display message from reprcrash in short test summary
2019-05-08 22:01:04 +02:00
Daniel Hahler
ed2b715f4c Merge pull request #5227 from Pulkit07/issue5214
logging: improve default logging format (issue5214)
2019-05-08 21:51:54 +02:00
Pulkit Goyal
7e08e09473 logging: improve default logging format (issue5214)
We improve the following things in the logging format:

  * Show module name instead of just the filename
  * show level of logging as the first thing
  * show lineno attached to module:file details

Thanks to @blueyed who suggested this on the github issue.

It's my first contribution and I have added myself to AUTHORS.

I also added to a changelog file.
2019-05-08 21:37:59 +03:00
Bruno Oliveira
3ac43314ee Preparing release version 4.4.2 2019-05-08 12:46:14 -03:00
Bruno Oliveira
972410f8b6 Require pluggy>=0.11 (#5229)
Require pluggy>=0.11
2019-05-08 12:40:49 -03:00
Romain Chossart
0cf267f187 Add changelog entry for #5229 2019-05-08 16:13:28 +01:00
Sitaktif
7161f5b372 Require pluggy>=0.11
Pluggy 0.10.0 introduced a new dependency `importlib-metadata` but that
package cannot be imported when installed as an egg and that is causing
problems for users relying on `setup.py` to install packages present in
`test_require`. This change was quickly reverted in pluggy 0.11.0.

See https://github.com/pytest-dev/pluggy/issues/205
2019-05-08 16:06:41 +01:00
Bruno Oliveira
2051e30b9b Show fixture scopes with `--fixtures`, except for "function" scope (#5221)
Show fixture scopes with ``--fixtures``, except for "function" scope
2019-05-07 19:50:53 -03:00
Bruno Oliveira
f339147d12 Add CHANGELOG entry about depending on wcwidth 2019-05-07 19:34:57 -03:00
Bruno Oliveira
c04767f946 Use msg.rstrip() as suggested in review 2019-05-07 15:20:00 -03:00
Bruno Oliveira
6d040370ed Show fixture scopes with `--fixtures`, except for "function" scope
Fix #5220
2019-05-07 14:32:20 -03:00
Bruno Oliveira
1d466d0aa7 Use exec directly (#5224)
Use exec directly
2019-05-07 10:02:12 -03:00
Bruno Oliveira
ef4dec0bcf Skip test_source_mtime_long_long on 32bit and lower platforms (#5045)
Skip test_source_mtime_long_long on 32bit and lower platforms
2019-05-07 09:42:18 -03:00
Bruno Oliveira
d76735f9e5 Restore usedevelop=True now that pip 19.1.1 restored the old behavior (#5222)
Restore usedevelop=True now that pip 19.1.1 restored the old behavior
2019-05-07 08:46:47 -03:00
Anthony Sottile
d1a48ad68f Use exec directly 2019-05-06 23:07:39 -07:00
Bruno Oliveira
6d259c400e Merge pull request #5223 from 5uper5hoot/patch-1
Clarify docs for pytest.raises `match`.
2019-05-06 21:57:47 -03:00
Bruno Oliveira
d3686361ba Fix linting 2019-05-07 00:52:40 +00:00
Peter Schutt
8605ed2a15 Update python_api.py 2019-05-07 10:10:25 +10:00
Peter Schutt
8b34d981fc Clarify docs for pytest.raises match.
For #5208.

Document explicit behavior of `match` and brief note on how to handle matching a string that may contain special re chars.
2019-05-07 09:56:13 +10:00
Bruno Oliveira
2795689435 Restore usedevelop=True now that pip 19.1.1 restored the old behavior
Fix #5167
2019-05-06 19:42:06 -03:00
Bruno Oliveira
dcf65a9643 Add links to pytest.raises message workaround (#5218)
Add links to pytest.raises `message` workaround
2019-05-06 18:56:40 -03:00
Bruno Oliveira
784e1e3b7e Add links to pytest.raises message workaround
Related to #3974
2019-05-06 12:35:27 -03:00
Bruno Oliveira
4a2fdce62b Emit a warning for record_property when used with xunit2 (#5204)
Emit a warning for record_property when used with xunit2
2019-05-05 21:33:31 -03:00
Bruno Oliveira
32a5e80a6d Add encoding: header and fix rep mock in test_line_with_reprcrash on py27 2019-05-05 09:33:37 -03:00
Bruno Oliveira
0e8a8f94f6 Add encoding header to test_terminal.py 2019-05-05 09:14:07 -03:00
Bruno Oliveira
8f23e19bcb Emit a warning for record_property when used with xunit2
"property" elements cannot be children of "testsuite" according to the schema, so it is incompatible with xunit2

Related to #5202
2019-05-05 09:01:13 -03:00
Daniel Hahler
f5c1f3df71 Merge pull request #5210 from nicoddemus/merge-master-into-features
Merge master into features
2019-05-05 08:02:06 +02:00
Daniel Hahler
b25802eca7 Merge pull request #5212 from jdufresne/new-black
Update Black URLs
2019-05-05 07:58:27 +02:00
Daniel Hahler
7f7f84757d Merge pull request #5211 from hugovk/upgrade-pypy
Upgrade PyPy to 7.1.1
2019-05-05 04:50:11 +02:00
Jon Dufresne
143499d041 Update Black URLs
> Black, your uncompromising #Python code formatter, was a project
> created with the community in mind from Day 1. Today we moved it under
> the PSF umbrella. It's now available on GitHub under
> https://github.com/python/black/ . You install and use it just like
> before.

https://twitter.com/llanga/status/1123980466292445190
2019-05-04 08:28:50 -07:00
Hugo
26b41a5914 Upgrade PyPy to 7.1.1 2019-05-04 17:54:57 +03:00
Bruno Oliveira
9f66102869 Merge remote-tracking branch 'upstream/master' into merge-master-into-features 2019-05-04 10:47:57 -03:00
Bruno Oliveira
e1a426c067 Unify pypy (#5209)
Unify pypy
2019-05-04 10:46:14 -03:00
Bruno Oliveira
2bd97ebaf7 Use 'pypy' as executable on PyPy env [skip travis] 2019-05-04 10:27:06 -03:00
Bruno Oliveira
45eeb53c98 Fix a typo (#5207)
Fix a typo
2019-05-04 10:04:50 -03:00
Don Kirkby
254b195f50 Fix a typo 2019-05-03 22:30:20 -07:00
Daniel Hahler
865e84d206 Merge pull request #5109 from blueyed/summary_passes-green
summary_passes: use bold green for report headers
2019-05-04 00:46:23 +02:00
Bruno Oliveira
1c13418a8b doc: fix hooks 'path' parameter doc type (#5198)
doc: fix hooks 'path' parameter doc type
2019-05-02 21:05:07 -03:00
DamianSkrzypczak
299e6479c1 add DamianSkrzypczak to AUTHORS 2019-05-02 23:45:34 +02:00
DamianSkrzypczak
6e81c3df92 add changelog for issue #5171 fixes 2019-05-02 21:30:03 +02:00
DamianSkrzypczak
1bd7d287a7 doc: fix hooks 'path' parameter doc type
by changing it from str to py.path.local
(#5171)
2019-05-02 20:51:11 +02:00
Anthony Sottile
b82e1b87cc Merge pull request #5195 from nicoddemus/pytest-config-docs
Add quick note about accessing config through session or item objects
2019-05-02 09:52:42 -07:00
Bruno Oliveira
af40473c9a Add quick note about accessing config through session or item objects
Fix #5030
2019-05-01 11:46:35 -03:00
Bruno Oliveira
f17b734989 Improve help for --runxfail flag (#5188)
Improve help for --runxfail flag
2019-05-01 11:00:31 -03:00
Allan Lewis
f050203f5d Improve help for --runxfail flag
The help for the '--runxfail' flag is somewhat misleading. The default
behaviour is to run tests marked as 'xfail' but to ignore the results. This
flag alters that behaviour by running these tests as if they weren't marked
'xfail', i.e. their results are not ignored.
2019-05-01 10:04:32 +01:00
Bruno Oliveira
3f5622c577 Use config_invocation_dir for startdirs (#5151)
Use config_invocation_dir for startdirs
2019-04-29 18:14:51 -03:00
Bruno Oliveira
1fb3f63f35 debugging: rename internal wrapper for pdb.Pdb (#5186)
debugging: rename internal wrapper for pdb.Pdb
2019-04-29 18:03:32 -03:00
Bruno Oliveira
fc2ad1dbed Warning subclasses (#5179)
Warning subclasses
2019-04-29 17:57:49 -03:00
Matt Cooper
bc6450773a remove PyPy special casing 2019-04-29 08:39:48 -04:00
Bruno Oliveira
204004c8b8 Review doctest docs (#5183)
Review doctest docs
2019-04-29 08:02:59 -03:00
Bruno Oliveira
772a4a5cf3 Remove all version references to obsolete pytest versions (#5184)
Remove all version references to obsolete pytest versions
2019-04-29 08:02:32 -03:00
Bruno Oliveira
fb6dad60a0 terminal: use pytest_collection_finish for reporting (#5113)
terminal: use pytest_collection_finish for reporting
2019-04-29 08:00:48 -03:00
Bruno Oliveira
d9cad1e759 Merge pull request #5176 from nicoddemus/initial-conftests-note
Add note about pytest_load_initial_conftests working only from plugins
2019-04-29 07:59:27 -03:00
Daniel Hahler
02053bf556 debugging: rename internal wrapper for pdb.Pdb
This is useful/clearer in case of errors / tracebacks - i.e. you see
clearly that it is coming from pytest.
2019-04-29 05:46:21 +02:00
Anthony Sottile
6fb3baf071 Merge pull request #5182 from nicoddemus/removed-unused-deprecation-msgs
Removed unused warning message
2019-04-28 20:26:11 -07:00
Daniel Hahler
ff5317a7f3 terminal: use pytest_collection_finish for reporting 2019-04-29 05:20:04 +02:00
Bruno Oliveira
766fc23151 Merge pull request #5185 from nicoddemus/lf-skip-files
--lf now skips colletion of files without failed tests
2019-04-28 21:48:53 -03:00
Bruno Oliveira
08734bdd18 --lf now skips colletion of files without failed tests
Fix #5172
2019-04-28 20:23:46 -03:00
Bruno Oliveira
e943aff995 Update blurb about Sybil 2019-04-28 20:01:22 -03:00
Bruno Oliveira
9c5da9c0d1 Remove all version references to obsolete pytest versions
Remove version references to pytest 2 and 3.

Just like Python 3 no longer has references to Python 2, I think
we should follow the same approach in pytest.
2019-04-28 12:37:58 -03:00
Bruno Oliveira
f6ab6d71ad Run regendoc 2019-04-28 12:17:15 -03:00
Bruno Oliveira
67755d67fb Review doctest docs
* Add pytest.skip() example
* Add blurb about Sybil
* Create a subsection for doctest-options
* Create a subsection for pytest-specific features
2019-04-28 12:17:15 -03:00
Bruno Oliveira
a3c2ec3c5b Add CHANGELOG for #5182 2019-04-28 11:10:21 -03:00
Bruno Oliveira
9742f11d37 Removed unused warning message 2019-04-28 11:06:47 -03:00
Bruno Oliveira
915ecb0dac Add CHANGELOG for #5177 2019-04-28 10:47:19 -03:00
Bruno Oliveira
53cd7fd2ea Introduce new warning subclasses
Fix #5177
2019-04-28 10:38:25 -03:00
Bruno Oliveira
8532e991a5 Publish UnknownMarkWarning as part of the public API and docs 2019-04-28 10:16:07 -03:00
Bruno Oliveira
50937fe622 Add note about pytest_load_initial_conftests working only from plugins
Fix #5175
2019-04-27 10:12:27 -03:00
Daniel Hahler
ebc0cea226 Merge pull request #5174 from blueyed/no-terminal
Terminal plugin is not semi-essential anymore
2019-04-27 09:51:32 +02:00
Daniel Hahler
65133018f3 Terminal plugin is not semi-essential anymore
Thanks to https://github.com/pytest-dev/pytest/pull/5138.
2019-04-27 03:39:00 +02:00
Anthony Sottile
ac7ee40aaf Merge pull request #5173 from blueyed/revert
Revert "Merge pull request #4854 from blueyed/pdb-skip"
2019-04-26 17:48:04 -07:00
Daniel Hahler
308b733b9d Revert "Merge pull request #4854 from blueyed/pdb-skip"
This reverts commit e88aa957ae, reversing
changes made to 1410d3dc9a.

I do not think it warrants an option anymore, and there is a way to
achieve this via `--pdbcls` if needed.
2019-04-27 02:25:38 +02:00
Daniel Hahler
76c6ed8b05 Merge pull request #5162 from blueyed/mm
Merge master into features
2019-04-27 01:42:42 +02:00
Daniel Hahler
7f519f8ab7 Merge master into features 2019-04-27 00:43:00 +02:00
Bruno Oliveira
9c700d1fd5 Workaround for editable installs with pip 19.1 (#5168)
Workaround for editable installs with pip 19.1
2019-04-26 18:29:28 -03:00
Bruno Oliveira
19cd4d0af7 Workaround for editable installs with pip 19.1
Related to #5167
2019-04-25 19:40:01 -03:00
Bruno Oliveira
bf0fe1a1fa GitHub: revisit issue/PR templates [ci skip] (#5158)
GitHub: revisit issue/PR templates  [ci skip]
2019-04-24 12:09:55 -03:00
Daniel Hahler
3df32e2732 GitHub: revisit issue/PR templates [ci skip]
The motivation here is to not have the same boilerplate with PRs.
2019-04-23 18:01:13 +02:00
Daniel Hahler
0bf363472e Use config_invocation_dir for startdirs
`Session.startdir` and `TerminalReporter.startdir` appear to be
redundant given `Config.invocation_dir`.
Keep them for backward compatibility reasons, but use
`config.invocation_dir` for them.
2019-04-22 02:05:59 +02:00
Daniel Hahler
34bc594beb Merge pull request #5133 from kondratyev-nv/fix-handle-repr-error-with-showlocals
Fix handle repr error with showlocals and verbose output
2019-04-19 19:23:39 +02:00
Nikolay Kondratyev
bc00d0f7db Fix handle repr error with showlocals and verbose output 2019-04-19 18:54:21 +03:00
Daniel Hahler
e3e57a755b Merge pull request #5083 from blueyed/capture-_suspended
capture: store _state
2019-04-19 17:32:54 +02:00
Daniel Hahler
79d5fc3a0b Merge pull request #5144 from blueyed/sessionfinish-exitstatus
pytest_sessionfinish: preset exitstatus with UsageErrors
2019-04-19 17:30:01 +02:00
Bruno Oliveira
322d686ab4 Merge pull request #5145 from blueyed/prefer-fast-wrapper
conftest: use a hookwrapper with sorting faster tests first
2019-04-19 12:25:55 -03:00
Daniel Hahler
f75f7c1925 conftest: use a hookwrapper with sorting faster tests first 2019-04-19 01:23:34 +02:00
Daniel Hahler
698c4e75fd capture: track current state in _state attributes
This is meant for debugging, and making assertions later.
2019-04-19 00:35:15 +02:00
Daniel Hahler
4749dca764 changelog [ci skip] 2019-04-18 23:54:20 +02:00
Daniel Hahler
649d23c8a8 pytest_sessionfinish: preset exitstatus with UsageErrors
Previously it would be 0.  Setting it to the expected outcome
(EXIT_USAGEERROR) here already helps `pytest_sessionfinish` hooks.
2019-04-18 23:18:59 +02:00
Daniel Hahler
e87d3d70e2 Merge pull request #5138 from ikonst/notify_exception_without_terminal
Fix dependencies on 'terminal' plugin
2019-04-17 23:20:49 +02:00
Daniel Hahler
1460ad6027 Merge pull request #5111 from blueyed/deselect_by_keyword-skip
deselect_by_keyword: skip without expression
2019-04-17 23:20:02 +02:00
Daniel Hahler
78cd1a07d0 Merge pull request #5140 from blueyed/rewrite-name
assertion rewriting: use actual helper name
2019-04-17 23:19:38 +02:00
Ilya Konstantinov
d67d68f6d3 Eliminate core dependency on 'terminal' plugin 2019-04-17 11:19:19 -07:00
Bruno Oliveira
008d04398a Merge pull request #5135 from dougthor42/patch-1
[Docs] Fix typo in skipping.rst
2019-04-17 14:36:57 -03:00
Daniel Hahler
c3178a176d move test 2019-04-17 15:30:34 +02:00
Daniel Hahler
df1d1105b0 Merge remote-tracking branch 'origin/features' into short-summary-message
Conflicts:
	src/_pytest/skipping.py
2019-04-17 15:30:19 +02:00
Daniel Hahler
2b11b2c093 Merge pull request #5126 from blueyed/report-get_verbose_word
terminal/reports: use get_verbose_word method
2019-04-17 14:43:54 +02:00
Daniel Hahler
adb8edbae1 assertion rewriting: use actual helper name
This makes it easier / possible to grep.
2019-04-17 14:41:34 +02:00
Douglas Thor
0e651d7297 [Docs] Fix typo in skipping.rst
One of the `pytest.mark.skipif` blocks does not use the `reason` kwarg.
2019-04-16 09:30:13 -07:00
Anthony Sottile
3cff5e252d Merge pull request #5117 from blueyed/cov-terminal
Minor coverage improvements for terminal plugin
2019-04-15 14:30:18 -07:00
Daniel Hahler
7412df0920 fixup! terminal: summary_errors: replace if with assert 2019-04-15 22:53:31 +02:00
Anthony Sottile
990133f804 Merge pull request #5132 from nicoddemus/merge-master-into-features
Merge master into features
2019-04-15 13:11:33 -07:00
Bruno Oliveira
df68808d29 Merge pull request #5116 from blueyed/cov-pytester
Minor coverage improvements for pytester
2019-04-15 14:49:28 -03:00
Bruno Oliveira
b64d9402ca Merge pull request #5108 from blueyed/summary
terminal summary: display passes after warnings
2019-04-15 14:49:01 -03:00
Bruno Oliveira
8d3a5dcd1b Merge remote-tracking branch 'upstream/master' into merge-master-into-features 2019-04-15 14:47:45 -03:00
Bruno Oliveira
9eac4733c5 Merge pull request #5129 from nicoddemus/release-4.4.1
Release version 4.4.1
2019-04-15 14:41:36 -03:00
Bruno Oliveira
24bd51bda0 Merge pull request #5131 from blueyed/_getfailureheadline
_getfailureheadline: get head_line property only once
2019-04-15 12:23:41 -03:00
Daniel Hahler
9374114370 terminal/reports: add/use _get_verbose_word method 2019-04-15 17:06:18 +02:00
Daniel Hahler
eb13530560 _getfailureheadline: get head_line property only once 2019-04-15 17:04:51 +02:00
Daniel Hahler
5530d3e15d Merge pull request #5120 from blueyed/minor
A collection of minor code tweaks
2019-04-15 16:32:20 +02:00
Daniel Hahler
ea79eb5c3f terminal summary: display passes after warnings
This displays passes (with output, `-rP`) before the short summary, and
before any other output from other plugins also.
2019-04-15 16:31:42 +02:00
Bruno Oliveira
c8b904a406 Merge pull request #5124 from blueyed/terminal-summary_failures
terminal: revisit summary_failures
2019-04-15 11:26:52 -03:00
Bruno Oliveira
d45fa7b212 Merge pull request #5123 from blueyed/clsname
TestReport: use class name in repr
2019-04-15 11:25:42 -03:00
Bruno Oliveira
852ca7ad59 Merge pull request #5114 from blueyed/fixtest
test_pytest_exit_returncode: ignore ResourceWarnings
2019-04-15 11:25:16 -03:00
Bruno Oliveira
006dc30476 Preparing release version 4.4.1 2019-04-15 14:24:17 +00:00
Daniel Hahler
45ba736c81 Merge pull request #5128 from blueyed/mark-is
Fix error message with unregistered markers
2019-04-15 16:23:54 +02:00
Bruno Oliveira
c453fe7053 Merge pull request #5118 from blueyed/mm
Merge master into features
2019-04-15 11:21:59 -03:00
Daniel Hahler
cc005af47e Fix error message with unregistered markers 2019-04-15 10:15:37 +02:00
Daniel Hahler
20c624efcf terminal: revisit summary_failures
- get the list of reports for teardown sections only once
- do not check option in loop
2019-04-15 06:47:51 +02:00
Daniel Hahler
b2be6c1a30 TestReport: use class name in repr 2019-04-15 05:47:45 +02:00
Daniel Hahler
c43a9c83ee doc: pytest_deselected: not only via keywords 2019-04-14 23:53:06 +02:00
Daniel Hahler
e804e419bc remove unnecessary newline 2019-04-14 23:53:06 +02:00
Daniel Hahler
992e7f7771 rename variable 2019-04-14 23:53:06 +02:00
Daniel Hahler
bd1a2e6435 fix typo 2019-04-14 23:53:06 +02:00
Daniel Hahler
1d137fd2fe minor: LFPlugin: de-indent code by returning if not active 2019-04-14 23:53:06 +02:00
Daniel Hahler
f1f1862b19 Update testing/test_runner.py 2019-04-14 23:26:56 +02:00
Daniel Hahler
6f0a5789fb Merge master into features 2019-04-14 23:22:21 +02:00
Daniel Hahler
cc78a533ae terminal: summary_errors: replace if with assert 2019-04-14 23:17:27 +02:00
Daniel Hahler
fd0b3e2e8b getreportopt: remove needless if 2019-04-14 23:17:27 +02:00
Daniel Hahler
f3dbe5a308 pytester: listoutcomes: assert instead of implicit if 2019-04-14 23:00:38 +02:00
Daniel Hahler
1da8ce65a6 pytester: raise_on_kwargs: ignore branch coverage 2019-04-14 23:00:38 +02:00
Daniel Hahler
1dd5f088fa test_pytest_exit_returncode: ignore ResourceWarnings
Fixes https://github.com/pytest-dev/pytest/issues/5088.
2019-04-14 21:55:15 +02:00
Daniel Hahler
6a73714b00 deselect_by_keyword: skip without expression
There is no need to iterate over all items always, if `-k` is not
specified.
2019-04-14 19:01:33 +02:00
Daniel Hahler
6371243c10 summary_passes: use bold green for report headers 2019-04-14 15:21:11 +02:00
Daniel Hahler
533e610a35 Merge pull request #5098 from blueyed/fix-syspath_prepend
monkeypatch.syspath_prepend: invalidate import cache
2019-04-13 18:46:16 +02:00
Daniel Hahler
8fd5a658eb monkeypatch.syspath_prepend: invalidate import cache
This was done with testdir only, and uses the fixed monkeypatch method
there now.
2019-04-13 16:15:44 +02:00
Anthony Sottile
c3b7efc818 Merge pull request #5097 from asottile/unknown_kwargs_param
Produce a warning when unknown arguments are passed to pytest.param()
2019-04-12 13:30:07 -07:00
Anthony Sottile
43e7401c91 Produce a warning when unknown arguments are passed to pytest.param() 2019-04-12 13:00:39 -07:00
Bruno Oliveira
a9e850f749 Merge pull request #5096 from asottile/docs_highlight
blacken-docs more code samples in docs
2019-04-12 10:00:26 -03:00
Anthony Sottile
da2e092163 pre-commit autoupdate 2019-04-12 04:52:47 -07:00
Anthony Sottile
8449294e5d blacken-docs more code samples in docs 2019-04-12 04:50:26 -07:00
Bruno Oliveira
19035f4b55 Merge pull request #5068 from blueyed/reportchars
Add support for reportchars=A (`-rA`)
2019-04-12 08:13:22 -03:00
Bruno Oliveira
48ed437e70 Merge pull request #5087 from samueljsb/issue/4907
Show XFail reason as part of JUnitXML message field
2019-04-11 19:20:21 -03:00
Bruno Oliveira
14d3d9187f Remove partial unicode characters from summary messages in Python 2 2019-04-11 19:01:21 -03:00
Samuel Searles-Bryant
a37d1df089 Show XFail reason as part of JUnitXML message field
Fixes #4907
2019-04-11 22:26:05 +01:00
Daniel Hahler
97cd5f0deb Merge pull request #5094 from blueyed/merge-master
Merge master into festures
2019-04-11 23:05:29 +02:00
Bruno Oliveira
1dafe969d1 Merge pull request #5093 from blueyed/tbreportdemo
docs: tbreportdemo: remove obsolete comment
2019-04-11 13:07:02 -03:00
Daniel Hahler
8b2fcf517c Merge master 2019-04-11 13:28:36 +02:00
Daniel Hahler
42e60d935a doc/changelog 2019-04-11 11:44:04 +02:00
Daniel Hahler
1f66e3b0d0 docs: tbreportdemo: remove obsolete comment 2019-04-11 11:39:23 +02:00
Daniel Hahler
b3759372ad Merge pull request #5082 from blueyed/pytester-raise_on_kwargs
pytester: improve/fix kwargs validation
2019-04-11 00:46:18 +02:00
Bruno Oliveira
f5d2b199e2 Merge pull request #5069 from blueyed/cleanup-summary-to-terminal
cleanup: move terminal summary code to terminal plugin
2019-04-10 19:32:01 -03:00
Bruno Oliveira
bc157417e1 Merge pull request #5051 from blueyed/fix-test
Fix test_conftest when run via pytest-randomly
2019-04-10 19:08:28 -03:00
Daniel Hahler
12133d4eb7 changelog [ci skip] 2019-04-10 23:15:25 +02:00
Daniel Hahler
148f2fc72c Fix test_error_during_readouterr: syspathinsert is unused 2019-04-10 21:57:45 +02:00
Daniel Hahler
5d9d12a6be pytester: improve/fix kwargs validation 2019-04-10 21:57:45 +02:00
Daniel Hahler
dde27a2305 changelog [ci skip] 2019-04-10 21:39:51 +02:00
Daniel Hahler
10fa66e5b5 Merge pull request #5059 from blueyed/pytester-popen-run-stdin
pytester: allow passing in stdin to run/popen
2019-04-10 20:32:22 +02:00
Bruno Oliveira
5e26304d81 Merge pull request #5075 from blueyed/console_output_style
terminal: console_output_style: document "count" with help
2019-04-09 20:54:12 -03:00
Bruno Oliveira
d0860a339b Merge pull request #5076 from blueyed/_show_progress_info
terminal: store console_output_style in _show_progress_info
2019-04-09 20:37:50 -03:00
Daniel Hahler
fcbfdef11b Merge pull request #5071 from blueyed/prefer-fast
Add a conftest to prefer faster tests
2019-04-10 01:22:24 +02:00
Daniel Hahler
b84f826fc8 test_run_stdin: add sleep 2019-04-10 00:03:49 +02:00
Daniel Hahler
ec46864922 run: pass through stdin, just close then 2019-04-10 00:02:38 +02:00
Daniel Hahler
c36a90531a Move CLOSE_STDIN to class 2019-04-10 00:01:15 +02:00
Daniel Hahler
3fa329c9e9 Merge pull request #5074 from blueyed/trace
pdb: add test for --trace with --pdbcls
2019-04-08 18:48:44 +02:00
Daniel Hahler
a70e5f119e terminal: store console_output_style in _show_progress_info
Avoids ini lookups.
2019-04-08 04:34:26 +02:00
Daniel Hahler
b6b7185b7b terminal: console_output_style: document "count" with help 2019-04-08 04:32:53 +02:00
Daniel Hahler
4fb7a91a5e pdb: add test for --trace with --pdbcls
Ensures that https://github.com/pytest-dev/pytest/issues/4111 is fixed,
which happened in 92a2884b as a byproduct.
2019-04-08 03:49:03 +02:00
Daniel Hahler
ff5e98c654 Change noqa comment to pragma 2019-04-08 03:48:42 +02:00
Daniel Hahler
2662c400ba dedent 2019-04-07 20:04:31 +02:00
Daniel Hahler
d8d835c1f5 minor: use functools.partial 2019-04-07 19:49:18 +02:00
Daniel Hahler
06029d11d3 Refactor into TerminalReporter.short_test_summary 2019-04-07 19:49:18 +02:00
Daniel Hahler
4c0ba6017d Add a conftest to prefer faster tests
This uses pytest_collection_modifyitems for pytest's own tests to order
them, preferring faster ones via quick'n'dirty heuristics only for now.
2019-04-07 19:11:17 +02:00
Daniel Hahler
c70ecd49ca cleanup: move terminal summary code to terminal plugin
Fixes https://github.com/pytest-dev/pytest/issues/5067.
2019-04-07 18:22:04 +02:00
Daniel Hahler
50edab8004 Add tests for reportchars=a
Ref: https://github.com/pytest-dev/pytest/issues/5066
2019-04-07 18:05:33 +02:00
Daniel Hahler
b4b9f788af Support reportchars=A (really all, including passed) 2019-04-07 18:05:33 +02:00
Daniel Hahler
a7e49e6c07 reportchars: fix/improve help message 2019-04-07 18:05:33 +02:00
Daniel Hahler
2b1ae8a66d __tracebackhide__ for check 2019-04-06 15:00:23 +02:00
Daniel Hahler
2ebb69b50a py2 fixes 2019-04-06 15:00:12 +02:00
Daniel Hahler
4fca86e2af testdir.popen: use kwargs with defaults for stdout/stderr 2019-04-06 12:13:48 +02:00
Daniel Hahler
9ad00714ba pytester: allow passing in stdin to run/popen 2019-04-06 12:13:28 +02:00
Bruno Oliveira
b549438423 Merge pull request #5058 from blueyed/merge-master-into-features
Merge master into features
2019-04-05 14:28:48 -03:00
Daniel Hahler
377888140f Merge master into features
Conflicts:
	testing/test_pdb.py
2019-04-05 17:50:32 +02:00
Daniel Hahler
df377b589f use wcwidth 2019-04-05 17:43:11 +02:00
Bruno Oliveira
87ce586d29 Merge pull request #5055 from blueyed/showhelp-lazy-fullwidth
showhelp: move tw.fullwidth out of the loop
2019-04-05 12:11:47 -03:00
Daniel Hahler
f599172add test with 😄 in message 2019-04-05 16:08:11 +02:00
Daniel Hahler
e20b39d928 showhelp: move tw.fullwidth out of the loop 2019-04-05 15:14:02 +02:00
Bruno Oliveira
4f33f46a02 Merge pull request #5026 from blueyed/compare-len-diff
Display number of different items with sequence/dict comparisons
2019-04-05 08:53:48 -03:00
Daniel Hahler
159704421e change separator to hyphen 2019-04-05 12:21:24 +02:00
Daniel Hahler
0f965e57a2 changelog, fix branch coverage 2019-04-05 12:12:29 +02:00
Daniel Hahler
8011ff5bda Add _sys_snapshot fixture and use it with more tests 2019-04-05 11:55:23 +02:00
Daniel Hahler
899e74aa14 tests: harden test_immediate_initialiation_and_incremental_are_the_same 2019-04-05 11:55:23 +02:00
Daniel Hahler
66f743c45a Fix test_conftest when run via pytest-randomly 2019-04-05 11:55:23 +02:00
Daniel Hahler
8ad99c5cab Merge pull request #5035 from blueyed/cache-glob
Support glob argument with ``--cache-show``
2019-04-05 10:25:19 +02:00
Jeffrey Rackauckas
da3f836ee3 Added the junit_log_passing_tests ini flag. 2019-04-04 20:26:48 -07:00
Daniel Hahler
37ecca3ba9 factor out _get_line_with_reprcrash_message 2019-04-04 22:13:28 +02:00
Daniel Hahler
3d0ecd03ed Display message from reprcrash in short test summary
This is useful to see common patterns easily, but also for single
failures already.
2019-04-04 18:49:13 +02:00
Daniel Hahler
eb5b2e0db5 Support glob argument with `--cache-show` 2019-04-04 18:10:39 +02:00
Daniel Hahler
47d92a0d96 Add tests and improve messages 2019-04-04 17:53:39 +02:00
Daniel Hahler
7f1bf44aa8 _compare_eq_dict: display number of different items 2019-04-04 17:16:21 +02:00
Daniel Hahler
5fec793bc7 _compare_eq_sequence: display number of extra items 2019-04-04 17:16:21 +02:00
Bruno Oliveira
e04936fc29 Merge pull request #5042 from blueyed/merge-regen-master-into-features
Merge master into features (with regen)
2019-04-04 10:44:30 -03:00
Daniel Hahler
13a9d876f7 Merge pull request #5037 from blueyed/regen
docs: revisit/fix regen
2019-04-04 13:36:47 +02:00
Ondřej Súkup
77526f412c Skip test_source_mtime_long_long on 32bit and lower platforms 2019-04-04 13:14:46 +02:00
Daniel Hahler
0d4636b056 Merge pull request #5034 from blueyed/run-last-failure-report
run-last-failure: improve reporting
2019-04-04 00:40:40 +02:00
Daniel Hahler
a65edf6711 Merge pull request #5028 from blueyed/fix-wrap_session-exit-code
wrap_session: restore old behavior for initstate=1
2019-04-04 00:39:38 +02:00
Bruno Oliveira
973301b675 Merge pull request #5041 from blueyed/fix-pdbcls-regression
pdb: try to import --pdbcls in pytest_configure only
2019-04-03 19:23:43 -03:00
Daniel Hahler
757ada2fd2 pdb: try to import --pdbcls in pytest_configure only
Fixes https://github.com/pytest-dev/pytest/issues/5039.
2019-04-03 22:35:18 +02:00
Daniel Hahler
e88aa957ae Merge pull request #4854 from blueyed/pdb-skip
pdb: add option to skip `pdb.set_trace()`
2019-04-03 22:25:38 +02:00
Daniel Hahler
8907fedc79 Merge master into features (with regen branch) 2019-04-03 22:11:00 +02:00
Daniel Hahler
befc8a3f10 Update via https://github.com/pytest-dev/regendoc/pull/8 2019-04-03 22:08:44 +02:00
Daniel Hahler
5935fbaa7a doc/en/Makefile: stabilize output between regendoc versions 2019-04-03 22:07:33 +02:00
Daniel Hahler
e8eaebe595 tox.ini: regen: clear pytest cache for stable outcome 2019-04-03 19:53:00 +02:00
Daniel Hahler
cec2dd6a7c doc/en/Makefile: allow passing in REGENDOC_FILES
This allows for:

> make -C doc/en regen REGENDOC_FILES=example/parametrize.rst
2019-04-03 19:53:00 +02:00
Daniel Hahler
266bf2c007 doc: make regen: replace trailing spaces already 2019-04-03 17:34:26 +02:00
Daniel Hahler
1f5a61e4ef run-last-failure: improve reporting 2019-04-03 16:27:12 +02:00
Bruno Oliveira
46df1d5fcf Merge pull request #5031 from blueyed/pytester-addopts
pytester: use monkeypatch with Testdir
2019-04-03 11:26:49 -03:00
Daniel Hahler
d91527599a pytester: use monkeypatch with Testdir 2019-04-03 15:02:53 +02:00
Bruno Oliveira
1410d3dc9a Merge pull request #5029 from blueyed/minor
Minor: doc, import
2019-04-03 08:58:12 -03:00
Daniel Hahler
7538aa7bb9 minor: check_interactive_exception: use Skipped 2019-04-03 11:45:45 +02:00
Daniel Hahler
db34bf01b6 doc: minor whitespace, punctuation 2019-04-03 11:45:45 +02:00
Daniel Hahler
9434541090 doc: mention that pytest.fixture's param is in request.param 2019-04-03 11:45:45 +02:00
Daniel Hahler
cc90bcce4c wrap_session: restore old behavior for initstate=1 2019-04-03 05:09:21 +02:00
Bruno Oliveira
15ea5cef46 Merge pull request #4943 from blueyed/remove-silence_logging_at_shutdown
capture: do not set logging.raiseExceptions = False
2019-04-02 22:46:15 -03:00
Daniel Hahler
32a8d503a2 Merge pull request #5005 from blueyed/essential_plugins
Split out list of essential plugins
2019-04-03 02:45:19 +02:00
Daniel Hahler
8c734dfc2f Split out list of essential plugins
Fixes https://github.com/pytest-dev/pytest/issues/4976.
2019-04-02 14:39:56 +02:00
Daniel Hahler
08ded2927a capture: do not set logging.raiseExceptions = False
Ref: https://github.com/pytest-dev/pytest/issues/4942
2019-04-02 13:20:39 +02:00
Zac Hatfield-Dodds
1c9dcf1f39 Merge pull request #4935 from Zac-HD/warn-unknown-marks
Emit warning on unknown marks via decorator
2019-04-02 21:29:09 +11:00
Zac Hatfield-Dodds
cab4069f42 Clarify mark.__getattr__ 2019-04-02 12:31:42 +11:00
Zac Hatfield-Dodds
4f6c67658c Use mark-specific warning type
So that we can ignore it in self-tests.
2019-04-01 12:38:33 +11:00
Zac Hatfield-Dodds
cda9ce198a Register marks from self-tests 2019-04-01 10:52:43 +11:00
Zac Hatfield-Dodds
9121138a1b Emit warning for unknown marks 2019-04-01 10:40:18 +11:00
Zac Hatfield-Dodds
407d74be27 Merge pull request #5015 from Zac-HD/mark-warning-prep
Pre-PR for warnings on unknown markers
2019-04-01 10:07:43 +11:00
Bruno Oliveira
49d690d137 Merge pull request #5014 from nicoddemus/release-4.4.0
Release 4.4.0
2019-03-31 18:14:27 -03:00
Daniel Hahler
deade370b9 Update doc/en/mark.rst
Co-Authored-By: Zac-HD <Zac-HD@users.noreply.github.com>
2019-04-01 07:13:45 +11:00
Zac-HD
00810b9b2a Register "issue" mark for self-tests 2019-03-31 14:22:30 +11:00
Zac-HD
bcc08ffe4d More docs on registering marks 2019-03-31 14:22:30 +11:00
Zac-HD
ba1fc02a9b Register mark used by pytester 2019-03-31 14:22:30 +11:00
Zac-HD
38d687f7c7 Fix typos in comments 2019-03-31 14:22:30 +11:00
Daniel Hahler
4621638f07 Update CHANGELOG.rst
Co-Authored-By: nicoddemus <nicoddemus@gmail.com>
2019-03-29 20:29:40 -03:00
Bruno Oliveira
8881b201aa Preparing release version 4.4.0 2019-03-29 20:49:18 +00:00
Bruno Oliveira
278b289f37 Merge pull request #4968 from blueyed/pdb-do_debug-quit
pdb: do not raise outcomes.Exit with quit in debug
2019-03-29 16:22:02 -03:00
Daniel Hahler
e7ade066b6 Merge pull request #5011 from blueyed/merge-master-into-features
Merge master into features
2019-03-29 18:35:13 +01:00
Daniel Hahler
dee520e310 Merge pull request #5008 from blueyed/setup-cfg-tool-pytest
setup.cfg: use existing [tool:pytest] (ignoring [pytest])
2019-03-29 16:47:31 +01:00
Daniel Hahler
adebfd0a84 pdb: add option to skip pdb.set_trace() 2019-03-29 11:13:38 +01:00
Daniel Hahler
4e931b258d Merge master into features 2019-03-29 11:05:46 +01:00
Daniel Hahler
4011021823 pdb: do not raise outcomes.Exit with quit in debug 2019-03-29 11:02:34 +01:00
Daniel Hahler
bfda2a0050 setup.cfg: use existing [tool:pytest] (ignoring [pytest]) 2019-03-29 10:59:27 +01:00
Bruno Oliveira
2812c087ec Merge pull request #5010 from garytyler/docupdate
Update docs for 'pytest_cmdline_parse' hook to note availability limi…
2019-03-28 22:32:50 -03:00
Bruno Oliveira
6b5cddc48a Merge pull request #4951 from blueyed/fix-pdb-capfix
pdb: handle capturing with fixtures only
2019-03-28 20:34:28 -03:00
Gary Tyler
403f556928 Update docs for 'pytest_cmdline_parse' hook to note availability liminations 2019-03-28 19:25:55 -04:00
Bruno Oliveira
d8ef86aadf Merge pull request #4993 from blueyed/stepwise-report
stepwise: report status via pytest_report_collectionfinish
2019-03-28 20:24:18 -03:00
Bruno Oliveira
a9fe1e159a Merge pull request #4965 from nicoddemus/serialization-hooks
Serialization hooks
2019-03-28 20:22:19 -03:00
Bruno Oliveira
65c8e8a09e Rename hooks: to/from_serializable 2019-03-28 13:41:56 -03:00
Daniel Hahler
46d9243eb0 changelog 2019-03-28 11:56:53 +01:00
Daniel Hahler
63a01bdb33 Factor out pytestPDB._is_capturing 2019-03-28 11:49:01 +01:00
Daniel Hahler
d53209956b test_pdb_continue_with_recursive_debug: mock pdb.set_trace 2019-03-28 11:49:01 +01:00
Daniel Hahler
951213ee09 Use new suspend/resume in global_and_fixture_disabled 2019-03-28 11:49:01 +01:00
Daniel Hahler
ae067df941 add test_pdb_continue_with_recursive_debug 2019-03-28 11:49:01 +01:00
Daniel Hahler
40718efacc Fix/revisit do_continue with regard to conditions 2019-03-28 11:49:01 +01:00
Daniel Hahler
d406786a8d pdb: handle capturing with fixtures only 2019-03-28 11:49:01 +01:00
Daniel Hahler
0ac069da13 Merge pull request #5006 from blueyed/capture-clean
tests: ensure cleanup with configs via get_config()
2019-03-28 11:38:30 +01:00
Daniel Hahler
d17ea7a9c0 tests: ensure cleanup with configs via get_config()
Also done in test_pluginmanager, although no resource warnings are
there at least.

Fixes https://github.com/pytest-dev/pytest/issues/4355.
2019-03-28 00:14:13 +01:00
Daniel Hahler
c92021fc4f Merge pull request #5003 from blueyed/off
Fix off-by-one error with lineno in mark collection error
2019-03-28 00:09:53 +01:00
Daniel Hahler
50a5cebba8 Merge pull request #5002 from blueyed/report
skipping: factor out _get_pos, pass only config to _get_report_str
2019-03-27 23:07:11 +01:00
Bruno Oliveira
6c602c2282 Merge pull request #4995 from youknowone/disble_test_id_escaping
add ini option to disable string escape for parametrization
2019-03-27 17:34:35 -03:00
Daniel Hahler
76c70cbf4c Fix off-by-one error with lineno in mark collection error 2019-03-27 17:44:52 +01:00
Bruno Oliveira
3d9e68ecfd Update doc/en/parametrize.rst 2019-03-28 00:07:28 +09:00
Jeong YunWon
8b0b7156d9 Fix glitches of original patch of disable-test-id-escaping 2019-03-28 00:07:28 +09:00
ApaDoctor
cf6e2ceafd add ini option to disable string escape for parametrization 2019-03-28 00:07:28 +09:00
Bruno Oliveira
69a55d334a Merge pull request #5004 from blueyed/doc-pdb
doc: fix note about output capturing with pdb
2019-03-26 20:20:05 -03:00
Bruno Oliveira
241b7433cd Merge pull request #4978 from blueyed/exit-from-from_assertrepr_compare
Do not swallow outcomes.Exit in assertrepr_compare
2019-03-26 18:39:13 -03:00
Bruno Oliveira
057c97812b Merge pull request #4975 from blueyed/verbose-fixes
Fix usages of "verbose" option
2019-03-26 18:38:39 -03:00
Bruno Oliveira
02188e399d Merge pull request #4987 from blueyed/collect-tbstyle-repr_failure
CollectError.repr_failure: honor explicit tbstyle option
2019-03-26 18:37:49 -03:00
Bruno Oliveira
aae02863db Merge pull request #4999 from nicoddemus/cmdline_parse-early
Docs: modules implementing pytest_cmdline_parse can be early-loaded
2019-03-26 18:14:31 -03:00
Daniel Hahler
49f36bb028 Merge pull request #4988 from blueyed/logging-close
logging: close log_file_handler
2019-03-26 19:57:57 +01:00
Daniel Hahler
52730f6330 doc: fix note about output capturing with pdb
[skip travis]
2019-03-26 18:33:00 +01:00
Daniel Hahler
538efef1ba logging: close log_file_handler
While it should be closed in logging's shutdown [1], the following would
still issue a ResourceWarning:

```
import logging

log_file_handler = logging.FileHandler("temp.log", mode="w", encoding="UTF-8")

root_logger = logging.getLogger()
root_logger.addHandler(log_file_handler)
root_logger.removeHandler(log_file_handler)
root_logger.error("error")

del log_file_handler
```

It looks like the weakref might get lost for some reason.

See https://github.com/pytest-dev/pytest/pull/4981/commits/92ffe42b45 / #4981
for more information.

1: c1419578a1/Lib/logging/__init__.py (L2107-L2139)
2019-03-26 18:24:19 +01:00
Bruno Oliveira
9311d822c7 Fix assertion in pytest_report_unserialize 2019-03-26 12:47:31 -03:00
Daniel Hahler
351529cb50 skipping: factor out _get_pos, pass only config to _get_report_str 2019-03-26 16:29:16 +01:00
Daniel Hahler
94a2e3dddc stepwise: report status via pytest_report_collectionfinish 2019-03-26 13:20:33 +01:00
Bruno Oliveira
ee96214a8d Merge pull request #5000 from blueyed/merge-master-into-features
Merge master into features
2019-03-26 09:01:46 -03:00
Daniel Hahler
e1ae469504 Merge master into features 2019-03-26 10:23:21 +01:00
Daniel Hahler
0d00be4f4f Do not swallow outcomes.Exit in assertrepr_compare 2019-03-26 10:20:00 +01:00
Daniel Hahler
23146e7527 Fix usages of "verbose" option
With `-qq` `bool(config.getoption("verbose"))` is True; it needs to be
checked for `> 0`.
2019-03-26 10:11:25 +01:00
Daniel Hahler
b18df936ea changelog 2019-03-26 10:06:53 +01:00
Daniel Hahler
4148663706 Merge pull request #4979 from blueyed/minor
Minor: whitespace, typo, docs
2019-03-26 10:01:13 +01:00
Bruno Oliveira
3e1971eb16 Merge pull request #4994 from blueyed/test_as_errors-subprocess
test_as_errors: use subprocess with `-W`
2019-03-25 20:50:15 -03:00
Bruno Oliveira
bcdb86ee7e Merge pull request #4991 from blueyed/fix-tests
Fix pytest's own tests with `-W error::ResourceWarning`
2019-03-25 20:47:51 -03:00
Bruno Oliveira
2d77018d1b Improve coverage for _report_unserialization_failure 2019-03-25 20:16:59 -03:00
Bruno Oliveira
ceef0af1ae Improve coverage for to_json() with paths in reports 2019-03-25 20:16:59 -03:00
Bruno Oliveira
e4eec3416a Note that tests from xdist reference the correct xdist issues 2019-03-25 20:16:59 -03:00
Bruno Oliveira
645774295f Add CHANGELOG 2019-03-25 20:16:59 -03:00
Bruno Oliveira
f2e0c740d3 Code review suggestions 2019-03-25 20:16:59 -03:00
Bruno Oliveira
d856f4e51f Make sure TestReports are not collected as test classes 2019-03-25 20:16:59 -03:00
Bruno Oliveira
7b9a414524 Add pytest_report_serialize and pytest_report_unserialize hooks
These hooks will be used by pytest-xdist and pytest-subtests to
serialize and customize reports.
2019-03-25 20:16:59 -03:00
Bruno Oliveira
0c63f99016 Add experimental _to_json and _from_json to TestReport and CollectReport
This methods were moved from xdist (ca03269).

Our intention is to keep this code closer to the core, given that it
might break easily due to refactorings.

Having it in the core might also allow to improve the code by moving
some responsibility to the "code" objects (ReprEntry, etc) which
are often found in the reports.

Finally pytest-xdist and pytest-subtests can use those functions
instead of coding it themselves.
2019-03-25 20:16:59 -03:00
Daniel Hahler
3bc9cbea63 Merge pull request #4989 from blueyed/test_collect_capturing
test_collect_capturing: cover captured stderr
2019-03-25 23:41:53 +01:00
Daniel Hahler
6eff3069da Merge pull request #4851 from blueyed/addopts-vv
ci: PYTEST_ADDOPTS=-vv
2019-03-25 23:41:33 +01:00
Daniel Hahler
58a14b6b99 Merge pull request #4986 from blueyed/fnmatch_lines-list
tests: fnmatch_lines: use list
2019-03-25 23:31:04 +01:00
Daniel Hahler
b53bf44139 Merge pull request #4985 from blueyed/assert-from_current
ExceptionInfo.from_current: assert current exception
2019-03-25 23:28:58 +01:00
Daniel Hahler
d8758443bd Merge pull request #4983 from blueyed/coveragerc
.coveragerc: use "src" only from current dir
2019-03-25 23:28:23 +01:00
Daniel Hahler
51f64c2920 Merge pull request #4980 from blueyed/fixup_namespace_packages
monkeypatch.syspath_prepend: call fixup_namespace_packages
2019-03-25 23:10:00 +01:00
Bruno Oliveira
cea42ff9e4 Docs: modules implementing pytest_cmdline_parse can be early-loaded
Related to #4974
2019-03-25 18:43:06 -03:00
Daniel Hahler
2df9d05981 Merge pull request #4982 from blueyed/cover
Revisit coverage in some tests
2019-03-25 10:28:55 +01:00
Daniel Hahler
4142c41ffc Merge pull request #4990 from blueyed/session-repr
Session repr
2019-03-24 19:54:18 +01:00
Daniel Hahler
de44293d59 CollectError.repr_failure: honor explicit tbstyle option 2019-03-24 11:24:19 +01:00
Daniel Hahler
5efe6ab93c test_log_cli_auto_enable: get stdout once 2019-03-24 11:22:07 +01:00
Daniel Hahler
ce59f42ce1 revisit test_root_logger_affected 2019-03-24 11:21:13 +01:00
Daniel Hahler
7da7b9610c minor: whitespace 2019-03-24 11:20:24 +01:00
Daniel Hahler
d44e42ec15 doc: improve warning_record_to_str 2019-03-24 11:20:01 +01:00
Daniel Hahler
0ea1889265 test_as_errors: use subprocess with -W
Ref: https://github.com/pytest-dev/pytest/pull/4981
2019-03-24 11:17:55 +01:00
Daniel Hahler
6352cf2374 test_implicit_bad_repr1: harden/cleanup 2019-03-24 11:15:40 +01:00
Daniel Hahler
3127ec737b Fix pytest's own tests with -W error::ResourceWarning 2019-03-24 11:05:00 +01:00
Daniel Hahler
aa0b657e58 Add Session.__repr__ 2019-03-24 11:02:58 +01:00
Daniel Hahler
d0f3f26fff test_collect_capturing: cover captured stderr 2019-03-23 23:17:07 +01:00
Daniel Hahler
08f3b02dfc tests: fnmatch_lines: use list
For strings fnmatch_lines converts it into a Source objects, splitted on
newlines.  This is not necessary here, and it is more consistent to use
lists here in the first place.
2019-03-23 11:36:18 +01:00
Daniel Hahler
2d690b83bf ExceptionInfo.from_current: assert current exception 2019-03-23 00:29:36 +01:00
Daniel Hahler
0642da0145 .coveragerc: use "src" only from current dir
This avoids including generated test files with "src" in their path.
2019-03-22 17:48:14 +01:00
Daniel Hahler
afa985c135 Revisit coverage in some tests 2019-03-22 17:26:16 +01:00
Daniel Hahler
fd64fa1863 Revisit test_importplugin_error_message
Should be more helpful in case of errors than before:

    >       assert re.match(expected_message, str(excinfo.value))
    E       _pytest.warning_types.PytestWarning: asserting the value None, please use "assert is None"

    https://travis-ci.org/pytest-dev/pytest/jobs/509970576#L208
2019-03-22 17:02:26 +01:00
Daniel Hahler
56dc01ffe0 minor: revisit _possibly_invalidate_import_caches 2019-03-22 17:02:26 +01:00
Daniel Hahler
5df45f5b27 Use fixup_namespace_packages also with pytester.syspathinsert 2019-03-22 17:02:26 +01:00
Daniel Hahler
05d55b86df tests: minor sys.path cleanup 2019-03-22 16:20:55 +01:00
Daniel Hahler
475119988c monkeypatch.syspath_prepend: call fixup_namespace_packages
Without the patch the test fails as follows:

            # Prepending should call fixup_namespace_packages.
            monkeypatch.syspath_prepend("world")
    >       import ns_pkg.world
    E       ModuleNotFoundError: No module named 'ns_pkg.world'
2019-03-22 15:29:08 +01:00
Daniel Hahler
7a6bcc3639 Add reference to test_cmdline_python_namespace_package 2019-03-22 13:23:44 +01:00
Daniel Hahler
8e125c9759 doc/en/reference.rst: whitespace/alignment 2019-03-22 13:23:44 +01:00
Daniel Hahler
ade773390a minor: rename inner test 2019-03-22 13:23:44 +01:00
Daniel Hahler
5c26ba9cb1 minor: wrap_session: s/Spurious/unexpected/ 2019-03-22 13:23:44 +01:00
Daniel Hahler
5a544d4fac tox.ini: usedevelop implies skipsdist 2019-03-22 13:23:44 +01:00
Daniel Hahler
2e7d6a6202 Fix test_assertrewrite in verbose mode
Fixes https://github.com/pytest-dev/pytest/issues/4879.
2019-03-22 13:00:35 +01:00
Daniel Hahler
ea7357bc58 ci: PYTEST_ADDOPTS=-vv in general
This is useful when viewing logs, especially with hanging tests.

Uses non-verbose mode with a single job for full coverage.
2019-03-22 07:56:15 +01:00
Bruno Oliveira
b3319a6074 Merge pull request #4944 from henrykironde/k-EXPRESSION
Add example for k flag
2019-03-21 19:33:53 -03:00
Bruno Oliveira
c9628c52d6 Merge pull request #4971 from bskinn/patch-1
Fix pytestmark syntax in reference.rst
2019-03-21 18:59:25 -03:00
Brian Skinn
dcbdcc729b Fix pytestmark syntax in reference.rst
pytest 4.3.1 throws an error if `pytestmark` is set to a tuple of marks; it appears to insist on a list.



With `pytestmark = [pytest.mark.api, pytest.mark.good]`:

```
============================== test session starts ==============================
platform win32 -- Python 3.6.3, pytest-4.3.1, py-1.8.0, pluggy-0.9.0
rootdir: C:\Temp\git\sphobjinv, inifile: tox.ini
plugins: timeout-1.3.3
collected 48 items / 41 deselected / 7 selected

tests\test_api_good.py .......                                             [100%]

==================== 7 passed, 41 deselected in 0.15 seconds ====================
```


With `pytestmark = (pytest.mark.api, pytest.mark.good)`:
```
==================================== ERRORS =====================================
____________________ ERROR collecting tests/test_api_good.py ____________________
env\lib\site-packages\_pytest\runner.py:226: in from_call
    result = func()
env\lib\site-packages\_pytest\runner.py:289: in <lambda>
    call = CallInfo.from_call(lambda: list(collector.collect()), "collect")
env\lib\site-packages\_pytest\python.py:435: in collect
    self._inject_setup_module_fixture()
env\lib\site-packages\_pytest\python.py:447: in _inject_setup_module_fixture
    setup_module = _get_non_fixture_func(self.obj, "setUpModule")
env\lib\site-packages\_pytest\python.py:255: in obj
    self.own_markers.extend(get_unpacked_marks(self.obj))
env\lib\site-packages\_pytest\mark\structures.py:244: in get_unpacked_marks
    return normalize_mark_list(mark_list)
env\lib\site-packages\_pytest\mark\structures.py:259: in normalize_mark_list
    raise TypeError("got {!r} instead of Mark".format(mark))
E   TypeError: got (MarkDecorator(mark=Mark(name='api', args=(), kwargs={})), MarkDecorator(mark=Mark(name='good', args=(), kwargs={}))) instead of Mark
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
==================== 19 deselected, 1 error in 0.27 seconds =====================
```
2019-03-21 15:14:28 -04:00
Daniel Hahler
15d608867d Merge pull request #4966 from blueyed/fix-preparse
config: fix consider_preparse with missing argument to -p
2019-03-21 19:12:57 +01:00
Daniel Hahler
ea2c6b8a88 config: fix consider_preparse with missing argument to -p
This is only required after/with 415899d4 - otherwise argparse ensures
there is an argument already.
2019-03-21 17:05:22 +01:00
Daniel Hahler
0e6cf0ff28 Merge pull request #4967 from blueyed/p-no-default
Fix some issues related to "-p no:X" with default_plugins
2019-03-21 17:02:34 +01:00
Daniel Hahler
553951c443 Fix some issues related to "-p no:X" with default_plugins 2019-03-21 17:01:50 +01:00
Bruno Oliveira
15ef168821 Merge pull request #4962 from blueyed/test_report_collect_after_half_a_second
tests: add test_report_collect_after_half_a_second
2019-03-20 19:35:08 -03:00
Daniel Hahler
cc6e5ec345 tests: add test_report_collect_after_half_a_second
This is meant for stable coverage with "collecting X item(s)".
2019-03-20 22:13:11 +01:00
Daniel Hahler
77643122a8 Merge pull request #4963 from blueyed/twisted
ci: rename "trial" tox factor to "twisted"
2019-03-20 21:58:48 +01:00
Daniel Hahler
832cef953b Merge pull request #4964 from blueyed/mkdir
Revisit mkdir/_ensure_supporting_files in cacheprovider
2019-03-20 21:58:24 +01:00
Daniel Hahler
bcdbb6b677 Revisit mkdir/_ensure_supporting_files in cacheprovider
- cacheprovider: move call to _ensure_supporting_files

  This makes it less likely to have a race here (which is not critical),
  but happened previously probably with xdist, causing flaky coverage with
  `if not readme_path.is_file():` etc checks in
  `_ensure_supporting_files`, which has been removed in the `features`
  branch already.
2019-03-20 19:00:11 +01:00
Daniel Hahler
543779fc43 tox: generic twisted factor 2019-03-20 18:41:48 +01:00
Daniel Hahler
2ade3d5c89 ci: rename "trial" tox factor to "twisted"
Ref: https://github.com/pytest-dev/pytest/pull/4848#issuecomment-467909204
2019-03-20 18:38:50 +01:00
Daniel Hahler
7939e5327c Merge pull request #4957 from blueyed/config-handle-pno-with-default-plugins
config: handle `-p no:plugin` with default plugins
2019-03-20 03:32:03 +01:00
Daniel Hahler
f7171034f9 terminal: remove unnecessary check in _get_progress_information_message
All calls to _get_progress_information_message are only done for
`_show_progress_info`, which is `False` with `capture=no`.
2019-03-20 03:04:41 +01:00
Daniel Hahler
c7c120fba6 terminal: handle "capture" option not being available
This is the case with `-p no:capture` now.
2019-03-20 03:01:26 +01:00
Daniel Hahler
415899d428 config: handle -p no:plugin with default plugins
`-p no:capture` should not load its fixtures in the first place.
2019-03-20 02:47:13 +01:00
Daniel Hahler
8dda5613ef Merge pull request #4956 from blueyed/home2
pytester: set HOME only with inline_run/popen
2019-03-20 02:29:29 +01:00
Daniel Hahler
714f2113bb Merge pull request #4929 from blueyed/fix-_factorytraceback-offset
Fix line offsets with `ScopeMismatch` errors
2019-03-20 01:30:58 +01:00
Daniel Hahler
a50b92ea67 pytester: set HOME only with inline_run/popen
Ref: https://github.com/pytest-dev/pytest/issues/4955
2019-03-20 01:15:51 +01:00
Daniel Hahler
da81c1e49a Merge pull request #4950 from blueyed/capture
Revisit capturing module: repr, doc fixes, minor
2019-03-20 01:12:22 +01:00
Bruno Oliveira
23ab43233e Merge pull request #4920 from nicoddemus/subtests-pytest-1367
Internal refactorings required for *external* pytest-subtests plugin
2019-03-19 18:57:11 -03:00
Bruno Oliveira
1a119a22d1 Internal refactorings in order to support the new pytest-subtests plugin
Related to #1367
2019-03-19 18:20:41 -03:00
Daniel Hahler
77c5191ad7 Merge pull request #4953 from blueyed/merge-master-into-features
Merge master into features
2019-03-19 04:13:31 +01:00
Daniel Hahler
7395501d1d Easier read with _colorama_workaround/_readline_workaround 2019-03-19 01:17:21 +01:00
Daniel Hahler
920bffbfbb Revisit _pytest.capture: repr, doc fixes, minor 2019-03-19 01:17:21 +01:00
Daniel Hahler
751c061d9a Merge master into features 2019-03-19 01:07:10 +01:00
Daniel Hahler
a624b84097 Merge pull request #4941 from blueyed/testdir-home
pytester: testdir: set $HOME to tmpdir
2019-03-18 23:02:15 +01:00
Daniel Hahler
c75dd10671 pytester: testdir: set $HOME to tmpdir
This avoids loading user configuration, which might interfere with test
results, e.g. a `~/.pdbrc.py` with pdb++.

Also sets USERPROFILE, which will be required with Python 3.8 [1].

1: https://bugs.python.org/issue36264
2019-03-18 20:55:39 +01:00
Bruno Oliveira
b696666f5a Merge pull request #4945 from blueyed/FDCapture-repr-None-targetfd_save
capture: fix FDCapture.__repr__ without targetfd_save
2019-03-18 13:09:30 -03:00
Bruno Oliveira
f4f6cb7532 Merge pull request #4946 from blueyed/fix-bench
Fix bench/bench.py without args
2019-03-18 13:04:12 -03:00
henrykironde
1e3d5a0412 Add example for k flag
Includes an example of multiple expressions
2019-03-17 22:33:16 -04:00
Daniel Hahler
98981276a0 capture: fix FDCapture.__repr__ without targetfd_save 2019-03-18 02:33:03 +01:00
Daniel Hahler
8c96b65082 Fix bench/bench.py without args
Fixes:

>   File "…/Vcs/pytest/src/_pytest/config/__init__.py", line 60, in main
>     config = _prepareconfig(args, plugins)
>   File "…/Vcs/pytest/src/_pytest/config/__init__.py", line 179, in _prepareconfig
>     raise TypeError(msg.format(args, type(args)))
> TypeError: `args` parameter expected to be a list or tuple of strings, got: 'empty.py' (type: <class 'str'>)
2019-03-18 02:28:41 +01:00
Bruno Oliveira
c926999cfb Merge pull request #4939 from smheidrich/mark_xfail_language
Minor grammar fixes in pytest.mark.xfail docs
2019-03-17 11:33:20 -03:00
smheidrich
519157cfcf Minor grammar fixes in pytest.mark.xfail docs 2019-03-17 10:14:40 +01:00
Bruno Oliveira
5d14362a75 Merge pull request #4936 from blueyed/use-blocked-plugin
Handle `-p plug` after `-p no:plug`
2019-03-16 12:21:33 -03:00
Daniel Hahler
15fe8c6e90 Handle -p plug after -p no:plug.
This can be used to override a blocked plugin (e.g. in "addopts") from the
command line etc.
2019-03-16 15:58:00 +01:00
Daniel Hahler
c1e01c2992 Merge pull request #4931 from blueyed/linematcher-list
pytester: LineMatcher: assert lines
2019-03-15 23:43:23 +01:00
Daniel Hahler
5e27ea5528 pytester: LineMatcher: assert Sequence when matching in order
This can be helpful when passing a set accidentally.
2019-03-15 23:07:08 +01:00
Bruno Oliveira
33d4c96aa2 Merge pull request #4830 from nicoddemus/warn-on-coroutine
Emit a warning when a coroutine test function is encountered
2019-03-15 09:51:34 -03:00
Bruno Oliveira
b3eb5d1eb7 Merge pull request #4932 from hroncok/sphinx2
Pin sphinx-removed-in to >= 0.2.0 to support Sphinx 2.0
2019-03-15 08:18:41 -03:00
Miro Hrončok
2af0a023c9 Pin sphinx-removed-in to >= 0.2.0 to support Sphinx 2.0
Fixes https://github.com/pytest-dev/pytest/issues/4912
2019-03-15 10:56:13 +01:00
Anthony Sottile
5f52d5ee17 Merge pull request #4927 from tkf/skip-doctest
Make pytest.skip work in doctest
2019-03-15 00:14:09 -07:00
Daniel Hahler
95701566f3 Update src/_pytest/outcomes.py
Co-Authored-By: tkf <takafumi.a@gmail.com>
2019-03-15 12:21:48 +09:00
Daniel Hahler
57be1d60dd Apply suggestions from code review
Co-Authored-By: tkf <takafumi.a@gmail.com>
2019-03-15 11:29:16 +09:00
Takafumi Arakaki
62f96eea6b Include documentation 2019-03-15 11:14:50 +09:00
Takafumi Arakaki
fa3cca51e1 Test pytest.skip in doctest 2019-03-15 11:06:57 +09:00
Daniel Hahler
d441fa66fe Fix line offsets with ScopeMismatch errors
Fixes https://github.com/pytest-dev/pytest/issues/4928.
2019-03-15 02:47:33 +01:00
Takafumi Arakaki
43aee15ba3 Make pytest.skip work in doctest 2019-03-15 10:20:46 +09:00
Bruno Oliveira
5c57d92978 Merge pull request #4926 from blueyed/merge-master-into-features
Merge master into features
2019-03-14 21:59:13 -03:00
Daniel Hahler
7afe17740f Merge master into features 2019-03-15 00:52:12 +01:00
Daniel Hahler
158432217c Merge pull request #4924 from blueyed/fix-pdbpp
Fix/harden some pdb tests
2019-03-15 00:51:12 +01:00
Daniel Hahler
437ff1c01a Merge pull request #4925 from blueyed/pm-super
pdb: post_mortem: use super()
2019-03-15 00:50:46 +01:00
Bruno Oliveira
40072b9511 Emit a warning when a async def function is not handled by a plugin
Fix #2224
2019-03-14 20:22:23 -03:00
Daniel Hahler
520af9d767 pdb: post_mortem: use super()
This is good practice in general, and I've seen it cause problems (MRO)
with pdb++.
2019-03-14 22:29:57 +01:00
Daniel Hahler
bdac9d3dd0 tests: improve test_pdb_interaction_doctest
- ignore pdbrc (might be done in general, but this was the only affected
  test)
- fail faster in case of unexpected failure
2019-03-14 19:16:34 +01:00
Daniel Hahler
37158f5303 tests: fix test_pdb_interaction_continue_recursive with pdbpp 2019-03-14 19:16:34 +01:00
Bruno Oliveira
612c3784e5 Merge pull request #4881 from blueyed/travis-cache
ci: Travis: disable cache by default, only for pre-commit
2019-03-14 12:39:47 -03:00
Daniel Hahler
951e07d71d Merge pull request #4919 from blueyed/opt
Optimize TracebackEntry.ishidden
2019-03-14 16:37:57 +01:00
Bruno Oliveira
36f774a8fb Merge pull request #4922 from hroncok/add_object_type
Remove deprecated Sphinx directive add_description_unit()
2019-03-14 12:31:34 -03:00
Bruno Oliveira
a2b921f890 Merge pull request #4921 from nicoddemus/mtime-test-for-4903
Add test for mtime issue in #4903
2019-03-14 10:56:08 -03:00
Bruno Oliveira
bd70f5c148 Add test for mtime issue in #4903 2019-03-14 10:16:08 -03:00
Miro Hrončok
134b957bf4 Remove deprecated Sphinx directive add_description_unit()
Partial solution for https://github.com/pytest-dev/pytest/issues/4912
2019-03-14 12:16:59 +01:00
Daniel Hahler
4d21dc4f2d Optimize TracebackEntry.ishidden
The expected behavior is that there is no "__tracebackhide__" attribute,
so use `getattr` instead of multiple try/except.
2019-03-14 01:02:46 +01:00
Bruno Oliveira
74416525d2 Merge pull request #4903 from bmwiedemann/y2038
Allow tests to pass after 2038
2019-03-13 20:07:25 -03:00
Bruno Oliveira
44cb51010c Improve CHANGELOG and code comment 2019-03-13 18:52:30 -03:00
Bruno Oliveira
90597226eb Merge pull request #4829 from nicoddemus/yield-tests-dead-code
Remove dead-code related to yield tests
2019-03-13 14:31:11 -03:00
Bruno Oliveira
7fb5ad82d9 Merge pull request #4916 from blueyed/pin-shinx
docs: pin Sphinx to <2.0
2019-03-12 22:55:24 -03:00
Daniel Hahler
f4bcb44025 docs: pin Sphinx to <2.0
Ref: https://github.com/pytest-dev/pytest/issues/4912
2019-03-13 02:36:15 +01:00
Bruno Oliveira
b7ae7a654b Remove callspec related block of code
It seems this is no longer required now that we don't support
yield tests anymore. The param attribute was added here:

91b6f2bda8/_pytest/python.py (L888-L891)
2019-03-12 20:10:59 -03:00
Bruno Oliveira
148e6a30c8 Improve coverage 2019-03-12 20:10:59 -03:00
Bruno Oliveira
47bd1688ed Remove dead-code related to yield tests
Just noticed some code that no longer is needed when we removed yield-tests
2019-03-12 20:10:59 -03:00
Daniel Hahler
6630d96253 Merge pull request #4914 from hroncok/issue4913
Fix pytest tests invocation with custom PYTHONPATH
2019-03-12 18:58:54 +01:00
Miro Hrončok
d32ab6029f Fix pytest tests invocation with custom PYTHONPATH
Fixes https://github.com/pytest-dev/pytest/issues/4913

Co-authored-by: Bruno Oliveira <nicoddemus@gmail.com>
2019-03-12 17:31:42 +01:00
Bruno Oliveira
76c00d1c09 Merge pull request #4909 from nicoddemus/release-4.3.1
Prepare release 4.3.1
2019-03-12 13:23:32 -03:00
Bernhard M. Wiedemann
489c61a22d Allow tests to pass after 2038
without this change, the python-apache-libcloud tests failed
in the year 2039 with

     fp.write(struct.pack("<ll", mtime, size))
 E   error: 'l' format requires -2147483648 <= number <= 2147483647
2019-03-10 05:22:21 +01:00
Bruno Oliveira
936f725b81 Merge pull request #4890 from blueyed/dead
pytester: remove unused anypython fixture
2019-03-06 14:35:23 -03:00
Daniel Hahler
c86d2daf81 pytester: remove unused anypython fixture
This became unused after ab9f6a75 (in 2009).
2019-03-06 17:42:21 +01:00
Daniel Hahler
a70c1ca100 ci: Travis: disable cache by default, only for pre-commit
For pip the usual http caching should be good enough.
This keeps the cache for pre-commit with the linting env for now.

Ref: https://github.com/pytest-dev/pytest/issues/3502
2019-03-05 23:12:11 +01:00
Daniel Hahler
4668ee03f6 Merge pull request #4887 from blueyed/merge-master-into-features
Merge master into features
2019-03-05 23:05:55 +01:00
Daniel Hahler
76687030f0 Merge branch 'master' into merge-master-into-features
Conflicts:
	appveyor.yml
	setup.py
2019-03-05 19:07:36 +01:00
Bruno Oliveira
23ea04f910 Merge pull request #4860 from nicoddemus/getfixturevalue-cleanup-1895
getfixturevalue does not correctly declare dependency with the calling fixture
2019-03-03 15:56:45 -03:00
Daniel Hahler
c334adc78f Apply suggestions from code review
Co-Authored-By: nicoddemus <nicoddemus@gmail.com>
2019-03-03 11:20:00 -03:00
Bruno Oliveira
35c85f0db9 Merge pull request #4876 from nicoddemus/show-testpaths-in-header-4875
Show testpaths option in the header if it has been used for collection
2019-03-02 13:01:50 -03:00
Bruno Oliveira
0deb7b1696 Do not show "inifile:" string if there's no configuration file 2019-03-02 11:45:08 -03:00
Bruno Oliveira
53b8aa065c Show testpaths option in the header if it has been used for collection
Fix #4875
2019-03-02 11:35:32 -03:00
Bruno Oliveira
6a2d122a50 Remove code debugging leftovers 2019-03-02 09:56:15 -03:00
Bruno Oliveira
d97473e551 Add test and CHANGELOG for #1895 2019-03-02 09:39:30 -03:00
Bruno Oliveira
525639eaa0 Rename fixtures testing file to be consistent with the module name 2019-03-02 09:37:30 -03:00
Bruno Oliveira
7dceabfcb2 Ensure fixtures obtained with getfixturevalue() are finalized in the correct order
Fix #1895
2019-03-02 09:36:16 -03:00
Daniel Hahler
e1f97e41e3 Merge pull request #4872 from blueyed/_ensure_supporting_files
cacheprovider: _ensure_supporting_files: remove unused branches
2019-03-02 02:35:07 +01:00
Daniel Hahler
2d2f6cd4fd cacheprovider: _ensure_supporting_files: remove unused branches
It is only called with empty/new dirs since 0385c273.
2019-03-01 22:51:45 +01:00
Bruno Oliveira
44c940765b Merge pull request #4868 from blueyed/pytester-unset-PYTEST_ADDOPTS
pytester: unset PYTEST_ADDOPTS
2019-03-01 18:48:36 -03:00
Daniel Hahler
db5cc35b44 pytester: unset PYTEST_ADDOPTS 2019-03-01 18:43:17 +01:00
Bruno Oliveira
84555c89de Merge pull request #4855 from blueyed/pdbcls-attr
--pdbcls: improve validation, and allow for "mod:attr.class"
2019-03-01 12:20:29 -03:00
Daniel Hahler
f7a3e001f7 pdb: allow for --pdbclass=mod:attr.class 2019-03-01 15:20:04 +01:00
Daniel Hahler
42561db1ae Merge pull request #4863 from blueyed/remove-import
Move import of  _format_explanation in _pytest.assertion.rewrite
2019-03-01 15:13:26 +01:00
Daniel Hahler
9cb71af9e5 _pytest.assertion.rewrite: move _format_explanation import 2019-03-01 14:13:28 +01:00
Daniel Hahler
a868a9ac13 pdb: validate --pdbcls option 2019-02-28 18:11:58 +01:00
Daniel Hahler
c7bbb2a788 Merge pull request #4833 from blueyed/merge-master
Merge master into features
2019-02-26 12:40:15 +01:00
Daniel Hahler
29112d7e0b Merge master into features 2019-02-26 11:48:10 +01:00
Bruno Oliveira
2cf1de3f2d Merge pull request #4727 from nicoddemus/early-load-4718
Change -p so it is possible to early load setuptools plugins
2019-02-25 10:05:51 -03:00
Anthony Sottile
c9e69438b1 Merge pull request #4822 from nicoddemus/funcsigs
Require funcsigs>=1.0 on Python 2.7
2019-02-24 09:14:09 -08:00
Bruno Oliveira
a0207274f4 -p option now can be used to early-load plugins by entry-point name
Fixes #4718
2019-02-24 13:20:17 -03:00
Bruno Oliveira
759d7fde5d Merge pull request #4786 from blueyed/av
AppVeyor: use xdist with pypy, drop pluggymaster
2019-02-24 12:17:59 -03:00
Bruno Oliveira
ede6387caa Require funcsigs>=1.0 on Python 2.7
Fix #4815
2019-02-24 12:11:08 -03:00
Daniel Hahler
dc8c27037a AppVeyor: drop pluggymaster 2019-02-23 20:15:11 +01:00
Daniel Hahler
63e7f8e340 Merge pull request #4817 from nicoddemus/merge-master-into-features
Merge master into features (including fix from 4816)
2019-02-23 08:24:21 +01:00
Bruno Oliveira
0ca1f6e0f4 Merge branch 'fix-new-pluggy' into merge-master-into-features 2019-02-22 18:59:51 -03:00
Bruno Oliveira
b9561e29ff Merge pull request #4808 from nicoddemus/merge-master-into-features
Merge master into features
2019-02-19 08:08:06 -03:00
244 changed files with 14393 additions and 7572 deletions

View File

@@ -1,6 +1,6 @@
[run]
include =
*/src/*
src/*
testing/*
*/lib/python*/site-packages/_pytest/*
*/lib/python*/site-packages/pytest.py
@@ -16,3 +16,11 @@ source = src/
*/lib/python*/site-packages/
*/pypy*/site-packages/
*\Lib\site-packages\
[report]
skip_covered = True
show_missing = True
exclude_lines =
\#\s*pragma: no cover
^\s*raise NotImplementedError\b
^\s*return NotImplemented\b

5
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,5 @@
# info:
# * https://help.github.com/en/articles/displaying-a-sponsor-button-in-your-repository
# * https://tidelift.com/subscription/how-to-connect-tidelift-with-github
tidelift: pypi/pytest
open_collective: pytest

View File

@@ -1,8 +1,10 @@
<!--
Thanks for submitting an issue!
Here's a quick checklist in what to include:
Here's a quick checklist for what to provide:
-->
- [ ] Include a detailed description of the bug or suggestion
- [ ] `pip list` of the virtual environment you are using
- [ ] a detailed description of the bug or suggestion
- [ ] output of `pip list` from the virtual environment you are using
- [ ] pytest and operating system versions
- [ ] Minimal example if possible
- [ ] minimal example if possible

View File

@@ -1,14 +1,16 @@
<!--
Thanks for submitting a PR, your contribution is really appreciated!
Here's a quick checklist that should be present in PRs (you can delete this text from the final description, this is
just a guideline):
Here is a quick checklist that should be present in PRs.
(please delete this text from the final description, this is just a guideline)
-->
- [ ] Create a new changelog file in the `changelog` folder, with a name like `<ISSUE NUMBER>.<TYPE>.rst`. See [changelog/README.rst](https://github.com/pytest-dev/pytest/blob/master/changelog/README.rst) for details.
- [ ] Target the `master` branch for bug fixes, documentation updates and trivial changes.
- [ ] Target the `features` branch for new features and removals/deprecations.
- [ ] Target the `features` branch for new features, improvements, and removals/deprecations.
- [ ] Include documentation when adding new features.
- [ ] Include new tests or update existing tests when applicable.
Unless your change is trivial or a small documentation fix (e.g., a typo or reword of a small section) please:
- [ ] Create a new changelog file in the `changelog` folder, with a name like `<ISSUE NUMBER>.<TYPE>.rst`. See [changelog/README.rst](https://github.com/pytest-dev/pytest/blob/master/changelog/README.rst) for details.
- [ ] Add yourself to `AUTHORS` in alphabetical order;

1
.gitignore vendored
View File

@@ -35,6 +35,7 @@ env/
.tox
.cache
.pytest_cache
.mypy_cache
.coverage
.coverage.*
coverage.xml

View File

@@ -1,58 +1,65 @@
exclude: doc/en/example/py2py3/test_py2.py
repos:
- repo: https://github.com/ambv/black
rev: 18.9b0
- repo: https://github.com/psf/black
rev: 19.3b0
hooks:
- id: black
args: [--safe, --quiet]
language_version: python3
- repo: https://github.com/asottile/blacken-docs
rev: v0.3.0
rev: v1.0.0
hooks:
- id: blacken-docs
additional_dependencies: [black==18.9b0]
language_version: python3
additional_dependencies: [black==19.3b0]
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.1.0
rev: v2.2.3
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: fix-encoding-pragma
args: [--remove]
- id: check-yaml
- id: debug-statements
exclude: _pytest/debugging.py
language_version: python3
- repo: https://gitlab.com/pycqa/flake8
rev: 3.7.0
rev: 3.7.7
hooks:
- id: flake8
language_version: python3
additional_dependencies: [flake8-typing-imports==1.3.0]
- repo: https://github.com/asottile/reorder_python_imports
rev: v1.3.5
rev: v1.4.0
hooks:
- id: reorder-python-imports
args: ['--application-directories=.:src']
args: ['--application-directories=.:src', --py3-plus]
- repo: https://github.com/asottile/pyupgrade
rev: v1.11.1
rev: v1.18.0
hooks:
- id: pyupgrade
args: [--keep-percent-format]
args: [--py3-plus]
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.2.0
rev: v1.4.0
hooks:
- id: rst-backticks
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.720
hooks:
- id: mypy
files: ^(src/|testing/)
args: []
- repo: local
hooks:
- id: rst
name: rst
entry: rst-lint --encoding utf-8
files: ^(CHANGELOG.rst|HOWTORELEASE.rst|README.rst|changelog/.*)$
files: ^(CHANGELOG.rst|HOWTORELEASE.rst|README.rst|TIDELIFT.rst|changelog/.*)$
language: python
additional_dependencies: [pygments, restructuredtext_lint]
- id: changelogs-rst
name: changelog filenames
language: fail
entry: 'changelog files must be named ####.(feature|bugfix|doc|deprecation|removal|vendor|trivial).rst'
exclude: changelog/(\d+\.(feature|bugfix|doc|deprecation|removal|vendor|trivial).rst|README.rst|_template.rst)
exclude: changelog/(\d+\.(feature|improvement|bugfix|doc|deprecation|removal|vendor|trivial).rst|README.rst|_template.rst)
files: ^changelog/
- id: py-deprecated
name: py library is deprecated

View File

@@ -6,29 +6,27 @@ stages:
if: repo = pytest-dev/pytest AND tag IS NOT present
- name: deploy
if: repo = pytest-dev/pytest AND tag IS present
python:
- '3.7'
python: '3.7'
cache: false
env:
global:
- PYTEST_ADDOPTS=-vv
# setuptools-scm needs all tags in order to obtain a proper version
git:
depth: false
install:
- python -m pip install --upgrade --pre tox
jobs:
include:
# OSX tests - first (in test stage), since they are the slower ones.
- &test-macos
# NOTE: (tests with) pexpect appear to be buggy on Travis,
# at least with coverage.
# Log: https://travis-ci.org/pytest-dev/pytest/jobs/500358864
os: osx
- os: osx
osx_image: xcode10.1
language: generic
# Coverage for:
# - py2 with symlink in test_cmdline_python_package_symlink.
env: TOXENV=py27-xdist PYTEST_COVERAGE=1
before_install:
- python -V
- test $(python -c 'import sys; print("%d%d" % sys.version_info[0:2])') = 27
- <<: *test-macos
env: TOXENV=py37-xdist
env: TOXENV=py37-xdist PYTEST_COVERAGE=1
before_install:
- which python3
- python3 -V
@@ -36,20 +34,14 @@ jobs:
- python -V
- test $(python -c 'import sys; print("%d%d" % sys.version_info[0:2])') = 37
# Full run of latest (major) supported versions, without xdist.
- env: TOXENV=py27
python: '2.7'
# Full run of latest supported version, without xdist.
- env: TOXENV=py37
python: '3.7'
# Coverage tracking is slow with pypy, skip it.
- env: TOXENV=pypy-xdist
python: 'pypy2.7-6.0'
- env: TOXENV=pypy3-xdist
python: 'pypy3.5-6.0'
python: 'pypy3'
- env: TOXENV=py34-xdist
python: '3.4'
- env: TOXENV=py35-xdist
python: '3.5'
@@ -57,40 +49,40 @@ jobs:
# - pytester's LsofFdLeakChecker
# - TestArgComplete (linux only)
# - numpy
- env: TOXENV=py37-lsof-numpy-xdist PYTEST_COVERAGE=1
# Specialized factors for py27.
- env: TOXENV=py27-nobyte-numpy-xdist
python: '2.7'
- env: TOXENV=py27-pluggymaster-xdist
python: '2.7'
# Empty PYTEST_ADDOPTS to run this non-verbose.
- env: TOXENV=py37-lsof-numpy-twisted-xdist PYTEST_COVERAGE=1 PYTEST_ADDOPTS=
# Specialized factors for py37.
# Coverage for:
# - test_sys_breakpoint_interception (via pexpect).
- env: TOXENV=py37-pexpect,py37-trial PYTEST_COVERAGE=1
- env: TOXENV=py37-pexpect PYTEST_COVERAGE=1
- env: TOXENV=py37-pluggymaster-xdist
- env: TOXENV=py37-freeze
# Jobs only run via Travis cron jobs (currently daily).
- env: TOXENV=py38-xdist
python: '3.8-dev'
if: type = cron
- stage: baseline
# Coverage for:
# - _pytest.unittest._handle_skip (via pexpect).
env: TOXENV=py27-pexpect,py27-trial PYTEST_COVERAGE=1
python: '2.7'
# Use py36 here for faster baseline.
- env: TOXENV=py36-xdist
env: TOXENV=py36-xdist
python: '3.6'
- env: TOXENV=linting,docs,doctesting PYTEST_COVERAGE=1
cache:
directories:
- $HOME/.cache/pre-commit
- stage: deploy
python: '3.6'
install: pip install -U setuptools setuptools_scm
install: pip install -U setuptools setuptools_scm tox
script: skip
# token to upload github release notes: GH_RELEASE_NOTES_TOKEN
env:
- secure: "OjOeL7/0JUDkV00SsTs732e8vQjHynpbG9FKTNtZZJ+1Zn4Cib+hAlwmlBnvVukML0X60YpcfjnC4quDOIGLPsh5zeXnvJmYtAIIUNQXjWz8NhcGYrhyzuP1rqV22U68RTCdmOq3lMYU/W2acwHP7T49PwJtOiUM5kF120UAQ0Zi5EmkqkIvH8oM5mO9Dlver+/U7Htpz9rhKrHBXQNCMZI6yj2aUyukqB2PN2fjAlDbCF//+FmvYw9NjT4GeFOSkTCf4ER9yfqs7yglRfwiLtOCZ2qKQhWZNsSJDB89rxIRXWavJUjJKeY2EW2/NkomYJDpqJLIF4JeFRw/HhA47CYPeo6BJqyyNV+0CovL1frpWfi9UQw2cMbgFUkUIUk3F6DD59PHNIOX2R/HX56dQsw7WKl3QuHlCOkICXYg8F7Ta684IoKjeTX03/6QNOkURfDBwfGszY0FpbxrjCSWKom6RyZdyidnESaxv9RzjcIRZVh1rp8KMrwS1OrwRSdG0zjlsPr49hWMenN/8fKgcHTV4/r1Tj6mip0dorSRCrgUNIeRBKgmui6FS8642ab5JNKOxMteVPVR2sFuhjOQ0Jy+PmvceYY9ZMWc3+/B/KVh0dZ3hwvLGZep/vxDS2PwCA5/xw31714vT5LxidKo8yECjBynMU/wUTTS695D3NY="
addons:
apt:
packages:
# required by publish_gh_release_notes
- pandoc
after_deploy: tox -e publish_gh_release_notes
deploy:
provider: pypi
user: nicoddemus
@@ -121,18 +113,12 @@ before_script:
export _PYTEST_TOX_EXTRA_DEP=coverage-enable-subprocess
fi
script: tox --recreate
script: tox
after_success:
- |
if [[ "$PYTEST_COVERAGE" = 1 ]]; then
set -e
# Add last TOXENV to $PATH.
PATH="$PWD/.tox/${TOXENV##*,}/bin:$PATH"
coverage combine
coverage xml
coverage report -m
bash <(curl -s https://codecov.io/bash) -Z -X gcov -X coveragepy -X search -X xcode -X gcovout -X fix -f coverage.xml -n $TOXENV-$TRAVIS_OS_NAME
env CODECOV_NAME="$TOXENV-$TRAVIS_OS_NAME" scripts/report-coverage.sh
fi
notifications:
@@ -144,7 +130,3 @@ notifications:
skip_join: true
email:
- pytest-commit@python.org
cache:
directories:
- $HOME/.cache/pip
- $HOME/.cache/pre-commit

20
AUTHORS
View File

@@ -9,11 +9,13 @@ Abhijeet Kasurde
Adam Johnson
Adam Uhlir
Ahn Ki-Wook
Akiomi Kamakura
Alan Velasco
Alexander Johnson
Alexei Kozlenok
Allan Feldman
Aly Sivji
Amir Elkess
Anatoly Bubenkoff
Anders Hovmöller
Andras Mitzki
@@ -21,6 +23,7 @@ Andras Tim
Andrea Cimatoribus
Andreas Zeidler
Andrey Paramonov
Andrzej Klajnert
Andrzej Ostrowski
Andy Freeland
Anthon van der Neut
@@ -53,12 +56,14 @@ Charnjit SiNGH (CCSJ)
Chris Lamb
Christian Boelsen
Christian Fetzer
Christian Neumüller
Christian Theunert
Christian Tismer
Christopher Gilling
Christopher Dignam
CrazyMerlyn
Cyrus Maden
Damian Skrzypczak
Dhiren Serai
Daniel Grana
Daniel Hahler
@@ -68,6 +73,7 @@ Danielle Jenkins
Dave Hunt
David Díaz-Barquero
David Mohr
David Paul Röthlisberger
David Szotten
David Vierra
Daw-Ran Liou
@@ -85,12 +91,14 @@ Endre Galaczi
Eric Hunsberger
Eric Siegerman
Erik M. Bray
Evan Kepner
Fabien Zarifian
Fabio Zadrozny
Feng Ma
Florian Bruhin
Floris Bruynooghe
Gabriel Reis
Gene Wood
George Kussumoto
Georgy Dyuldin
Graham Horler
@@ -105,6 +113,7 @@ Hugo van Kemenade
Hui Wang (coldnight)
Ian Bicking
Ian Lesperance
Ilya Konstantinov
Ionuț Turturică
Iwan Briquemont
Jaap Broekhuizen
@@ -131,6 +140,7 @@ Kale Kundert
Katarzyna Jachim
Katerina Koukiou
Kevin Cox
Kevin J. Foley
Kodi B. Arfer
Kostis Anagnostopoulos
Kristoffer Nordström
@@ -166,6 +176,7 @@ mbyt
Michael Aquilina
Michael Birtwell
Michael Droettboom
Michael Goerz
Michael Seifert
Michal Wajszczuk
Mihai Capotă
@@ -179,6 +190,7 @@ Nicholas Devenish
Nicholas Murphy
Niclas Olofsson
Nicolas Delaby
Nikolay Kondratyev
Oleg Pidsadnyi
Oleg Sushchenko
Oliver Bestwalter
@@ -191,14 +203,17 @@ Paweł Adamczak
Pedro Algarvio
Pieter Mulder
Piotr Banaszkiewicz
Pulkit Goyal
Punyashloka Biswal
Quentin Pradet
Ralf Schmitt
Ralph Giles
Ran Benita
Raphael Castaneda
Raphael Pierzina
Raquel Alegre
Ravi Chandra
Robert Holt
Roberto Polli
Roland Puntaier
Romain Dorgueil
@@ -208,6 +223,7 @@ Ross Lawley
Russel Winder
Ryan Wooden
Samuel Dion-Girardeau
Samuel Searles-Bryant
Samuele Pedroni
Sankt Petersbug
Segev Finer
@@ -222,11 +238,13 @@ Steffen Allner
Stephan Obermann
Sven-Hendrik Haase
Tadek Teleżyński
Takafumi Arakaki
Tarcisio Fischer
Tareq Alayan
Ted Xiao
Thomas Grainger
Thomas Hisch
Tim Hoffmann
Tim Strazny
Tom Dalton
Tom Viner
@@ -241,10 +259,12 @@ Vidar T. Fauske
Virgil Dupras
Vitaly Lashmanov
Vlad Dragos
Volodymyr Piskun
Wil Cooley
William Lee
Wim Glenn
Wouter van Ackooy
Xixi Zhao
Xuan Luong
Xuecong Liao
Zac Hatfield-Dodds

File diff suppressed because it is too large Load Diff

84
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,84 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at coc@pytest.org. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
The coc@pytest.org address is routed to the following people who can also be
contacted individually:
- Brianna Laugher ([@pfctdayelise](https://github.com/pfctdayelise)): brianna@laugher.id.au
- Bruno Oliveira ([@nicoddemus](https://github.com/nicoddemus)): nicoddemus@gmail.com
- Florian Bruhin ([@the-compiler](https://github.com/the-compiler)): pytest@the-compiler.org
- Ronny Pfannschmidt ([@RonnyPfannschmidt](https://github.com/RonnyPfannschmidt)): ich@ronnypfannschmidt.de
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@@ -5,8 +5,9 @@ Contribution getting started
Contributions are highly welcomed and appreciated. Every little help counts,
so do not hesitate!
.. contents:: Contribution links
.. contents::
:depth: 2
:backlinks: none
.. _submitfeedback:
@@ -166,14 +167,14 @@ Short version
#. Enable and install `pre-commit <https://pre-commit.com>`_ to ensure style-guides and code checks are followed.
#. Target ``master`` for bugfixes and doc changes.
#. Target ``features`` for new features or functionality changes.
#. Follow **PEP-8** for naming and `black <https://github.com/ambv/black>`_ for formatting.
#. Follow **PEP-8** for naming and `black <https://github.com/psf/black>`_ for formatting.
#. Tests are run using ``tox``::
tox -e linting,py27,py37
tox -e linting,py37
The test environments above are usually enough to cover most cases locally.
#. Write a ``changelog`` entry: ``changelog/2574.bugfix``, use issue id number
#. Write a ``changelog`` entry: ``changelog/2574.bugfix.rst``, use issue id number
and one of ``bugfix``, ``removal``, ``feature``, ``vendor``, ``doc`` or
``trivial`` for the issue type.
#. Unless your change is a trivial or a documentation fix (e.g., a typo or reword of a small section) please
@@ -217,7 +218,9 @@ Here is a simple overview, with pytest-specific bits:
If you need some help with Git, follow this quick start
guide: https://git.wiki.kernel.org/index.php/QuickStart
#. Install `pre-commit <https://pre-commit.com>`_ and its hook on the pytest repo::
#. Install `pre-commit <https://pre-commit.com>`_ and its hook on the pytest repo:
**Note: pre-commit must be installed as admin, as it will not function otherwise**::
$ pip install --user pre-commit
$ pre-commit install
@@ -237,20 +240,20 @@ Here is a simple overview, with pytest-specific bits:
#. Run all the tests
You need to have Python 2.7 and 3.7 available in your system. Now
You need to have Python 3.7 available in your system. Now
running tests is as simple as issuing this command::
$ tox -e linting,py27,py37
$ tox -e linting,py37
This command will run tests via the "tox" tool against Python 2.7 and 3.7
This command will run tests via the "tox" tool against Python 3.7
and also perform "lint" coding-style checks.
#. You can now edit your local working copy and run the tests again as necessary. Please follow PEP-8 for naming.
You can pass different options to ``tox``. For example, to run tests on Python 2.7 and pass options to pytest
You can pass different options to ``tox``. For example, to run tests on Python 3.7 and pass options to pytest
(e.g. enter pdb on failure) to pytest you can do::
$ tox -e py27 -- --pdb
$ tox -e py37 -- --pdb
Or to only run tests in a particular test module on Python 3.7::
@@ -264,9 +267,10 @@ Here is a simple overview, with pytest-specific bits:
$ git commit -a -m "<commit message>"
$ git push -u
#. Create a new changelog entry in ``changelog``. The file should be named ``<issueid>.<type>``,
#. Create a new changelog entry in ``changelog``. The file should be named ``<issueid>.<type>.rst``,
where *issueid* is the number of the issue related to the change and *type* is one of
``bugfix``, ``removal``, ``feature``, ``vendor``, ``doc`` or ``trivial``.
``bugfix``, ``removal``, ``feature``, ``vendor``, ``doc`` or ``trivial``. You may not create a
changelog entry if the change doesn't affect the documented behaviour of Pytest.
#. Add yourself to ``AUTHORS`` file if not there yet, in alphabetical order.

View File

@@ -12,6 +12,8 @@ taking a lot of time to make a new one.
#. Create a branch ``release-X.Y.Z`` with the version for the release.
* **maintenance releases**: from ``4.6-maintenance``;
* **patch releases**: from the latest ``master``;
* **minor releases**: from the latest ``features``; then merge with the latest ``master``;
@@ -24,7 +26,8 @@ taking a lot of time to make a new one.
This will generate a commit with all the changes ready for pushing.
#. Open a PR for this branch targeting ``master``.
#. Open a PR for this branch targeting ``master`` (or ``4.6-maintenance`` for
maintenance releases).
#. After all tests pass and the PR has been approved, publish to PyPI by pushing the tag::
@@ -33,7 +36,16 @@ taking a lot of time to make a new one.
Wait for the deploy to complete, then make sure it is `available on PyPI <https://pypi.org/project/pytest>`_.
#. Merge the PR into ``master``.
#. Merge the PR.
#. If this is a maintenance release, cherry-pick the CHANGELOG / announce
files to the ``master`` branch::
git fetch --all --prune
git checkout origin/master -b cherry-pick-maintenance-release
git cherry-pick --no-commit -m1 origin/4.6-maintenance
git checkout origin/master -- changelog
git commit # no arguments
#. Send an email announcement with the contents from::

44
OPENCOLLECTIVE.rst Normal file
View File

@@ -0,0 +1,44 @@
==============
OpenCollective
==============
pytest has a collective setup at `OpenCollective`_. This document describes how the core team manages
OpenCollective-related activities.
What is it
==========
Open Collective is an online funding platform for open and transparent communities.
It provides tools to raise money and share your finances in full transparency.
It is the platform of choice for individuals and companies that want to make one-time or
monthly donations directly to the project.
Funds
=====
The OpenCollective funds donated to pytest will be used to fund overall maintenance,
local sprints, merchandising (stickers to distribute in conferences for example), and future
gatherings of pytest developers (sprints).
`Core contributors`_ which are contributing on a continuous basis are free to submit invoices
to bill maintenance hours using the platform. How much each contributor should request is still an
open question, but we should use common sense and trust in the contributors, most of which know
themselves in-person. A good rule of thumb is to bill the same amount as monthly payments
contributors which participate in the `Tidelift`_ subscription. If in doubt, just ask.
Admins
======
A few people have admin access to the OpenCollective dashboard to make changes. Those people
are part of the `@pytest-dev/opencollective-admins`_ team.
`Core contributors`_ interested in helping out with OpenCollective maintenance are welcome! We don't
expect much work here other than the occasional approval of expenses from other core contributors.
Just drop a line to one of the `@pytest-dev/opencollective-admins`_ or use the mailing list.
.. _`OpenCollective`: https://opencollective.com/pytest
.. _`Tidelift`: https://tidelift.com
.. _`core contributors`: https://github.com/orgs/pytest-dev/teams/core/members
.. _`@pytest-dev/opencollective-admins`: https://github.com/orgs/pytest-dev/teams/opencollective-admins/members

View File

@@ -26,7 +26,7 @@
:target: https://dev.azure.com/pytest-dev/pytest
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
:target: https://github.com/ambv/black
:target: https://github.com/psf/black
.. image:: https://www.codetriage.com/pytest-dev/pytest/badges/users.svg
:target: https://www.codetriage.com/pytest-dev/pytest
@@ -85,7 +85,7 @@ Features
- Can run `unittest <https://docs.pytest.org/en/latest/unittest.html>`_ (or trial),
`nose <https://docs.pytest.org/en/latest/nose.html>`_ test suites out of the box;
- Python 2.7, Python 3.4+, PyPy 2.3, Jython 2.5 (untested);
- Python 3.5+ and PyPy3;
- Rich plugin architecture, with over 315+ `external plugins <http://plugincompat.herokuapp.com>`_ and thriving community;
@@ -108,6 +108,26 @@ Changelog
Consult the `Changelog <https://docs.pytest.org/en/latest/changelog.html>`__ page for fixes and enhancements of each version.
Support pytest
--------------
You can support pytest by obtaining a `Tidelift subscription`_.
Tidelift gives software development teams a single source for purchasing and maintaining their software,
with professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools.
.. _`Tidelift subscription`: https://tidelift.com/subscription/pkg/pypi-pytest?utm_source=pypi-pytest&utm_medium=referral&utm_campaign=readme
Security
^^^^^^^^
pytest has never been associated with a security vunerability, but in any case, to report a
security vulnerability please use the `Tidelift security contact <https://tidelift.com/security>`_.
Tidelift will coordinate the fix and disclosure.
License
-------

60
TIDELIFT.rst Normal file
View File

@@ -0,0 +1,60 @@
========
Tidelift
========
pytest is a member of `Tidelift`_. This document describes how the core team manages
Tidelift-related activities.
What is it
==========
Tidelift aims to make Open Source sustainable by offering subscriptions to companies which rely
on Open Source packages. This subscription allows it to pay maintainers of those Open Source
packages to aid sustainability of the work.
It is the perfect platform for companies that want to support Open Source packages and at the same
time obtain assurances regarding maintenance, quality and security.
Funds
=====
It was decided in the `mailing list`_ that the Tidelift contribution will be split evenly between
members of the `contributors team`_ interested in receiving funding.
The current list of contributors receiving funding are:
* `@asottile`_
* `@blueyed`_
* `@nicoddemus`_
Contributors interested in receiving a part of the funds just need to submit a PR adding their
name to the list. Contributors that want to stop receiving the funds should also submit a PR
in the same way.
The PR should mention `@pytest-dev/tidelift-admins`_ so appropriate changes
can be made in the Tidelift platform.
After the PR has been accepted and merged, the contributor should register in the `Tidelift`_
platform and follow the instructions there, including signing an `agreement`_.
Admins
======
A few people have admin access to the Tidelift dashboard to make changes. Those people
are part of the `@pytest-dev/tidelift-admins`_ team.
`Core contributors`_ interested in helping out with Tidelift maintenance are welcome! We don't
expect much work here other than the occasional adding/removal of a contributor from receiving
funds. Just drop a line to one of the `@pytest-dev/tidelift-admins`_ or use the mailing list.
.. _`Tidelift`: https://tidelift.com
.. _`mailing list`: https://mail.python.org/pipermail/pytest-dev/2019-May/004716.html
.. _`contributors team`: https://github.com/orgs/pytest-dev/teams/contributors
.. _`core contributors`: https://github.com/orgs/pytest-dev/teams/core/members
.. _`@pytest-dev/tidelift-admins`: https://github.com/orgs/pytest-dev/teams/tidelift-admins/members
.. _`agreement`: https://tidelift.com/docs/lifting/agreement
.. _`@asottile`: https://github.com/asottile
.. _`@blueyed`: https://github.com/blueyed
.. _`@nicoddemus`: https://github.com/nicoddemus

View File

@@ -3,11 +3,7 @@ trigger:
- features
variables:
PYTEST_ADDOPTS: "--junitxml=build/test-results/$(tox.env).xml"
python.needs_vc: False
python.exe: "python"
COVERAGE_FILE: "$(Build.Repository.LocalPath)/.coverage"
COVERAGE_PROCESS_START: "$(Build.Repository.LocalPath)/.coveragerc"
PYTEST_ADDOPTS: "--junitxml=build/test-results/$(tox.env).xml -vv"
PYTEST_COVERAGE: '0'
jobs:
@@ -17,46 +13,10 @@ jobs:
vmImage: "vs2017-win2016"
strategy:
matrix:
py27:
python.version: '2.7'
tox.env: 'py27'
py27-nobyte-lsof-numpy:
python.version: '2.7'
tox.env: 'py27-lsof-nobyte-numpy'
# Coverage for:
# - test_supports_breakpoint_module_global
# - test_terminal_reporter_writer_attr (without xdist)
# - "if write" branch in _pytest.assertion.rewrite
# - numpy
# - pytester's LsofFdLeakChecker (being skipped)
PYTEST_COVERAGE: '1'
py27-trial:
python.version: '2.7'
tox.env: 'py27-trial'
python.needs_vc: True
py27-pluggymaster-xdist:
python.version: '2.7'
tox.env: 'py27-pluggymaster-xdist'
# Coverage for:
# - except-IOError in _attempt_to_close_capture_file for py2.
# Also seen with py27-nobyte (using xdist), and py27-xdist.
# But no exception with py27-pexpect,py27-trial,py27-numpy.
PYTEST_COVERAGE: '1'
pypy:
python.version: 'pypy'
tox.env: 'pypy'
python.exe: 'pypy'
# NOTE: pypy3 fails to install pip currently due to an interal error.
# -- pypy3 disabled for now: #5279 --
# pypy3:
# python.version: 'pypy3'
# tox.env: 'pypy3'
# python.exe: 'pypy3'
py34-xdist:
python.version: '3.4'
tox.env: 'py34-xdist'
# Coverage for:
# - _pytest.compat._bytes_to_ascii
PYTEST_COVERAGE: '1'
py35-xdist:
python.version: '3.5'
tox.env: 'py35-xdist'
@@ -68,7 +28,7 @@ jobs:
tox.env: 'py36-xdist'
py37:
python.version: '3.7'
tox.env: 'py37'
tox.env: 'py37-twisted-numpy'
# Coverage for:
# - _py36_windowsconsoleio_workaround (with py36+)
# - test_request_garbage (no xdist)
@@ -76,9 +36,6 @@ jobs:
py37-linting/docs/doctesting:
python.version: '3.7'
tox.env: 'linting,docs,doctesting'
py37-trial/numpy:
python.version: '3.7'
tox.env: 'py37-trial,py37-numpy'
py37-pluggymaster-xdist:
python.version: '3.7'
tox.env: 'py37-pluggymaster-xdist'
@@ -86,38 +43,21 @@ jobs:
steps:
- task: UsePythonVersion@0
condition: not(startsWith(variables['python.exe'], 'pypy'))
inputs:
versionSpec: '$(python.version)'
architecture: 'x64'
- script: choco install vcpython27
condition: eq(variables['python.needs_vc'], True)
displayName: 'Install VC for py27'
- script: choco install python.pypy
condition: eq(variables['python.exe'], 'pypy')
displayName: 'Install pypy'
- script: choco install pypy3
condition: eq(variables['python.exe'], 'pypy3')
displayName: 'Install pypy3'
- task: PowerShell@2
inputs:
targetType: 'inline'
script: |
Invoke-WebRequest -Uri "https://bootstrap.pypa.io/get-pip.py" -OutFile "get-pip.py"
$(python.exe) get-pip.py
condition: startsWith(variables['python.exe'], 'pypy')
displayName: 'Install pip'
- script: $(python.exe) -m pip install --upgrade pip && $(python.exe) -m pip install tox
- script: python -m pip install --upgrade pip && python -m pip install tox
displayName: 'Install tox'
- script: |
call scripts/setup-coverage-vars.bat || goto :eof
$(python.exe) -m tox -e $(tox.env)
- bash: |
if [[ "$PYTEST_COVERAGE" == "1" ]]; then
export _PYTEST_TOX_COVERAGE_RUN="coverage run -m"
export _PYTEST_TOX_EXTRA_DEP=coverage-enable-subprocess
export COVERAGE_FILE="$PWD/.coverage"
export COVERAGE_PROCESS_START="$PWD/.coveragerc"
fi
python -m tox -e $(tox.env)
displayName: 'Run tests'
- task: PublishTestResults@2
@@ -126,10 +66,12 @@ jobs:
testRunTitle: '$(tox.env)'
condition: succeededOrFailed()
- script: call scripts\upload-coverage.bat
displayName: 'Report and upload coverage'
condition: eq(variables['PYTEST_COVERAGE'], '1')
- bash: |
if [[ "$PYTEST_COVERAGE" == 1 ]]; then
scripts/report-coverage.sh
fi
env:
PYTHON: $(python.exe)
CODECOV_NAME: $(tox.env)
CODECOV_TOKEN: $(CODECOV_TOKEN)
PYTEST_CODECOV_NAME: $(tox.env)
displayName: Report and upload coverage
condition: eq(variables['PYTEST_COVERAGE'], '1')

View File

@@ -5,8 +5,8 @@ if __name__ == "__main__":
import pytest # NOQA
import pstats
script = sys.argv[1:] if len(sys.argv) > 1 else "empty.py"
stats = cProfile.run("pytest.cmdline.main(%r)" % script, "prof")
script = sys.argv[1:] if len(sys.argv) > 1 else ["empty.py"]
cProfile.run("pytest.cmdline.main(%r)" % script, "prof")
p = pstats.Stats("prof")
p.strip_dirs()
p.sort_stats("cumulative")

View File

@@ -16,4 +16,4 @@ run = 'fc("/d")'
if __name__ == "__main__":
print(timeit.timeit(run, setup=setup % imports[0], number=count))
print((timeit.timeit(run, setup=setup % imports[1], number=count)))
print(timeit.timeit(run, setup=setup % imports[1], number=count))

View File

@@ -1,4 +1,2 @@
import six
for i in range(1000):
six.exec_("def test_func_%d(): pass" % i)
exec("def test_func_%d(): pass" % i)

View File

@@ -1,5 +1,3 @@
from six.moves import range
import pytest
SKIP = True

View File

@@ -12,6 +12,7 @@ Each file should be named like ``<ISSUE>.<TYPE>.rst``, where
``<ISSUE>`` is an issue number, and ``<TYPE>`` is one of:
* ``feature``: new user facing features, like new command-line options and new behavior.
* ``improvement``: improvement of existing functionality, usually without requiring user intervention (for example, new fields being written in ``--junitxml``, improved colors in terminal, etc).
* ``bugfix``: fixes a reported bug.
* ``doc``: documentation improvement, like rewording an entire session or adding missing docs.
* ``deprecation``: feature deprecation.

7
codecov.yml Normal file
View File

@@ -0,0 +1,7 @@
coverage:
status:
project: true
patch: true
changes: true
comment: off

View File

@@ -13,7 +13,10 @@ PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
REGENDOC_ARGS := \
--normalize "/in \d+.\d+ seconds/in 0.12 seconds/" \
--normalize "/[ \t]+\n/\n/" \
--normalize "~\$$REGENDOC_TMPDIR~/home/sweet/project~" \
--normalize "~/path/to/example~/home/sweet/project~" \
--normalize "/in \d.\d\ds/in 0.12s/" \
--normalize "@/tmp/pytest-of-.*/pytest-\d+@PYTEST_TMPDIR@" \
--normalize "@pytest-(\d+)\\.[^ ,]+@pytest-\1.x.y@" \
--normalize "@(This is pytest version )(\d+)\\.[^ ,]+@\1\2.x.y@" \
@@ -38,8 +41,9 @@ help:
clean:
-rm -rf $(BUILDDIR)/*
regen: REGENDOC_FILES:=*.rst */*.rst
regen:
PYTHONDONTWRITEBYTECODE=1 PYTEST_ADDOPTS=-pno:hypothesis COLUMNS=76 regendoc --update *.rst */*.rst ${REGENDOC_ARGS}
PYTHONDONTWRITEBYTECODE=1 PYTEST_ADDOPTS="-pno:hypothesis -Wignore::pytest.PytestUnknownMarkWarning" COLUMNS=76 regendoc --update ${REGENDOC_FILES} ${REGENDOC_ARGS}
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html

View File

@@ -4,12 +4,14 @@
<li><a href="{{ pathto('index') }}">Home</a></li>
<li><a href="{{ pathto('getting-started') }}">Install</a></li>
<li><a href="{{ pathto('contents') }}">Contents</a></li>
<li><a href="{{ pathto('reference') }}">Reference</a></li>
<li><a href="{{ pathto('reference') }}">API Reference</a></li>
<li><a href="{{ pathto('example/index') }}">Examples</a></li>
<li><a href="{{ pathto('customize') }}">Customize</a></li>
<li><a href="{{ pathto('changelog') }}">Changelog</a></li>
<li><a href="{{ pathto('contributing') }}">Contributing</a></li>
<li><a href="{{ pathto('backwards-compatibility') }}">Backwards Compatibility</a></li>
<li><a href="{{ pathto('py27-py34-deprecation') }}">Python 2.7 and 3.4 Support</a></li>
<li><a href="{{ pathto('sponsor') }}">Sponsor</a></li>
<li><a href="{{ pathto('license') }}">License</a></li>
<li><a href="{{ pathto('contact') }}">Contact Channels</a></li>
</ul>

View File

@@ -16,7 +16,7 @@
{%- block footer %}
<div class="footer">
&copy; Copyright {{ copyright }}.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a>.
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> {{ sphinx_version }}.
</div>
{% if pagename == 'index' %}
</div>

View File

@@ -0,0 +1,15 @@
{#
basic/searchbox.html with heading removed.
#}
{%- if pagename != "search" and builder != "singlehtml" %}
<div id="searchbox" style="display: none" role="search">
<div class="searchformwrapper">
<form class="search" action="{{ pathto('search') }}" method="get">
<input type="text" name="q" aria-labelledby="searchlabel"
placeholder="Search"/>
<input type="submit" value="{{ _('Go') }}" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
{%- endif %}

View File

@@ -8,11 +8,12 @@
{% set page_width = '1020px' %}
{% set sidebar_width = '220px' %}
/* orange of logo is #d67c29 but we use black for links for now */
{% set link_color = '#000' %}
{% set link_hover_color = '#000' %}
/* muted version of green logo color #C9D22A */
{% set link_color = '#606413' %}
/* blue logo color */
{% set link_hover_color = '#009de0' %}
{% set base_font = 'sans-serif' %}
{% set header_font = 'serif' %}
{% set header_font = 'sans-serif' %}
@import url("basic.css");
@@ -20,7 +21,7 @@
body {
font-family: {{ base_font }};
font-size: 17px;
font-size: 16px;
background-color: white;
color: #000;
margin: 0;
@@ -78,13 +79,13 @@ div.related {
}
div.sphinxsidebar a {
color: #444;
text-decoration: none;
border-bottom: 1px dotted #999;
border-bottom: none;
}
div.sphinxsidebar a:hover {
border-bottom: 1px solid #999;
color: {{ link_hover_color }};
border-bottom: 1px solid {{ link_hover_color }};
}
div.sphinxsidebar {
@@ -106,14 +107,14 @@ div.sphinxsidebar h3,
div.sphinxsidebar h4 {
font-family: {{ header_font }};
color: #444;
font-size: 24px;
font-size: 21px;
font-weight: normal;
margin: 0 0 5px 0;
margin: 16px 0 0 0;
padding: 0;
}
div.sphinxsidebar h4 {
font-size: 20px;
font-size: 18px;
}
div.sphinxsidebar h3 a {
@@ -205,10 +206,22 @@ div.body p, div.body dd, div.body li {
line-height: 1.4em;
}
ul.simple li {
margin-bottom: 0.5em;
}
div.topic ul.simple li {
margin-bottom: 0;
}
div.topic li > p:first-child {
margin-top: 0;
margin-bottom: 0;
}
div.admonition {
background: #fafafa;
margin: 20px -30px;
padding: 10px 30px;
padding: 10px 20px;
border-top: 1px solid #ccc;
border-bottom: 1px solid #ccc;
}
@@ -217,11 +230,6 @@ div.admonition tt.xref, div.admonition a tt {
border-bottom: 1px solid #fafafa;
}
dd div.admonition {
margin-left: -60px;
padding-left: 60px;
}
div.admonition p.admonition-title {
font-family: {{ header_font }};
font-weight: normal;
@@ -231,7 +239,7 @@ div.admonition p.admonition-title {
line-height: 1;
}
div.admonition p.last {
div.admonition :last-child {
margin-bottom: 0;
}
@@ -243,7 +251,7 @@ dt:target, .highlight {
background: #FAF3E8;
}
div.note {
div.note, div.warning {
background-color: #eee;
border: 1px solid #ccc;
}
@@ -257,6 +265,11 @@ div.topic {
background-color: #eee;
}
div.topic a {
text-decoration: none;
border-bottom: none;
}
p.admonition-title {
display: inline;
}
@@ -358,21 +371,10 @@ ul, ol {
pre {
background: #eee;
padding: 7px 30px;
margin: 15px -30px;
padding: 7px 12px;
line-height: 1.3em;
}
dl pre, blockquote pre, li pre {
margin-left: -60px;
padding-left: 60px;
}
dl dl pre {
margin-left: -90px;
padding-left: 90px;
}
tt {
background-color: #ecf0f3;
color: #222;
@@ -393,6 +395,20 @@ a.reference:hover {
border-bottom: 1px solid {{ link_hover_color }};
}
li.toctree-l1 a.reference,
li.toctree-l2 a.reference,
li.toctree-l3 a.reference,
li.toctree-l4 a.reference {
border-bottom: none;
}
li.toctree-l1 a.reference:hover,
li.toctree-l2 a.reference:hover,
li.toctree-l3 a.reference:hover,
li.toctree-l4 a.reference:hover {
border-bottom: 1px solid {{ link_hover_color }};
}
a.footnote-reference {
text-decoration: none;
font-size: 0.7em;
@@ -408,6 +424,56 @@ a:hover tt {
background: #EEE;
}
#reference div.section h2 {
/* separate code elements in the reference section */
border-top: 2px solid #ccc;
padding-top: 0.5em;
}
#reference div.section h3 {
/* separate code elements in the reference section */
border-top: 1px solid #ccc;
padding-top: 0.5em;
}
dl.class, dl.function {
margin-top: 1em;
margin-bottom: 1em;
}
dl.class > dd {
border-left: 3px solid #ccc;
margin-left: 0px;
padding-left: 30px;
}
dl.field-list {
flex-direction: column;
}
dl.field-list dd {
padding-left: 4em;
border-left: 3px solid #ccc;
margin-bottom: 0.5em;
}
dl.field-list dd > ul {
list-style: none;
padding-left: 0px;
}
dl.field-list dd > ul > li li :first-child {
text-indent: 0;
}
dl.field-list dd > ul > li :first-child {
text-indent: -2em;
padding-left: 0px;
}
dl.field-list dd > p:first-child {
text-indent: -2em;
}
@media screen and (max-width: 870px) {

View File

@@ -24,11 +24,9 @@ The ideal pytest helper
- feels confident in using pytest (e.g. has explored command line options, knows how to write parametrized tests, has an idea about conftest contents)
- does not need to be an expert in every aspect!
`Pytest helpers, sign up here`_! (preferably in February, hard deadline 22 March)
Pytest helpers, sign up here! (preferably in February, hard deadline 22 March)
.. _`Pytest helpers, sign up here`: http://goo.gl/forms/nxqAhqWt1P
The ideal partner project
-----------------------------------------
@@ -40,11 +38,9 @@ The ideal partner project
- has the support of the core development team, in trying out pytest adoption
- has no tests... or 100% test coverage... or somewhere in between!
`Partner projects, sign up here`_! (by 22 March)
Partner projects, sign up here! (by 22 March)
.. _`Partner projects, sign up here`: http://goo.gl/forms/ZGyqlHiwk3
What does it mean to "adopt pytest"?
-----------------------------------------
@@ -68,11 +64,11 @@ Progressive success might look like:
It may be after the month is up, the partner project decides that pytest is not right for it. That's okay - hopefully the pytest team will also learn something about its weaknesses or deficiencies.
.. _`nose and unittest`: faq.html#how-does-pytest-relate-to-nose-and-unittest
.. _assert: asserts.html
.. _assert: assert.html
.. _pycmd: https://bitbucket.org/hpk42/pycmd/overview
.. _`setUp/tearDown methods`: xunit_setup.html
.. _fixtures: fixture.html
.. _markers: markers.html
.. _markers: mark.html
.. _distributed: xdist.html

View File

@@ -6,6 +6,23 @@ Release announcements
:maxdepth: 2
release-5.2.0
release-5.1.3
release-5.1.2
release-5.1.1
release-5.1.0
release-5.0.1
release-5.0.0
release-4.6.5
release-4.6.4
release-4.6.3
release-4.6.2
release-4.6.1
release-4.6.0
release-4.5.0
release-4.4.2
release-4.4.1
release-4.4.0
release-4.3.1
release-4.3.0
release-4.2.1

View File

@@ -12,7 +12,7 @@ courtesy of Benjamin Peterson. You can now safely use ``assert``
statements in test modules without having to worry about side effects
or python optimization ("-OO") options. This is achieved by rewriting
assert statements in test modules upon import, using a PEP302 hook.
See http://pytest.org/assert.html#advanced-assertion-introspection for
See https://docs.pytest.org/en/latest/assert.html for
detailed information. The work has been partly sponsored by my company,
merlinux GmbH.

View File

@@ -75,7 +75,7 @@ The py.test Development Team
**Changes**
* **Important**: `py.code <https://pylib.readthedocs.io/en/latest/code.html>`_ has been
* **Important**: `py.code <https://pylib.readthedocs.io/en/stable/code.html>`_ has been
merged into the ``pytest`` repository as ``pytest._code``. This decision
was made because ``py.code`` had very few uses outside ``pytest`` and the
fact that it was in a different repository made it difficult to fix bugs on
@@ -88,7 +88,7 @@ The py.test Development Team
**experimental**, so you definitely should not import it explicitly!
Please note that the original ``py.code`` is still available in
`pylib <https://pylib.readthedocs.io>`_.
`pylib <https://pylib.readthedocs.io/en/stable/>`_.
* ``pytest_enter_pdb`` now optionally receives the pytest config object.
Thanks `@nicoddemus`_ for the PR.

View File

@@ -66,8 +66,8 @@ The py.test Development Team
.. _#510: https://github.com/pytest-dev/pytest/issues/510
.. _#1506: https://github.com/pytest-dev/pytest/pull/1506
.. _#1496: https://github.com/pytest-dev/pytest/issue/1496
.. _#1524: https://github.com/pytest-dev/pytest/issue/1524
.. _#1496: https://github.com/pytest-dev/pytest/issues/1496
.. _#1524: https://github.com/pytest-dev/pytest/pull/1524
.. _@astraw38: https://github.com/astraw38
.. _@hackebrot: https://github.com/hackebrot

View File

@@ -20,7 +20,7 @@ Thanks to all who contributed to this release, among them:
* Jeffrey Rackauckas
* Jose Carlos Menezes
* Ronny Pfannschmidt
* Zac-HD
* Zac Hatfield-Dodds
* iwanb

View File

@@ -21,7 +21,6 @@ Thanks to all who contributed to this release, among them:
* Kyle Altendorf
* Stephan Hoyer
* Zac Hatfield-Dodds
* Zac-HD
* songbowen

View File

@@ -0,0 +1,39 @@
pytest-4.4.0
=======================================
The pytest team is proud to announce the 4.4.0 release!
pytest is a mature Python testing tool with more than a 2000 tests
against itself, passing on many different interpreters and platforms.
This release contains a number of bugs fixes and improvements, so users are encouraged
to take a look at the CHANGELOG:
https://docs.pytest.org/en/latest/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/latest/
As usual, you can upgrade from pypi via:
pip install -U pytest
Thanks to all who contributed to this release, among them:
* Anthony Sottile
* ApaDoctor
* Bernhard M. Wiedemann
* Brian Skinn
* Bruno Oliveira
* Daniel Hahler
* Gary Tyler
* Jeong YunWon
* Miro Hrončok
* Takafumi Arakaki
* henrykironde
* smheidrich
Happy testing,
The Pytest Development Team

View File

@@ -0,0 +1,20 @@
pytest-4.4.1
=======================================
pytest 4.4.1 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* Anthony Sottile
* Bruno Oliveira
* Daniel Hahler
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,33 @@
pytest-4.4.2
=======================================
pytest 4.4.2 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* Allan Lewis
* Anthony Sottile
* Bruno Oliveira
* DamianSkrzypczak
* Daniel Hahler
* Don Kirkby
* Douglas Thor
* Hugo
* Ilya Konstantinov
* Jon Dufresne
* Matt Cooper
* Nikolay Kondratyev
* Ondřej Súkup
* Peter Schutt
* Romain Chossart
* Sitaktif
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,34 @@
pytest-4.5.0
=======================================
The pytest team is proud to announce the 4.5.0 release!
pytest is a mature Python testing tool with more than a 2000 tests
against itself, passing on many different interpreters and platforms.
This release contains a number of bugs fixes and improvements, so users are encouraged
to take a look at the CHANGELOG:
https://docs.pytest.org/en/latest/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/latest/
As usual, you can upgrade from pypi via:
pip install -U pytest
Thanks to all who contributed to this release, among them:
* Anthony Sottile
* Bruno Oliveira
* Daniel Hahler
* Floris Bruynooghe
* Pulkit Goyal
* Samuel Searles-Bryant
* Zac Hatfield-Dodds
Happy testing,
The Pytest Development Team

View File

@@ -0,0 +1,43 @@
pytest-4.6.0
=======================================
The pytest team is proud to announce the 4.6.0 release!
pytest is a mature Python testing tool with more than a 2000 tests
against itself, passing on many different interpreters and platforms.
This release contains a number of bugs fixes and improvements, so users are encouraged
to take a look at the CHANGELOG:
https://docs.pytest.org/en/latest/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/latest/
As usual, you can upgrade from pypi via:
pip install -U pytest
Thanks to all who contributed to this release, among them:
* Akiomi Kamakura
* Anthony Sottile
* Bruno Oliveira
* Daniel Hahler
* David Röthlisberger
* Evan Kepner
* Jeffrey Rackauckas
* MyComputer
* Nikita Krokosh
* Raul Tambre
* Thomas Hisch
* Tim Hoffmann
* Tomer Keren
* Victor Maryama
* danielx123
* oleg-yegorov
Happy testing,
The Pytest Development Team

View File

@@ -0,0 +1,19 @@
pytest-4.6.1
=======================================
pytest 4.6.1 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* Anthony Sottile
* Bruno Oliveira
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,18 @@
pytest-4.6.2
=======================================
pytest 4.6.2 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* Anthony Sottile
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,21 @@
pytest-4.6.3
=======================================
pytest 4.6.3 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* Anthony Sottile
* Bruno Oliveira
* Daniel Hahler
* Dirk Thomas
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,22 @@
pytest-4.6.4
=======================================
pytest 4.6.4 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* Anthony Sottile
* Bruno Oliveira
* Daniel Hahler
* Thomas Grainger
* Zac Hatfield-Dodds
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,21 @@
pytest-4.6.5
=======================================
pytest 4.6.5 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* Anthony Sottile
* Bruno Oliveira
* Daniel Hahler
* Thomas Grainger
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,46 @@
pytest-5.0.0
=======================================
The pytest team is proud to announce the 5.0.0 release!
pytest is a mature Python testing tool with more than a 2000 tests
against itself, passing on many different interpreters and platforms.
This release contains a number of bugs fixes and improvements, so users are encouraged
to take a look at the CHANGELOG:
https://docs.pytest.org/en/latest/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/latest/
As usual, you can upgrade from pypi via:
pip install -U pytest
Thanks to all who contributed to this release, among them:
* Anthony Sottile
* Bruno Oliveira
* Daniel Hahler
* Dirk Thomas
* Evan Kepner
* Florian Bruhin
* Hugo
* Kevin J. Foley
* Pulkit Goyal
* Ralph Giles
* Ronny Pfannschmidt
* Thomas Grainger
* Thomas Hisch
* Tim Gates
* Victor Maryama
* Yuri Apollov
* Zac Hatfield-Dodds
* curiousjazz77
* patriksevallius
Happy testing,
The Pytest Development Team

View File

@@ -0,0 +1,25 @@
pytest-5.0.1
=======================================
pytest 5.0.1 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* AmirElkess
* Andreu Vallbona Plazas
* Anthony Sottile
* Bruno Oliveira
* Florian Bruhin
* Michael Moore
* Niklas Meinzer
* Thomas Grainger
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,56 @@
pytest-5.1.0
=======================================
The pytest team is proud to announce the 5.1.0 release!
pytest is a mature Python testing tool with more than a 2000 tests
against itself, passing on many different interpreters and platforms.
This release contains a number of bugs fixes and improvements, so users are encouraged
to take a look at the CHANGELOG:
https://docs.pytest.org/en/latest/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/latest/
As usual, you can upgrade from pypi via:
pip install -U pytest
Thanks to all who contributed to this release, among them:
* Albert Tugushev
* Alexey Zankevich
* Anthony Sottile
* Bruno Oliveira
* Daniel Hahler
* David Röthlisberger
* Florian Bruhin
* Ilya Stepin
* Jon Dufresne
* Kaiqi
* Max R
* Miro Hrončok
* Oliver Bestwalter
* Ran Benita
* Ronny Pfannschmidt
* Samuel Searles-Bryant
* Semen Zhydenko
* Steffen Schroeder
* Thomas Grainger
* Tim Hoffmann
* William Woodall
* Wojtek Erbetowski
* Xixi Zhao
* Yash Todi
* boris
* dmitry.dygalo
* helloocc
* martbln
* mei-li
Happy testing,
The Pytest Development Team

View File

@@ -0,0 +1,24 @@
pytest-5.1.1
=======================================
pytest 5.1.1 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* Anthony Sottile
* Bruno Oliveira
* Daniel Hahler
* Florian Bruhin
* Hugo van Kemenade
* Ran Benita
* Ronny Pfannschmidt
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,23 @@
pytest-5.1.2
=======================================
pytest 5.1.2 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* Andrzej Klajnert
* Anthony Sottile
* Bruno Oliveira
* Christian Neumüller
* Robert Holt
* linchiwei123
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,23 @@
pytest-5.1.3
=======================================
pytest 5.1.3 has just been released to PyPI.
This is a bug-fix release, being a drop-in replacement. To upgrade::
pip install --upgrade pytest
The full changelog is available at https://docs.pytest.org/en/latest/changelog.html.
Thanks to all who contributed to this release, among them:
* Anthony Sottile
* Bruno Oliveira
* Christian Neumüller
* Daniel Hahler
* Gene Wood
* Hugo
Happy testing,
The pytest Development Team

View File

@@ -0,0 +1,36 @@
pytest-5.2.0
=======================================
The pytest team is proud to announce the 5.2.0 release!
pytest is a mature Python testing tool with more than a 2000 tests
against itself, passing on many different interpreters and platforms.
This release contains a number of bugs fixes and improvements, so users are encouraged
to take a look at the CHANGELOG:
https://docs.pytest.org/en/latest/changelog.html
For complete documentation, please visit:
https://docs.pytest.org/en/latest/
As usual, you can upgrade from pypi via:
pip install -U pytest
Thanks to all who contributed to this release, among them:
* Andrzej Klajnert
* Anthony Sottile
* Bruno Oliveira
* Daniel Hahler
* James Cooke
* Michael Goerz
* Ran Benita
* Tomáš Chvátal
* aklajnert
Happy testing,
The Pytest Development Team

View File

@@ -12,12 +12,15 @@ Asserting with the ``assert`` statement
``pytest`` allows you to use the standard python ``assert`` for verifying
expectations and values in Python tests. For example, you can write the
following::
following:
.. code-block:: python
# content of test_assert1.py
def f():
return 3
def test_function():
assert f() == 4
@@ -28,9 +31,9 @@ you will see the return value of the function call:
$ pytest test_assert1.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_assert1.py F [100%]
@@ -43,8 +46,8 @@ you will see the return value of the function call:
E assert 3 == 4
E + where 3 = f()
test_assert1.py:5: AssertionError
========================= 1 failed in 0.12 seconds =========================
test_assert1.py:6: AssertionError
============================ 1 failed in 0.12s =============================
``pytest`` has support for showing the values of the most common subexpressions
including calls, attributes, comparisons, and binary and unary
@@ -52,7 +55,9 @@ operators. (See :ref:`tbreportdemo`). This allows you to use the
idiomatic python constructs without boilerplate code while not losing
introspection information.
However, if you specify a message with the assertion like this::
However, if you specify a message with the assertion like this:
.. code-block:: python
assert a % 2 == 0, "value was odd, should be even"
@@ -67,22 +72,29 @@ Assertions about expected exceptions
------------------------------------------
In order to write assertions about raised exceptions, you can use
``pytest.raises`` as a context manager like this::
``pytest.raises`` as a context manager like this:
.. code-block:: python
import pytest
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
and if you need to have access to the actual exception info you may use::
and if you need to have access to the actual exception info you may use:
.. code-block:: python
def test_recursion_depth():
with pytest.raises(RuntimeError) as excinfo:
def f():
f()
f()
assert 'maximum recursion' in str(excinfo.value)
assert "maximum recursion" in str(excinfo.value)
``excinfo`` is a ``ExceptionInfo`` instance, which is a wrapper around
the actual exception raised. The main attributes of interest are
@@ -90,15 +102,19 @@ the actual exception raised. The main attributes of interest are
You can pass a ``match`` keyword parameter to the context-manager to test
that a regular expression matches on the string representation of an exception
(similar to the ``TestCase.assertRaisesRegexp`` method from ``unittest``)::
(similar to the ``TestCase.assertRaisesRegexp`` method from ``unittest``):
.. code-block:: python
import pytest
def myfunc():
raise ValueError("Exception 123 raised")
def test_match():
with pytest.raises(ValueError, match=r'.* 123 .*'):
with pytest.raises(ValueError, match=r".* 123 .*"):
myfunc()
The regexp parameter of the ``match`` method is matched with the ``re.search``
@@ -107,7 +123,9 @@ well.
There's an alternate form of the ``pytest.raises`` function where you pass
a function that will be executed with the given ``*args`` and ``**kwargs`` and
assert that the given exception is raised::
assert that the given exception is raised:
.. code-block:: python
pytest.raises(ExpectedException, func, *args, **kwargs)
@@ -116,7 +134,9 @@ exception* or *wrong exception*.
Note that it is also possible to specify a "raises" argument to
``pytest.mark.xfail``, which checks that the test is failing in a more
specific way than just having any exception raised::
specific way than just having any exception raised:
.. code-block:: python
@pytest.mark.xfail(raises=IndexError)
def test_f():
@@ -134,7 +154,7 @@ or bugs in dependencies.
Assertions about expected warnings
-----------------------------------------
.. versionadded:: 2.8
You can check that code raises a particular warning using
:ref:`pytest.warns <warns>`.
@@ -145,13 +165,16 @@ You can check that code raises a particular warning using
Making use of context-sensitive comparisons
-------------------------------------------------
.. versionadded:: 2.0
``pytest`` has rich support for providing context-sensitive information
when it encounters comparisons. For example::
when it encounters comparisons. For example:
.. code-block:: python
# content of test_assert2.py
def test_set_comparison():
set1 = set("1308")
set2 = set("8035")
@@ -163,9 +186,9 @@ if you run this module:
$ pytest test_assert2.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_assert2.py F [100%]
@@ -184,8 +207,8 @@ if you run this module:
E '5'
E Use -v to get the full diff
test_assert2.py:5: AssertionError
========================= 1 failed in 0.12 seconds =========================
test_assert2.py:6: AssertionError
============================ 1 failed in 0.12s =============================
Special comparisons are done for a number of cases:
@@ -205,25 +228,34 @@ the ``pytest_assertrepr_compare`` hook.
:noindex:
As an example consider adding the following hook in a :ref:`conftest.py <conftest.py>`
file which provides an alternative explanation for ``Foo`` objects::
file which provides an alternative explanation for ``Foo`` objects:
.. code-block:: python
# content of conftest.py
from test_foocompare import Foo
def pytest_assertrepr_compare(op, left, right):
if isinstance(left, Foo) and isinstance(right, Foo) and op == "==":
return ['Comparing Foo instances:',
' vals: %s != %s' % (left.val, right.val)]
return [
"Comparing Foo instances:",
" vals: {} != {}".format(left.val, right.val),
]
now, given this test module::
now, given this test module:
.. code-block:: python
# content of test_foocompare.py
class Foo(object):
class Foo:
def __init__(self, val):
self.val = val
def __eq__(self, other):
return self.val == other.val
def test_compare():
f1 = Foo(1)
f2 = Foo(2)
@@ -246,8 +278,8 @@ the conftest file:
E assert Comparing Foo instances:
E vals: 1 != 2
test_foocompare.py:11: AssertionError
1 failed in 0.12 seconds
test_foocompare.py:12: AssertionError
1 failed in 0.12s
.. _assert-details:
.. _`assert introspection`:
@@ -255,7 +287,7 @@ the conftest file:
Assertion introspection details
-------------------------------
.. versionadded:: 2.1
Reporting details about a failing assertion is achieved by rewriting assert
@@ -306,13 +338,13 @@ If this is the case you have two options:
* Disable rewriting for all modules by using ``--assert=plain``.
.. versionadded:: 2.1
Add assert rewriting as an alternate introspection technique.
.. versionchanged:: 2.1
Introduce the ``--assert`` option. Deprecate ``--no-assert`` and
``--nomagic``.
.. versionchanged:: 3.0
Removes the ``--no-assert`` and ``--nomagic`` options.
Removes the ``--assert=reinterp`` option.

View File

@@ -27,36 +27,47 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
name of your plugin or application to avoid clashes with other cache users.
Values can be any object handled by the json stdlib module.
capsys
Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
captured output available via ``capsys.readouterr()`` method calls
which return a ``(out, err)`` namedtuple. ``out`` and ``err`` will be ``text``
objects.
Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.
The captured output is made available via ``capsys.readouterr()`` method
calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``text`` objects.
capsysbinary
Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
captured output available via ``capsys.readouterr()`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``bytes``
objects.
Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.
The captured output is made available via ``capsysbinary.readouterr()``
method calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``bytes`` objects.
capfd
Enable capturing of writes to file descriptors ``1`` and ``2`` and make
captured output available via ``capfd.readouterr()`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``text``
objects.
Enable text capturing of writes to file descriptors ``1`` and ``2``.
The captured output is made available via ``capfd.readouterr()`` method
calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``text`` objects.
capfdbinary
Enable capturing of write to file descriptors 1 and 2 and make
captured output available via ``capfdbinary.readouterr`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be
``bytes`` objects.
doctest_namespace
Enable bytes capturing of writes to file descriptors ``1`` and ``2``.
The captured output is made available via ``capfd.readouterr()`` method
calls, which return a ``(out, err)`` namedtuple.
``out`` and ``err`` will be ``byte`` objects.
doctest_namespace [session scope]
Fixture that returns a :py:class:`dict` that will be injected into the namespace of doctests.
pytestconfig
pytestconfig [session scope]
Session-scoped fixture that returns the :class:`_pytest.config.Config` object.
Example::
def test_foo(pytestconfig):
if pytestconfig.getoption("verbose"):
if pytestconfig.getoption("verbose") > 0:
...
record_property
Add an extra properties the calling test.
User properties become part of the test report and are available to the
@@ -68,10 +79,26 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
def test_function(record_property):
record_property("example_key", 1)
record_xml_attribute
Add extra xml attributes to the tag for the calling test.
The fixture is callable with ``(name, value)``, with value being
automatically xml-encoded
record_testsuite_property [session scope]
Records a new ``<property>`` tag as child of the root ``<testsuite>``. This is suitable to
writing global information regarding the entire test suite, and is compatible with ``xunit2`` JUnit family.
This is a ``session``-scoped fixture which is called with ``(name, value)``. Example:
.. code-block:: python
def test_foo(record_testsuite_property):
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.
caplog
Access and control log capturing.
@@ -81,6 +108,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
* caplog.records -> list of logging.LogRecord instances
* caplog.record_tuples -> list of (logger_name, level, message) tuples
* caplog.clear() -> clear captured records and formatted log output string
monkeypatch
The returned ``monkeypatch`` fixture provides these
helper methods to modify objects, dictionaries or os.environ::
@@ -98,15 +126,19 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
test function or fixture has finished. The ``raising``
parameter determines if a KeyError or AttributeError
will be raised if the set/deletion operation has no target.
recwarn
Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
See http://docs.python.org/library/warnings.html for information
on warning categories.
tmpdir_factory
tmpdir_factory [session scope]
Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.
tmp_path_factory
tmp_path_factory [session scope]
Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session.
tmpdir
Return a temporary directory path object
which is unique to each test function invocation,
@@ -115,6 +147,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
path object.
.. _`py.path.local`: https://py.readthedocs.io/en/latest/path.html
tmp_path
Return a temporary directory path object
which is unique to each test function invocation,
@@ -126,9 +159,13 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
in python < 3.6 this is a pathlib2.Path
no tests ran in 0.12 seconds
You can also interactively ask for help, e.g. by typing on the Python interactive prompt something like::
no tests ran in 0.12s
You can also interactively ask for help, e.g. by typing on the Python interactive prompt something like:
.. code-block:: python
import pytest
help(pytest)

View File

@@ -5,7 +5,7 @@
Cache: working with cross-testrun state
=======================================
.. versionadded:: 2.8
Usage
---------
@@ -33,15 +33,18 @@ Other plugins may access the `config.cache`_ object to set/get
Rerunning only failures or failures first
-----------------------------------------------
First, let's create 50 test invocation of which only 2 fail::
First, let's create 50 test invocation of which only 2 fail:
.. code-block:: python
# content of test_50.py
import pytest
@pytest.mark.parametrize("i", range(50))
def test_num(i):
if i in (17, 25):
pytest.fail("bad luck")
pytest.fail("bad luck")
If you run this for the first time you will see two failures:
@@ -57,10 +60,10 @@ If you run this for the first time you will see two failures:
@pytest.mark.parametrize("i", range(50))
def test_num(i):
if i in (17, 25):
> pytest.fail("bad luck")
E Failed: bad luck
> pytest.fail("bad luck")
E Failed: bad luck
test_50.py:6: Failed
test_50.py:7: Failed
_______________________________ test_num[25] _______________________________
i = 25
@@ -68,11 +71,11 @@ If you run this for the first time you will see two failures:
@pytest.mark.parametrize("i", range(50))
def test_num(i):
if i in (17, 25):
> pytest.fail("bad luck")
E Failed: bad luck
> pytest.fail("bad luck")
E Failed: bad luck
test_50.py:6: Failed
2 failed, 48 passed in 0.12 seconds
test_50.py:7: Failed
2 failed, 48 passed in 0.12s
If you then run it with ``--lf``:
@@ -80,9 +83,9 @@ If you then run it with ``--lf``:
$ pytest --lf
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 50 items / 48 deselected / 2 selected
run-last-failure: rerun previous 2 failures
@@ -96,10 +99,10 @@ If you then run it with ``--lf``:
@pytest.mark.parametrize("i", range(50))
def test_num(i):
if i in (17, 25):
> pytest.fail("bad luck")
E Failed: bad luck
> pytest.fail("bad luck")
E Failed: bad luck
test_50.py:6: Failed
test_50.py:7: Failed
_______________________________ test_num[25] _______________________________
i = 25
@@ -107,14 +110,14 @@ If you then run it with ``--lf``:
@pytest.mark.parametrize("i", range(50))
def test_num(i):
if i in (17, 25):
> pytest.fail("bad luck")
E Failed: bad luck
> pytest.fail("bad luck")
E Failed: bad luck
test_50.py:6: Failed
================= 2 failed, 48 deselected in 0.12 seconds ==================
test_50.py:7: Failed
===================== 2 failed, 48 deselected in 0.12s =====================
You have run only the two failing test from the last run, while 48 tests have
not been run ("deselected").
You have run only the two failing tests from the last run, while the 48 passing
tests have not been run ("deselected").
Now, if you run with the ``--ff`` option, all tests will be run but the first
previous failures will be executed first (as can be seen from the series
@@ -124,9 +127,9 @@ of ``FF`` and dots):
$ pytest --ff
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 50 items
run-last-failure: rerun previous 2 failures first
@@ -140,10 +143,10 @@ of ``FF`` and dots):
@pytest.mark.parametrize("i", range(50))
def test_num(i):
if i in (17, 25):
> pytest.fail("bad luck")
E Failed: bad luck
> pytest.fail("bad luck")
E Failed: bad luck
test_50.py:6: Failed
test_50.py:7: Failed
_______________________________ test_num[25] _______________________________
i = 25
@@ -151,11 +154,11 @@ of ``FF`` and dots):
@pytest.mark.parametrize("i", range(50))
def test_num(i):
if i in (17, 25):
> pytest.fail("bad luck")
E Failed: bad luck
> pytest.fail("bad luck")
E Failed: bad luck
test_50.py:6: Failed
=================== 2 failed, 48 passed in 0.12 seconds ====================
test_50.py:7: Failed
======================= 2 failed, 48 passed in 0.12s =======================
.. _`config.cache`:
@@ -183,15 +186,19 @@ The new config.cache object
Plugins or conftest.py support code can get a cached value using the
pytest ``config`` object. Here is a basic example plugin which
implements a :ref:`fixture` which re-uses previously created state
across pytest invocations::
across pytest invocations:
.. code-block:: python
# content of test_caching.py
import pytest
import time
def expensive_computation():
print("running expensive computation...")
@pytest.fixture
def mydata(request):
val = request.config.cache.get("example/value", None)
@@ -201,6 +208,7 @@ across pytest invocations::
request.config.cache.set("example/value", val)
return val
def test_function(mydata):
assert mydata == 23
@@ -218,15 +226,13 @@ If you run this command for the first time, you can see the print statement:
def test_function(mydata):
> assert mydata == 23
E assert 42 == 23
E -42
E +23
test_caching.py:17: AssertionError
test_caching.py:20: AssertionError
-------------------------- Captured stdout setup ---------------------------
running expensive computation...
1 failed in 0.12 seconds
1 failed in 0.12s
If you run it a second time the value will be retrieved from
If you run it a second time, the value will be retrieved from
the cache and nothing will be printed:
.. code-block:: pytest
@@ -241,17 +247,15 @@ the cache and nothing will be printed:
def test_function(mydata):
> assert mydata == 23
E assert 42 == 23
E -42
E +23
test_caching.py:17: AssertionError
1 failed in 0.12 seconds
test_caching.py:20: AssertionError
1 failed in 0.12s
See the :ref:`cache-api` for more details.
Inspecting Cache content
-------------------------------
------------------------
You can always peek at the content of the cache using the
``--cache-show`` command line option:
@@ -260,11 +264,11 @@ You can always peek at the content of the cache using the
$ pytest --cache-show
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
cachedir: $PYTHON_PREFIX/.pytest_cache
------------------------------- cache values -------------------------------
--------------------------- cache values for '*' ---------------------------
cache/lastfailed contains:
{'test_50.py::test_num[17]': True,
'test_50.py::test_num[25]': True,
@@ -279,10 +283,27 @@ You can always peek at the content of the cache using the
example/value contains:
42
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
``--cache-show`` takes an optional argument to specify a glob pattern for
filtering:
.. code-block:: pytest
$ pytest --cache-show example/*
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR
cachedir: $PYTHON_PREFIX/.pytest_cache
----------------------- cache values for 'example/*' -----------------------
example/value contains:
42
========================== no tests ran in 0.12s ===========================
Clearing Cache content
-------------------------------
----------------------
You can instruct pytest to clear all cache files and values
by adding the ``--cache-clear`` option like this:

View File

@@ -49,16 +49,21 @@ Using print statements for debugging
---------------------------------------------------
One primary benefit of the default capturing of stdout/stderr output
is that you can use print statements for debugging::
is that you can use print statements for debugging:
.. code-block:: python
# content of test_module.py
def setup_function(function):
print("setting up %s" % function)
print("setting up", function)
def test_func1():
assert True
def test_func2():
assert False
@@ -69,9 +74,9 @@ of the failing function and hide the other one:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 2 items
test_module.py .F [100%]
@@ -83,10 +88,10 @@ of the failing function and hide the other one:
> assert False
E assert False
test_module.py:9: AssertionError
test_module.py:12: AssertionError
-------------------------- Captured stdout setup ---------------------------
setting up <function test_func2 at 0xdeadbeef>
==================== 1 failed, 1 passed in 0.12 seconds ====================
======================= 1 failed, 1 passed in 0.12s ========================
Accessing captured output from a test function
---------------------------------------------------
@@ -121,11 +126,11 @@ same interface but allows to also capture output from
libraries or subprocesses that directly write to operating
system level output streams (FD1 and FD2).
.. versionadded:: 3.3
The return value from ``readouterr`` changed to a ``namedtuple`` with two attributes, ``out`` and ``err``.
.. versionadded:: 3.3
If the code under test writes non-textual data, you can capture this using
the ``capsysbinary`` fixture which instead returns ``bytes`` from
@@ -133,7 +138,7 @@ the ``readouterr`` method. The ``capfsysbinary`` fixture is currently only
available in python 3.
.. versionadded:: 3.3
If the code under test writes non-textual data, you can capture this using
the ``capfdbinary`` fixture which instead returns ``bytes`` from
@@ -141,7 +146,7 @@ the ``readouterr`` method. The ``capfdbinary`` fixture operates on the
filedescriptor level.
.. versionadded:: 3.0
To temporarily disable capture within a test, both ``capsys``
and ``capfd`` have a ``disabled()`` method that can be used

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# pytest documentation build configuration file, created by
# sphinx-quickstart on Fri Oct 8 17:54:28 2010.
@@ -16,7 +15,6 @@
#
# The full version, including alpha/beta/rc tags.
# The short X.Y version.
import datetime
import os
import sys
@@ -63,9 +61,8 @@ source_suffix = ".rst"
master_doc = "contents"
# General information about the project.
project = u"pytest"
year = datetime.datetime.utcnow().year
copyright = u"20152019 , holger krekel and pytest-dev team"
project = "pytest"
copyright = "20152019, holger krekel and pytest-dev team"
# The language for content autogenerated by Sphinx. Refer to documentation
@@ -168,18 +165,18 @@ html_favicon = "img/pytest1favi.ico"
html_sidebars = {
"index": [
"slim_searchbox.html",
"sidebarintro.html",
"globaltoc.html",
"links.html",
"sourcelink.html",
"searchbox.html",
],
"**": [
"slim_searchbox.html",
"globaltoc.html",
"relations.html",
"links.html",
"sourcelink.html",
"searchbox.html",
],
}
@@ -233,8 +230,8 @@ latex_documents = [
(
"contents",
"pytest.tex",
u"pytest Documentation",
u"holger krekel, trainer and consultant, http://merlinux.eu",
"pytest Documentation",
"holger krekel, trainer and consultant, http://merlinux.eu",
"manual",
)
]
@@ -266,16 +263,16 @@ latex_domain_indices = False
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [("usage", "pytest", u"pytest usage", [u"holger krekel at merlinux eu"], 1)]
man_pages = [("usage", "pytest", "pytest usage", ["holger krekel at merlinux eu"], 1)]
# -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u"pytest"
epub_author = u"holger krekel at merlinux eu"
epub_publisher = u"holger krekel at merlinux eu"
epub_copyright = u"2013, holger krekel et alii"
epub_title = "pytest"
epub_author = "holger krekel at merlinux eu"
epub_publisher = "holger krekel at merlinux eu"
epub_copyright = "2013, holger krekel et alii"
# The language of the text. It defaults to the language option
# or en if the language is not set.
@@ -335,7 +332,7 @@ intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}
def setup(app):
# from sphinx.ext.autodoc import cut_lines
# app.connect('autodoc-process-docstring', cut_lines(4, what=['module']))
app.add_description_unit(
app.add_object_type(
"confval",
"confval",
objname="configuration value",

View File

@@ -50,6 +50,7 @@ Full pytest documentation
projects
faq
contact
sponsor
.. only:: html

View File

@@ -20,7 +20,7 @@ which were registered by installed plugins.
Initialization: determining rootdir and inifile
-----------------------------------------------
.. versionadded:: 2.7
pytest determines a ``rootdir`` for each test run which depends on
the command line arguments (specified test files, paths) and on
@@ -90,7 +90,7 @@ The ``config`` object will subsequently carry these attributes:
- ``config.inifile``: the determined ini-file, may be ``None``.
The rootdir is used a reference directory for constructing test
The rootdir is used as a reference directory for constructing test
addresses ("nodeids") and can be used also by plugins for storing
per-testrun information.
@@ -107,8 +107,8 @@ check for ini-files as follows:
# first look for pytest.ini files
path/pytest.ini
path/setup.cfg # must also contain [tool:pytest] section to match
path/tox.ini # must also contain [pytest] section to match
path/setup.cfg # must also contain [tool:pytest] section to match
pytest.ini
... # all the way down to the root

View File

@@ -19,10 +19,62 @@ Below is a complete list of all pytest features which are considered deprecated.
:class:`_pytest.warning_types.PytestWarning` or subclasses, which can be filtered using
:ref:`standard warning filters <warnings>`.
``funcargnames`` alias for ``fixturenames``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 5.0
The ``FixtureRequest``, ``Metafunc``, and ``Function`` classes track the names of
their associated fixtures, with the aptly-named ``fixturenames`` attribute.
Prior to pytest 2.3, this attribute was named ``funcargnames``, and we have kept
that as an alias since. It is finally due for removal, as it is often confusing
in places where we or plugin authors must distinguish between fixture names and
names supplied by non-fixture things such as ``pytest.mark.parametrize``.
Result log (``--result-log``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 4.0
The ``--result-log`` option produces a stream of test reports which can be
analysed at runtime. It uses a custom format which requires users to implement their own
parser, but the team believes using a line-based format that can be parsed using standard
tools would provide a suitable and better alternative.
The current plan is to provide an alternative in the pytest 5.0 series and remove the ``--result-log``
option in pytest 6.0 after the new implementation proves satisfactory to all users and is deemed
stable.
The actual alternative is still being discussed in issue `#4488 <https://github.com/pytest-dev/pytest/issues/4488>`__.
Removed Features
----------------
As stated in our :ref:`backwards-compatibility` policy, deprecated features are removed only in major releases after
an appropriate period of deprecation has passed.
``pytest.config`` global
~~~~~~~~~~~~~~~~~~~~~~~~
.. versionremoved:: 5.0
The ``pytest.config`` global object is deprecated. Instead use
``request.config`` (via the ``request`` fixture) or if you are a plugin author
use the ``pytest_configure(config)`` hook. Note that many hooks can also access
the ``config`` object indirectly, through ``session.config`` or ``item.config`` for example.
.. _`raises message deprecated`:
``"message"`` parameter of ``pytest.raises``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 4.1
.. versionremoved:: 5.0
It is a common mistake to think this parameter will match the exception message, while in fact
it only serves to provide a custom message in case the ``pytest.raises`` check fails. To prevent
@@ -53,21 +105,12 @@ If you still have concerns about this deprecation and future removal, please com
`issue #3974 <https://github.com/pytest-dev/pytest/issues/3974>`__.
``pytest.config`` global
~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 4.1
The ``pytest.config`` global object is deprecated. Instead use
``request.config`` (via the ``request`` fixture) or if you are a plugin author
use the ``pytest_configure(config)`` hook.
.. _raises-warns-exec:
``raises`` / ``warns`` with a string as the second argument
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 4.1
.. versionremoved:: 5.0
Use the context manager form of these instead. When necessary, invoke ``exec``
directly.
@@ -99,26 +142,6 @@ Becomes:
Result log (``--result-log``)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. deprecated:: 3.0
The ``--resultlog`` command line option has been deprecated: it is little used
and there are more modern and better alternatives, for example `pytest-tap <https://tappy.readthedocs.io/en/latest/>`_.
This feature will be effectively removed in pytest 4.0 as the team intends to include a better alternative in the core.
If you have any concerns, please don't hesitate to `open an issue <https://github.com/pytest-dev/pytest/issues>`__.
Removed Features
----------------
As stated in our :ref:`backwards-compatibility` policy, deprecated features are removed only in major releases after
an appropriate period of deprecation has passed.
Using ``Class`` in custom Collectors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -436,7 +459,9 @@ Internal classes accessed through ``Node``
.. versionremoved:: 4.0
Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances now issue
this warning::
this warning:
.. code-block:: text
usage of Function.Module is deprecated, please use pytest.Module instead

View File

@@ -10,29 +10,63 @@ can change the pattern by issuing:
pytest --doctest-glob='*.rst'
on the command line. Since version ``2.9``, ``--doctest-glob``
can be given multiple times in the command-line.
on the command line. ``--doctest-glob`` can be given multiple times in the command-line.
.. versionadded:: 3.1
If you then have a text file like this:
You can specify the encoding that will be used for those doctest files
using the ``doctest_encoding`` ini option:
.. code-block:: text
.. code-block:: ini
# content of test_example.txt
# content of pytest.ini
[pytest]
doctest_encoding = latin1
hello this is a doctest
>>> x = 3
>>> x
3
The default encoding is UTF-8.
then you can just invoke ``pytest`` directly:
You can also trigger running of doctests
from docstrings in all python modules (including regular
python test modules):
.. code-block:: pytest
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_example.txt . [100%]
============================ 1 passed in 0.12s =============================
By default, pytest will collect ``test*.txt`` files looking for doctest directives, but you
can pass additional globs using the ``--doctest-glob`` option (multi-allowed).
In addition to text files, you can also execute doctests directly from docstrings of your classes
and functions, including from test modules:
.. code-block:: python
# content of mymodule.py
def something():
""" a doctest in a docstring
>>> something()
42
"""
return 42
.. code-block:: bash
pytest --doctest-modules
$ pytest --doctest-modules
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR
collected 2 items
mymodule.py . [ 50%]
test_example.txt . [100%]
============================ 2 passed in 0.12s =============================
You can make these changes permanent in your project by
putting them into a pytest.ini file like this:
@@ -43,41 +77,123 @@ putting them into a pytest.ini file like this:
[pytest]
addopts = --doctest-modules
If you then have a text file like this:
.. note::
.. code-block:: text
The builtin pytest doctest supports only ``doctest`` blocks, but if you are looking
for more advanced checking over *all* your documentation,
including doctests, ``.. codeblock:: python`` Sphinx directive support,
and any other examples your documentation may include, you may wish to
consider `Sybil <https://sybil.readthedocs.io/en/latest/index.html>`__.
It provides pytest integration out of the box.
# content of example.rst
hello this is a doctest
>>> x = 3
>>> x
3
Encoding
--------
and another like this::
The default encoding is **UTF-8**, but you can specify the encoding
that will be used for those doctest files using the
``doctest_encoding`` ini option:
# content of mymodule.py
def something():
""" a doctest in a docstring
>>> something()
42
"""
return 42
.. code-block:: ini
then you can just invoke ``pytest`` without command line options:
# content of pytest.ini
[pytest]
doctest_encoding = latin1
.. code-block:: pytest
Using 'doctest' options
-----------------------
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini
collected 1 item
Python's standard ``doctest`` module provides some `options <https://docs.python.org/3/library/doctest.html#option-flags>`__
to configure the strictness of doctest tests. In pytest, you can enable those flags using the
configuration file.
mymodule.py . [100%]
For example, to make pytest ignore trailing whitespaces and ignore
lengthy exception stack traces you can just write:
========================= 1 passed in 0.12 seconds =========================
.. code-block:: ini
[pytest]
doctest_optionflags= NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL
Alternatively, options can be enabled by an inline comment in the doc test
itself:
.. code-block:: rst
>>> something_that_raises() # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
ValueError: ...
pytest also introduces new options:
* ``ALLOW_UNICODE``: when enabled, the ``u`` prefix is stripped from unicode
strings in expected doctest output. This allows doctests to run in Python 2
and Python 3 unchanged.
* ``ALLOW_BYTES``: similarly, the ``b`` prefix is stripped from byte strings
in expected doctest output.
* ``NUMBER``: when enabled, floating-point numbers only need to match as far as
the precision you have written in the expected doctest output. For example,
the following output would only need to match to 2 decimal places::
>>> math.pi
3.14
If you wrote ``3.1416`` then the actual output would need to match to 4
decimal places; and so on.
This avoids false positives caused by limited floating-point precision, like
this::
Expected:
0.233
Got:
0.23300000000000001
``NUMBER`` also supports lists of floating-point numbers -- in fact, it
matches floating-point numbers appearing anywhere in the output, even inside
a string! This means that it may not be appropriate to enable globally in
``doctest_optionflags`` in your configuration file.
Continue on failure
-------------------
By default, pytest would report only the first failure for a given doctest. If
you want to continue the test even when you have failures, do:
.. code-block:: bash
pytest --doctest-modules --doctest-continue-on-failure
Output format
-------------
You can change the diff output format on failure for your doctests
by using one of standard doctest modules format in options
(see :data:`python:doctest.REPORT_UDIFF`, :data:`python:doctest.REPORT_CDIFF`,
:data:`python:doctest.REPORT_NDIFF`, :data:`python:doctest.REPORT_ONLY_FIRST_FAILURE`):
.. code-block:: bash
pytest --doctest-modules --doctest-report none
pytest --doctest-modules --doctest-report udiff
pytest --doctest-modules --doctest-report cdiff
pytest --doctest-modules --doctest-report ndiff
pytest --doctest-modules --doctest-report only_first_failure
pytest-specific features
------------------------
Some features are provided to make writing doctests easier or with better integration with
your existing test suite. Keep in mind however that by using those features you will make
your doctests incompatible with the standard ``doctests`` module.
Using fixtures
^^^^^^^^^^^^^^
It is possible to use fixtures using the ``getfixture`` helper:
@@ -91,72 +207,32 @@ It is possible to use fixtures using the ``getfixture`` helper:
Also, :ref:`usefixtures` and :ref:`autouse` fixtures are supported
when executing text doctest files.
The standard ``doctest`` module provides some setting flags to configure the
strictness of doctest tests. In pytest, you can enable those flags using the
configuration file. To make pytest ignore trailing whitespaces and ignore
lengthy exception stack traces you can just write:
.. code-block:: ini
[pytest]
doctest_optionflags= NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL
pytest also introduces new options to allow doctests to run in Python 2 and
Python 3 unchanged:
* ``ALLOW_UNICODE``: when enabled, the ``u`` prefix is stripped from unicode
strings in expected doctest output.
* ``ALLOW_BYTES``: when enabled, the ``b`` prefix is stripped from byte strings
in expected doctest output.
As with any other option flag, these flags can be enabled in ``pytest.ini`` using
the ``doctest_optionflags`` ini option:
.. code-block:: ini
[pytest]
doctest_optionflags = ALLOW_UNICODE ALLOW_BYTES
Alternatively, it can be enabled by an inline comment in the doc test
itself:
.. code-block:: rst
# content of example.rst
>>> get_unicode_greeting() # doctest: +ALLOW_UNICODE
'Hello'
By default, pytest would report only the first failure for a given doctest. If
you want to continue the test even when you have failures, do:
.. code-block:: bash
pytest --doctest-modules --doctest-continue-on-failure
.. _`doctest_namespace`:
The 'doctest_namespace' fixture
-------------------------------
.. versionadded:: 3.0
'doctest_namespace' fixture
^^^^^^^^^^^^^^^^^^^^^^^^^^^
The ``doctest_namespace`` fixture can be used to inject items into the
namespace in which your doctests run. It is intended to be used within
your own fixtures to provide the tests that use them with context.
``doctest_namespace`` is a standard ``dict`` object into which you
place the objects you want to appear in the doctest namespace::
place the objects you want to appear in the doctest namespace:
.. code-block:: python
# content of conftest.py
import numpy
@pytest.fixture(autouse=True)
def add_np(doctest_namespace):
doctest_namespace['np'] = numpy
doctest_namespace["np"] = numpy
which can then be used in your doctests directly::
which can then be used in your doctests directly:
.. code-block:: python
# content of numpy.py
def arange():
@@ -171,20 +247,16 @@ Note that like the normal ``conftest.py``, the fixtures are discovered in the di
Meaning that if you put your doctest with your source code, the relevant conftest.py needs to be in the same directory tree.
Fixtures will not be discovered in a sibling directory tree!
Output format
-------------
Skipping tests dynamically
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.0
.. versionadded:: 4.4
You can change the diff output format on failure for your doctests
by using one of standard doctest modules format in options
(see :data:`python:doctest.REPORT_UDIFF`, :data:`python:doctest.REPORT_CDIFF`,
:data:`python:doctest.REPORT_NDIFF`, :data:`python:doctest.REPORT_ONLY_FIRST_FAILURE`):
You can use ``pytest.skip`` to dynamically skip doctests. For example:
.. code-block:: bash
.. code-block:: text
pytest --doctest-modules --doctest-report none
pytest --doctest-modules --doctest-report udiff
pytest --doctest-modules --doctest-report cdiff
pytest --doctest-modules --doctest-report ndiff
pytest --doctest-modules --doctest-report only_first_failure
>>> import sys, pytest
>>> if sys.platform.startswith('win'):
... pytest.skip('this doctest does not work on Windows')
...

View File

@@ -1,5 +1,3 @@
import six
import _pytest._code
import pytest
from pytest import raises
@@ -22,7 +20,7 @@ def test_generative(param1, param2):
assert param1 * 2 < param2
class TestFailing(object):
class TestFailing:
def test_simple(self):
def f():
return 42
@@ -42,7 +40,7 @@ class TestFailing(object):
assert not f()
class TestSpecialisedExplanations(object):
class TestSpecialisedExplanations:
def test_eq_text(self):
assert "spam" == "eggs"
@@ -102,7 +100,7 @@ class TestSpecialisedExplanations(object):
from dataclasses import dataclass
@dataclass
class Foo(object):
class Foo:
a: int
b: str
@@ -114,7 +112,7 @@ class TestSpecialisedExplanations(object):
import attr
@attr.s
class Foo(object):
class Foo:
a = attr.ib()
b = attr.ib()
@@ -124,7 +122,7 @@ class TestSpecialisedExplanations(object):
def test_attribute():
class Foo(object):
class Foo:
b = 1
i = Foo()
@@ -132,14 +130,14 @@ def test_attribute():
def test_attribute_instance():
class Foo(object):
class Foo:
b = 1
assert Foo().b == 2
def test_attribute_failure():
class Foo(object):
class Foo:
def _get_b(self):
raise Exception("Failed to get attrib")
@@ -150,10 +148,10 @@ def test_attribute_failure():
def test_attribute_multiple():
class Foo(object):
class Foo:
b = 1
class Bar(object):
class Bar:
b = 2
assert Foo().b == Bar().b
@@ -163,7 +161,7 @@ def globf(x):
return x + 1
class TestRaises(object):
class TestRaises:
def test_raises(self):
s = "qwe"
raises(TypeError, int, s)
@@ -179,7 +177,7 @@ class TestRaises(object):
def test_reinterpret_fails_with_print_for_the_fun_of_it(self):
items = [1, 2, 3]
print("items is %r" % items)
print("items is {!r}".format(items))
a, b = items.pop()
def test_some_error(self):
@@ -192,19 +190,20 @@ class TestRaises(object):
# thanks to Matthew Scott for this test
def test_dynamic_compile_shows_nicely():
import imp
import importlib.util
import sys
src = "def foo():\n assert 1 == 0\n"
name = "abc-123"
module = imp.new_module(name)
spec = importlib.util.spec_from_loader(name, loader=None)
module = importlib.util.module_from_spec(spec)
code = _pytest._code.compile(src, name, "exec")
six.exec_(code, module.__dict__)
exec(code, module.__dict__)
sys.modules[name] = module
module.foo()
class TestMoreErrors(object):
class TestMoreErrors:
def test_complex_error(self):
def f():
return 44
@@ -254,16 +253,16 @@ class TestMoreErrors(object):
x = 0
class TestCustomAssertMsg(object):
class TestCustomAssertMsg:
def test_single_line(self):
class A(object):
class A:
a = 1
b = 2
assert A.a == b, "A.a appears not to be b"
def test_multiline(self):
class A(object):
class A:
a = 1
b = 2
@@ -272,7 +271,7 @@ class TestCustomAssertMsg(object):
), "A.a appears not to be b\nor does not appear to be b\none of those"
def test_custom_repr(self):
class JSON(object):
class JSON:
a = 1
def __repr__(self):

View File

@@ -2,7 +2,7 @@ def setup_module(module):
module.TestStateFullThing.classcount = 0
class TestStateFullThing(object):
class TestStateFullThing:
def setup_class(cls):
cls.classcount += 1

View File

@@ -18,7 +18,7 @@ example: specifying and selecting acceptance tests
return AcceptFixture(request)
class AcceptFixture(object):
class AcceptFixture:
def __init__(self, request):
if not request.config.getoption("acceptance"):
pytest.skip("specify -A to run acceptance tests")
@@ -65,7 +65,7 @@ extend the `accept example`_ by putting this in our test module:
return arg
class TestSpecialAcceptance(object):
class TestSpecialAcceptance:
def test_sometest(self, accept):
assert accept.tmpdir.join("special").check()

View File

@@ -1,14 +1,14 @@
import pytest
@pytest.fixture("session")
@pytest.fixture(scope="session")
def setup(request):
setup = CostlySetup()
yield setup
setup.finalize()
class CostlySetup(object):
class CostlySetup:
def __init__(self):
import time

View File

@@ -0,0 +1,38 @@
import pytest
# fixtures documentation order example
order = []
@pytest.fixture(scope="session")
def s1():
order.append("s1")
@pytest.fixture(scope="module")
def m1():
order.append("m1")
@pytest.fixture
def f1(f3):
order.append("f1")
@pytest.fixture
def f3():
order.append("f3")
@pytest.fixture(autouse=True)
def a1():
order.append("a1")
@pytest.fixture
def f2():
order.append("f2")
def test_order(f1, m1, f2, s1):
assert order == ["s1", "m1", "a1", "f3", "f1", "f2"]

View File

@@ -4,28 +4,40 @@
Working with custom markers
=================================================
Here are some example using the :ref:`mark` mechanism.
Here are some examples using the :ref:`mark` mechanism.
.. _`mark run`:
Marking test functions and selecting them for a run
----------------------------------------------------
You can "mark" a test function with custom metadata like this::
You can "mark" a test function with custom metadata like this:
.. code-block:: python
# content of test_server.py
import pytest
@pytest.mark.webtest
def test_send_http():
pass # perform some webtest test for your app
pass # perform some webtest test for your app
def test_something_quick():
pass
def test_another():
pass
class TestClass(object):
class TestClass:
def test_method(self):
pass
.. versionadded:: 2.2
You can then restrict a test run to only run tests marked with ``webtest``:
@@ -33,14 +45,14 @@ You can then restrict a test run to only run tests marked with ``webtest``:
$ pytest -v -m webtest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 4 items / 3 deselected / 1 selected
test_server.py::test_send_http PASSED [100%]
================== 1 passed, 3 deselected in 0.12 seconds ==================
===================== 1 passed, 3 deselected in 0.12s ======================
Or the inverse, running all tests except the webtest ones:
@@ -48,16 +60,16 @@ Or the inverse, running all tests except the webtest ones:
$ pytest -v -m "not webtest"
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 4 items / 1 deselected / 3 selected
test_server.py::test_something_quick PASSED [ 33%]
test_server.py::test_another PASSED [ 66%]
test_server.py::TestClass::test_method PASSED [100%]
================== 3 passed, 1 deselected in 0.12 seconds ==================
===================== 3 passed, 1 deselected in 0.12s ======================
Selecting tests based on their node ID
--------------------------------------
@@ -70,14 +82,14 @@ tests based on their module, class, method, or function name:
$ pytest -v test_server.py::TestClass::test_method
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 1 item
test_server.py::TestClass::test_method PASSED [100%]
========================= 1 passed in 0.12 seconds =========================
============================ 1 passed in 0.12s =============================
You can also select on the class:
@@ -85,14 +97,14 @@ You can also select on the class:
$ pytest -v test_server.py::TestClass
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 1 item
test_server.py::TestClass::test_method PASSED [100%]
========================= 1 passed in 0.12 seconds =========================
============================ 1 passed in 0.12s =============================
Or select multiple nodes:
@@ -100,15 +112,15 @@ Or select multiple nodes:
$ pytest -v test_server.py::TestClass test_server.py::test_send_http
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 2 items
test_server.py::TestClass::test_method PASSED [ 50%]
test_server.py::test_send_http PASSED [100%]
========================= 2 passed in 0.12 seconds =========================
============================ 2 passed in 0.12s =============================
.. _node-id:
@@ -140,14 +152,14 @@ select tests based on their names:
$ pytest -v -k http # running with the above defined example module
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 4 items / 3 deselected / 1 selected
test_server.py::test_send_http PASSED [100%]
================== 1 passed, 3 deselected in 0.12 seconds ==================
===================== 1 passed, 3 deselected in 0.12s ======================
And you can also run all tests except the ones that match the keyword:
@@ -155,16 +167,16 @@ And you can also run all tests except the ones that match the keyword:
$ pytest -k "not send_http" -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 4 items / 1 deselected / 3 selected
test_server.py::test_something_quick PASSED [ 33%]
test_server.py::test_another PASSED [ 66%]
test_server.py::TestClass::test_method PASSED [100%]
================== 3 passed, 1 deselected in 0.12 seconds ==================
===================== 3 passed, 1 deselected in 0.12s ======================
Or to select "http" and "quick" tests:
@@ -172,15 +184,15 @@ Or to select "http" and "quick" tests:
$ pytest -k "http or quick" -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 4 items / 2 deselected / 2 selected
test_server.py::test_send_http PASSED [ 50%]
test_server.py::test_something_quick PASSED [100%]
================== 2 passed, 2 deselected in 0.12 seconds ==================
===================== 2 passed, 2 deselected in 0.12s ======================
.. note::
@@ -200,7 +212,7 @@ Or to select "http" and "quick" tests:
Registering markers
-------------------------------------
.. versionadded:: 2.2
.. ini-syntax for custom markers:
@@ -249,7 +261,7 @@ For an example on how to add and work with markers from a plugin, see
* Asking for existing markers via ``pytest --markers`` gives good output
* Typos in function markers are treated as an error if you use
the ``--strict`` option.
the ``--strict-markers`` option.
.. _`scoped-marking`:
@@ -257,33 +269,43 @@ Marking whole classes or modules
----------------------------------------------------
You may use ``pytest.mark`` decorators with classes to apply markers to all of
its test methods::
its test methods:
.. code-block:: python
# content of test_mark_classlevel.py
import pytest
@pytest.mark.webtest
class TestClass(object):
class TestClass:
def test_startup(self):
pass
def test_startup_and_more(self):
pass
This is equivalent to directly applying the decorator to the
two test functions.
To remain backward-compatible with Python 2.4 you can also set a
``pytestmark`` attribute on a TestClass like this::
Due to legacy reasons, it is possible to set the ``pytestmark`` attribute on a TestClass like this:
.. code-block:: python
import pytest
class TestClass(object):
class TestClass:
pytestmark = pytest.mark.webtest
or if you need to use multiple markers you can use a list::
or if you need to use multiple markers you can use a list:
.. code-block:: python
import pytest
class TestClass(object):
class TestClass:
pytestmark = [pytest.mark.webtest, pytest.mark.slowtest]
You can also set a module level marker::
@@ -305,18 +327,19 @@ Marking individual tests when using parametrize
When using parametrize, applying a mark will make it apply
to each individual test. However it is also possible to
apply a marker to an individual test instance::
apply a marker to an individual test instance:
.. code-block:: python
import pytest
@pytest.mark.foo
@pytest.mark.parametrize(("n", "expected"), [
(1, 2),
pytest.param((1, 3), marks=pytest.mark.bar),
(2, 3),
])
@pytest.mark.parametrize(
("n", "expected"), [(1, 2), pytest.param(1, 3, marks=pytest.mark.bar), (2, 3)]
)
def test_increment(n, expected):
assert n + 1 == expected
assert n + 1 == expected
In this example the mark "foo" will apply to each of the three
tests, whereas the "bar" mark is only applied to the second test.
@@ -332,31 +355,46 @@ 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::
specifies via named environments:
.. code-block:: python
# content of conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption("-E", action="store", metavar="NAME",
help="only run tests matching the environment NAME.")
parser.addoption(
"-E",
action="store",
metavar="NAME",
help="only run tests matching the environment NAME.",
)
def pytest_configure(config):
# register an additional marker
config.addinivalue_line("markers",
"env(name): mark test to run only on named environment")
config.addinivalue_line(
"markers", "env(name): mark test to run only on named environment"
)
def pytest_runtest_setup(item):
envnames = [mark.args[0] for mark in item.iter_markers(name='env')]
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" % envnames)
pytest.skip("test requires env in {!r}".format(envnames))
A test file using this local plugin::
A test file using this local plugin:
.. code-block:: python
# content of test_someenv.py
import pytest
@pytest.mark.env("stage1")
def test_basic_db_operation():
pass
@@ -368,14 +406,14 @@ the test needs:
$ pytest -E stage2
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_someenv.py s [100%]
======================== 1 skipped in 0.12 seconds =========================
============================ 1 skipped in 0.12s ============================
and here is one that specifies exactly the environment needed:
@@ -383,14 +421,14 @@ and here is one that specifies exactly the environment needed:
$ pytest -E stage1
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_someenv.py . [100%]
========================= 1 passed in 0.12 seconds =========================
============================ 1 passed in 0.12s =============================
The ``--markers`` option always gives you a list of available markers:
@@ -423,25 +461,32 @@ Passing a callable to custom markers
.. regendoc:wipe
Below is the config file that will be used in the next examples::
Below is the config file that will be used in the next examples:
.. code-block:: python
# content of conftest.py
import sys
def pytest_runtest_setup(item):
for marker in item.iter_markers(name='my_marker'):
for marker in item.iter_markers(name="my_marker"):
print(marker)
sys.stdout.flush()
A custom marker can have its argument set, i.e. ``args`` and ``kwargs`` properties, defined by either invoking it as a callable or using ``pytest.mark.MARKER_NAME.with_args``. These two methods achieve the same effect most of the time.
However, if there is a callable as the single positional argument with no keyword arguments, using the ``pytest.mark.MARKER_NAME(c)`` will not pass ``c`` as a positional argument but decorate ``c`` with the custom marker (see :ref:`MarkDecorator <mark>`). Fortunately, ``pytest.mark.MARKER_NAME.with_args`` comes to the rescue::
However, if there is a callable as the single positional argument with no keyword arguments, using the ``pytest.mark.MARKER_NAME(c)`` will not pass ``c`` as a positional argument but decorate ``c`` with the custom marker (see :ref:`MarkDecorator <mark>`). Fortunately, ``pytest.mark.MARKER_NAME.with_args`` comes to the rescue:
.. code-block:: python
# content of test_custom_marker.py
import pytest
def hello_world(*args, **kwargs):
return 'Hello World'
return "Hello World"
@pytest.mark.my_marker.with_args(hello_world)
def test_with_args():
@@ -454,7 +499,7 @@ The output is as follows:
$ pytest -q -s
Mark(name='my_marker', args=(<function hello_world at 0xdeadbeef>,), kwargs={})
.
1 passed in 0.12 seconds
1 passed in 0.12s
We can see that the custom marker has its argument set extended with the function ``hello_world``. This is the key difference between creating a custom marker as a callable, which invokes ``__call__`` behind the scenes, and using ``with_args``.
@@ -467,27 +512,34 @@ Reading markers which were set from multiple places
.. regendoc:wipe
If you are heavily using markers in your test suite you may encounter the case where a marker is applied several times to a test function. From plugin
code you can read over all such settings. Example::
code you can read over all such settings. Example:
.. code-block:: python
# content of test_mark_three_times.py
import pytest
pytestmark = pytest.mark.glob("module", x=1)
@pytest.mark.glob("class", x=2)
class TestClass(object):
class TestClass:
@pytest.mark.glob("function", x=3)
def test_something(self):
pass
Here we have the marker "glob" applied three times to the same
test function. From a conftest file we can read it like this::
test function. From a conftest file we can read it like this:
.. code-block:: python
# content of conftest.py
import sys
def pytest_runtest_setup(item):
for mark in item.iter_markers(name='glob'):
print("glob args=%s kwargs=%s" % (mark.args, mark.kwargs))
for mark in item.iter_markers(name="glob"):
print("glob args={} kwargs={}".format(mark.args, mark.kwargs))
sys.stdout.flush()
Let's run this without capturing output and see what we get:
@@ -499,7 +551,7 @@ Let's run this without capturing output and see what we get:
glob args=('class',) kwargs={'x': 2}
glob args=('module',) kwargs={'x': 1}
.
1 passed in 0.12 seconds
1 passed in 0.12s
marking platform specific tests with pytest
--------------------------------------------------------------
@@ -510,7 +562,9 @@ Consider you have a test suite which marks tests for particular platforms,
namely ``pytest.mark.darwin``, ``pytest.mark.win32`` etc. and you
also have tests that run on all platforms and have no specific
marker. If you now want to have a way to only run the tests
for your particular platform, you could use the following plugin::
for your particular platform, you could use the following plugin:
.. code-block:: python
# content of conftest.py
#
@@ -519,31 +573,38 @@ for your particular platform, you could use the following plugin::
ALL = set("darwin linux win32".split())
def pytest_runtest_setup(item):
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 %s" % (plat))
pytest.skip("cannot run on platform {}".format(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::
Let's do a little test file to show how this looks like:
.. code-block:: python
# content of test_plat.py
import pytest
@pytest.mark.darwin
def test_if_apple_is_evil():
pass
@pytest.mark.linux
def test_if_linux_works():
pass
@pytest.mark.win32
def test_if_win32_crashes():
pass
def test_runs_everywhere():
pass
@@ -553,16 +614,16 @@ then you will see two tests skipped and two executed tests as expected:
$ pytest -rs # this option reports skip reasons
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 4 items
test_plat.py s.s. [100%]
========================= short test summary info ==========================
SKIPPED [2] $REGENDOC_TMPDIR/conftest.py:12: cannot run on platform linux
=================== 2 passed, 2 skipped in 0.12 seconds ====================
========================= short test summary info ==========================
SKIPPED [2] $REGENDOC_TMPDIR/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:
@@ -570,14 +631,14 @@ Note that if you specify a platform via the marker-command line option like this
$ pytest -m linux
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 4 items / 3 deselected / 1 selected
test_plat.py . [100%]
================== 1 passed, 3 deselected in 0.12 seconds ==================
===================== 1 passed, 3 deselected in 0.12s ======================
then the unmarked-tests will not be run. It is thus a way to restrict the run to the specific tests.
@@ -589,28 +650,38 @@ Automatically adding markers based on test names
If you a test suite where test function names indicate a certain
type of test, you can implement a hook that automatically defines
markers so that you can use the ``-m`` option with it. Let's look
at this test module::
at this test module:
.. code-block:: python
# content of test_module.py
def test_interface_simple():
assert 0
def test_interface_complex():
assert 0
def test_event_simple():
assert 0
def test_something_else():
assert 0
We want to dynamically define two markers and can do it in a
``conftest.py`` plugin::
``conftest.py`` plugin:
.. code-block:: python
# content of conftest.py
import pytest
def pytest_collection_modifyitems(items):
for item in items:
if "interface" in item.nodeid:
@@ -624,23 +695,23 @@ We can now use the ``-m option`` to select one set:
$ pytest -m interface --tb=short
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 4 items / 2 deselected / 2 selected
test_module.py FF [100%]
================================= FAILURES =================================
__________________________ test_interface_simple ___________________________
test_module.py:3: in test_interface_simple
test_module.py:4: in test_interface_simple
assert 0
E assert 0
__________________________ test_interface_complex __________________________
test_module.py:6: in test_interface_complex
test_module.py:8: in test_interface_complex
assert 0
E assert 0
================== 2 failed, 2 deselected in 0.12 seconds ==================
===================== 2 failed, 2 deselected in 0.12s ======================
or to select both "event" and "interface" tests:
@@ -648,24 +719,24 @@ or to select both "event" and "interface" tests:
$ pytest -m "interface or event" --tb=short
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 4 items / 1 deselected / 3 selected
test_module.py FFF [100%]
================================= FAILURES =================================
__________________________ test_interface_simple ___________________________
test_module.py:3: in test_interface_simple
test_module.py:4: in test_interface_simple
assert 0
E assert 0
__________________________ test_interface_complex __________________________
test_module.py:6: in test_interface_complex
test_module.py:8: in test_interface_complex
assert 0
E assert 0
____________________________ test_event_simple _____________________________
test_module.py:9: in test_event_simple
test_module.py:12: in test_event_simple
assert 0
E assert 0
================== 3 failed, 1 deselected in 0.12 seconds ==================
===================== 3 failed, 1 deselected in 0.12s ======================

View File

@@ -2,13 +2,13 @@
module containing a parametrized tests testing cross-python
serialization via the pickle module.
"""
import distutils.spawn
import shutil
import subprocess
import textwrap
import pytest
pythonlist = ["python2.7", "python3.4", "python3.5"]
pythonlist = ["python3.5", "python3.6", "python3.7"]
@pytest.fixture(params=pythonlist)
@@ -22,9 +22,9 @@ def python2(request, python1):
return Python(request.param, python1.picklefile)
class Python(object):
class Python:
def __init__(self, version, picklefile):
self.pythonpath = distutils.spawn.find_executable(version)
self.pythonpath = shutil.which(version)
if not self.pythonpath:
pytest.skip("{!r} not found".format(version))
self.picklefile = picklefile
@@ -69,4 +69,4 @@ class Python(object):
@pytest.mark.parametrize("obj", [42, {}, {1: 3}])
def test_basic_objects(python1, python2, obj):
python1.dumps(obj)
python2.load_and_is_true("obj == %s" % obj)
python2.load_and_is_true("obj == {}".format(obj))

View File

@@ -12,14 +12,14 @@ A basic example for specifying tests in Yaml files
.. _`pytest-yamlwsgi`: http://bitbucket.org/aafshar/pytest-yamlwsgi/src/tip/pytest_yamlwsgi.py
.. _`PyYAML`: https://pypi.org/project/PyYAML/
Here is an example ``conftest.py`` (extracted from Ali Afshnars special purpose `pytest-yamlwsgi`_ plugin). This ``conftest.py`` will collect ``test*.yml`` files and will execute the yaml-formatted content as custom tests:
Here is an example ``conftest.py`` (extracted from Ali Afshnars special purpose `pytest-yamlwsgi`_ plugin). This ``conftest.py`` will collect ``test*.yaml`` files and will execute the yaml-formatted content as custom tests:
.. include:: nonpython/conftest.py
:literal:
You can create a simple example file:
.. include:: nonpython/test_simple.yml
.. include:: nonpython/test_simple.yaml
:literal:
and if you installed `PyYAML`_ or a compatible YAML-parser you can
@@ -27,21 +27,21 @@ now execute the test specification:
.. code-block:: pytest
nonpython $ pytest test_simple.yml
nonpython $ pytest test_simple.yaml
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR/nonpython, inifile:
rootdir: $REGENDOC_TMPDIR/nonpython
collected 2 items
test_simple.yml F. [100%]
test_simple.yaml F. [100%]
================================= FAILURES =================================
______________________________ usecase: hello ______________________________
usecase execution failed
spec failed: 'some': 'other'
no further details known at this point.
==================== 1 failed, 1 passed in 0.12 seconds ====================
======================= 1 failed, 1 passed in 0.12s ========================
.. regendoc:wipe
@@ -64,20 +64,20 @@ consulted when reporting in ``verbose`` mode:
nonpython $ pytest -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR/nonpython, inifile:
rootdir: $REGENDOC_TMPDIR/nonpython
collecting ... collected 2 items
test_simple.yml::hello FAILED [ 50%]
test_simple.yml::ok PASSED [100%]
test_simple.yaml::hello FAILED [ 50%]
test_simple.yaml::ok PASSED [100%]
================================= FAILURES =================================
______________________________ usecase: hello ______________________________
usecase execution failed
spec failed: 'some': 'other'
no further details known at this point.
==================== 1 failed, 1 passed in 0.12 seconds ====================
======================= 1 failed, 1 passed in 0.12s ========================
.. regendoc:wipe
@@ -88,13 +88,13 @@ interesting to just look at the collection tree:
nonpython $ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR/nonpython, inifile:
rootdir: $REGENDOC_TMPDIR/nonpython
collected 2 items
<Package $REGENDOC_TMPDIR/nonpython>
<YamlFile test_simple.yml>
<YamlFile test_simple.yaml>
<YamlItem hello>
<YamlItem ok>
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================

View File

@@ -3,7 +3,7 @@ import pytest
def pytest_collect_file(parent, path):
if path.ext == ".yml" and path.basename.startswith("test"):
if path.ext == ".yaml" and path.basename.startswith("test"):
return YamlFile(path, parent)
@@ -18,7 +18,7 @@ class YamlFile(pytest.File):
class YamlItem(pytest.Item):
def __init__(self, name, parent, spec):
super(YamlItem, self).__init__(name, parent)
super().__init__(name, parent)
self.spec = spec
def runtest(self):
@@ -33,13 +33,13 @@ class YamlItem(pytest.Item):
return "\n".join(
[
"usecase execution failed",
" spec failed: %r: %r" % excinfo.value.args[1:3],
" spec failed: {1!r}: {2!r}".format(*excinfo.value.args),
" no further details known at this point.",
]
)
def reportinfo(self):
return self.fspath, 0, "usecase: %s" % self.name
return self.fspath, 0, "usecase: {}".format(self.name)
class YamlException(Exception):

View File

@@ -1,4 +1,4 @@
# test_simple.yml
# test_simple.yaml
ok:
sub1: sub1

View File

@@ -19,24 +19,30 @@ Generating parameters combinations, depending on command line
Let's say we want to execute a test with different computation
parameters and the parameter range shall be determined by a command
line argument. Let's first write a simple (do-nothing) computation test::
line argument. Let's first write a simple (do-nothing) computation test:
.. code-block:: python
# content of test_compute.py
def test_compute(param1):
assert param1 < 4
Now we add a test configuration like this::
Now we add a test configuration like this:
.. code-block:: python
# content of conftest.py
def pytest_addoption(parser):
parser.addoption("--all", action="store_true",
help="run all combinations")
parser.addoption("--all", action="store_true", help="run all combinations")
def pytest_generate_tests(metafunc):
if 'param1' in metafunc.fixturenames:
if metafunc.config.getoption('all'):
if "param1" in metafunc.fixturenames:
if metafunc.config.getoption("all"):
end = 5
else:
end = 2
@@ -48,7 +54,7 @@ This means that we only run 2 tests if we do not pass ``--all``:
$ pytest -q test_compute.py
.. [100%]
2 passed in 0.12 seconds
2 passed in 0.12s
We run only two computations, so we see two dots.
let's run the full monty:
@@ -66,8 +72,8 @@ let's run the full monty:
> assert param1 < 4
E assert 4 < 4
test_compute.py:3: AssertionError
1 failed, 4 passed in 0.12 seconds
test_compute.py:4: AssertionError
1 failed, 4 passed in 0.12s
As expected when running the full range of ``param1`` values
we'll get an error on the last one.
@@ -83,7 +89,9 @@ Running pytest with ``--collect-only`` will show the generated IDs.
Numbers, strings, booleans and None will have their usual string representation
used in the test ID. For other objects, pytest will make a string based on
the argument name::
the argument name:
.. code-block:: python
# content of test_time.py
@@ -112,7 +120,7 @@ the argument name::
def idfn(val):
if isinstance(val, (datetime,)):
# note this wouldn't show any hours/minutes/seconds
return val.strftime('%Y%m%d')
return val.strftime("%Y%m%d")
@pytest.mark.parametrize("a,b,expected", testdata, ids=idfn)
@@ -120,12 +128,18 @@ the argument name::
diff = a - b
assert diff == expected
@pytest.mark.parametrize("a,b,expected", [
pytest.param(datetime(2001, 12, 12), datetime(2001, 12, 11),
timedelta(1), id='forward'),
pytest.param(datetime(2001, 12, 11), datetime(2001, 12, 12),
timedelta(-1), id='backward'),
])
@pytest.mark.parametrize(
"a,b,expected",
[
pytest.param(
datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1), id="forward"
),
pytest.param(
datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1), id="backward"
),
],
)
def test_timedistance_v3(a, b, expected):
diff = a - b
assert diff == expected
@@ -144,9 +158,9 @@ objects, they are still using the default pytest representation:
$ pytest test_time.py --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 8 items
<Module test_time.py>
<Function test_timedistance_v0[a0-b0-expected0]>
@@ -158,7 +172,7 @@ objects, they are still using the default pytest representation:
<Function test_timedistance_v3[forward]>
<Function test_timedistance_v3[backward]>
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
In ``test_timedistance_v3``, we used ``pytest.param`` to specify the test IDs
together with the actual data, instead of listing them separately.
@@ -171,10 +185,13 @@ A quick port of "testscenarios"
Here is a quick port to run tests configured with `test scenarios`_,
an add-on from Robert Collins for the standard unittest framework. We
only have to work a bit to construct the correct arguments for pytest's
:py:func:`Metafunc.parametrize`::
:py:func:`Metafunc.parametrize`:
.. code-block:: python
# content of test_scenarios.py
def pytest_generate_tests(metafunc):
idlist = []
argvalues = []
@@ -182,13 +199,15 @@ only have to work a bit to construct the correct arguments for pytest's
idlist.append(scenario[0])
items = scenario[1].items()
argnames = [x[0] for x in items]
argvalues.append(([x[1] for x in items]))
argvalues.append([x[1] for x in items])
metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")
scenario1 = ('basic', {'attribute': 'value'})
scenario2 = ('advanced', {'attribute': 'value2'})
class TestSampleWithScenarios(object):
scenario1 = ("basic", {"attribute": "value"})
scenario2 = ("advanced", {"attribute": "value2"})
class TestSampleWithScenarios:
scenarios = [scenario1, scenario2]
def test_demo1(self, attribute):
@@ -203,14 +222,14 @@ this is a fully self-contained example which you can run with:
$ pytest test_scenarios.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 4 items
test_scenarios.py .... [100%]
========================= 4 passed in 0.12 seconds =========================
============================ 4 passed in 0.12s =============================
If you just collect tests you'll also nicely see 'advanced' and 'basic' as variants for the test function:
@@ -218,9 +237,9 @@ If you just collect tests you'll also nicely see 'advanced' and 'basic' as varia
$ pytest --collect-only test_scenarios.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 4 items
<Module test_scenarios.py>
<Class TestSampleWithScenarios>
@@ -229,7 +248,7 @@ If you just collect tests you'll also nicely see 'advanced' and 'basic' as varia
<Function test_demo1[advanced]>
<Function test_demo2[advanced]>
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
Note that we told ``metafunc.parametrize()`` that your scenario values
should be considered class-scoped. With pytest-2.3 this leads to a
@@ -243,12 +262,16 @@ Deferring the setup of parametrized resources
The parametrization of test functions happens at collection
time. It is a good idea to setup expensive resources like DB
connections or subprocess only when the actual test is run.
Here is a simple example how you can achieve that, first
the actual test requiring a ``db`` object::
Here is a simple example how you can achieve that. This test
requires a ``db`` object fixture:
.. code-block:: python
# content of test_backends.py
import pytest
def test_db_initialized(db):
# a dummy test
if db.__class__.__name__ == "DB2":
@@ -256,20 +279,27 @@ the actual test requiring a ``db`` object::
We can now add a test configuration that generates two invocations of
the ``test_db_initialized`` function and also implements a factory that
creates a database object for the actual test invocations::
creates a database object for the actual test invocations:
.. code-block:: python
# content of conftest.py
import pytest
def pytest_generate_tests(metafunc):
if 'db' in metafunc.fixturenames:
metafunc.parametrize("db", ['d1', 'd2'], indirect=True)
class DB1(object):
def pytest_generate_tests(metafunc):
if "db" in metafunc.fixturenames:
metafunc.parametrize("db", ["d1", "d2"], indirect=True)
class DB1:
"one database object"
class DB2(object):
class DB2:
"alternative database object"
@pytest.fixture
def db(request):
if request.param == "d1":
@@ -285,15 +315,15 @@ Let's first see how it looks like at collection time:
$ pytest test_backends.py --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 2 items
<Module test_backends.py>
<Function test_db_initialized[d1]>
<Function test_db_initialized[d2]>
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
And then when we run the test:
@@ -312,8 +342,8 @@ And then when we run the test:
> pytest.fail("deliberately failing for demo purposes")
E Failed: deliberately failing for demo purposes
test_backends.py:6: Failed
1 failed, 1 passed in 0.12 seconds
test_backends.py:8: Failed
1 failed, 1 passed in 0.12s
The first invocation with ``db == "DB1"`` passed while the second with ``db == "DB2"`` failed. Our ``db`` fixture function has instantiated each of the DB values during the setup phase while the ``pytest_generate_tests`` generated two according calls to the ``test_db_initialized`` during the collection phase.
@@ -327,23 +357,29 @@ parameter on particular arguments. It can be done by passing list or tuple of
arguments' names to ``indirect``. In the example below there is a function ``test_indirect`` which uses
two fixtures: ``x`` and ``y``. Here we give to indirect the list, which contains the name of the
fixture ``x``. The indirect parameter will be applied to this argument only, and the value ``a``
will be passed to respective fixture function::
will be passed to respective fixture function:
.. code-block:: python
# content of test_indirect_list.py
import pytest
@pytest.fixture(scope='function')
@pytest.fixture(scope="function")
def x(request):
return request.param * 3
@pytest.fixture(scope='function')
@pytest.fixture(scope="function")
def y(request):
return request.param * 2
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])
def test_indirect(x,y):
assert x == 'aaa'
assert y == 'b'
@pytest.mark.parametrize("x, y", [("a", "b")], indirect=["x"])
def test_indirect(x, y):
assert x == "aaa"
assert y == "b"
The result of this test will be successful:
@@ -351,14 +387,14 @@ The result of this test will be successful:
$ pytest test_indirect_list.py --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 1 item
<Module test_indirect_list.py>
<Function test_indirect[a-b]>
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
.. regendoc:wipe
@@ -370,23 +406,28 @@ Parametrizing test methods through per-class configuration
Here is an example ``pytest_generate_tests`` function implementing a
parametrization scheme similar to Michael Foord's `unittest
parametrizer`_ but in a lot less code::
parametrizer`_ but in a lot less code:
.. code-block:: python
# content of ./test_parametrize.py
import pytest
def pytest_generate_tests(metafunc):
# called once per each test function
funcarglist = metafunc.cls.params[metafunc.function.__name__]
argnames = sorted(funcarglist[0])
metafunc.parametrize(argnames, [[funcargs[name] for name in argnames]
for funcargs in funcarglist])
metafunc.parametrize(
argnames, [[funcargs[name] for name in argnames] for funcargs in funcarglist]
)
class TestClass(object):
class TestClass:
# a map specifying multiple argument sets for a test method
params = {
'test_equals': [dict(a=1, b=2), dict(a=3, b=3), ],
'test_zerodivision': [dict(a=1, b=0), ],
"test_equals": [dict(a=1, b=2), dict(a=3, b=3)],
"test_zerodivision": [dict(a=1, b=0)],
}
def test_equals(self, a, b):
@@ -411,11 +452,9 @@ argument sets to use for each test function. Let's run it:
def test_equals(self, a, b):
> assert a == b
E assert 1 == 2
E -1
E +2
test_parametrize.py:18: AssertionError
1 failed, 2 passed in 0.12 seconds
test_parametrize.py:21: AssertionError
1 failed, 2 passed in 0.12s
Indirect parametrization with multiple fixtures
--------------------------------------------------------------
@@ -431,15 +470,16 @@ is to be run with different sets of arguments for its three arguments:
.. literalinclude:: multipython.py
Running it results in some skips if we don't have all the python interpreters installed and otherwise runs all combinations (5 interpreters times 5 interpreters times 3 objects to serialize/deserialize):
Running it results in some skips if we don't have all the python interpreters installed and otherwise runs all combinations (3 interpreters times 3 interpreters times 3 objects to serialize/deserialize):
.. code-block:: pytest
. $ pytest -rs -q multipython.py
...sss...sssssssss...sss... [100%]
ssssssssssssssssssssssss... [100%]
========================= short test summary info ==========================
SKIPPED [15] $REGENDOC_TMPDIR/CWD/multipython.py:30: 'python3.4' not found
12 passed, 15 skipped in 0.12 seconds
SKIPPED [12] $REGENDOC_TMPDIR/CWD/multipython.py:30: 'python3.5' not found
SKIPPED [12] $REGENDOC_TMPDIR/CWD/multipython.py:30: 'python3.6' not found
3 passed, 24 skipped in 0.12s
Indirect parametrization of optional implementations/imports
--------------------------------------------------------------------
@@ -448,36 +488,47 @@ If you want to compare the outcomes of several implementations of a given
API, you can write test functions that receive the already imported implementations
and get skipped in case the implementation is not importable/available. Let's
say we have a "base" implementation and the other (possibly optimized ones)
need to provide similar results::
need to provide similar results:
.. code-block:: python
# content of conftest.py
import pytest
@pytest.fixture(scope="session")
def basemod(request):
return pytest.importorskip("base")
@pytest.fixture(scope="session", params=["opt1", "opt2"])
def optmod(request):
return pytest.importorskip(request.param)
And then a base implementation of a simple function::
And then a base implementation of a simple function:
.. code-block:: python
# content of base.py
def func1():
return 1
And an optimized version::
And an optimized version:
.. code-block:: python
# content of opt1.py
def func1():
return 1.0001
And finally a little test module::
And finally a little test module:
.. code-block:: python
# content of test_module.py
def test_func1(basemod, optmod):
assert round(basemod.func1(), 3) == round(optmod.func1(), 3)
@@ -488,16 +539,16 @@ If you run this with reporting for skips enabled:
$ pytest -rs test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 2 items
test_module.py .s [100%]
========================= short test summary info ==========================
SKIPPED [1] $REGENDOC_TMPDIR/conftest.py:11: could not import 'opt2'
=================== 1 passed, 1 skipped in 0.12 seconds ====================
========================= short test summary info ==========================
SKIPPED [1] $REGENDOC_TMPDIR/conftest.py:13: could not import 'opt2': No module named 'opt2'
======================= 1 passed, 1 skipped in 0.12s =======================
You'll see that we don't have an ``opt2`` module and thus the second test run
of our ``test_func1`` was skipped. A few notes:
@@ -517,21 +568,25 @@ Set marks or test ID for individual parametrized test
--------------------------------------------------------------------
Use ``pytest.param`` to apply marks or set test ID to individual parametrized test.
For example::
For example:
.. code-block:: python
# content of test_pytest_param_example.py
import pytest
@pytest.mark.parametrize('test_input,expected', [
('3+5', 8),
pytest.param('1+7', 8,
marks=pytest.mark.basic),
pytest.param('2+4', 6,
marks=pytest.mark.basic,
id='basic_2+4'),
pytest.param('6*9', 42,
marks=[pytest.mark.basic, pytest.mark.xfail],
id='basic_6*9'),
])
@pytest.mark.parametrize(
"test_input,expected",
[
("3+5", 8),
pytest.param("1+7", 8, marks=pytest.mark.basic),
pytest.param("2+4", 6, marks=pytest.mark.basic, id="basic_2+4"),
pytest.param(
"6*9", 42, marks=[pytest.mark.basic, pytest.mark.xfail], id="basic_6*9"
),
],
)
def test_eval(test_input, expected):
assert eval(test_input) == expected
@@ -546,16 +601,16 @@ Then run ``pytest`` with verbose mode and with only the ``basic`` marker:
$ pytest -v -m basic
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
collecting ... collected 17 items / 14 deselected / 3 selected
rootdir: $REGENDOC_TMPDIR
collecting ... collected 18 items / 15 deselected / 3 selected
test_pytest_param_example.py::test_eval[1+7-8] PASSED [ 33%]
test_pytest_param_example.py::test_eval[basic_2+4] PASSED [ 66%]
test_pytest_param_example.py::test_eval[basic_6*9] XFAIL [100%]
============ 2 passed, 14 deselected, 1 xfailed in 0.12 seconds ============
=============== 2 passed, 15 deselected, 1 xfailed in 0.12s ================
As the result:
@@ -576,22 +631,28 @@ Use :func:`pytest.raises` with the
in which some tests raise exceptions and others do not.
It is helpful to define a no-op context manager ``does_not_raise`` to serve
as a complement to ``raises``. For example::
as a complement to ``raises``. For example:
.. code-block:: python
from contextlib import contextmanager
import pytest
@contextmanager
def does_not_raise():
yield
@pytest.mark.parametrize('example_input,expectation', [
(3, does_not_raise()),
(2, does_not_raise()),
(1, does_not_raise()),
(0, pytest.raises(ZeroDivisionError)),
])
@pytest.mark.parametrize(
"example_input,expectation",
[
(3, does_not_raise()),
(2, does_not_raise()),
(1, does_not_raise()),
(0, pytest.raises(ZeroDivisionError)),
],
)
def test_division(example_input, expectation):
"""Test how much I know division."""
with expectation:
@@ -601,14 +662,20 @@ In the example above, the first three test cases should run unexceptionally,
while the fourth should raise ``ZeroDivisionError``.
If you're only supporting Python 3.7+, you can simply use ``nullcontext``
to define ``does_not_raise``::
to define ``does_not_raise``:
.. code-block:: python
from contextlib import nullcontext as does_not_raise
Or, if you're supporting Python 3.3+ you can use::
Or, if you're supporting Python 3.3+ you can use:
.. code-block:: python
from contextlib import ExitStack as does_not_raise
Or, if desired, you can ``pip install contextlib2`` and use::
Or, if desired, you can ``pip install contextlib2`` and use:
.. code-block:: python
from contextlib2 import ExitStack as does_not_raise

View File

@@ -6,7 +6,7 @@ def test_function():
pass
class TestClass(object):
class TestClass:
def test_method(self):
pass

View File

@@ -31,7 +31,7 @@ you will see that ``pytest`` only collects test-modules, which do not match the
.. code-block:: pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
rootdir: $REGENDOC_TMPDIR, inifile:
collected 5 items
@@ -131,12 +131,15 @@ Here is an example:
This would make ``pytest`` look for tests in files that match the ``check_*
.py`` glob-pattern, ``Check`` prefixes in classes, and functions and methods
that match ``*_check``. For example, if we have::
that match ``*_check``. For example, if we have:
.. code-block:: python
# content of check_myapp.py
class CheckMyApp(object):
class CheckMyApp:
def simple_check(self):
pass
def complex_check(self):
pass
@@ -146,7 +149,7 @@ The test collection would look like this:
$ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini
collected 2 items
@@ -155,7 +158,7 @@ The test collection would look like this:
<Function simple_check>
<Function complex_check>
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
You can check for multiple glob patterns by adding a space between the patterns:
@@ -208,7 +211,7 @@ You can always peek at the collection tree without running tests like this:
. $ pytest --collect-only pythoncollection.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini
collected 3 items
@@ -218,7 +221,7 @@ You can always peek at the collection tree without running tests like this:
<Function test_method>
<Function test_anothermethod>
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
.. _customizing-test-collection:
@@ -238,7 +241,9 @@ You can easily instruct ``pytest`` to discover tests from every Python file:
However, many projects will have a ``setup.py`` which they don't want to be
imported. Moreover, there may files only importable by a specific python
version. For such cases you can dynamically define files to be ignored by
listing them in a ``conftest.py`` file::
listing them in a ``conftest.py`` file:
.. code-block:: python
# content of conftest.py
import sys
@@ -247,7 +252,9 @@ listing them in a ``conftest.py`` file::
if sys.version_info[0] > 2:
collect_ignore.append("pkg/module_py2.py")
and then if you have a module file like this::
and then if you have a module file like this:
.. code-block:: python
# content of pkg/module_py2.py
def test_only_on_python2():
@@ -256,10 +263,12 @@ and then if you have a module file like this::
except Exception, e:
pass
and a ``setup.py`` dummy file like this::
and a ``setup.py`` dummy file like this:
.. code-block:: python
# content of setup.py
0/0 # will raise exception if imported
0 / 0 # will raise exception if imported
If you run with a Python 2 interpreter then you will find the one test and will
leave out the ``setup.py`` file:
@@ -283,19 +292,21 @@ file will be left out:
$ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile: pytest.ini
collected 0 items
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
It's also possible to ignore files based on Unix shell-style wildcards by adding
patterns to ``collect_ignore_glob``.
The following example ``conftest.py`` ignores the file ``setup.py`` and in
addition all files that end with ``*_py2.py`` when executed with a Python 3
interpreter::
interpreter:
.. code-block:: python
# content of conftest.py
import sys

View File

@@ -1,21 +1,17 @@
.. _`tbreportdemo`:
Demo of Python failure reports with pytest
==================================================
==========================================
Here is a nice run of several tens of failures
and how ``pytest`` presents things (unfortunately
not showing the nice colors here in the HTML that you
get on the terminal - we are working on that):
Here is a nice run of several failures and how ``pytest`` presents things:
.. code-block:: pytest
assertion $ pytest failure_demo.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR/assertion, inifile:
rootdir: $REGENDOC_TMPDIR/assertion
collected 44 items
failure_demo.py FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF [100%]
@@ -30,7 +26,7 @@ get on the terminal - we are working on that):
> assert param1 * 2 < param2
E assert (3 * 2) < 6
failure_demo.py:22: AssertionError
failure_demo.py:20: AssertionError
_________________________ TestFailing.test_simple __________________________
self = <failure_demo.TestFailing object at 0xdeadbeef>
@@ -47,7 +43,7 @@ get on the terminal - we are working on that):
E + where 42 = <function TestFailing.test_simple.<locals>.f at 0xdeadbeef>()
E + and 43 = <function TestFailing.test_simple.<locals>.g at 0xdeadbeef>()
failure_demo.py:33: AssertionError
failure_demo.py:31: AssertionError
____________________ TestFailing.test_simple_multiline _____________________
self = <failure_demo.TestFailing object at 0xdeadbeef>
@@ -55,7 +51,7 @@ get on the terminal - we are working on that):
def test_simple_multiline(self):
> otherfunc_multi(42, 6 * 9)
failure_demo.py:36:
failure_demo.py:34:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
a = 42, b = 54
@@ -64,7 +60,7 @@ get on the terminal - we are working on that):
> assert a == b
E assert 42 == 54
failure_demo.py:17: AssertionError
failure_demo.py:15: AssertionError
___________________________ TestFailing.test_not ___________________________
self = <failure_demo.TestFailing object at 0xdeadbeef>
@@ -77,7 +73,7 @@ get on the terminal - we are working on that):
E assert not 42
E + where 42 = <function TestFailing.test_not.<locals>.f at 0xdeadbeef>()
failure_demo.py:42: AssertionError
failure_demo.py:40: AssertionError
_________________ TestSpecialisedExplanations.test_eq_text _________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -88,7 +84,7 @@ get on the terminal - we are working on that):
E - spam
E + eggs
failure_demo.py:47: AssertionError
failure_demo.py:45: AssertionError
_____________ TestSpecialisedExplanations.test_eq_similar_text _____________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -101,7 +97,7 @@ get on the terminal - we are working on that):
E + foo 2 bar
E ? ^
failure_demo.py:50: AssertionError
failure_demo.py:48: AssertionError
____________ TestSpecialisedExplanations.test_eq_multiline_text ____________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -114,7 +110,7 @@ get on the terminal - we are working on that):
E + eggs
E bar
failure_demo.py:53: AssertionError
failure_demo.py:51: AssertionError
______________ TestSpecialisedExplanations.test_eq_long_text _______________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -123,7 +119,7 @@ get on the terminal - we are working on that):
a = "1" * 100 + "a" + "2" * 100
b = "1" * 100 + "b" + "2" * 100
> assert a == b
E AssertionError: assert '111111111111...2222222222222' == '1111111111111...2222222222222'
E AssertionError: assert '111111111111...2222222222222' == '111111111111...2222222222222'
E Skipping 90 identical leading characters in diff, use -v to show
E Skipping 91 identical trailing characters in diff, use -v to show
E - 1111111111a222222222
@@ -131,7 +127,7 @@ get on the terminal - we are working on that):
E + 1111111111b222222222
E ? ^
failure_demo.py:58: AssertionError
failure_demo.py:56: AssertionError
_________ TestSpecialisedExplanations.test_eq_long_text_multiline __________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -140,7 +136,7 @@ get on the terminal - we are working on that):
a = "1\n" * 100 + "a" + "2\n" * 100
b = "1\n" * 100 + "b" + "2\n" * 100
> assert a == b
E AssertionError: assert '1\n1\n1\n1\n...n2\n2\n2\n2\n' == '1\n1\n1\n1\n1...n2\n2\n2\n2\n'
E AssertionError: assert '1\n1\n1\n1\n...n2\n2\n2\n2\n' == '1\n1\n1\n1\n...n2\n2\n2\n2\n'
E Skipping 190 identical leading characters in diff, use -v to show
E Skipping 191 identical trailing characters in diff, use -v to show
E 1
@@ -151,7 +147,7 @@ get on the terminal - we are working on that):
E
E ...Full output truncated (7 lines hidden), use '-vv' to show
failure_demo.py:63: AssertionError
failure_demo.py:61: AssertionError
_________________ TestSpecialisedExplanations.test_eq_list _________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -162,7 +158,7 @@ get on the terminal - we are working on that):
E At index 2 diff: 2 != 3
E Use -v to get the full diff
failure_demo.py:66: AssertionError
failure_demo.py:64: AssertionError
______________ TestSpecialisedExplanations.test_eq_list_long _______________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -175,7 +171,7 @@ get on the terminal - we are working on that):
E At index 100 diff: 1 != 2
E Use -v to get the full diff
failure_demo.py:71: AssertionError
failure_demo.py:69: AssertionError
_________________ TestSpecialisedExplanations.test_eq_dict _________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -186,14 +182,14 @@ get on the terminal - we are working on that):
E Omitting 1 identical items, use -vv to show
E Differing items:
E {'b': 1} != {'b': 2}
E Left contains more items:
E Left contains 1 more item:
E {'c': 0}
E Right contains more items:
E Right contains 1 more item:
E {'d': 0}...
E
E ...Full output truncated (2 lines hidden), use '-vv' to show
failure_demo.py:74: AssertionError
failure_demo.py:72: AssertionError
_________________ TestSpecialisedExplanations.test_eq_set __________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -211,7 +207,7 @@ get on the terminal - we are working on that):
E
E ...Full output truncated (2 lines hidden), use '-vv' to show
failure_demo.py:77: AssertionError
failure_demo.py:75: AssertionError
_____________ TestSpecialisedExplanations.test_eq_longer_list ______________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -219,10 +215,10 @@ get on the terminal - we are working on that):
def test_eq_longer_list(self):
> assert [1, 2] == [1, 2, 3]
E assert [1, 2] == [1, 2, 3]
E Right contains more items, first extra item: 3
E Right contains one more item: 3
E Use -v to get the full diff
failure_demo.py:80: AssertionError
failure_demo.py:78: AssertionError
_________________ TestSpecialisedExplanations.test_in_list _________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -231,7 +227,7 @@ get on the terminal - we are working on that):
> assert 1 in [0, 2, 3, 4, 5]
E assert 1 in [0, 2, 3, 4, 5]
failure_demo.py:83: AssertionError
failure_demo.py:81: AssertionError
__________ TestSpecialisedExplanations.test_not_in_text_multiline __________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -239,7 +235,7 @@ get on the terminal - we are working on that):
def test_not_in_text_multiline(self):
text = "some multiline\ntext\nwhich\nincludes foo\nand a\ntail"
> assert "foo" not in text
E AssertionError: assert 'foo' not in 'some multiline\ntext\nw...ncludes foo\nand a\ntail'
E AssertionError: assert 'foo' not in 'some multil...nand a\ntail'
E 'foo' is contained here:
E some multiline
E text
@@ -250,7 +246,7 @@ get on the terminal - we are working on that):
E
E ...Full output truncated (2 lines hidden), use '-vv' to show
failure_demo.py:87: AssertionError
failure_demo.py:85: AssertionError
___________ TestSpecialisedExplanations.test_not_in_text_single ____________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -263,7 +259,7 @@ get on the terminal - we are working on that):
E single foo line
E ? +++
failure_demo.py:91: AssertionError
failure_demo.py:89: AssertionError
_________ TestSpecialisedExplanations.test_not_in_text_single_long _________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -271,12 +267,12 @@ get on the terminal - we are working on that):
def test_not_in_text_single_long(self):
text = "head " * 50 + "foo " + "tail " * 20
> assert "foo" not in text
E AssertionError: assert 'foo' not in 'head head head head hea...ail tail tail tail tail '
E AssertionError: assert 'foo' not in 'head head h...l tail tail '
E 'foo' is contained here:
E head head foo tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail
E ? +++
failure_demo.py:95: AssertionError
failure_demo.py:93: AssertionError
______ TestSpecialisedExplanations.test_not_in_text_single_long_term _______
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -284,12 +280,12 @@ get on the terminal - we are working on that):
def test_not_in_text_single_long_term(self):
text = "head " * 50 + "f" * 70 + "tail " * 20
> assert "f" * 70 not in text
E AssertionError: assert 'fffffffffff...ffffffffffff' not in 'head head he...l tail tail '
E AssertionError: assert 'fffffffffff...ffffffffffff' not in 'head head h...l tail tail '
E 'ffffffffffffffffff...fffffffffffffffffff' is contained here:
E head head fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffftail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail tail
E ? ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
failure_demo.py:99: AssertionError
failure_demo.py:97: AssertionError
______________ TestSpecialisedExplanations.test_eq_dataclass _______________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -298,19 +294,19 @@ get on the terminal - we are working on that):
from dataclasses import dataclass
@dataclass
class Foo(object):
class Foo:
a: int
b: str
left = Foo(1, "b")
right = Foo(1, "c")
> assert left == right
E AssertionError: assert TestSpecialis...oo(a=1, b='b') == TestSpecialise...oo(a=1, b='c')
E AssertionError: assert TestSpecialis...oo(a=1, b='b') == TestSpecialis...oo(a=1, b='c')
E Omitting 1 identical items, use -vv to show
E Differing attributes:
E b: 'b' != 'c'
failure_demo.py:111: AssertionError
failure_demo.py:109: AssertionError
________________ TestSpecialisedExplanations.test_eq_attrs _________________
self = <failure_demo.TestSpecialisedExplanations object at 0xdeadbeef>
@@ -319,7 +315,7 @@ get on the terminal - we are working on that):
import attr
@attr.s
class Foo(object):
class Foo:
a = attr.ib()
b = attr.ib()
@@ -331,11 +327,11 @@ get on the terminal - we are working on that):
E Differing attributes:
E b: 'b' != 'c'
failure_demo.py:123: AssertionError
failure_demo.py:121: AssertionError
______________________________ test_attribute ______________________________
def test_attribute():
class Foo(object):
class Foo:
b = 1
i = Foo()
@@ -343,11 +339,11 @@ get on the terminal - we are working on that):
E assert 1 == 2
E + where 1 = <failure_demo.test_attribute.<locals>.Foo object at 0xdeadbeef>.b
failure_demo.py:131: AssertionError
failure_demo.py:129: AssertionError
_________________________ test_attribute_instance __________________________
def test_attribute_instance():
class Foo(object):
class Foo:
b = 1
> assert Foo().b == 2
@@ -355,11 +351,11 @@ get on the terminal - we are working on that):
E + where 1 = <failure_demo.test_attribute_instance.<locals>.Foo object at 0xdeadbeef>.b
E + where <failure_demo.test_attribute_instance.<locals>.Foo object at 0xdeadbeef> = <class 'failure_demo.test_attribute_instance.<locals>.Foo'>()
failure_demo.py:138: AssertionError
failure_demo.py:136: AssertionError
__________________________ test_attribute_failure __________________________
def test_attribute_failure():
class Foo(object):
class Foo:
def _get_b(self):
raise Exception("Failed to get attrib")
@@ -368,7 +364,7 @@ get on the terminal - we are working on that):
i = Foo()
> assert i.b == 2
failure_demo.py:149:
failure_demo.py:147:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <failure_demo.test_attribute_failure.<locals>.Foo object at 0xdeadbeef>
@@ -377,14 +373,14 @@ get on the terminal - we are working on that):
> raise Exception("Failed to get attrib")
E Exception: Failed to get attrib
failure_demo.py:144: Exception
failure_demo.py:142: Exception
_________________________ test_attribute_multiple __________________________
def test_attribute_multiple():
class Foo(object):
class Foo:
b = 1
class Bar(object):
class Bar:
b = 2
> assert Foo().b == Bar().b
@@ -394,7 +390,7 @@ get on the terminal - we are working on that):
E + and 2 = <failure_demo.test_attribute_multiple.<locals>.Bar object at 0xdeadbeef>.b
E + where <failure_demo.test_attribute_multiple.<locals>.Bar object at 0xdeadbeef> = <class 'failure_demo.test_attribute_multiple.<locals>.Bar'>()
failure_demo.py:159: AssertionError
failure_demo.py:157: AssertionError
__________________________ TestRaises.test_raises __________________________
self = <failure_demo.TestRaises object at 0xdeadbeef>
@@ -404,7 +400,7 @@ get on the terminal - we are working on that):
> raises(TypeError, int, s)
E ValueError: invalid literal for int() with base 10: 'qwe'
failure_demo.py:169: ValueError
failure_demo.py:167: ValueError
______________________ TestRaises.test_raises_doesnt _______________________
self = <failure_demo.TestRaises object at 0xdeadbeef>
@@ -413,7 +409,7 @@ get on the terminal - we are working on that):
> raises(IOError, int, "3")
E Failed: DID NOT RAISE <class 'OSError'>
failure_demo.py:172: Failed
failure_demo.py:170: Failed
__________________________ TestRaises.test_raise ___________________________
self = <failure_demo.TestRaises object at 0xdeadbeef>
@@ -422,7 +418,7 @@ get on the terminal - we are working on that):
> raise ValueError("demo error")
E ValueError: demo error
failure_demo.py:175: ValueError
failure_demo.py:173: ValueError
________________________ TestRaises.test_tupleerror ________________________
self = <failure_demo.TestRaises object at 0xdeadbeef>
@@ -431,18 +427,18 @@ get on the terminal - we are working on that):
> a, b = [1] # NOQA
E ValueError: not enough values to unpack (expected 2, got 1)
failure_demo.py:178: ValueError
failure_demo.py:176: ValueError
______ TestRaises.test_reinterpret_fails_with_print_for_the_fun_of_it ______
self = <failure_demo.TestRaises object at 0xdeadbeef>
def test_reinterpret_fails_with_print_for_the_fun_of_it(self):
items = [1, 2, 3]
print("items is %r" % items)
print("items is {!r}".format(items))
> a, b = items.pop()
E TypeError: 'int' object is not iterable
E TypeError: cannot unpack non-iterable int object
failure_demo.py:183: TypeError
failure_demo.py:181: TypeError
--------------------------- Captured stdout call ---------------------------
items is [1, 2, 3]
________________________ TestRaises.test_some_error ________________________
@@ -453,29 +449,30 @@ get on the terminal - we are working on that):
> if namenotexi: # NOQA
E NameError: name 'namenotexi' is not defined
failure_demo.py:186: NameError
failure_demo.py:184: NameError
____________________ test_dynamic_compile_shows_nicely _____________________
def test_dynamic_compile_shows_nicely():
import imp
import importlib.util
import sys
src = "def foo():\n assert 1 == 0\n"
name = "abc-123"
module = imp.new_module(name)
spec = importlib.util.spec_from_loader(name, loader=None)
module = importlib.util.module_from_spec(spec)
code = _pytest._code.compile(src, name, "exec")
six.exec_(code, module.__dict__)
exec(code, module.__dict__)
sys.modules[name] = module
> module.foo()
failure_demo.py:204:
failure_demo.py:203:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
def foo():
> assert 1 == 0
E AssertionError
<0-codegen 'abc-123' $REGENDOC_TMPDIR/assertion/failure_demo.py:201>:2: AssertionError
<0-codegen 'abc-123' $REGENDOC_TMPDIR/assertion/failure_demo.py:200>:2: AssertionError
____________________ TestMoreErrors.test_complex_error _____________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
@@ -489,9 +486,9 @@ get on the terminal - we are working on that):
> somefunc(f(), g())
failure_demo.py:215:
failure_demo.py:214:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
failure_demo.py:13: in somefunc
failure_demo.py:11: in somefunc
otherfunc(x, y)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
@@ -501,7 +498,7 @@ get on the terminal - we are working on that):
> assert a == b
E assert 44 == 43
failure_demo.py:9: AssertionError
failure_demo.py:7: AssertionError
___________________ TestMoreErrors.test_z1_unpack_error ____________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
@@ -511,7 +508,7 @@ get on the terminal - we are working on that):
> a, b = items
E ValueError: not enough values to unpack (expected 2, got 0)
failure_demo.py:219: ValueError
failure_demo.py:218: ValueError
____________________ TestMoreErrors.test_z2_type_error _____________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
@@ -519,9 +516,9 @@ get on the terminal - we are working on that):
def test_z2_type_error(self):
items = 3
> a, b = items
E TypeError: 'int' object is not iterable
E TypeError: cannot unpack non-iterable int object
failure_demo.py:223: TypeError
failure_demo.py:222: TypeError
______________________ TestMoreErrors.test_startswith ______________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
@@ -534,7 +531,7 @@ get on the terminal - we are working on that):
E + where False = <built-in method startswith of str object at 0xdeadbeef>('456')
E + where <built-in method startswith of str object at 0xdeadbeef> = '123'.startswith
failure_demo.py:228: AssertionError
failure_demo.py:227: AssertionError
__________________ TestMoreErrors.test_startswith_nested ___________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
@@ -553,7 +550,7 @@ get on the terminal - we are working on that):
E + where '123' = <function TestMoreErrors.test_startswith_nested.<locals>.f at 0xdeadbeef>()
E + and '456' = <function TestMoreErrors.test_startswith_nested.<locals>.g at 0xdeadbeef>()
failure_demo.py:237: AssertionError
failure_demo.py:236: AssertionError
_____________________ TestMoreErrors.test_global_func ______________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
@@ -564,7 +561,7 @@ get on the terminal - we are working on that):
E + where False = isinstance(43, float)
E + where 43 = globf(42)
failure_demo.py:240: AssertionError
failure_demo.py:239: AssertionError
_______________________ TestMoreErrors.test_instance _______________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
@@ -575,7 +572,7 @@ get on the terminal - we are working on that):
E assert 42 != 42
E + where 42 = <failure_demo.TestMoreErrors object at 0xdeadbeef>.x
failure_demo.py:244: AssertionError
failure_demo.py:243: AssertionError
_______________________ TestMoreErrors.test_compare ________________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
@@ -585,7 +582,7 @@ get on the terminal - we are working on that):
E assert 11 < 5
E + where 11 = globf(10)
failure_demo.py:247: AssertionError
failure_demo.py:246: AssertionError
_____________________ TestMoreErrors.test_try_finally ______________________
self = <failure_demo.TestMoreErrors object at 0xdeadbeef>
@@ -596,13 +593,13 @@ get on the terminal - we are working on that):
> assert x == 0
E assert 1 == 0
failure_demo.py:252: AssertionError
failure_demo.py:251: AssertionError
___________________ TestCustomAssertMsg.test_single_line ___________________
self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef>
def test_single_line(self):
class A(object):
class A:
a = 1
b = 2
@@ -611,13 +608,13 @@ get on the terminal - we are working on that):
E assert 1 == 2
E + where 1 = <class 'failure_demo.TestCustomAssertMsg.test_single_line.<locals>.A'>.a
failure_demo.py:263: AssertionError
failure_demo.py:262: AssertionError
____________________ TestCustomAssertMsg.test_multiline ____________________
self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef>
def test_multiline(self):
class A(object):
class A:
a = 1
b = 2
@@ -630,13 +627,13 @@ get on the terminal - we are working on that):
E assert 1 == 2
E + where 1 = <class 'failure_demo.TestCustomAssertMsg.test_multiline.<locals>.A'>.a
failure_demo.py:270: AssertionError
failure_demo.py:269: AssertionError
___________________ TestCustomAssertMsg.test_custom_repr ___________________
self = <failure_demo.TestCustomAssertMsg object at 0xdeadbeef>
def test_custom_repr(self):
class JSON(object):
class JSON:
a = 1
def __repr__(self):
@@ -652,5 +649,5 @@ get on the terminal - we are working on that):
E assert 1 == 2
E + where 1 = This is JSON\n{\n 'foo': 'bar'\n}.a
failure_demo.py:283: AssertionError
======================== 44 failed in 0.12 seconds =========================
failure_demo.py:282: AssertionError
============================ 44 failed in 0.12s ============================

View File

@@ -65,7 +65,7 @@ Let's run this without supplying our new option:
test_sample.py:6: AssertionError
--------------------------- Captured stdout call ---------------------------
first
1 failed in 0.12 seconds
1 failed in 0.12s
And now with supplying a command line option:
@@ -89,7 +89,7 @@ And now with supplying a command line option:
test_sample.py:6: AssertionError
--------------------------- Captured stdout call ---------------------------
second
1 failed in 0.12 seconds
1 failed in 0.12s
You can see that the command line option arrived in our test. This
completes the basic pattern. However, one often rather wants to process
@@ -107,7 +107,7 @@ the command line arguments before they get processed:
.. code-block:: python
# content of conftest.py
# setuptools plugin
import sys
@@ -127,12 +127,12 @@ directory with the above conftest.py:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 0 items
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
.. _`excontrolskip`:
@@ -157,6 +157,10 @@ line option to control skipping of ``pytest.mark.slow`` marked tests:
)
def pytest_configure(config):
config.addinivalue_line("markers", "slow: mark test as slow to run")
def pytest_collection_modifyitems(config, items):
if config.getoption("--runslow"):
# --runslow given in cli: do not skip slow tests
@@ -188,16 +192,16 @@ and when running it will see a skipped "slow" test:
$ pytest -rs # "-rs" means report details on the little 's'
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 2 items
test_module.py .s [100%]
========================= short test summary info ==========================
SKIPPED [1] test_module.py:8: need --runslow option to run
=================== 1 passed, 1 skipped in 0.12 seconds ====================
======================= 1 passed, 1 skipped in 0.12s =======================
Or run it including the ``slow`` marked test:
@@ -205,14 +209,14 @@ Or run it including the ``slow`` marked test:
$ pytest --runslow
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 2 items
test_module.py .. [100%]
========================= 2 passed in 0.12 seconds =========================
============================ 2 passed in 0.12s =============================
Writing well integrated assertion helpers
--------------------------------------------------
@@ -234,7 +238,7 @@ Example:
def checkconfig(x):
__tracebackhide__ = True
if not hasattr(x, "config"):
pytest.fail("not configured: %s" % (x,))
pytest.fail("not configured: {}".format(x))
def test_something():
@@ -257,7 +261,7 @@ Let's run our little function:
E Failed: not configured: 42
test_checkconfig.py:11: Failed
1 failed in 0.12 seconds
1 failed in 0.12s
If you only want to hide certain exceptions, you can set ``__tracebackhide__``
to a callable which gets the ``ExceptionInfo`` object. You can for example use
@@ -276,7 +280,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: %s" % (x,))
raise ConfigException("not configured: {}".format(x))
def test_something():
@@ -348,13 +352,13 @@ which will add the string to the test header accordingly:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
project deps: mylib-1.1
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 0 items
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
.. regendoc:wipe
@@ -377,14 +381,14 @@ which will add info only when run with "--v":
$ pytest -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
info1: did you know that ...
did you?
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 0 items
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
and nothing when run plainly:
@@ -392,12 +396,12 @@ and nothing when run plainly:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 0 items
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
profiling test duration
--------------------------
@@ -432,9 +436,9 @@ Now we can profile which test functions execute the slowest:
$ pytest --durations=3
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 3 items
test_some_are_slow.py ... [100%]
@@ -443,7 +447,7 @@ Now we can profile which test functions execute the slowest:
0.30s call test_some_are_slow.py::test_funcslow2
0.20s call test_some_are_slow.py::test_funcslow1
0.10s call test_some_are_slow.py::test_funcfast
========================= 3 passed in 0.12 seconds =========================
============================ 3 passed in 0.12s =============================
incremental testing - test steps
---------------------------------------------------
@@ -474,7 +478,7 @@ an ``incremental`` marker which is to be used on classes:
if "incremental" in item.keywords:
previousfailed = getattr(item.parent, "_previousfailed", None)
if previousfailed is not None:
pytest.xfail("previous test failed (%s)" % previousfailed.name)
pytest.xfail("previous test failed ({})".format(previousfailed.name))
These two hook implementations work together to abort incremental-marked
tests in a class. Here is a test module example:
@@ -487,7 +491,7 @@ tests in a class. Here is a test module example:
@pytest.mark.incremental
class TestUserHandling(object):
class TestUserHandling:
def test_login(self):
pass
@@ -507,9 +511,9 @@ If we run this:
$ pytest -rx
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 4 items
test_step.py .Fx. [100%]
@@ -527,7 +531,7 @@ If we run this:
========================= short test summary info ==========================
XFAIL test_step.py::TestUserHandling::test_deletion
reason: previous test failed (test_modification)
============== 1 failed, 2 passed, 1 xfailed in 0.12 seconds ===============
================== 1 failed, 2 passed, 1 xfailed in 0.12s ==================
We'll see that ``test_deletion`` was not executed because ``test_modification``
failed. It is reported as an "expected failure".
@@ -552,7 +556,7 @@ Here is an example for making a ``db`` fixture available in a directory:
import pytest
class DB(object):
class DB:
pass
@@ -591,9 +595,9 @@ We can run this:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 7 items
test_step.py .Fx. [ 57%]
@@ -606,7 +610,7 @@ We can run this:
file $REGENDOC_TMPDIR/b/test_error.py, line 1
def test_root(db): # no db here, will error out
E fixture 'db' not found
> available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
> available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
> use 'pytest --fixtures [testpath]' for help on them.
$REGENDOC_TMPDIR/b/test_error.py:1
@@ -640,7 +644,7 @@ We can run this:
E assert 0
a/test_db2.py:2: AssertionError
========== 3 failed, 2 passed, 1 xfailed, 1 error in 0.12 seconds ==========
============= 3 failed, 2 passed, 1 xfailed, 1 error in 0.12s ==============
The two test modules in the ``a`` directory see the same ``db`` fixture instance
while the one test in the sister-directory ``b`` doesn't see it. We could of course
@@ -680,7 +684,7 @@ case we just write some information out to a ``failures`` file:
with open("failures", mode) as f:
# let's also access a fixture for the fun of it
if "tmpdir" in item.fixturenames:
extra = " (%s)" % item.funcargs["tmpdir"]
extra = " ({})".format(item.funcargs["tmpdir"])
else:
extra = ""
@@ -705,9 +709,9 @@ and run them:
$ pytest test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 2 items
test_module.py FF [100%]
@@ -729,7 +733,7 @@ and run them:
E assert 0
test_module.py:6: AssertionError
========================= 2 failed in 0.12 seconds =========================
============================ 2 failed in 0.12s =============================
you will have a "failures" file which contains the failing test ids:
@@ -809,9 +813,9 @@ and run it:
$ pytest -s test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 3 items
test_module.py Esetting up a test failed! test_module.py::test_setup_fails
@@ -844,7 +848,7 @@ and run it:
E assert 0
test_module.py:19: AssertionError
==================== 2 failed, 1 error in 0.12 seconds =====================
======================== 2 failed, 1 error in 0.12s ========================
You'll see that the fixture finalizers could use the precise reporting
information.
@@ -854,7 +858,7 @@ information.
``PYTEST_CURRENT_TEST`` environment variable
--------------------------------------------
.. versionadded:: 3.2
Sometimes a test session might get stuck and there might be no easy way to figure out
which test got stuck, for example if pytest was run in quiet mode (``-q``) or you don't have access to the console

View File

@@ -5,30 +5,36 @@ A session-scoped fixture effectively has access to all
collected test items. Here is an example of a fixture
function which walks all collected tests and looks
if their test class defines a ``callme`` method and
calls it::
calls it:
.. code-block:: python
# content of conftest.py
import pytest
@pytest.fixture(scope="session", autouse=True)
def callattr_ahead_of_alltests(request):
print("callattr_ahead_of_alltests called")
seen = set([None])
seen = {None}
session = request.node
for item in session.items:
cls = item.getparent(pytest.Class)
if cls not in seen:
if hasattr(cls.obj, "callme"):
cls.obj.callme()
cls.obj.callme()
seen.add(cls)
test classes may now define a ``callme`` method which
will be called ahead of running any tests::
will be called ahead of running any tests:
.. code-block:: python
# content of test_module.py
class TestHello(object):
class TestHello:
@classmethod
def callme(cls):
print("callme called!")
@@ -39,16 +45,20 @@ will be called ahead of running any tests::
def test_method2(self):
print("test_method1 called")
class TestOther(object):
class TestOther:
@classmethod
def callme(cls):
print("callme other called")
def test_other(self):
print("test other")
# works with unittest as well ...
import unittest
class SomeTest(unittest.TestCase):
@classmethod
def callme(self):
@@ -71,4 +81,4 @@ If you run this without output capturing:
.test other
.test_unit1 method called
.
4 passed in 0.12 seconds
4 passed in 0.12s

View File

@@ -15,7 +15,9 @@ Running an existing test suite with pytest
Say you want to contribute to an existing repository somewhere.
After pulling the code into your development space using some
flavor of version control and (optionally) setting up a virtualenv
you will want to run::
you will want to run:
.. code-block:: bash
cd <repository>
pip install -e . # Environment dependent alternatives include

View File

@@ -7,7 +7,7 @@ pytest fixtures: explicit, modular, scalable
.. currentmodule:: _pytest.python
.. versionadded:: 2.0/2.3/2.4
.. _`xUnit`: http://en.wikipedia.org/wiki/XUnit
.. _`purpose of test fixtures`: http://en.wikipedia.org/wiki/Test_fixture#Software
@@ -49,20 +49,25 @@ argument. For each argument name, a fixture function with that name provides
the fixture object. Fixture functions are registered by marking them with
:py:func:`@pytest.fixture <_pytest.python.fixture>`. Let's look at a simple
self-contained test module containing a fixture and a test function
using it::
using it:
.. code-block:: python
# content of ./test_smtpsimple.py
import pytest
@pytest.fixture
def smtp_connection():
import smtplib
return smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
def test_ehlo(smtp_connection):
response, msg = smtp_connection.ehlo()
assert response == 250
assert 0 # for demo purposes
assert 0 # for demo purposes
Here, the ``test_ehlo`` needs the ``smtp_connection`` fixture value. pytest
will discover and call the :py:func:`@pytest.fixture <_pytest.python.fixture>`
@@ -72,9 +77,9 @@ marked ``smtp_connection`` fixture function. Running the test looks like this:
$ pytest test_smtpsimple.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_smtpsimple.py F [100%]
@@ -87,11 +92,11 @@ marked ``smtp_connection`` fixture function. Running the test looks like this:
def test_ehlo(smtp_connection):
response, msg = smtp_connection.ehlo()
assert response == 250
> assert 0 # for demo purposes
> assert 0 # for demo purposes
E assert 0
test_smtpsimple.py:11: AssertionError
========================= 1 failed in 0.12 seconds =========================
test_smtpsimple.py:14: AssertionError
============================ 1 failed in 0.12s =============================
In the failure traceback we see that the test function was called with a
``smtp_connection`` argument, the ``smtplib.SMTP()`` instance created by the fixture
@@ -180,12 +185,15 @@ Possible values for ``scope`` are: ``function``, ``class``, ``module``, ``packag
The next example puts the fixture function into a separate ``conftest.py`` file
so that tests from multiple test modules in the directory can
access the fixture function::
access the fixture function:
.. code-block:: python
# content of conftest.py
import pytest
import smtplib
@pytest.fixture(scope="module")
def smtp_connection():
return smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
@@ -193,16 +201,20 @@ access the fixture function::
The name of the fixture again is ``smtp_connection`` and you can access its
result by listing the name ``smtp_connection`` as an input parameter in any
test or fixture function (in or below the directory where ``conftest.py`` is
located)::
located):
.. code-block:: python
# content of test_module.py
def test_ehlo(smtp_connection):
response, msg = smtp_connection.ehlo()
assert response == 250
assert b"smtp.gmail.com" in msg
assert 0 # for demo purposes
def test_noop(smtp_connection):
response, msg = smtp_connection.noop()
assert response == 250
@@ -215,9 +227,9 @@ inspect what is going on and can now run the tests:
$ pytest test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 2 items
test_module.py FF [100%]
@@ -234,7 +246,7 @@ inspect what is going on and can now run the tests:
> assert 0 # for demo purposes
E assert 0
test_module.py:6: AssertionError
test_module.py:7: AssertionError
________________________________ test_noop _________________________________
smtp_connection = <smtplib.SMTP object at 0xdeadbeef>
@@ -245,8 +257,8 @@ inspect what is going on and can now run the tests:
> assert 0 # for demo purposes
E assert 0
test_module.py:11: AssertionError
========================= 2 failed in 0.12 seconds =========================
test_module.py:13: AssertionError
============================ 2 failed in 0.12s =============================
You see the two ``assert 0`` failing and more importantly you can also see
that the same (module-scoped) ``smtp_connection`` object was passed into the
@@ -276,7 +288,7 @@ Finally, the ``class`` scope will invoke the fixture once per test *class*.
``package`` scope (experimental)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.7
In pytest 3.7 the ``package`` scope has been introduced. Package-scoped fixtures
are finalized when the last test of a *package* finishes.
@@ -289,51 +301,55 @@ are finalized when the last test of a *package* finishes.
Use this new feature sparingly and please make sure to report any issues you find.
Higher-scoped fixtures are instantiated first
---------------------------------------------
Dynamic scope
^^^^^^^^^^^^^
.. versionadded:: 3.5
In some cases, you might want to change the scope of the fixture without changing the code.
To do that, pass a callable to ``scope``. The callable must return a string with a valid scope
and will be executed only once - during the fixture definition. It will be called with two
keyword arguments - ``fixture_name`` as a string and ``config`` with a configuration object.
Within a function request for features, fixture of higher-scopes (such as ``session``) are instantiated first than
lower-scoped fixtures (such as ``function`` or ``class``). The relative order of fixtures of same scope follows
the declared order in the test function and honours dependencies between fixtures.
Consider the code below:
This can be especially useful when dealing with fixtures that need time for setup, like spawning
a docker container. You can use the command-line argument to control the scope of the spawned
containers for different environments. See the example below.
.. code-block:: python
@pytest.fixture(scope="session")
def s1():
pass
def determine_scope(fixture_name, config):
if config.getoption("--keep-containers"):
return "session"
return "function"
@pytest.fixture(scope="module")
def m1():
pass
@pytest.fixture(scope=determine_scope)
def docker_container():
yield spawn_container()
@pytest.fixture
def f1(tmpdir):
pass
Order: Higher-scoped fixtures are instantiated first
----------------------------------------------------
@pytest.fixture
def f2():
pass
Within a function request for features, fixture of higher-scopes (such as ``session``) are instantiated first than
lower-scoped fixtures (such as ``function`` or ``class``). The relative order of fixtures of same scope follows
the declared order in the test function and honours dependencies between fixtures. Autouse fixtures will be
instantiated before explicitly used fixtures.
def test_foo(f1, m1, f2, s1):
...
Consider the code below:
.. literalinclude:: example/fixtures/test_fixtures_order.py
The fixtures requested by ``test_foo`` will be instantiated in the following order:
The fixtures requested by ``test_order`` will be instantiated in the following order:
1. ``s1``: is the highest-scoped fixture (``session``).
2. ``m1``: is the second highest-scoped fixture (``module``).
3. ``tmpdir``: is a ``function``-scoped fixture, required by ``f1``: it needs to be instantiated at this point
because it is a dependency of ``f1``.
4. ``f1``: is the first ``function``-scoped fixture in ``test_foo`` parameter list.
5. ``f2``: is the last ``function``-scoped fixture in ``test_foo`` parameter list.
3. ``a1``: is a ``function``-scoped ``autouse`` fixture: it will be instantiated before other fixtures
within the same scope.
4. ``f3``: is a ``function``-scoped fixture, required by ``f1``: it needs to be instantiated at this point
5. ``f1``: is the first ``function``-scoped fixture in ``test_order`` parameter list.
6. ``f2``: is the last ``function``-scoped fixture in ``test_order`` parameter list.
.. _`finalization`:
@@ -371,7 +387,7 @@ Let's execute it:
$ pytest -s -q --tb=no
FFteardown smtp
2 failed in 0.12 seconds
2 failed in 0.12s
We see that the ``smtp_connection`` instance is finalized after the two
tests finished execution. Note that if we decorated our fixture
@@ -400,6 +416,34 @@ The ``smtp_connection`` connection will be closed after the test finished
execution because the ``smtp_connection`` object automatically closes when
the ``with`` statement ends.
Using the contextlib.ExitStack context manager finalizers will always be called
regardless if the fixture *setup* code raises an exception. This is handy to properly
close all resources created by a fixture even if one of them fails to be created/acquired:
.. code-block:: python
# content of test_yield3.py
import contextlib
import pytest
@contextlib.contextmanager
def connect(port):
... # create connection
yield
... # close connection
@pytest.fixture
def equipments():
with contextlib.ExitStack() as stack:
yield [stack.enter_context(connect(port)) for port in ("C1", "C3", "C28")]
In the example above, if ``"C28"`` fails with an exception, ``"C1"`` and ``"C3"`` will still
be properly closed.
Note that if an exception happens during the *setup* code (before the ``yield`` keyword), the
*teardown* code (after the ``yield``) will not be called.
@@ -428,27 +472,39 @@ Here's the ``smtp_connection`` fixture changed to use ``addfinalizer`` for clean
return smtp_connection # provide the fixture value
Here's the ``equipments`` fixture changed to use ``addfinalizer`` for cleanup:
.. code-block:: python
# content of test_yield3.py
import contextlib
import functools
import pytest
@contextlib.contextmanager
def connect(port):
... # create connection
yield
... # close connection
@pytest.fixture
def equipments(request):
r = []
for port in ("C1", "C3", "C28"):
cm = connect(port)
equip = cm.__enter__()
request.addfinalizer(functools.partial(cm.__exit__, None, None, None))
r.append(equip)
return r
Both ``yield`` and ``addfinalizer`` methods work similarly by calling their code after the test
ends, but ``addfinalizer`` has two key differences over ``yield``:
1. It is possible to register multiple finalizer functions.
2. Finalizers will always be called regardless if the fixture *setup* code raises an exception.
This is handy to properly close all resources created by a fixture even if one of them
fails to be created/acquired::
@pytest.fixture
def equipments(request):
r = []
for port in ('C1', 'C3', 'C28'):
equip = connect(port)
request.addfinalizer(equip.disconnect)
r.append(equip)
return r
In the example above, if ``"C28"`` fails with an exception, ``"C1"`` and ``"C3"`` will still
be properly closed. Of course, if an exception happens before the finalize function is
registered then it will not be executed.
ends. Of course, if an exception happens before the finalize function is registered then it
will not be executed.
.. _`request-context`:
@@ -459,18 +515,21 @@ Fixtures can introspect the requesting test context
Fixture functions can accept the :py:class:`request <FixtureRequest>` object
to introspect the "requesting" test function, class or module context.
Further extending the previous ``smtp_connection`` fixture example, let's
read an optional server URL from the test module which uses our fixture::
read an optional server URL from the test module which uses our fixture:
.. code-block:: python
# content of conftest.py
import pytest
import smtplib
@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 %s (%s)" % (smtp_connection, server))
print("finalizing {} ({})".format(smtp_connection, server))
smtp_connection.close()
We use the ``request.module`` attribute to optionally obtain an
@@ -482,15 +541,18 @@ again, nothing much has changed:
$ pytest -s -q --tb=no
FFfinalizing <smtplib.SMTP object at 0xdeadbeef> (smtp.gmail.com)
2 failed in 0.12 seconds
2 failed in 0.12s
Let's quickly create another test module that actually sets the
server URL in its module namespace::
server URL in its module namespace:
.. code-block:: python
# content of test_anothersmtp.py
smtpserver = "mail.python.org" # will be read by smtp fixture
def test_showhelo(smtp_connection):
assert 0, smtp_connection.helo()
@@ -502,7 +564,7 @@ Running it:
F [100%]
================================= FAILURES =================================
______________________________ test_showhelo _______________________________
test_anothersmtp.py:5: in test_showhelo
test_anothersmtp.py:6: in test_showhelo
assert 0, smtp_connection.helo()
E AssertionError: (250, b'mail.python.org')
E assert 0
@@ -522,16 +584,14 @@ of a fixture is needed multiple times in a single test. Instead of returning
data directly, the fixture instead returns a function which generates the data.
This function can then be called multiple times in the test.
Factories can have have parameters as needed::
Factories can have parameters as needed:
.. code-block:: python
@pytest.fixture
def make_customer_record():
def _make_customer_record(name):
return {
"name": name,
"orders": []
}
return {"name": name, "orders": []}
return _make_customer_record
@@ -541,7 +601,9 @@ Factories can have have parameters as needed::
customer_2 = make_customer_record("Mike")
customer_3 = make_customer_record("Meredith")
If the data created by the factory requires managing, the fixture can take care of that::
If the data created by the factory requires managing, the fixture can take care of that:
.. code-block:: python
@pytest.fixture
def make_customer_record():
@@ -580,18 +642,20 @@ configured in multiple ways.
Extending the previous example, we can flag the fixture to create two
``smtp_connection`` fixture instances which will cause all tests using the fixture
to run twice. The fixture function gets access to each parameter
through the special :py:class:`request <FixtureRequest>` object::
through the special :py:class:`request <FixtureRequest>` object:
.. code-block:: python
# content of conftest.py
import pytest
import smtplib
@pytest.fixture(scope="module",
params=["smtp.gmail.com", "mail.python.org"])
@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 %s" % smtp_connection)
print("finalizing {}".format(smtp_connection))
smtp_connection.close()
The main change is the declaration of ``params`` with
@@ -616,7 +680,7 @@ So let's just do another run:
> assert 0 # for demo purposes
E assert 0
test_module.py:6: AssertionError
test_module.py:7: AssertionError
________________________ test_noop[smtp.gmail.com] _________________________
smtp_connection = <smtplib.SMTP object at 0xdeadbeef>
@@ -627,7 +691,7 @@ So let's just do another run:
> assert 0 # for demo purposes
E assert 0
test_module.py:11: AssertionError
test_module.py:13: AssertionError
________________________ test_ehlo[mail.python.org] ________________________
smtp_connection = <smtplib.SMTP object at 0xdeadbeef>
@@ -638,7 +702,7 @@ So let's just do another run:
> assert b"smtp.gmail.com" in msg
E AssertionError: assert b'smtp.gmail.com' in b'mail.python.org\nPIPELINING\nSIZE 51200000\nETRN\nSTARTTLS\nAUTH DIGEST-MD5 NTLM CRAM-MD5\nENHANCEDSTATUSCODES\n8BITMIME\nDSN\nSMTPUTF8\nCHUNKING'
test_module.py:5: AssertionError
test_module.py:6: AssertionError
-------------------------- Captured stdout setup ---------------------------
finalizing <smtplib.SMTP object at 0xdeadbeef>
________________________ test_noop[mail.python.org] ________________________
@@ -651,10 +715,10 @@ So let's just do another run:
> assert 0 # for demo purposes
E assert 0
test_module.py:11: AssertionError
test_module.py:13: AssertionError
------------------------- Captured stdout teardown -------------------------
finalizing <smtplib.SMTP object at 0xdeadbeef>
4 failed in 0.12 seconds
4 failed in 0.12s
We see that our two test functions each ran twice, against the different
``smtp_connection`` instances. Note also, that with the ``mail.python.org``
@@ -672,28 +736,35 @@ Numbers, strings, booleans and None will have their usual string
representation used in the test ID. For other objects, pytest will
make a string based on the argument name. It is possible to customise
the string used in a test ID for a certain fixture value by using the
``ids`` keyword argument::
``ids`` keyword argument:
.. code-block:: python
# content of test_ids.py
import pytest
@pytest.fixture(params=[0, 1], ids=["spam", "ham"])
def a(request):
return request.param
def test_a(a):
pass
def idfn(fixture_value):
if fixture_value == 0:
return "eggs"
else:
return None
@pytest.fixture(params=[0, 1], ids=idfn)
def b(request):
return request.param
def test_b(b):
pass
@@ -708,9 +779,9 @@ Running the above tests results in the following test IDs being used:
$ pytest --collect-only
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 10 items
<Module test_anothersmtp.py>
<Function test_showhelo[smtp.gmail.com]>
@@ -726,7 +797,7 @@ Running the above tests results in the following test IDs being used:
<Function test_ehlo[mail.python.org]>
<Function test_noop[mail.python.org]>
======================= no tests ran in 0.12 seconds =======================
========================== no tests ran in 0.12s ===========================
.. _`fixture-parametrize-marks`:
@@ -736,14 +807,19 @@ Using marks with parametrized fixtures
:func:`pytest.param` can be used to apply marks in values sets of parametrized fixtures in the same way
that they can be used with :ref:`@pytest.mark.parametrize <@pytest.mark.parametrize>`.
Example::
Example:
.. code-block:: python
# content of test_fixture_marks.py
import pytest
@pytest.fixture(params=[0, 1, pytest.param(2, marks=pytest.mark.skip)])
def data_set(request):
return request.param
def test_data(data_set):
pass
@@ -753,16 +829,16 @@ Running this test will *skip* the invocation of ``data_set`` with value ``2``:
$ pytest test_fixture_marks.py -v
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 3 items
test_fixture_marks.py::test_data[0] PASSED [ 33%]
test_fixture_marks.py::test_data[1] PASSED [ 66%]
test_fixture_marks.py::test_data[2] SKIPPED [100%]
=================== 2 passed, 1 skipped in 0.12 seconds ====================
======================= 2 passed, 1 skipped in 0.12s =======================
.. _`interdependent fixtures`:
@@ -774,20 +850,25 @@ can use other fixtures themselves. This contributes to a modular design
of your fixtures and allows re-use of framework-specific fixtures across
many projects. As a simple example, we can extend the previous example
and instantiate an object ``app`` where we stick the already defined
``smtp_connection`` resource into it::
``smtp_connection`` resource into it:
.. code-block:: python
# content of test_appsetup.py
import pytest
class App(object):
class App:
def __init__(self, smtp_connection):
self.smtp_connection = smtp_connection
@pytest.fixture(scope="module")
def app(smtp_connection):
return App(smtp_connection)
def test_smtp_connection_exists(app):
assert app.smtp_connection
@@ -798,15 +879,15 @@ Here we declare an ``app`` fixture which receives the previously defined
$ pytest -v test_appsetup.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 2 items
test_appsetup.py::test_smtp_connection_exists[smtp.gmail.com] PASSED [ 50%]
test_appsetup.py::test_smtp_connection_exists[mail.python.org] PASSED [100%]
========================= 2 passed in 0.12 seconds =========================
============================ 2 passed in 0.12s =============================
Due to the parametrization of ``smtp_connection``, the test will run twice with two
different ``App`` instances and respective smtp servers. There is no
@@ -836,31 +917,40 @@ this eases testing of applications which create and use global state.
The following example uses two parametrized fixtures, one of which is
scoped on a per-module basis, and all the functions perform ``print`` calls
to show the setup/teardown flow::
to show the setup/teardown flow:
.. code-block:: python
# content of test_module.py
import pytest
@pytest.fixture(scope="module", params=["mod1", "mod2"])
def modarg(request):
param = request.param
print(" SETUP modarg %s" % param)
print(" SETUP modarg", param)
yield param
print(" TEARDOWN modarg %s" % param)
print(" TEARDOWN modarg", param)
@pytest.fixture(scope="function", params=[1,2])
@pytest.fixture(scope="function", params=[1, 2])
def otherarg(request):
param = request.param
print(" SETUP otherarg %s" % param)
print(" SETUP otherarg", param)
yield param
print(" TEARDOWN otherarg %s" % param)
print(" TEARDOWN otherarg", param)
def test_0(otherarg):
print(" RUN test0 with otherarg %s" % otherarg)
print(" RUN test0 with otherarg", otherarg)
def test_1(modarg):
print(" RUN test1 with modarg %s" % modarg)
print(" RUN test1 with modarg", modarg)
def test_2(otherarg, modarg):
print(" RUN test2 with otherarg %s and modarg %s" % (otherarg, modarg))
print(" RUN test2 with otherarg {} and modarg {}".format(otherarg, modarg))
Let's run the tests in verbose mode and with looking at the print-output:
@@ -869,9 +959,9 @@ Let's run the tests in verbose mode and with looking at the print-output:
$ pytest -v -s test_module.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y -- $PYTHON_PREFIX/bin/python
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collecting ... collected 8 items
test_module.py::test_0[1] SETUP otherarg 1
@@ -907,7 +997,7 @@ Let's run the tests in verbose mode and with looking at the print-output:
TEARDOWN modarg mod2
========================= 8 passed in 0.12 seconds =========================
============================ 8 passed in 0.12s =============================
You can see that the parametrized module-scoped ``modarg`` resource caused an
ordering of test execution that lead to the fewest possible "active" resources.
@@ -935,7 +1025,9 @@ current working directory but otherwise do not care for the concrete
directory. Here is how you can use the standard `tempfile
<http://docs.python.org/library/tempfile.html>`_ and pytest fixtures to
achieve it. We separate the creation of the fixture into a conftest.py
file::
file:
.. code-block:: python
# content of conftest.py
@@ -943,19 +1035,23 @@ file::
import tempfile
import os
@pytest.fixture()
def cleandir():
newpath = tempfile.mkdtemp()
os.chdir(newpath)
and declare its use in a test module via a ``usefixtures`` marker::
and declare its use in a test module via a ``usefixtures`` marker:
.. code-block:: python
# content of test_setenv.py
import os
import pytest
@pytest.mark.usefixtures("cleandir")
class TestDirectoryInit(object):
class TestDirectoryInit:
def test_cwd_starts_empty(self):
assert os.listdir(os.getcwd()) == []
with open("myfile", "w") as f:
@@ -973,7 +1069,7 @@ to verify our fixture is activated and the tests pass:
$ pytest -q
.. [100%]
2 passed in 0.12 seconds
2 passed in 0.12s
You can specify multiple fixtures like this:
@@ -1032,25 +1128,32 @@ without declaring a function argument explicitly or a `usefixtures`_ decorator.
As a practical example, suppose we have a database fixture which has a
begin/rollback/commit architecture and we want to automatically surround
each test method by a transaction and a rollback. Here is a dummy
self-contained implementation of this idea::
self-contained implementation of this idea:
.. code-block:: python
# content of test_db_transact.py
import pytest
class DB(object):
class DB:
def __init__(self):
self.intransaction = []
def begin(self, name):
self.intransaction.append(name)
def rollback(self):
self.intransaction.pop()
@pytest.fixture(scope="module")
def db():
return DB()
class TestClass(object):
class TestClass:
@pytest.fixture(autouse=True)
def transact(self, request, db):
db.begin(request.function.__name__)
@@ -1074,7 +1177,7 @@ If we run it, we get two passing tests:
$ pytest -q
.. [100%]
2 passed in 0.12 seconds
2 passed in 0.12s
Here is how autouse fixtures work in other scopes:
@@ -1098,7 +1201,9 @@ Here is how autouse fixtures work in other scopes:
Note that the above ``transact`` fixture may very well be a fixture that
you want to make available in your project without having it generally
active. The canonical way to do that is to put the transact definition
into a conftest.py file **without** using ``autouse``::
into a conftest.py file **without** using ``autouse``:
.. code-block:: python
# content of conftest.py
@pytest.fixture
@@ -1107,10 +1212,12 @@ into a conftest.py file **without** using ``autouse``::
yield
db.rollback()
and then e.g. have a TestClass using it by declaring the need::
and then e.g. have a TestClass using it by declaring the need:
.. code-block:: python
@pytest.mark.usefixtures("transact")
class TestClass(object):
class TestClass:
def test_method1(self):
...
@@ -1179,6 +1286,8 @@ Given the tests file structure is:
conftest.py
# content of tests/conftest.py
import pytest
@pytest.fixture
def username():
return 'username'

View File

@@ -122,4 +122,4 @@ Resources
* Google:
* `Flaky Tests at Google and How We Mitigate Them <https://testing.googleblog.com/2016/05/flaky-tests-at-google-and-how-we.html>`_ by John Micco, 2016
* `Where do Google's flaky tests come from? <https://docs.google.com/document/d/1mZ0-Kc97DI_F3tf_GBW_NB_aqka-P1jVOsFfufxqUUM/edit#heading=h.ec0r4fypsleh>`_ by Jeff Listfield, 2017
* `Where do Google's flaky tests come from? <https://testing.googleblog.com/2017/04/where-do-our-flaky-tests-come-from.html>`_ by Jeff Listfield, 2017

View File

@@ -21,19 +21,23 @@ funcarg for a test function is required. If a factory wants to
re-use a resource across different scopes, it often used
the ``request.cached_setup()`` helper to manage caching of
resources. Here is a basic example how we could implement
a per-session Database object::
a per-session Database object:
.. code-block:: python
# content of conftest.py
class Database(object):
class Database:
def __init__(self):
print("database instance created")
def destroy(self):
print("database instance destroyed")
def pytest_funcarg__db(request):
return request.cached_setup(setup=DataBase,
teardown=lambda db: db.destroy,
scope="session")
return request.cached_setup(
setup=DataBase, teardown=lambda db: db.destroy, scope="session"
)
There are several limitations and difficulties with this approach:
@@ -68,7 +72,9 @@ Direct scoping of fixture/funcarg factories
Instead of calling cached_setup() with a cache scope, you can use the
:ref:`@pytest.fixture <pytest.fixture>` decorator and directly state
the scope::
the scope:
.. code-block:: python
@pytest.fixture(scope="session")
def db(request):
@@ -90,11 +96,13 @@ Previously, funcarg factories could not directly cause parametrization.
You needed to specify a ``@parametrize`` decorator on your test function
or implement a ``pytest_generate_tests`` hook to perform
parametrization, i.e. calling a test multiple times with different value
sets. pytest-2.3 introduces a decorator for use on the factory itself::
sets. pytest-2.3 introduces a decorator for use on the factory itself:
.. code-block:: python
@pytest.fixture(params=["mysql", "pg"])
def db(request):
... # use request.param
... # use request.param
Here the factory will be invoked twice (with the respective "mysql"
and "pg" values set as ``request.param`` attributes) and all of
@@ -107,7 +115,9 @@ allow to re-use already written factories because effectively
parametrized via
:py:func:`~_pytest.python.Metafunc.parametrize(indirect=True)` calls.
Of course it's perfectly fine to combine parametrization and scoping::
Of course it's perfectly fine to combine parametrization and scoping:
.. code-block:: python
@pytest.fixture(scope="session", params=["mysql", "pg"])
def db(request):
@@ -128,7 +138,9 @@ No ``pytest_funcarg__`` prefix when using @fixture decorator
When using the ``@fixture`` decorator the name of the function
denotes the name under which the resource can be accessed as a function
argument::
argument:
.. code-block:: python
@pytest.fixture()
def db(request):
@@ -137,7 +149,9 @@ argument::
The name under which the funcarg resource can be requested is ``db``.
You can still use the "old" non-decorator way of specifying funcarg factories
aka::
aka:
.. code-block:: python
def pytest_funcarg__db(request):
...

View File

@@ -1,9 +1,9 @@
Installation and Getting Started
===================================
**Pythons**: Python 2.7, 3.4, 3.5, 3.6, 3.7, Jython, PyPy-2.3
**Pythons**: Python 3.5, 3.6, 3.7, PyPy3
**Platforms**: Unix/Posix and Windows
**Platforms**: Linux and Windows
**PyPI package name**: `pytest <https://pypi.org/project/pytest/>`_
@@ -28,19 +28,22 @@ Install ``pytest``
.. code-block:: bash
$ pytest --version
This is pytest version 4.x.y, imported from $PYTHON_PREFIX/lib/python3.6/site-packages/pytest.py
This is pytest version 5.x.y, imported from $PYTHON_PREFIX/lib/python3.7/site-packages/pytest.py
.. _`simpletest`:
Create your first test
----------------------------------------------------------
Create a simple test function with just four lines of code::
Create a simple test function with just four lines of code:
.. code-block:: python
# content of test_sample.py
def func(x):
return x + 1
def test_answer():
assert func(3) == 5
@@ -50,9 +53,9 @@ Thats it. You can now execute the test function:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_sample.py F [100%]
@@ -65,8 +68,8 @@ Thats it. You can now execute the test function:
E assert 4 == 5
E + where 4 = func(3)
test_sample.py:5: AssertionError
========================= 1 failed in 0.12 seconds =========================
test_sample.py:6: AssertionError
============================ 1 failed in 0.12s =============================
This test returns a failure report because ``func(3)`` does not return ``5``.
@@ -83,13 +86,18 @@ Run multiple tests
Assert that a certain exception is raised
--------------------------------------------------------------
Use the ``raises`` helper to assert that some code raises an exception::
Use the :ref:`raises <assertraises>` helper to assert that some code raises an exception:
.. code-block:: python
# content of test_sysexit.py
import pytest
def f():
raise SystemExit(1)
def test_mytest():
with pytest.raises(SystemExit):
f()
@@ -100,22 +108,24 @@ Execute the test function with “quiet” reporting mode:
$ pytest -q test_sysexit.py
. [100%]
1 passed in 0.12 seconds
1 passed in 0.12s
Group multiple tests in a class
--------------------------------------------------------------
Once you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a class containing more than one test::
Once you develop multiple tests, you may want to group them into a class. pytest makes it easy to create a class containing more than one test:
.. code-block:: python
# content of test_class.py
class TestClass(object):
class TestClass:
def test_one(self):
x = "this"
assert 'h' in x
assert "h" in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
assert hasattr(x, "check")
``pytest`` discovers all tests following its :ref:`Conventions for Python test discovery <test discovery>`, so it finds both ``test_`` prefixed functions. There is no need to subclass anything. We can simply run the module by passing its filename:
@@ -130,19 +140,21 @@ Once you develop multiple tests, you may want to group them into a class. pytest
def test_two(self):
x = "hello"
> assert hasattr(x, 'check')
> assert hasattr(x, "check")
E AssertionError: assert False
E + where False = hasattr('hello', 'check')
test_class.py:8: AssertionError
1 failed, 1 passed in 0.12 seconds
1 failed, 1 passed in 0.12s
The first test passed and the second failed. You can easily see the intermediate values in the assertion to help you understand the reason for the failure.
Request a unique temporary directory for functional tests
--------------------------------------------------------------
``pytest`` provides `Builtin fixtures/function arguments <https://docs.pytest.org/en/latest/builtin.html#builtinfixtures>`_ to request arbitrary resources, like a unique temporary directory::
``pytest`` provides `Builtin fixtures/function arguments <https://docs.pytest.org/en/latest/builtin.html>`_ to request arbitrary resources, like a unique temporary directory:
.. code-block:: python
# content of test_tmpdir.py
def test_needsfiles(tmpdir):
@@ -168,7 +180,7 @@ List the name ``tmpdir`` in the test function signature and ``pytest`` will look
test_tmpdir.py:3: AssertionError
--------------------------- Captured stdout call ---------------------------
PYTEST_TMPDIR/test_needsfiles0
1 failed in 0.12 seconds
1 failed in 0.12s
More info on tmpdir handling is available at :ref:`Temporary directories and files <tmpdir handling>`.

View File

@@ -7,19 +7,22 @@ Good Integration Practices
Install package with pip
-------------------------------------------------
For development, we recommend you use venv_ for virtual environments
(or virtualenv_ for Python 2.7) and
For development, we recommend you use venv_ for virtual environments and
pip_ for installing your application and any dependencies,
as well as the ``pytest`` package itself.
This ensures your code and dependencies are isolated from your system Python installation.
Next, place a ``setup.py`` file in the root of your package with the following minimum content::
Next, place a ``setup.py`` file in the root of your package with the following minimum content:
.. code-block:: python
from setuptools import setup, find_packages
setup(name="PACKAGENAME", packages=find_packages())
Where ``PACKAGENAME`` is the name of your package. You can then install your package in "editable" mode by running from the same directory::
Where ``PACKAGENAME`` is the name of your package. You can then install your package in "editable" mode by running from the same directory:
.. code-block:: bash
pip install -e .
@@ -61,7 +64,9 @@ Tests outside application code
Putting tests into an extra directory outside your actual application code
might be useful if you have many functional tests or for other reasons want
to keep tests separate from actual application code (often a good idea)::
to keep tests separate from actual application code (often a good idea):
.. code-block:: text
setup.py
mypkg/
@@ -83,7 +88,7 @@ This has the following benefits:
.. note::
See :ref:`pythonpath` for more information about the difference between calling ``pytest`` and
See :ref:`pytest vs python -m pytest` for more information about the difference between calling ``pytest`` and
``python -m pytest``.
Note that using this scheme your test files must have **unique names**, because
@@ -93,7 +98,9 @@ be imported as ``test_app`` and ``test_view`` top-level modules by adding ``test
``sys.path``.
If you need to have test modules with the same name, you might add ``__init__.py`` files to your
``tests`` folder and subfolders, changing them to packages::
``tests`` folder and subfolders, changing them to packages:
.. code-block:: text
setup.py
mypkg/
@@ -115,7 +122,9 @@ This is problematic if you are using a tool like `tox`_ to test your package in
because you want to test the *installed* version of your package, not the local code from the repository.
In this situation, it is **strongly** suggested to use a ``src`` layout where application root package resides in a
sub-directory of your root::
sub-directory of your root:
.. code-block:: text
setup.py
src/
@@ -141,7 +150,9 @@ Tests as part of application code
Inlining test directories into your application package
is useful if you have direct relation between tests and application modules and
want to distribute them along with your application::
want to distribute them along with your application:
.. code-block:: text
setup.py
mypkg/
@@ -154,7 +165,9 @@ want to distribute them along with your application::
test_view.py
...
In this scheme, it is easy to run your tests using the ``--pyargs`` option::
In this scheme, it is easy to run your tests using the ``--pyargs`` option:
.. code-block:: bash
pytest --pyargs mypkg
@@ -220,101 +233,4 @@ against your source code checkout, helping to detect packaging
glitches.
Integrating with setuptools / ``python setup.py test`` / ``pytest-runner``
--------------------------------------------------------------------------
You can integrate test runs into your setuptools based project
with the `pytest-runner <https://pypi.org/project/pytest-runner/>`_ plugin.
Add this to ``setup.py`` file:
.. code-block:: python
from setuptools import setup
setup(
# ...,
setup_requires=["pytest-runner", ...],
tests_require=["pytest", ...],
# ...,
)
And create an alias into ``setup.cfg`` file:
.. code-block:: ini
[aliases]
test=pytest
If you now type::
python setup.py test
this will execute your tests using ``pytest-runner``. As this is a
standalone version of ``pytest`` no prior installation whatsoever is
required for calling the test command. You can also pass additional
arguments to pytest such as your test directory or other
options using ``--addopts``.
You can also specify other pytest-ini options in your ``setup.cfg`` file
by putting them into a ``[tool:pytest]`` section:
.. code-block:: ini
[tool:pytest]
addopts = --verbose
python_files = testing/*/*.py
Manual Integration
^^^^^^^^^^^^^^^^^^
If for some reason you don't want/can't use ``pytest-runner``, you can write
your own setuptools Test command for invoking pytest.
.. code-block:: python
import sys
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
user_options = [("pytest-args=", "a", "Arguments to pass to pytest")]
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = ""
def run_tests(self):
import shlex
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(shlex.split(self.pytest_args))
sys.exit(errno)
setup(
# ...,
tests_require=["pytest"],
cmdclass={"pytest": PyTest},
)
Now if you run::
python setup.py test
this will download ``pytest`` if needed and then run your tests
as you would expect it to. You can pass a single string of arguments
using the ``--pytest-args`` or ``-a`` command-line option. For example::
python setup.py test -a "--durations=5"
is equivalent to running ``pytest --durations=5``.
.. include:: links.inc

View File

@@ -4,10 +4,121 @@ Historical Notes
This page lists features or behavior from previous versions of pytest which have changed over the years. They are
kept here as a historical note so users looking at old code can find documentation related to them.
.. _marker-revamp:
Marker revamp and iteration
---------------------------
.. versionchanged:: 3.6
pytest's marker implementation traditionally worked by simply updating the ``__dict__`` attribute of functions to cumulatively add markers. As a result, markers would unintentionally be passed along class hierarchies in surprising ways. Further, the API for retrieving them was inconsistent, as markers from parameterization would be stored differently than markers applied using the ``@pytest.mark`` decorator and markers added via ``node.add_marker``.
This state of things made it technically next to impossible to use data from markers correctly without having a deep understanding of the internals, leading to subtle and hard to understand bugs in more advanced usages.
Depending on how a marker got declared/changed one would get either a ``MarkerInfo`` which might contain markers from sibling classes,
``MarkDecorators`` when marks came from parameterization or from a ``node.add_marker`` call, discarding prior marks. Also ``MarkerInfo`` acts like a single mark, when it in fact represents a merged view on multiple marks with the same name.
On top of that markers were not accessible in the same way for modules, classes, and functions/methods.
In fact, markers were only accessible in functions, even if they were declared on classes/modules.
A new API to access markers has been introduced in pytest 3.6 in order to solve the problems with
the initial design, providing the :func:`_pytest.nodes.Node.iter_markers` method to iterate over
markers in a consistent manner and reworking the internals, which solved a great deal of problems
with the initial design.
.. _update marker code:
Updating code
~~~~~~~~~~~~~
The old ``Node.get_marker(name)`` function is considered deprecated because it returns an internal ``MarkerInfo`` object
which contains the merged name, ``*args`` and ``**kwargs`` of all the markers which apply to that node.
In general there are two scenarios on how markers should be handled:
1. Marks overwrite each other. Order matters but you only want to think of your mark as a single item. E.g.
``log_level('info')`` at a module level can be overwritten by ``log_level('debug')`` for a specific test.
In this case, use ``Node.get_closest_marker(name)``:
.. code-block:: python
# replace this:
marker = item.get_marker("log_level")
if marker:
level = marker.args[0]
# by this:
marker = item.get_closest_marker("log_level")
if marker:
level = marker.args[0]
2. Marks compose in an additive manner. E.g. ``skipif(condition)`` marks mean you just want to evaluate all of them,
order doesn't even matter. You probably want to think of your marks as a set here.
In this case iterate over each mark and handle their ``*args`` and ``**kwargs`` individually.
.. code-block:: python
# replace this
skipif = item.get_marker("skipif")
if skipif:
for condition in skipif.args:
# eval condition
...
# by this:
for skipif in item.iter_markers("skipif"):
condition = skipif.args[0]
# eval condition
If you are unsure or have any questions, please consider opening
`an issue <https://github.com/pytest-dev/pytest/issues>`_.
Related issues
~~~~~~~~~~~~~~
Here is a non-exhaustive list of issues fixed by the new implementation:
* Marks don't pick up nested classes (`#199 <https://github.com/pytest-dev/pytest/issues/199>`_).
* Markers stain on all related classes (`#568 <https://github.com/pytest-dev/pytest/issues/568>`_).
* Combining marks - args and kwargs calculation (`#2897 <https://github.com/pytest-dev/pytest/issues/2897>`_).
* ``request.node.get_marker('name')`` returns ``None`` for markers applied in classes (`#902 <https://github.com/pytest-dev/pytest/issues/902>`_).
* Marks applied in parametrize are stored as markdecorator (`#2400 <https://github.com/pytest-dev/pytest/issues/2400>`_).
* Fix marker interaction in a backward incompatible way (`#1670 <https://github.com/pytest-dev/pytest/issues/1670>`_).
* Refactor marks to get rid of the current "marks transfer" mechanism (`#2363 <https://github.com/pytest-dev/pytest/issues/2363>`_).
* Introduce FunctionDefinition node, use it in generate_tests (`#2522 <https://github.com/pytest-dev/pytest/issues/2522>`_).
* Remove named marker attributes and collect markers in items (`#891 <https://github.com/pytest-dev/pytest/issues/891>`_).
* skipif mark from parametrize hides module level skipif mark (`#1540 <https://github.com/pytest-dev/pytest/issues/1540>`_).
* skipif + parametrize not skipping tests (`#1296 <https://github.com/pytest-dev/pytest/issues/1296>`_).
* Marker transfer incompatible with inheritance (`#535 <https://github.com/pytest-dev/pytest/issues/535>`_).
More details can be found in the `original PR <https://github.com/pytest-dev/pytest/pull/3317>`_.
.. note::
in a future major relase of pytest we will introduce class based markers,
at which point markers will no longer be limited to instances of :py:class:`Mark`.
cache plugin integrated into the core
-------------------------------------
.. versionadded:: 2.8
The functionality of the :ref:`core cache <cache>` plugin was previously distributed
as a third party plugin named ``pytest-cache``. The core plugin
@@ -18,7 +129,7 @@ can only store/receive data between test runs that is json-serializable.
funcargs and ``pytest_funcarg__``
---------------------------------
.. versionchanged:: 2.3
In versions prior to 2.3 there was no ``@pytest.fixture`` marker
and you had to use a magic ``pytest_funcarg__NAME`` prefix
@@ -30,7 +141,7 @@ functions.
``@pytest.yield_fixture`` decorator
-----------------------------------
.. versionchanged:: 2.10
Prior to version 2.10, in order to use a ``yield`` statement to execute teardown code one
had to mark a fixture using the ``yield_fixture`` marker. From 2.10 onward, normal
@@ -41,7 +152,7 @@ and considered deprecated.
``[pytest]`` header in ``setup.cfg``
------------------------------------
.. versionchanged:: 3.0
Prior to 3.0, the supported section name was ``[pytest]``. Due to how
this may collide with some distutils commands, the recommended
@@ -54,17 +165,19 @@ name is ``[pytest]``.
Applying marks to ``@pytest.mark.parametrize`` parameters
---------------------------------------------------------
.. versionchanged:: 3.1
Prior to version 3.1 the supported mechanism for marking values
used the syntax::
used the syntax:
.. code-block:: python
import pytest
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
pytest.mark.xfail(("6*9", 42),),
])
@pytest.mark.parametrize(
"test_input,expected", [("3+5", 8), ("2+4", 6), pytest.mark.xfail(("6*9", 42))]
)
def test_eval(test_input, expected):
assert eval(test_input) == expected
@@ -78,7 +191,7 @@ The old syntax is planned to be removed in pytest-4.0.
``@pytest.mark.parametrize`` argument names as a tuple
------------------------------------------------------
.. versionchanged:: 2.4
In versions prior to 2.4 one needed to specify the argument
names as a tuple. This remains valid but the simpler ``"name1,name2,..."``
@@ -89,7 +202,7 @@ it's easier to write and produces less line noise.
setup: is now an "autouse fixture"
----------------------------------
.. versionchanged:: 2.3
During development prior to the pytest-2.3 release the name
``pytest.setup`` was used but before the release it was renamed
@@ -102,12 +215,16 @@ namely :ref:`autouse fixtures`
Conditions as strings instead of booleans
-----------------------------------------
.. versionchanged:: 2.4
Prior to pytest-2.4 the only way to specify skipif/xfail conditions was
to use strings::
to use strings:
.. code-block:: python
import sys
@pytest.mark.skipif("sys.version_info >= (3,3)")
def test_function():
...
@@ -139,17 +256,20 @@ dictionary which is constructed as follows:
expression is applied.
The pytest ``config`` object allows you to skip based on a test
configuration value which you might have added::
configuration value which you might have added:
.. code-block:: python
@pytest.mark.skipif("not config.getvalue('db')")
def test_function(...):
def test_function():
...
The equivalent with "boolean conditions" is::
The equivalent with "boolean conditions" is:
@pytest.mark.skipif(not pytest.config.getvalue("db"),
reason="--db was not specified")
def test_function(...):
.. code-block:: python
@pytest.mark.skipif(not pytest.config.getvalue("db"), reason="--db was not specified")
def test_function():
pass
.. note::
@@ -162,14 +282,18 @@ The equivalent with "boolean conditions" is::
``pytest.set_trace()``
----------------------
.. versionchanged:: 2.4
Previous to version 2.4 to set a break point in code one needed to use ``pytest.set_trace()``::
Previous to version 2.4 to set a break point in code one needed to use ``pytest.set_trace()``:
.. code-block:: python
import pytest
def test_function():
...
pytest.set_trace() # invoke PDB debugger and tracing
pytest.set_trace() # invoke PDB debugger and tracing
This is no longer needed and one can use the native ``import pdb;pdb.set_trace()`` call directly.
@@ -179,7 +303,7 @@ For more details see :ref:`breakpoints`.
"compat" properties
-------------------
.. deprecated:: 3.9
Access of ``Module``, ``Function``, ``Class``, ``Instance``, ``File`` and ``Item`` through ``Node`` instances have long
been documented as deprecated, but started to emit warnings from pytest ``3.9`` and onward.

View File

@@ -28,9 +28,9 @@ To execute it:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 1 item
test_sample.py F [100%]
@@ -44,7 +44,7 @@ To execute it:
E + where 4 = inc(3)
test_sample.py:6: AssertionError
========================= 1 failed in 0.12 seconds =========================
============================ 1 failed in 0.12s =============================
Due to ``pytest``'s detailed assertion introspection, only plain ``assert`` statements are used.
See :ref:`Getting Started <getstarted>` for more examples.
@@ -61,7 +61,7 @@ Features
- Can run :ref:`unittest <unittest>` (including trial) and :ref:`nose <noseintegration>` test suites out of the box;
- Python 2.7, Python 3.4+, PyPy 2.3, Jython 2.5 (untested);
- Python 3.5+ and PyPy 3;
- Rich plugin architecture, with over 315+ `external plugins <http://plugincompat.herokuapp.com>`_ and thriving community;

View File

@@ -9,7 +9,7 @@ Distributed under the terms of the `MIT`_ license, pytest is free and open sourc
The MIT License (MIT)
Copyright (c) 2004-2017 Holger Krekel and others
Copyright (c) 2004-2019 Holger Krekel and others
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in

View File

@@ -14,7 +14,7 @@
.. _`distribute docs`:
.. _`distribute`: https://pypi.org/project/distribute/
.. _`pip`: https://pypi.org/project/pip/
.. _`venv`: https://docs.python.org/3/library/venv.html/
.. _`venv`: https://docs.python.org/3/library/venv.html
.. _`virtualenv`: https://pypi.org/project/virtualenv/
.. _hudson: http://hudson-ci.org/
.. _jenkins: http://jenkins-ci.org/

View File

@@ -3,8 +3,8 @@
Logging
-------
.. versionadded:: 3.3
.. versionchanged:: 3.4
pytest captures log messages of level ``WARNING`` or above automatically and displays them in their own section
for each failed test in the same manner as captured stdout and stderr.
@@ -70,7 +70,9 @@ caplog fixture
^^^^^^^^^^^^^^
Inside tests it is possible to change the log level for the captured log
messages. This is supported by the ``caplog`` fixture::
messages. This is supported by the ``caplog`` fixture:
.. code-block:: python
def test_foo(caplog):
caplog.set_level(logging.INFO)
@@ -78,59 +80,69 @@ messages. This is supported by the ``caplog`` fixture::
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
logger::
logger:
.. code-block:: python
def test_foo(caplog):
caplog.set_level(logging.CRITICAL, logger='root.baz')
caplog.set_level(logging.CRITICAL, logger="root.baz")
pass
The log levels set are restored automatically at the end of the test.
It is also possible to use a context manager to temporarily change the log
level inside a ``with`` block::
level inside a ``with`` block:
.. code-block:: python
def test_bar(caplog):
with caplog.at_level(logging.INFO):
pass
Again, by default the level of the root logger is affected but the level of any
logger can be changed instead with::
logger can be changed instead with:
.. code-block:: python
def test_bar(caplog):
with caplog.at_level(logging.CRITICAL, logger='root.baz'):
with caplog.at_level(logging.CRITICAL, logger="root.baz"):
pass
Lastly all the logs sent to the logger during the test run are made available on
the fixture in the form of both the ``logging.LogRecord`` instances and the final log text.
This is useful for when you want to assert on the contents of a message::
This is useful for when you want to assert on the contents of a message:
.. code-block:: python
def test_baz(caplog):
func_under_test()
for record in caplog.records:
assert record.levelname != 'CRITICAL'
assert 'wally' not in caplog.text
assert record.levelname != "CRITICAL"
assert "wally" not in caplog.text
For all the available attributes of the log records see the
``logging.LogRecord`` class.
You can also resort to ``record_tuples`` if all you want to do is to ensure,
that certain messages have been logged under a given logger name with a given
severity and message::
severity and message:
.. code-block:: python
def test_foo(caplog):
logging.getLogger().info('boo %s', 'arg')
logging.getLogger().info("boo %s", "arg")
assert caplog.record_tuples == [
('root', logging.INFO, 'boo arg'),
]
assert caplog.record_tuples == [("root", logging.INFO, "boo arg")]
You can call ``caplog.clear()`` to reset the captured log records in a test::
You can call ``caplog.clear()`` to reset the captured log records in a test:
.. code-block:: python
def test_something_with_clearing_records(caplog):
some_method_that_creates_log_records()
caplog.clear()
your_test_method()
assert ['Foo'] == [rec.message for rec in caplog.records]
assert ["Foo"] == [rec.message for rec in caplog.records]
The ``caplog.records`` attribute contains records from the current stage only, so
@@ -149,7 +161,7 @@ the records for the ``setup`` and ``call`` stages during teardown like so:
yield window
for when in ("setup", "call"):
messages = [
x.message for x in caplog.get_records(when) if x.level == logging.WARNING
x.message for x in caplog.get_records(when) if x.levelno == logging.WARNING
]
if messages:
pytest.fail(

View File

@@ -1,9 +1,7 @@
.. _mark:
Marking test functions with attributes
=================================================================
======================================
By using the ``pytest.mark`` helper you can easily set
metadata on your test functions. There are
@@ -17,8 +15,10 @@ some builtin markers, for example:
to the same test function.
It's easy to create custom markers or to apply markers
to whole test classes or modules. See :ref:`mark examples` for examples
which also serve as documentation.
to whole test classes or modules. Those markers can be used by plugins, and also
are commonly used to :ref:`select tests <mark run>` on the command-line with the ``-m`` option.
See :ref:`mark examples` for examples which also serve as documentation.
.. note::
@@ -26,136 +26,53 @@ which also serve as documentation.
:ref:`fixtures <fixtures>`.
Raising errors on unknown marks: --strict
-----------------------------------------
Registering marks
-----------------
When the ``--strict`` command-line flag is passed, any unknown marks applied
with the ``@pytest.mark.name_of_the_mark`` decorator will trigger an error.
Marks defined or added by pytest or by a plugin will not trigger an error.
Marks can be registered in ``pytest.ini`` like this:
You can register custom marks in your ``pytest.ini`` file like this:
.. code-block:: ini
[pytest]
markers =
slow
slow: marks tests as slow (deselect with '-m "not slow"')
serial
This can be used to prevent users mistyping mark names by accident. Test suites that want to enforce this
should add ``--strict`` to ``addopts``:
Note that everything after the ``:`` is an optional description.
Alternatively, you can register new markers programmatically in a
:ref:`pytest_configure <initialization-hooks>` hook:
.. code-block:: python
def pytest_configure(config):
config.addinivalue_line(
"markers", "env(name): mark test to run only on named environment"
)
Registered marks appear in pytest's help text and do not emit warnings (see the next section). It
is recommended that third-party plugins always :ref:`register their markers <registering-markers>`.
.. _unknown-marks:
Raising errors on unknown marks
-------------------------------
Unregistered marks applied with the ``@pytest.mark.name_of_the_mark`` decorator
will always emit a warning in order to avoid silently doing something
surprising due to mis-typed names. As described in the previous section, you can disable
the warning for custom marks by registering them in your ``pytest.ini`` file or
using a custom ``pytest_configure`` hook.
When the ``--strict-markers`` command-line flag is passed, any unknown marks applied
with the ``@pytest.mark.name_of_the_mark`` decorator will trigger an error. You can
enforce this validation in your project by adding ``--strict-markers`` to ``addopts``:
.. code-block:: ini
[pytest]
addopts = --strict
addopts = --strict-markers
markers =
slow
slow: marks tests as slow (deselect with '-m "not slow"')
serial
.. _marker-revamp:
Marker revamp and iteration
---------------------------
.. versionadded:: 3.6
pytest's marker implementation traditionally worked by simply updating the ``__dict__`` attribute of functions to cumulatively add markers. As a result, markers would unintentionally be passed along class hierarchies in surprising ways. Further, the API for retrieving them was inconsistent, as markers from parameterization would be stored differently than markers applied using the ``@pytest.mark`` decorator and markers added via ``node.add_marker``.
This state of things made it technically next to impossible to use data from markers correctly without having a deep understanding of the internals, leading to subtle and hard to understand bugs in more advanced usages.
Depending on how a marker got declared/changed one would get either a ``MarkerInfo`` which might contain markers from sibling classes,
``MarkDecorators`` when marks came from parameterization or from a ``node.add_marker`` call, discarding prior marks. Also ``MarkerInfo`` acts like a single mark, when it in fact represents a merged view on multiple marks with the same name.
On top of that markers were not accessible the same way for modules, classes, and functions/methods.
In fact, markers were only accessible in functions, even if they were declared on classes/modules.
A new API to access markers has been introduced in pytest 3.6 in order to solve the problems with the initial design, providing :func:`_pytest.nodes.Node.iter_markers` method to iterate over markers in a consistent manner and reworking the internals, which solved great deal of problems with the initial design.
.. _update marker code:
Updating code
~~~~~~~~~~~~~
The old ``Node.get_marker(name)`` function is considered deprecated because it returns an internal ``MarkerInfo`` object
which contains the merged name, ``*args`` and ``**kwargs`` of all the markers which apply to that node.
In general there are two scenarios on how markers should be handled:
1. Marks overwrite each other. Order matters but you only want to think of your mark as a single item. E.g.
``log_level('info')`` at a module level can be overwritten by ``log_level('debug')`` for a specific test.
In this case, use ``Node.get_closest_marker(name)``:
.. code-block:: python
# replace this:
marker = item.get_marker("log_level")
if marker:
level = marker.args[0]
# by this:
marker = item.get_closest_marker("log_level")
if marker:
level = marker.args[0]
2. Marks compose in an additive manner. E.g. ``skipif(condition)`` marks mean you just want to evaluate all of them,
order doesn't even matter. You probably want to think of your marks as a set here.
In this case iterate over each mark and handle their ``*args`` and ``**kwargs`` individually.
.. code-block:: python
# replace this
skipif = item.get_marker("skipif")
if skipif:
for condition in skipif.args:
# eval condition
...
# by this:
for skipif in item.iter_markers("skipif"):
condition = skipif.args[0]
# eval condition
If you are unsure or have any questions, please consider opening
`an issue <https://github.com/pytest-dev/pytest/issues>`_.
Related issues
~~~~~~~~~~~~~~
Here is a non-exhaustive list of issues fixed by the new implementation:
* Marks don't pick up nested classes (`#199 <https://github.com/pytest-dev/pytest/issues/199>`_).
* Markers stain on all related classes (`#568 <https://github.com/pytest-dev/pytest/issues/568>`_).
* Combining marks - args and kwargs calculation (`#2897 <https://github.com/pytest-dev/pytest/issues/2897>`_).
* ``request.node.get_marker('name')`` returns ``None`` for markers applied in classes (`#902 <https://github.com/pytest-dev/pytest/issues/902>`_).
* Marks applied in parametrize are stored as markdecorator (`#2400 <https://github.com/pytest-dev/pytest/issues/2400>`_).
* Fix marker interaction in a backward incompatible way (`#1670 <https://github.com/pytest-dev/pytest/issues/1670>`_).
* Refactor marks to get rid of the current "marks transfer" mechanism (`#2363 <https://github.com/pytest-dev/pytest/issues/2363>`_).
* Introduce FunctionDefinition node, use it in generate_tests (`#2522 <https://github.com/pytest-dev/pytest/issues/2522>`_).
* Remove named marker attributes and collect markers in items (`#891 <https://github.com/pytest-dev/pytest/issues/891>`_).
* skipif mark from parametrize hides module level skipif mark (`#1540 <https://github.com/pytest-dev/pytest/issues/1540>`_).
* skipif + parametrize not skipping tests (`#1296 <https://github.com/pytest-dev/pytest/issues/1296>`_).
* Marker transfer incompatible with inheritance (`#535 <https://github.com/pytest-dev/pytest/issues/535>`_).
More details can be found in the `original PR <https://github.com/pytest-dev/pytest/pull/3317>`_.
.. note::
in a future major relase of pytest we will introduce class based markers,
at which point markers will no longer be limited to instances of :py:class:`Mark`

View File

@@ -8,46 +8,218 @@ Sometimes tests need to invoke functionality which depends
on global settings or which invokes code which cannot be easily
tested such as network access. The ``monkeypatch`` fixture
helps you to safely set/delete an attribute, dictionary item or
environment variable or to modify ``sys.path`` for importing.
environment variable, or to modify ``sys.path`` for importing.
The ``monkeypatch`` fixture provides these helper methods for safely patching and mocking
functionality in tests:
.. code-block:: python
monkeypatch.setattr(obj, name, value, raising=True)
monkeypatch.delattr(obj, name, raising=True)
monkeypatch.setitem(mapping, name, value)
monkeypatch.delitem(obj, name, raising=True)
monkeypatch.setenv(name, value, prepend=False)
monkeypatch.delenv(name, raising=True)
monkeypatch.syspath_prepend(path)
monkeypatch.chdir(path)
All modifications will be undone after the requesting
test function or fixture has finished. The ``raising``
parameter determines if a ``KeyError`` or ``AttributeError``
will be raised if the target of the set/deletion operation does not exist.
Consider the following scenarios:
1. Modifying the behavior of a function or the property of a class for a test e.g.
there is an API call or database connection you will not make for a test but you know
what the expected output should be. Use :py:meth:`monkeypatch.setattr` to patch the
function or property with your desired testing behavior. This can include your own functions.
Use :py:meth:`monkeypatch.delattr` to remove the function or property for the test.
2. Modifying the values of dictionaries e.g. you have a global configuration that
you want to modify for certain test cases. Use :py:meth:`monkeypatch.setitem` to patch the
dictionary for the test. :py:meth:`monkeypatch.delitem` can be used to remove items.
3. Modifying environment variables for a test e.g. to test program behavior if an
environment variable is missing, or to set multiple values to a known variable.
:py:meth:`monkeypatch.setenv` and :py:meth:`monkeypatch.delenv` can be used for
these patches.
4. Use ``monkeypatch.setenv("PATH", value, prepend=os.pathsep)`` to modify ``$PATH``, and
:py:meth:`monkeypatch.chdir` to change the context of the current working directory
during a test.
5. Use :py:meth:`monkeypatch.syspath_prepend` to modify ``sys.path`` which will also
call :py:meth:`pkg_resources.fixup_namespace_packages` and :py:meth:`importlib.invalidate_caches`.
See the `monkeypatch blog post`_ for some introduction material
and a discussion of its motivation.
.. _`monkeypatch blog post`: http://tetamap.wordpress.com/2009/03/03/monkeypatching-in-unit-tests-done-right/
Simple example: monkeypatching functions
---------------------------------------------------
----------------------------------------
If you want to pretend that ``os.expanduser`` returns a certain
directory, you can use the :py:meth:`monkeypatch.setattr` method to
patch this function before calling into a function which uses it::
Consider a scenario where you are working with user directories. In the context of
testing, you do not want your test to depend on the running user. ``monkeypatch``
can be used to patch functions dependent on the user to always return a
specific value.
# content of test_module.py
import os.path
def getssh(): # pseudo application code
return os.path.join(os.path.expanduser("~admin"), '.ssh')
In this example, :py:meth:`monkeypatch.setattr` is used to patch ``Path.home``
so that the known testing path ``Path("/abc")`` is always used when the test is run.
This removes any dependency on the running user for testing purposes.
:py:meth:`monkeypatch.setattr` must be called before the function which will use
the patched function is called.
After the test function finishes the ``Path.home`` modification will be undone.
def test_mytest(monkeypatch):
def mockreturn(path):
return '/abc'
monkeypatch.setattr(os.path, 'expanduser', mockreturn)
.. code-block:: python
# contents of test_module.py with source code and the test
from pathlib import Path
def getssh():
"""Simple function to return expanded homedir ssh path."""
return Path.home() / ".ssh"
def test_getssh(monkeypatch):
# mocked return function to replace Path.home
# always return '/abc'
def mockreturn():
return Path("/abc")
# Application of the monkeypatch to replace Path.home
# with the behavior of mockreturn defined above.
monkeypatch.setattr(Path, "home", mockreturn)
# Calling getssh() will use mockreturn in place of Path.home
# for this test with the monkeypatch.
x = getssh()
assert x == '/abc/.ssh'
assert x == Path("/abc/.ssh")
Here our test function monkeypatches ``os.path.expanduser`` and
then calls into a function that calls it. After the test function
finishes the ``os.path.expanduser`` modification will be undone.
example: preventing "requests" from remote operations
Monkeypatching returned objects: building mock classes
------------------------------------------------------
If you want to prevent the "requests" library from performing http
requests in all your tests, you can do::
:py:meth:`monkeypatch.setattr` can be used in conjunction with classes to mock returned
objects from functions instead of values.
Imagine a simple function to take an API url and return the json response.
# content of conftest.py
.. code-block:: python
# contents of app.py, a simple API retrieval example
import requests
def get_json(url):
"""Takes a URL, and returns the JSON."""
r = requests.get(url)
return r.json()
We need to mock ``r``, the returned response object for testing purposes.
The mock of ``r`` needs a ``.json()`` method which returns a dictionary.
This can be done in our test file by defining a class to represent ``r``.
.. code-block:: python
# contents of test_app.py, a simple test for our API retrieval
# import requests for the purposes of monkeypatching
import requests
# our app.py that includes the get_json() function
# this is the previous code block example
import app
# custom class to be the mock return value
# will override the requests.Response returned from requests.get
class MockResponse:
# mock json() method always returns a specific testing dictionary
@staticmethod
def json():
return {"mock_key": "mock_response"}
def test_get_json(monkeypatch):
# Any arguments may be passed and mock_get() will always return our
# mocked object, which only has the .json() method.
def mock_get(*args, **kwargs):
return MockResponse()
# apply the monkeypatch for requests.get to mock_get
monkeypatch.setattr(requests, "get", mock_get)
# app.get_json, which contains requests.get, uses the monkeypatch
result = app.get_json("https://fakeurl")
assert result["mock_key"] == "mock_response"
``monkeypatch`` applies the mock for ``requests.get`` with our ``mock_get`` function.
The ``mock_get`` function returns an instance of the ``MockResponse`` class, which
has a ``json()`` method defined to return a known testing dictionary and does not
require any outside API connection.
You can build the ``MockResponse`` class with the appropriate degree of complexity for
the scenario you are testing. For instance, it could include an ``ok`` property that
always returns ``True``, or return different values from the ``json()`` mocked method
based on input strings.
This mock can be shared across tests using a ``fixture``:
.. code-block:: python
# contents of test_app.py, a simple test for our API retrieval
import pytest
import requests
# app.py that includes the get_json() function
import app
# custom class to be the mock return value of requests.get()
class MockResponse:
@staticmethod
def json():
return {"mock_key": "mock_response"}
# monkeypatched requests.get moved to a fixture
@pytest.fixture
def mock_response(monkeypatch):
"""Requests.get() mocked to return {'mock_key':'mock_response'}."""
def mock_get(*args, **kwargs):
return MockResponse()
monkeypatch.setattr(requests, "get", mock_get)
# notice our test uses the custom fixture instead of monkeypatch directly
def test_get_json(mock_response):
result = app.get_json("https://fakeurl")
assert result["mock_key"] == "mock_response"
Furthermore, if the mock was designed to be applied to all tests, the ``fixture`` could
be moved to a ``conftest.py`` file and use the with ``autouse=True`` option.
Global patch example: preventing "requests" from remote operations
------------------------------------------------------------------
If you want to prevent the "requests" library from performing http
requests in all your tests, you can do:
.. code-block:: python
# contents of conftest.py
import pytest
@pytest.fixture(autouse=True)
def no_requests(monkeypatch):
"""Remove requests.sessions.Session.request for all tests."""
monkeypatch.delattr("requests.sessions.Session.request")
This autouse fixture will be executed for each test function and it
@@ -81,6 +253,187 @@ so that any attempts within tests to create http requests will fail.
See issue `#3290 <https://github.com/pytest-dev/pytest/issues/3290>`_ for details.
Monkeypatching environment variables
------------------------------------
If you are working with environment variables you often need to safely change the values
or delete them from the system for testing purposes. ``monkeypatch`` provides a mechanism
to do this using the ``setenv`` and ``delenv`` method. Our example code to test:
.. code-block:: python
# contents of our original code file e.g. code.py
import os
def get_os_user_lower():
"""Simple retrieval function.
Returns lowercase USER or raises EnvironmentError."""
username = os.getenv("USER")
if username is None:
raise OSError("USER environment is not set.")
return username.lower()
There are two potential paths. First, the ``USER`` environment variable is set to a
value. Second, the ``USER`` environment variable does not exist. Using ``monkeypatch``
both paths can be safely tested without impacting the running environment:
.. code-block:: python
# contents of our test file e.g. test_code.py
import pytest
def test_upper_to_lower(monkeypatch):
"""Set the USER env var to assert the behavior."""
monkeypatch.setenv("USER", "TestingUser")
assert get_os_user_lower() == "testinguser"
def test_raise_exception(monkeypatch):
"""Remove the USER env var and assert EnvironmentError is raised."""
monkeypatch.delenv("USER", raising=False)
with pytest.raises(OSError):
_ = get_os_user_lower()
This behavior can be moved into ``fixture`` structures and shared across tests:
.. code-block:: python
# contents of our test file e.g. test_code.py
import pytest
@pytest.fixture
def mock_env_user(monkeypatch):
monkeypatch.setenv("USER", "TestingUser")
@pytest.fixture
def mock_env_missing(monkeypatch):
monkeypatch.delenv("USER", raising=False)
# notice the tests reference the fixtures for mocks
def test_upper_to_lower(mock_env_user):
assert get_os_user_lower() == "testinguser"
def test_raise_exception(mock_env_missing):
with pytest.raises(OSError):
_ = get_os_user_lower()
Monkeypatching dictionaries
---------------------------
:py:meth:`monkeypatch.setitem` can be used to safely set the values of dictionaries
to specific values during tests. Take this simplified connection string example:
.. code-block:: python
# contents of app.py to generate a simple connection string
DEFAULT_CONFIG = {"user": "user1", "database": "db1"}
def create_connection_string(config=None):
"""Creates a connection string from input or defaults."""
config = config or DEFAULT_CONFIG
return f"User Id={config['user']}; Location={config['database']};"
For testing purposes we can patch the ``DEFAULT_CONFIG`` dictionary to specific values.
.. code-block:: python
# contents of test_app.py
# app.py with the connection string function (prior code block)
import app
def test_connection(monkeypatch):
# Patch the values of DEFAULT_CONFIG to specific
# testing values only for this test.
monkeypatch.setitem(app.DEFAULT_CONFIG, "user", "test_user")
monkeypatch.setitem(app.DEFAULT_CONFIG, "database", "test_db")
# expected result based on the mocks
expected = "User Id=test_user; Location=test_db;"
# the test uses the monkeypatched dictionary settings
result = app.create_connection_string()
assert result == expected
You can use the :py:meth:`monkeypatch.delitem` to remove values.
.. code-block:: python
# contents of test_app.py
import pytest
# app.py with the connection string function
import app
def test_missing_user(monkeypatch):
# patch the DEFAULT_CONFIG t be missing the 'user' key
monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False)
# Key error expected because a config is not passed, and the
# default is now missing the 'user' entry.
with pytest.raises(KeyError):
_ = app.create_connection_string()
The modularity of fixtures gives you the flexibility to define
separate fixtures for each potential mock and reference them in the needed tests.
.. code-block:: python
# contents of test_app.py
import pytest
# app.py with the connection string function
import app
# all of the mocks are moved into separated fixtures
@pytest.fixture
def mock_test_user(monkeypatch):
"""Set the DEFAULT_CONFIG user to test_user."""
monkeypatch.setitem(app.DEFAULT_CONFIG, "user", "test_user")
@pytest.fixture
def mock_test_database(monkeypatch):
"""Set the DEFAULT_CONFIG database to test_db."""
monkeypatch.setitem(app.DEFAULT_CONFIG, "database", "test_db")
@pytest.fixture
def mock_missing_default_user(monkeypatch):
"""Remove the user key from DEFAULT_CONFIG"""
monkeypatch.delitem(app.DEFAULT_CONFIG, "user", raising=False)
# tests reference only the fixture mocks that are needed
def test_connection(mock_test_user, mock_test_database):
expected = "User Id=test_user; Location=test_db;"
result = app.create_connection_string()
assert result == expected
def test_missing_user(mock_missing_default_user):
with pytest.raises(KeyError):
_ = app.create_connection_string()
.. currentmodule:: _pytest.monkeypatch
API Reference

View File

@@ -46,7 +46,7 @@ Unsupported idioms / known issues
<https://github.com/pytest-dev/pytest/issues/377/>`_.
- nose imports test modules with the same import path (e.g.
``tests.test_mod``) but different file system paths
``tests.test_mode``) but different file system paths
(e.g. ``tests/test_mode.py`` and ``other/tests/test_mode.py``)
by extending sys.path/import semantics. pytest does not do that
but there is discussion in `#268 <https://github.com/pytest-dev/pytest/issues/268>`_ for adding some support. Note that

View File

@@ -29,22 +29,22 @@ pytest enables test parametrization at several levels:
.. regendoc: wipe
.. versionadded:: 2.2
.. versionchanged:: 2.4
Several improvements.
The builtin :ref:`pytest.mark.parametrize ref` decorator enables
parametrization of arguments for a test function. Here is a typical example
of a test function that implements checking that a certain input leads
to an expected output::
to an expected output:
.. code-block:: python
# content of test_expectation.py
import pytest
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
def test_eval(test_input, expected):
assert eval(test_input) == expected
@@ -56,9 +56,9 @@ them in turn:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 3 items
test_expectation.py ..F [100%]
@@ -68,18 +68,29 @@ them in turn:
test_input = '6*9', expected = 42
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
@pytest.mark.parametrize("test_input,expected", [("3+5", 8), ("2+4", 6), ("6*9", 42)])
def test_eval(test_input, expected):
> assert eval(test_input) == expected
E AssertionError: assert 54 == 42
E + where 54 = eval('6*9')
test_expectation.py:8: AssertionError
==================== 1 failed, 2 passed in 0.12 seconds ====================
test_expectation.py:6: AssertionError
======================= 1 failed, 2 passed in 0.12s ========================
.. note::
pytest by default escapes any non-ascii characters used in unicode strings
for the parametrization because it has several downsides.
If however you would like to use unicode strings in parametrization and see them in the terminal as is (non-escaped), use this option in your ``pytest.ini``:
.. code-block:: ini
[pytest]
disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True
Keep in mind however that this might cause unwanted side effects and
even bugs depending on the OS used and plugins currently installed, so use it at your own risk.
As designed in this example, only one pair of input/output values fails
the simple test function. And as usual with test function arguments,
@@ -89,16 +100,18 @@ Note that you could also use the parametrize marker on a class or a module
(see :ref:`mark`) which would invoke several functions with the argument sets.
It is also possible to mark individual test instances within parametrize,
for example with the builtin ``mark.xfail``::
for example with the builtin ``mark.xfail``:
.. code-block:: python
# content of test_expectation.py
import pytest
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
pytest.param("6*9", 42,
marks=pytest.mark.xfail),
])
@pytest.mark.parametrize(
"test_input,expected",
[("3+5", 8), ("2+4", 6), pytest.param("6*9", 42, marks=pytest.mark.xfail)],
)
def test_eval(test_input, expected):
assert eval(test_input) == expected
@@ -108,14 +121,14 @@ Let's run this:
$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
rootdir: $REGENDOC_TMPDIR
collected 3 items
test_expectation.py ..x [100%]
=================== 2 passed, 1 xfailed in 0.12 seconds ====================
======================= 2 passed, 1 xfailed in 0.12s =======================
The one parameter set which caused a failure previously now
shows up as an "xfailed (expected to fail)" test.
@@ -125,9 +138,13 @@ example, if they're dynamically generated by some function - the behaviour of
pytest is defined by the :confval:`empty_parameter_set_mark` option.
To get all combinations of multiple parametrized arguments you can stack
``parametrize`` decorators::
``parametrize`` decorators:
.. code-block:: python
import pytest
@pytest.mark.parametrize("x", [0, 1])
@pytest.mark.parametrize("y", [2, 3])
def test_foo(x, y):
@@ -151,26 +168,36 @@ parametrization.
For example, let's say we want to run a test taking string inputs which
we want to set via a new ``pytest`` command line option. Let's first write
a simple test accepting a ``stringinput`` fixture function argument::
a simple test accepting a ``stringinput`` fixture function argument:
.. code-block:: python
# content of test_strings.py
def test_valid_string(stringinput):
assert stringinput.isalpha()
Now we add a ``conftest.py`` file containing the addition of a
command line option and the parametrization of our test function::
command line option and the parametrization of our test function:
.. code-block:: python
# content of conftest.py
def pytest_addoption(parser):
parser.addoption("--stringinput", action="append", default=[],
help="list of stringinputs to pass to test functions")
parser.addoption(
"--stringinput",
action="append",
default=[],
help="list of stringinputs to pass to test functions",
)
def pytest_generate_tests(metafunc):
if 'stringinput' in metafunc.fixturenames:
metafunc.parametrize("stringinput",
metafunc.config.getoption('stringinput'))
if "stringinput" in metafunc.fixturenames:
metafunc.parametrize("stringinput", metafunc.config.getoption("stringinput"))
If we now pass two stringinput values, our test will run twice:
@@ -178,7 +205,7 @@ If we now pass two stringinput values, our test will run twice:
$ pytest -q --stringinput="hello" --stringinput="world" test_strings.py
.. [100%]
2 passed in 0.12 seconds
2 passed in 0.12s
Let's also run with a stringinput that will lead to a failing test:
@@ -197,8 +224,8 @@ Let's also run with a stringinput that will lead to a failing test:
E + where False = <built-in method isalpha of str object at 0xdeadbeef>()
E + where <built-in method isalpha of str object at 0xdeadbeef> = '!'.isalpha
test_strings.py:3: AssertionError
1 failed in 0.12 seconds
test_strings.py:4: AssertionError
1 failed in 0.12s
As expected our test function fails.
@@ -211,8 +238,8 @@ list:
$ pytest -q -rs test_strings.py
s [100%]
========================= short test summary info ==========================
SKIPPED [1] test_strings.py: got empty parameter set ['stringinput'], function test_valid_string at $REGENDOC_TMPDIR/test_strings.py:1
1 skipped in 0.12 seconds
SKIPPED [1] test_strings.py: got empty parameter set ['stringinput'], function test_valid_string at $REGENDOC_TMPDIR/test_strings.py:2
1 skipped in 0.12s
Note that when calling ``metafunc.parametrize`` multiple times with different parameter sets, all parameter names across
those sets cannot be duplicated, otherwise an error will be raised.

View File

@@ -8,7 +8,9 @@ Installing and Using plugins
This section talks about installing and using third party plugins.
For writing your own plugins, please refer to :ref:`writing-plugins`.
Installing a third party plugin can be easily done with ``pip``::
Installing a third party plugin can be easily done with ``pip``:
.. code-block:: bash
pip install pytest-NAME
pip uninstall pytest-NAME
@@ -27,7 +29,7 @@ Here is a little annotated list for some popular plugins:
for `twisted <http://twistedmatrix.com>`_ apps, starting a reactor and
processing deferreds from test functions.
* `pytest-cov <https://pypi.org/project/pytest-cov/>`_:
* `pytest-cov <https://pypi.org/project/pytest-cov/>`__:
coverage reporting, compatible with distributed testing
* `pytest-xdist <https://pypi.org/project/pytest-xdist/>`_:
@@ -95,7 +97,9 @@ Finding out which plugins are active
------------------------------------
If you want to find out which plugins are active in your
environment you can type::
environment you can type:
.. code-block:: bash
pytest --trace-config
@@ -108,7 +112,9 @@ and their names. It will also print local plugins aka
Deactivating / unregistering a plugin by name
---------------------------------------------
You can prevent plugins from loading or unregister them::
You can prevent plugins from loading or unregister them:
.. code-block:: bash
pytest -p no:NAME

View File

@@ -28,7 +28,6 @@ Here are some examples of projects using ``pytest`` (please send notes via :ref:
* `sentry <https://getsentry.com/welcome/>`_, realtime app-maintenance and exception tracking
* `Astropy <http://www.astropy.org/>`_ and `affiliated packages <http://www.astropy.org/affiliated/index.html>`_
* `tox <http://testrun.org/tox>`_, virtualenv/Hudson integration tool
* `PIDA <http://pida.co.uk>`_ framework for integrated development
* `PyPM <http://code.activestate.com/pypm/>`_ ActiveState's package manager
* `Fom <http://packages.python.org/Fom/>`_ a fluid object mapper for FluidDB
* `applib <https://github.com/ActiveState/applib>`_ cross-platform utilities
@@ -37,8 +36,7 @@ Here are some examples of projects using ``pytest`` (please send notes via :ref:
* `mwlib <https://pypi.org/project/mwlib/>`_ mediawiki parser and utility library
* `The Translate Toolkit <http://translate.sourceforge.net/wiki/toolkit/index>`_ for localization and conversion
* `execnet <http://codespeak.net/execnet>`_ rapid multi-Python deployment
* `pylib <https://py.readthedocs.io>`_ cross-platform path, IO, dynamic code library
* `Pacha <http://pacha.cafepais.com/>`_ configuration management in five minutes
* `pylib <https://pylib.readthedocs.io/en/stable/>`_ cross-platform path, IO, dynamic code library
* `bbfreeze <https://pypi.org/project/bbfreeze/>`_ create standalone executables from Python scripts
* `pdb++ <http://bitbucket.org/antocuni/pdb>`_ a fancier version of PDB
* `py-s3fuse <http://code.google.com/p/py-s3fuse/>`_ Amazon S3 FUSE based filesystem
@@ -77,7 +75,7 @@ Some organisations using pytest
* `Tandberg <http://www.tandberg.com/>`_
* `Shootq <http://web.shootq.com/>`_
* `Stups department of Heinrich Heine University Duesseldorf <http://www.stups.uni-duesseldorf.de/projects.php>`_
* `cellzome <http://www.cellzome.com/>`_
* cellzome
* `Open End, Gothenborg <http://www.openend.se>`_
* `Laboratory of Bioinformatics, Warsaw <http://genesilico.pl/>`_
* `merlinux, Germany <http://merlinux.eu>`_

View File

@@ -7,16 +7,20 @@ Python 3.4's last release is scheduled for
`March 2019 <https://www.python.org/dev/peps/pep-0429/#release-schedule>`__. pytest is one of
the participating projects of the https://python3statement.org.
We plan to drop support for Python 2.7 and 3.4 at the same time with the release of **pytest 5.0**,
scheduled to be released by **mid-2019**. Thanks to the `python_requires <https://packaging.python.org/guides/distributing-packages-using-setuptools/#python-requires>`__ ``setuptools`` option,
The **pytest 4.6** series is the last to support Python 2.7 and 3.4, and was released in
**June 2019**. **pytest 5.0** and onwards will support only Python 3.5+.
Thanks to the `python_requires`_ ``setuptools`` option,
Python 2.7 and Python 3.4 users using a modern ``pip`` version
will install the last compatible pytest ``4.X`` version automatically even if ``5.0`` or later
will install the last pytest ``4.6`` version automatically even if ``5.0`` or later
are available on PyPI.
During the period **from mid-2019 and 2020**, the pytest core team plans to make
bug-fix releases of the pytest ``4.X`` series by back-porting patches to the ``4.x-maintenance``
branch.
While pytest ``5.0`` will be the new mainstream and development version, until **January 2020**
the pytest core team plans to make bug-fix releases of the pytest ``4.6`` series by
back-porting patches to the ``4.6-maintenance`` branch that affect Python 2 users.
**After 2020**, the core team will no longer actively back port-patches, but the ``4.x-maintenance``
branch will continue to exist so the community itself can contribute patches. The
core team will be happy to accept those patches and make new ``4.X`` releases **until mid-2020**.
**After 2020**, the core team will no longer actively backport patches, but the ``4.6-maintenance``
branch will continue to exist so the community itself can contribute patches. The core team will
be happy to accept those patches and make new ``4.6`` releases **until mid-2020**.
.. _`python_requires`: https://packaging.python.org/guides/distributing-packages-using-setuptools/#python-requires

View File

@@ -22,7 +22,9 @@ Consider this file and directory layout::
|- test_foo.py
When executing::
When executing:
.. code-block:: bash
pytest root/
@@ -54,7 +56,9 @@ Consider this file and directory layout::
|- test_foo.py
When executing::
When executing:
.. code-block:: bash
pytest root/
@@ -68,6 +72,8 @@ imported in the global import namespace.
This is also discussed in details in :ref:`test discovery`.
.. _`pytest vs python -m pytest`:
Invoking ``pytest`` versus ``python -m pytest``
-----------------------------------------------

View File

@@ -1,6 +1,5 @@
Reference
=========
API Reference
=============
This page contains the full reference to pytest's API.
@@ -28,6 +27,8 @@ pytest.skip
.. autofunction:: _pytest.outcomes.skip(msg, [allow_module_level=False])
.. _`pytest.importorskip ref`:
pytest.importorskip
~~~~~~~~~~~~~~~~~~~
@@ -49,7 +50,7 @@ pytest.main
.. autofunction:: _pytest.config.main
pytest.param
~~~~~~~~~~~~~
~~~~~~~~~~~~
.. autofunction:: pytest.param(*values, [id], [marks])
@@ -58,7 +59,7 @@ pytest.raises
**Tutorial**: :ref:`assertraises`.
.. autofunction:: pytest.raises(expected_exception: Exception, [match], [message])
.. autofunction:: pytest.raises(expected_exception: Exception, [match])
:with: excinfo
pytest.deprecated_call
@@ -199,16 +200,18 @@ Marks a test function as *expected to fail*.
.. py:function:: pytest.mark.xfail(condition=None, *, reason=None, raises=None, run=True, strict=False)
:type condition: bool or str
:param condition: ``True/False`` if the condition should be marked as xfail or a :ref:`condition string <string conditions>`.
:param condition:
Condition for marking the test function as xfail (``True/False`` or a
:ref:`condition string <string conditions>`).
:keyword str reason: Reason why the test function is marked as xfail.
:keyword Exception raises: Exception subclass expected to be raised by the test function; other exceptions will fail the test.
:keyword bool run:
If the test function should actually be executed. If ``False``, the function will always xfail and will
not be executed (useful a function is segfaulting).
not be executed (useful if a function is segfaulting).
:keyword bool strict:
* If ``False`` (the default) the function will be shown in the terminal output as ``xfailed`` if it fails
and as ``xpass`` if it passes. In both cases this will not cause the test suite to fail as a whole. This
is particularly useful to mark *flaky* tests (tests that random at fail) to be tackled later.
is particularly useful to mark *flaky* tests (tests that fail at random) to be tackled later.
* If ``True``, the function will be shown in the terminal output as ``xfailed`` if it fails, but if it
unexpectedly passes then it will **fail** the test suite. This is particularly useful to mark functions
that are always failing and there should be a clear indication if they unexpectedly start to pass (for example
@@ -423,6 +426,14 @@ record_property
.. autofunction:: _pytest.junitxml.record_property()
record_testsuite_property
~~~~~~~~~~~~~~~~~~~~~~~~~
**Tutorial**: :ref:`record_testsuite_property example`.
.. autofunction:: _pytest.junitxml.record_testsuite_property()
caplog
~~~~~~
@@ -460,9 +471,11 @@ testdir
This fixture provides a :class:`Testdir` instance useful for black-box testing of test files, making it ideal to
test plugins.
To use it, include in your top-most ``conftest.py`` file::
To use it, include in your top-most ``conftest.py`` file:
pytest_plugins = 'pytester'
.. code-block:: python
pytest_plugins = "pytester"
@@ -572,6 +585,8 @@ Bootstrapping hooks called for plugins registered early enough (internal and set
.. autofunction:: pytest_cmdline_parse
.. autofunction:: pytest_cmdline_main
.. _`initialization-hooks`:
Initialization hooks
~~~~~~~~~~~~~~~~~~~~
@@ -654,15 +669,14 @@ Session related reporting hooks:
.. autofunction:: pytest_fixture_post_finalizer
.. autofunction:: pytest_warning_captured
And here is the central hook for reporting about
test execution:
Central hook for reporting about test execution:
.. autofunction:: pytest_runtest_logreport
You can also use this hook to customize assertion representation for some
types:
Assertion related hooks:
.. autofunction:: pytest_assertrepr_compare
.. autofunction:: pytest_assertion_pass
Debugging/Interaction hooks
@@ -716,6 +730,14 @@ ExceptionInfo
.. autoclass:: _pytest._code.ExceptionInfo
:members:
pytest.ExitCode
~~~~~~~~~~~~~~~
.. autoclass:: _pytest.main.ExitCode
:members:
FixtureDef
~~~~~~~~~~
@@ -881,7 +903,7 @@ pytest_mark
**Tutorial**: :ref:`scoped-marking`
Can be declared at the **global** level in *test modules* to apply one or more :ref:`marks <marks ref>` to all
test functions and methods. Can be either a single mark or a sequence of marks.
test functions and methods. Can be either a single mark or a list of marks.
.. code-block:: python
@@ -894,7 +916,7 @@ test functions and methods. Can be either a single mark or a sequence of marks.
import pytest
pytestmark = (pytest.mark.integration, pytest.mark.slow)
pytestmark = [pytest.mark.integration, pytest.mark.slow]
PYTEST_DONT_REWRITE (module docstring)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -940,6 +962,14 @@ PYTEST_CURRENT_TEST
This is not meant to be set by users, but is set by pytest internally with the name of the current test so other
processes can inspect it, see :ref:`pytest current test env` for more information.
Exceptions
----------
UsageError
~~~~~~~~~~
.. autoclass:: _pytest.config.UsageError()
.. _`ini options ref`:
@@ -975,6 +1005,8 @@ passed multiple times. The expected format is ``name=value``. For example::
issuing ``pytest test_hello.py`` actually means::
.. code-block:: bash
pytest --maxfail=2 -rf test_hello.py
Default is to add no options.
@@ -982,7 +1014,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: cache_dir
.. versionadded:: 3.2
Sets a directory where stores content of cache plugin. Default directory is
``.pytest_cache`` which is created in :ref:`rootdir <rootdir>`. Directory may be
@@ -1002,7 +1034,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: console_output_style
.. versionadded:: 3.3
Sets the console output style while running tests:
@@ -1022,7 +1054,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: doctest_encoding
.. versionadded:: 3.1
Default encoding to use to decode text files with docstrings.
:doc:`See how pytest handles doctests <doctest>`.
@@ -1036,7 +1068,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: empty_parameter_set_mark
.. versionadded:: 3.4
Allows to pick the action for empty parametersets in parameterization
@@ -1057,9 +1089,26 @@ passed multiple times. The expected format is ``name=value``. For example::
for more details.
.. confval:: faulthandler_timeout
Dumps the tracebacks of all threads if a test takes longer than ``X`` seconds to run (including
fixture setup and teardown). Implemented using the `faulthandler.dump_traceback_later`_ function,
so all caveats there apply.
.. code-block:: ini
# content of pytest.ini
[pytest]
faulthandler_timeout=5
For more information please refer to :ref:`faulthandler`.
.. _`faulthandler.dump_traceback_later`: https://docs.python.org/3/library/faulthandler.html#faulthandler.dump_traceback_later
.. confval:: filterwarnings
.. versionadded:: 3.1
Sets a list of filters and actions that should be taken for matched
warnings. By default all warnings emitted during the test session
@@ -1076,6 +1125,22 @@ passed multiple times. The expected format is ``name=value``. For example::
This tells pytest to ignore deprecation warnings and turn all other warnings
into errors. For more information please refer to :ref:`warnings`.
.. confval:: junit_duration_report
.. versionadded:: 4.1
Configures how durations are recorded into the JUnit XML report:
* ``total`` (the default): duration times reported include setup, call, and teardown times.
* ``call``: duration times reported include only call times, excluding setup and teardown.
.. code-block:: ini
[pytest]
junit_duration_report = call
.. confval:: junit_family
.. versionadded:: 4.2
@@ -1091,9 +1156,34 @@ passed multiple times. The expected format is ``name=value``. For example::
[pytest]
junit_family = xunit2
.. confval:: junit_suite_name
.. versionadded:: 3.1
.. confval:: junit_logging
.. versionadded:: 3.5
Configures if stdout/stderr should be written to the JUnit XML file. Valid values are
``system-out``, ``system-err``, and ``no`` (the default).
.. code-block:: ini
[pytest]
junit_logging = system-out
.. confval:: junit_log_passing_tests
.. versionadded:: 4.6
If ``junit_logging != "no"``, configures if the captured output should be written
to the JUnit XML file for **passing** tests. Default is ``True``.
.. code-block:: ini
[pytest]
junit_log_passing_tests = False
.. confval:: junit_suite_name
To set the name of the root test suite xml item, you can configure the ``junit_suite_name`` option in your config file:
@@ -1105,7 +1195,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_cli_date_format
.. versionadded:: 3.3
Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for live logging.
@@ -1118,7 +1208,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_cli_format
.. versionadded:: 3.3
Sets a :py:mod:`logging`-compatible string used to format live logging messages.
@@ -1132,7 +1222,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_cli_level
.. versionadded:: 3.3
Sets the minimum log message level that should be captured for live logging. The integer value or
the names of the levels can be used.
@@ -1147,7 +1237,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_date_format
.. versionadded:: 3.3
Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for logging capture.
@@ -1161,7 +1251,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_file
.. versionadded:: 3.3
Sets a file name relative to the ``pytest.ini`` file where log messages should be written to, in addition
to the other logging facilities that are active.
@@ -1176,7 +1266,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_file_date_format
.. versionadded:: 3.3
Sets a :py:func:`time.strftime`-compatible string that will be used when formatting dates for the logging file.
@@ -1189,7 +1279,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_file_format
.. versionadded:: 3.3
Sets a :py:mod:`logging`-compatible string used to format logging messages redirected to the logging file.
@@ -1202,7 +1292,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_file_level
.. versionadded:: 3.3
Sets the minimum log message level that should be captured for the logging file. The integer value or
the names of the levels can be used.
@@ -1217,7 +1307,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_format
.. versionadded:: 3.3
Sets a :py:mod:`logging`-compatible string used to format captured logging messages.
@@ -1231,7 +1321,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_level
.. versionadded:: 3.3
Sets the minimum log message level that should be captured for logging capture. The integer value or
the names of the levels can be used.
@@ -1246,7 +1336,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: log_print
.. versionadded:: 3.3
If set to ``False``, will disable displaying captured logging messages for failed tests.
@@ -1260,15 +1350,17 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: markers
When the ``--strict`` command-line argument is used, only known markers -
defined in code by core pytest or some plugin - are allowed.
You can list additional markers in this setting to add them to the whitelist.
When the ``--strict-markers`` or ``--strict`` command-line arguments are used,
only known markers - defined in code by core pytest or some plugin - are allowed.
You can list one marker name per line, indented from the option name.
You can list additional markers in this setting to add them to the whitelist,
in which case you probably want to add ``--strict-markers`` to ``addopts``
to avoid future regressions:
.. code-block:: ini
[pytest]
addopts = --strict-markers
markers =
slow
serial
@@ -1383,7 +1475,7 @@ passed multiple times. The expected format is ``name=value``. For example::
.. confval:: testpaths
.. versionadded:: 2.8
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

View File

@@ -1,4 +1,4 @@
pygments-pytest>=1.1.0
sphinx>=1.8.2
sphinx>=1.8.2,<2.1
sphinxcontrib-trio
sphinx-removed-in>=0.1.3
sphinx-removed-in>=0.2.0

View File

@@ -39,7 +39,7 @@ More details on the ``-r`` option can be found by running ``pytest -h``.
Skipping test functions
-----------------------
.. versionadded:: 2.9
The simplest way to skip a test function is to mark it with the ``skip`` decorator
which may be passed an optional ``reason``:
@@ -80,36 +80,48 @@ It is also possible to skip the whole module using
``skipif``
~~~~~~~~~~
.. versionadded:: 2.0
If you wish to skip something conditionally then you can use ``skipif`` instead.
Here is an example of marking a test function to be skipped
when run on an interpreter earlier than Python3.6::
when run on an interpreter earlier than Python3.6:
.. code-block:: python
import sys
@pytest.mark.skipif(sys.version_info < (3,6),
reason="requires python3.6 or higher")
@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires python3.6 or higher")
def test_function():
...
If the condition evaluates to ``True`` during collection, the test function will be skipped,
with the specified reason appearing in the summary when using ``-rs``.
You can share ``skipif`` markers between modules. Consider this test module::
You can share ``skipif`` markers between modules. Consider this test module:
.. code-block:: python
# content of test_mymodule.py
import mymodule
minversion = pytest.mark.skipif(mymodule.__versioninfo__ < (1,1),
reason="at least mymodule-1.1 required")
minversion = pytest.mark.skipif(
mymodule.__versioninfo__ < (1, 1), reason="at least mymodule-1.1 required"
)
@minversion
def test_function():
...
You can import the marker and reuse it in another test module::
You can import the marker and reuse it in another test module:
.. code-block:: python
# test_myothermodule.py
from test_mymodule import minversion
@minversion
def test_anotherfunction():
...
@@ -128,12 +140,12 @@ so they are supported mainly for backward compatibility reasons.
Skip all test functions of a class or module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use the ``skipif`` marker (as any other marker) on classes::
You can use the ``skipif`` marker (as any other marker) on classes:
@pytest.mark.skipif(sys.platform == 'win32',
reason="does not run on windows")
class TestPosixCalls(object):
.. code-block:: python
@pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows")
class TestPosixCalls:
def test_function(self):
"will not be setup or run under 'win32' platform"
@@ -167,14 +179,17 @@ information.
Skipping on a missing import dependency
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can use the following helper at module level
or within a test or test setup function::
You can skip tests on a missing import by using :ref:`pytest.importorskip ref`
at module level, within a test, or test setup function.
.. code-block:: python
docutils = pytest.importorskip("docutils")
If ``docutils`` cannot be imported here, this will lead to a
skip outcome of the test. You can also skip based on the
version number of a library::
If ``docutils`` cannot be imported here, this will lead to a skip outcome of
the test. You can also skip based on the version number of a library:
.. code-block:: python
docutils = pytest.importorskip("docutils", minversion="0.3")
@@ -196,7 +211,7 @@ Here's a quick guide on how to skip tests in a module in different situations:
.. code-block:: python
pytestmark = pytest.mark.skipif(sys.platform == "win32", "tests for linux only")
pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="tests for linux only")
3. Skip all tests in a module if some import is missing:
@@ -211,7 +226,9 @@ XFail: mark test functions as expected to fail
----------------------------------------------
You can use the ``xfail`` marker to indicate that you
expect a test to fail::
expect a test to fail:
.. code-block:: python
@pytest.mark.xfail
def test_function():
@@ -242,7 +259,7 @@ internally by raising a known exception.
``strict`` parameter
~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 2.9
Both ``XFAIL`` and ``XPASS`` don't fail the test suite, unless the ``strict`` keyword-only
parameter is passed as ``True``:
@@ -269,10 +286,11 @@ You can change the default value of the ``strict`` parameter using the
~~~~~~~~~~~~~~~~~~~~
As with skipif_ you can also mark your expectation of a failure
on a particular platform::
on a particular platform:
@pytest.mark.xfail(sys.version_info >= (3,6),
reason="python3.6 api changes")
.. code-block:: python
@pytest.mark.xfail(sys.version_info >= (3, 6), reason="python3.6 api changes")
def test_function():
...
@@ -333,12 +351,13 @@ Running it with the report-on-xfail option gives this output:
example $ pytest -rx xfail_demo.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
platform linux -- Python 3.x.y, pytest-5.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR/example, inifile:
rootdir: $REGENDOC_TMPDIR/example
collected 7 items
xfail_demo.py xxxxxxx [100%]
========================= short test summary info ==========================
XFAIL xfail_demo.py::test_hello
XFAIL xfail_demo.py::test_hello2
@@ -352,8 +371,7 @@ Running it with the report-on-xfail option gives this output:
XFAIL xfail_demo.py::test_hello6
reason: reason
XFAIL xfail_demo.py::test_hello7
======================== 7 xfailed in 0.12 seconds =========================
============================ 7 xfailed in 0.12s ============================
.. _`skip/xfail with parametrize`:

39
doc/en/sponsor.rst Normal file
View File

@@ -0,0 +1,39 @@
Sponsor
=======
pytest is maintained by a team of volunteers from all around the world in their free time. While
we work on pytest because we love the project and use it daily at our daily jobs, monetary
compensation when possible is welcome to justify time away from friends, family and personal time.
Money is also used to fund local sprints, merchandising (stickers to distribute in conferences for example)
and every few years a large sprint involving all members.
If you or your company benefit from pytest and would like to contribute to the project financially,
we are members of two online donation platforms to better suit your needs.
Tidelift
--------
`Tidelift`_ aims to make Open Source sustainable by offering subscriptions to companies which rely
on Open Source packages. This subscription allows it to pay maintainers of those Open Source
packages to aid sustainability of the work.
You can help pytest and the ecosystem by obtaining a `Tidelift subscription`_.
OpenCollective
--------------
`Open Collective`_ is an online funding platform for open and transparent communities.
It provide tools to raise money and share your finances in full transparency.
It is the platform of choice for individuals and companies that want to make one-time or
monthly donations directly to the project.
See more datails in the `pytest collective`_.
.. _Tidelift: https://tidelift.com
.. _Tidelift subscription: https://tidelift.com/subscription/pkg/pypi-pytest
.. _Open Collective: https://opencollective.com
.. _pytest collective: https://opencollective.com/pytest

View File

@@ -2,12 +2,9 @@
Talks and Tutorials
==========================
..
.. sidebar:: Next Open Trainings
.. sidebar:: Next Open Trainings
`Professional Testing with Python
<http://www.python-academy.com/courses/specialtopics/python_course_testing.html>`_,
26-28 April 2017, Leipzig, Germany.
- `3 day hands-on workshop covering pytest, tox and devpi: "Professional Testing with Python" <https://python-academy.com/courses/specialtopics/python_course_testing.html>`_ (English), October 21 - 23, 2019, Leipzig, Germany.
.. _`funcargs`: funcargs.html
@@ -23,6 +20,8 @@ Books
Talks and blog postings
---------------------------------------------
- `pytest: recommendations, basic packages for testing in Python and Django, Andreu Vallbona, PyBCN June 2019 <https://www.slideshare.net/AndreuVallbonaPlazas/pybcn-pytest-recomendaciones-paquetes-bsicos-para-testing-en-python-y-django>`_.
- pytest: recommendations, basic packages for testing in Python and Django, Andreu Vallbona, PyconES 2017 (`slides in english <http://talks.apsl.io/testing-pycones-2017/>`_, `video in spanish <https://www.youtube.com/watch?v=K20GeR-lXDk>`_)
- `pytest advanced, Andrew Svetlov (Russian, PyCon Russia, 2016)

Some files were not shown because too many files have changed in this diff Show More