Compare commits

...

1662 Commits
2.7.3 ... 3.0.2

Author SHA1 Message Date
Bruno Oliveira
4e58c9a7d0 Fix use of deprecated getfuncargvalue method in the internal doctest plugin
Fix #1898
2016-09-01 07:19:11 -04:00
Bruno Oliveira
a9f3053f72 Fix version typo in announce for 3.0.2 2016-09-01 06:59:31 -04:00
Bruno Oliveira
d512e7f26b Run regendoc for 3.0.2 release 2016-08-31 20:32:05 -04:00
Bruno Oliveira
f985f47a02 Fix reportingdemo call to pytest 2016-08-31 20:30:06 -04:00
Bruno Oliveira
4c45b93007 Changes for 3.0.2 release 2016-08-31 20:28:38 -04:00
Bruno Oliveira
a094fb3aa6 Merge pull request #1890 from mbyt/disable_tearDown_and_cleanups_for_post_mortem_debugging
unittest runner: avoid tearDown and cleanup to ease post mortem debugging
2016-08-31 21:09:45 -03:00
mbyt
e43d1174f7 spelling 2016-08-31 22:46:40 +02:00
mbyt
696a9112be integrating review commets of @nicoddemus
plus small scale refactoring
2016-08-31 22:33:47 +02:00
mbyt
be08223d5a Merge branch 'master' into disable_tearDown_and_cleanups_for_post_mortem_debugging
Conflicts:
	CHANGELOG.rst
2016-08-31 20:35:31 +02:00
mbyt
10b3274924 adding corresponding test, authors and changelog 2016-08-31 20:22:54 +02:00
Florian Bruhin
67ba8aaaa2 Merge pull request #1891 from nicoddemus/find-spec-rewrite-hook
Fix issue pytest_plugins as string was marking wrong modules for rewrite
2016-08-31 05:23:33 +02:00
Bruno Oliveira
edf8283bd8 Add CHANGELOG entry for #1888 2016-08-30 23:13:27 -03:00
Bruno Oliveira
c8a366e551 Fix issue where pytest_plugins as string was marking wrong modules for rewrite
Fix #1888
2016-08-30 22:53:50 -03:00
mbyt
4eeb475138 avoid tearDown and cleanup for unittest debugging 2016-08-30 21:55:49 +02:00
Bruno Oliveira
82218e4ee1 Merge pull request #1887 from mbyt/pdbcls_example_with_tab_completion
pdbcls ipython example with tab completion
2016-08-29 17:11:51 -03:00
mbyt
8593bb12ee pdbcls ipython example with tab completion 2016-08-29 21:15:12 +02:00
Raphael Pierzina
e75078eae2 Merge pull request #1848 from pytest-dev/doc-warnings
docs warnings as errors and initial page similar to README
2016-08-26 23:02:28 +01:00
Bruno Oliveira
519f02b014 docs warnings as errors and initial page similar to README
* Changed "index" to be more similar to the README (#1708).
* Fixes numerous issues like missing documents, syntax errors, etc (#1829, #432).
* Mention all docs in "contents.rst" so it's easier for users to locate (#1112).
* Add doc generation and checking to Travis and AppVeyor, to avoid re-introducing errors.

Fixes #432, Fixes #1112, Fixes #1708, Fixes #1829
2016-08-26 17:47:18 -03:00
Florian Bruhin
cb7c472e34 Merge pull request #1876 from nicoddemus/remove-monkeypatch-invocation-example
Remove example of "monkeypatch" used in session scope
2016-08-26 06:15:07 +02:00
Bruno Oliveira
a947e83be9 Merge pull request #1870 from AiOO/bugfix/assertion-with-unicode
Fix UnicodeEncodeError when string comparison with unicode has failed.
2016-08-25 22:29:32 -03:00
Bruno Oliveira
e92d373460 Remove example of "monkeypatch" used in session scope
This is a leftover when invocation-scoped fixtures
were pulled back.

Fix #1872
2016-08-25 21:50:57 -03:00
Ahn Ki-Wook
86b8801470 Update AUTHORS and CHANGELOG 2016-08-26 09:42:17 +09:00
Ahn Ki-Wook
856ad719d3 Fix UnicodeEncodeError when string comparison with unicode has failed. 2016-08-26 09:41:40 +09:00
Ronny Pfannschmidt
9c45d6cd83 Merge pull request #1866 from joguSD/bugfix-stdin-stub-buffer
Add buffer attribute to DontReadFromInput
2016-08-25 07:07:44 +02:00
Jordan Guymon
a152ea2dbb Add buffer attribute to stdin stub 2016-08-24 16:26:34 -07:00
Florian Bruhin
3345ac9216 Merge pull request #1861 from nicoddemus/ids-invalid-type-msg
Improve error message when passing non-string ids to pytest.mark.parametrize
2016-08-24 06:43:57 +02:00
Bruno Oliveira
972a5fb5d5 Improve error message when passing non-string ids to pytest.mark.parametrize
Fix #1857
2016-08-23 23:31:45 -03:00
Bruno Oliveira
ea0febad28 Updates for new patch version 3.0.2 2016-08-23 21:33:57 -03:00
Bruno Oliveira
ecb20b96fc Merge pull request #1856 from nicoddemus/release-3.0.1
Changes for 3.0.1 release
2016-08-23 21:21:24 -03:00
Bruno Oliveira
49fc4e5e4c Changes for 3.0.1 release 2016-08-23 18:15:43 -04:00
Florian Bruhin
3c866e7080 Merge pull request #1855 from nicoddemus/fix-empty-parametrize-ids
Fix internal error when parametrizing using and empty list of ids()
2016-08-23 23:38:27 +02:00
Bruno Oliveira
df200297e2 Fix internal error when parametrizing using and empty list of ids()
Fix #1849
2016-08-23 18:18:46 -03:00
Ronny Pfannschmidt
7538680c98 Merge pull request #1847 from nicoddemus/parametrize-session-scopes
Fix code which guesses parametrized scope based on arguments
2016-08-23 18:03:52 +02:00
Bruno Oliveira
847067fb02 Merge pull request #1851 from adamchainz/deprecated_setup.cfg
Delete unreferenced setup.cfg from docs
2016-08-23 12:35:48 -03:00
Adam Chainz
1673667232 Delete unreferenced setup.cfg from docs
Noticed it's not using the new `[tool:pytest]` header as changed in #567, can't find any reference to it or `testfilepatterns`. It was added in b1e4301457 6 years ago, there don't seem to have ever been references to it.
2016-08-23 16:08:24 +01:00
Bruno Oliveira
53a0e2b118 Fix code which guesses parametrized scope based on arguments
Fix #1832
2016-08-22 21:05:41 -03:00
Bruno Oliveira
d99ceb1218 Merge pull request #1844 from nicoddemus/importer-error
Importer loader error
2016-08-22 20:47:25 -03:00
Bruno Oliveira
b54ea74d4d Update AUTHORS and CHANGELOG for #1837 2016-08-22 17:59:42 -03:00
Bruno Oliveira
6a8160b318 Add acceptance test for module loader
Related to #1837
2016-08-22 17:57:25 -03:00
Bruno Oliveira
c3148d1d6b Merge pull request #1842 from Stranger6667/doc-fix
Fix documentation
2016-08-22 14:11:36 -03:00
Bruno Oliveira
b0ede044ac Merge pull request #1835 from RonnyPfannschmidt/mark-extract-param
mark plugin: move the unclean marked parameter extraction
2016-08-22 14:11:11 -03:00
Dmitry Dygalo
3fbf2e7a80 Fix documentation 2016-08-22 18:38:02 +02:00
Florian Bruhin
af0ec120fe Merge pull request #1836 from asvetlov/patch-1
Remove duplicated name
2016-08-21 22:09:58 +02:00
Marcin Bachry
678750c8f8 Fix importer call 2016-08-21 22:07:18 +02:00
Andrew Svetlov
4e9c1fbe96 Remove duplicated name 2016-08-21 22:20:29 +03:00
Ronny Pfannschmidt
406777d104 mark plugin: move the unclean marked parameter extraction 2016-08-21 20:44:37 +02:00
Florian Bruhin
abe8f5e23f Merge pull request #1824 from nicoddemus/update-howtorelease
Update HOWTORELEASE based on the 3.0.0 release
2016-08-20 23:03:59 +02:00
Bruno Oliveira
6a0e849067 Update HOWTORELEASE based on the 3.0.0 release 2016-08-20 15:47:34 -03:00
Florian Bruhin
a20c3f9c44 Merge pull request #1827 from blueyed/Fix-spelling-s-outside-a-outside-of-a-
Fix spelling: s/outside a/outside of a/
2016-08-20 20:04:58 +02:00
Florian Bruhin
783aff17dd Merge pull request #1828 from blueyed/minor-s-no-pkg_resources-pkg_resources-
minor: s/no pkg_resources/pkg_resources/
2016-08-20 20:04:48 +02:00
Daniel Hahler
86ec3f37af minor: s/no pkg_resources/pkg_resources/ 2016-08-20 18:47:42 +02:00
Daniel Hahler
e306a53999 Fix spelling: s/outside a/outside of a/ 2016-08-20 18:43:39 +02:00
Florian Bruhin
90fb8cb08b Merge pull request #1823 from nicoddemus/importorskip-regression
Fix regression when using importorskip at module level
2016-08-20 18:37:14 +02:00
Bruno Oliveira
5129c2f867 Merge pull request #1826 from blueyed/Remove-duplicate-entry-for-#717-in-CHANGELOG
Remove duplicate entry for #717 in CHANGELOG
2016-08-20 11:21:53 -03:00
Daniel Hahler
87d2d1d838 Remove duplicate entry for #717 in CHANGELOG 2016-08-20 15:12:08 +02:00
Bruno Oliveira
9aec8d9a47 py.test team -> Pytest team :) 2016-08-19 18:59:13 -03:00
Bruno Oliveira
c8f53d6690 Fix typo in 3.0.0 release announcement 2016-08-19 18:58:14 -03:00
Bruno Oliveira
875bcd4224 Add 3.0.0 release announcement to index.rst 2016-08-19 18:30:11 -03:00
Bruno Oliveira
63dc71c57e Fix regression when using importorskip at module level
Fix #1822
2016-08-19 18:21:25 -03:00
Bruno Oliveira
3a200b75c9 Bump version to 3.0.1.dev 2016-08-19 17:41:45 -03:00
Bruno Oliveira
745c8c17f1 Merge remote-tracking branch 'upstream/master' 2016-08-19 17:38:21 -03:00
Bruno Oliveira
5ecf3d78f1 Merge pull request #1819 from matthiasha/patch-1
Documentation update for rootdir discovery
2016-08-19 17:36:44 -03:00
Bruno Oliveira
b85a3b0d71 Merge pull request #1820 from The-Compiler/changelog-duplicates
Remove duplicate CHANGELOG messages
2016-08-19 17:35:23 -03:00
Bruno Oliveira
8777f61e7b Merge pull request #1818 from nicoddemus/release-3.0
Release 3.0
2016-08-19 17:33:15 -03:00
Florian Bruhin
31ede2432c Remove duplicate CHANGELOG messages
Those are both already mentioned in the breaking changes at the top.
2016-08-19 17:05:02 +02:00
matthiasha
c8fbf3ae34 remove dot in pytest 2016-08-19 14:02:25 +02:00
matthiasha
3455dfc804 add missing @matthiasha link 2016-08-19 14:01:07 +02:00
matthiasha
cd39cc1eec Mention doc update in CHANGELOG 2016-08-19 09:08:11 +02:00
matthiasha
ccfa8d15bf Update AUTHORS 2016-08-19 09:04:19 +02:00
matthiasha
799dab9dba Documentation update for rootdir discovery
This covers issue https://github.com/pytest-dev/pytest/issues/1435.
2016-08-19 09:01:12 +02:00
Bruno Oliveira
c74ce371ab Add release announcement 2016-08-18 12:02:01 -04:00
Bruno Oliveira
7f18367582 Finalize CHANGELOG 2016-08-18 11:43:21 -04:00
Bruno Oliveira
a3e6c14da3 Bump version to 3.0.0 2016-08-18 11:41:10 -04:00
Florian Bruhin
be9356aeba Merge pull request #1817 from nicoddemus/regendoc-run
Run regendoc for 3.0 release
2016-08-18 15:31:03 +02:00
Bruno Oliveira
9ce30e0085 Run regendoc for 3.0 release 2016-08-18 08:27:16 -04:00
Bruno Oliveira
3748112a94 Merge pull request #1816 from nicoddemus/merge-master-into-features
Merge master into features
2016-08-18 08:48:01 -03:00
Bruno Oliveira
0334e75c30 Use "pytest" instead of "py.test" on trial environments 2016-08-18 08:37:55 -03:00
Bruno Oliveira
56df9fcc72 Tweak CHANGELOG: move "change" entry to the proper place 2016-08-17 23:08:13 -03:00
Bruno Oliveira
66673c0dd3 Remove obsolete docstring 2016-08-17 22:59:18 -03:00
Bruno Oliveira
030c42203d Fix conflicts in CHANGELOG 2016-08-17 22:58:12 -03:00
Bruno Oliveira
3ba475c0f2 Move internal _is_unittest_unexpected_success_a_failure to "compat" module
Fix #1815
2016-08-17 22:50:10 -03:00
Bruno Oliveira
463e6572c5 Merge branch 'master' into merge-master-into-features
Preparing for 3.0
2016-08-17 22:39:23 -03:00
Bruno Oliveira
3e685d6a8d Merge pull request #1795 from hackebrot/fix-report-outcome-for-xpass
WIP Change outcome to 'passed' for xfail unless it's strict
2016-08-17 22:18:06 -03:00
Bruno Oliveira
68ebf552a1 Merge remote-tracking branch 'upstream/master' into fix-report-outcome-for-xpass 2016-08-17 21:55:10 -03:00
Bruno Oliveira
a01cbce662 Merge pull request #1814 from nicoddemus/py35-trial-windows
Enable py35-trial testenv on Windows
2016-08-17 21:54:47 -03:00
Bruno Oliveira
0fb34cd2a1 Update CHANGELOG entries 2016-08-17 21:32:07 -03:00
Bruno Oliveira
224ef67374 Quick fix for tests in config depended on the current directory
When running those tests from pytest's root folder, they would
fail because they would end up picking pytest's own pytest.ini
2016-08-17 21:32:05 -03:00
Bruno Oliveira
4ed412eb59 unittest's unexpectedSuccess should work as non-strict xpass
Make sure tests for that behavior obtain the same return code
using either pytest or unittest to run the same file
2016-08-17 21:32:04 -03:00
Bruno Oliveira
92498109e4 Enable py35-trial testenv on Windows 2016-08-17 21:20:12 -03:00
Raphael Pierzina
dfc659f781 Fix sys.version_info expression in xfail marker 2016-08-17 23:32:56 +01:00
Raphael Pierzina
0173952961 Fix py3 xfail expression evaluation and parametrize strict 2016-08-17 23:15:14 +01:00
Raphael Pierzina
767c28d422 Fix broken test in test_junitxml 2016-08-17 22:32:27 +01:00
Raphael Pierzina
d1f2f779ee Use a better xfail reason 2016-08-17 22:31:56 +01:00
Raphael Pierzina
bb3d6d87b6 Merge branch 'master' into fix-report-outcome-for-xpass 2016-08-17 22:15:29 +01:00
Raphael Pierzina
018197d72a Fix broken test in test_skipping and add one for strict xfail 2016-08-17 22:14:51 +01:00
Raphael Pierzina
ea379e0e4f Fix test in test_junitxml and add one for strict 2016-08-17 22:02:54 +01:00
Florian Bruhin
789e4670e7 Merge pull request #1813 from nicoddemus/pytest-setup.cfg
Support [tool:pytest] in setup.cfg files
2016-08-17 20:33:57 +02:00
Florian Bruhin
c8ab79402c Merge pull request #1811 from nicoddemus/revert-invocation-fixtures
Revert invocation-fixtures code
2016-08-17 20:32:54 +02:00
Bruno Oliveira
ab86dea529 Support [tool:pytest] in setup.cfg files
Also deprecate [pytest] usage in setup.cfg files

Fix #567
2016-08-17 08:19:38 -03:00
Bruno Oliveira
707b6b5e3f Revert all invocation-fixtures code
Due to a serious regression found in #1794, it was decided to pull off
invocation features from 3.0 so it can be (hopefully) re-introduced
in 3.1
2016-08-17 08:12:55 -03:00
Florian Bruhin
09e647c7d9 Merge pull request #1812 from nicoddemus/deprecate-resultlog
Deprecate --resultlog cmdline option
2016-08-17 09:17:13 +02:00
Bruno Oliveira
f25771a101 Deprecate --resultlog cmdline option
Fix #830
2016-08-16 21:40:34 -03:00
Raphael Pierzina
55ec1d7f56 Update test_junitxml.py to interpret XPASS as passed 2016-08-15 23:58:16 +01:00
Bruno Oliveira
497152505e Add CHANGELOG entry for #1809 2016-08-15 19:31:00 -03:00
Bruno Oliveira
ca5957932b Merge pull request #1806 from blueyed/fix-off-by-one-error-with-warnings
Fix off-by-one error with lines from request.node.warn
2016-08-15 19:04:00 -03:00
Bruno Oliveira
d58a8e36d7 Merge pull request #1807 from blueyed/improve-multiline-error-format
Improve display of continuation lines with multiline errors
2016-08-15 19:03:35 -03:00
Bruno Oliveira
d3b855104c Merge pull request #1809 from blueyed/exitstatus-with-pytest_terminal_summary
Pass exitstatus to pytest_terminal_summary hook
2016-08-15 19:02:30 -03:00
Daniel Hahler
c163cc7937 Improve display of continuation lines with multiline errors
Fixes https://github.com/pytest-dev/pytest/issues/717.
Follow-up to https://github.com/pytest-dev/pytest/pull/1762.
2016-08-14 22:34:31 +02:00
Daniel Hahler
16cb5d01b1 Fix off-by-one error with lines from request.node.warn
The line numbers in `node.location` seem to be zero-based?!
2016-08-14 22:10:01 +02:00
Daniel Hahler
5b95ee3c19 Pass exitstatus to pytest_terminal_summary hook
This is useful to know if a testrun has been interrupted
(EXIT_INTERRUPTED).
2016-08-14 22:06:35 +02:00
Raphael Pierzina
225341cf2c Set wasxfail only for xpass w/o strict and else set longrepr 2016-08-13 00:00:51 +01:00
Raphael Pierzina
14a4dd0697 Extend test to verify longrepr in stdout 2016-08-12 23:31:38 +01:00
Raphael Pierzina
296f42a2c9 Treat unittest.expectedFailure pass as a failure 2016-08-12 23:18:36 +01:00
Raphael Pierzina
10a6ed1707 Update unittest test to expect failure for an unexpected success 2016-08-12 23:18:02 +01:00
Bruno Oliveira
34925a31a9 Merge pull request #1799 from cryporchild/junitxml-tests-tally-fix
Fix #1798 to include errors in total tests in junit xml output.
2016-08-08 10:43:38 -03:00
Christian Boelsen
c4d9c7ea55 Add thanks as requested. 2016-08-08 13:45:10 +01:00
Christian Boelsen
e4028b4505 Fix #1798 to include errors in total tests in junit xml output. 2016-08-08 13:35:49 +01:00
Floris Bruynooghe
99a4a1a784 Merge pull request #1791 from nicoddemus/ide-integration-1790
Internal adjustments for easier integration with IDEs
2016-08-07 23:50:50 +01:00
Bruno Oliveira
4ab2e57ebd Merge pull request #1797 from nicoddemus/merge-master-into-features
Merge master into features
2016-08-06 18:48:40 -03:00
Bruno Oliveira
802755ceed Merge remote-tracking branch 'upstream/master' into merge-master-into-features 2016-08-06 17:58:17 -03:00
Bruno Oliveira
ac5c39e534 Merge pull request #1796 from nicoddemus/fix-rootdir-common-ancestor
Fix rootdir common ancestor
2016-08-06 17:38:42 -03:00
Bruno Oliveira
21230aa017 Add CHANGELOG entry 2016-08-06 17:14:13 -03:00
Dave Hunt
eb08135280 Update documentation to describe expected rootdir behaviour 2016-08-06 19:35:40 +02:00
Daniel Hahler
a2891420de Fix determining rootdir from common_ancestor 2016-08-06 19:35:40 +02:00
Raphael Pierzina
4fc20d09fe Change outcome to 'passed' for xfail unless it's strict 2016-08-05 19:25:55 +01:00
Bruno Oliveira
1a79137d04 Add originalname attribute to Function
Related to #1790
2016-08-03 22:56:12 -03:00
Bruno Oliveira
530b0050b4 Improve TestReport.sections docs a bit
Related to #1790
2016-08-03 21:57:58 -03:00
Bruno Oliveira
ff296fd541 Add capstdout and capstderr attrs to TestReport
Related to #1790
2016-08-03 21:49:43 -03:00
Bruno Oliveira
08002ab75a Add longreprtext property to TestReport objects
Related to #1790
2016-08-03 21:49:28 -03:00
Bruno Oliveira
6759b042b5 Merge pull request #1789 from nicoddemus/regendoc-take-2
Regendoc take 2
2016-08-03 18:21:36 -03:00
Bruno Oliveira
8b8c698f1a Add more interpreter versions to multipython example 2016-08-03 16:48:49 -04:00
Bruno Oliveira
d28801d794 Make parametrize example deterministic 2016-08-03 16:48:11 -04:00
Bruno Oliveira
72df32f1fd Fix missing print() 2016-08-03 17:34:55 -03:00
Bruno Oliveira
701d5fc727 Regendoc after more fixes on features branch 2016-08-03 16:31:44 -04:00
Bruno Oliveira
6e3105dc8f Merge pull request #1787 from nicoddemus/fix-rewrite-conftest
Rewrite asserts in test-modules loaded very early in the startup
2016-08-03 16:10:55 -03:00
Bruno Oliveira
6711b1d6ab Rewrite asserts in test-modules loaded very early in the startup
Also now match modules which start with any of the names registered
using register_assert_rewrite as discussed in #1787

Fix #1784
2016-08-03 12:49:48 -03:00
Florian Bruhin
d5be6cba13 Merge pull request #1788 from nicoddemus/available-fixtures-sorted
Sort fixture names when a fixture lookup error occurs
2016-08-03 07:31:28 +02:00
Bruno Oliveira
277b6d3974 Sort fixture names when a fixture lookup error occurs 2016-08-02 19:45:31 -03:00
Bruno Oliveira
ea6191a0cd Merge pull request #1779 from RonnyPfannschmidt/deselect-no-reason
terminal: dont pretend to know the deselection reason
2016-08-02 08:38:17 -03:00
Floris Bruynooghe
9540106fe7 Merge pull request #1780 from nicoddemus/regen-pytest30
Run regen-docs for pytest 3.0
2016-08-02 12:07:16 +01:00
Ronny Pfannschmidt
1c8fe962f3 add changelog entry 2016-08-02 10:51:10 +02:00
Ronny Pfannschmidt
48f4e18280 fix deselect tests to match reason removal 2016-08-02 10:43:25 +02:00
Bruno Oliveira
21a90c8c50 Run regendoc again 2016-08-01 20:12:00 -04:00
Bruno Oliveira
eed21e06db Sort yml items to get same results for regendoc runs 2016-08-01 20:09:35 -04:00
Bruno Oliveira
a6b2732507 Pass list of params to pytest.main() in docs 2016-08-01 20:09:35 -04:00
Bruno Oliveira
946466abf4 Run regen-docs for pytest 3.0 2016-08-01 20:09:35 -04:00
Raphael Pierzina
3cd2e37c55 Merge pull request #1783 from nicoddemus/inv-scoped-fixture-msg
Strip invocation-scope suffix when displaying fixture lookup error
2016-08-02 01:08:25 +01:00
Bruno Oliveira
553dc2600f Strip invocation-scope suffix when displaying fixture lookup error 2016-08-01 20:34:56 -03:00
Raphael Pierzina
226f2795ba Merge pull request #1782 from nicoddemus/invocation-fixtures-help
invocation-scoped fixtures show up once with --fixtures
2016-08-01 23:21:28 +01:00
Bruno Oliveira
b380eb5b34 Merge pull request #1781 from nicoddemus/highlight-file-loc
Highlight the path of file location in error report
2016-08-01 19:18:52 -03:00
Bruno Oliveira
44ecf2ab2f invocation-scoped fixtures show up once with --fixtures 2016-08-01 18:48:29 -03:00
Bruno Oliveira
31c5194562 Fix broken test in py3k 2016-08-01 18:35:42 -03:00
satoru
3c8222f1db Highlight the path of file location in error report
So that it's more obvious when we need to copy the file path.
2016-08-01 17:42:20 -03:00
Ronny Pfannschmidt
ac215e9cff terminal: dont pretend to know the deselection reason
this addresses #1372 - we pretend we know the deselection reason from internal plugins and ignore 3rd party/local reasons
2016-08-01 13:50:59 +02:00
Bruno Oliveira
aa145fa83e Add 'invocation' scope option to fixture docstring 2016-07-29 12:47:30 -03:00
Bruno Oliveira
76fbc6379f Fix deprecated directive in docstring 2016-07-29 12:39:48 -03:00
Bruno Oliveira
80508203b0 Merge pull request #1776 from nicoddemus/pytest-30-version
Set version to 3.0.0.dev1
2016-07-28 21:57:13 -03:00
Bruno Oliveira
eaf8d9ce19 Set version to 3.0.0.dev1
For a long time now we've considering the next version to be 3.0.0
2016-07-28 21:30:16 -03:00
Floris Bruynooghe
510a6083ba Merge pull request #1758 from nicoddemus/deprecated-module
Add deprecation module to centralize deprecation messages and bits of…
2016-07-28 22:36:55 +01:00
Florian Bruhin
ffb583ae91 Merge pull request #1773 from nicoddemus/fix-freeze
Use PyInstaller for freeze test env
2016-07-27 15:06:54 +02:00
Bruno Oliveira
ae9d3bf886 Freeze docs: PyInstaller hook and wording
As discussed during the review, suggest in general
to use PyInstaller and just mention pytest.freeze_includes()
in less detail on how to actually use it, because it varies
from tool to tool.
2016-07-27 09:15:40 -03:00
Florian Bruhin
7b1520687e Merge pull request #1771 from nicoddemus/sort-links-changelog
Sort link refs in CHANGELOG
2016-07-27 06:26:45 +02:00
Florian Bruhin
fd765f854c Merge pull request #1772 from nicoddemus/pdf-link
Fix pdf links in docs and point to docs.pytest.org in README
2016-07-27 06:25:41 +02:00
Bruno Oliveira
ed36d627e4 Use PyInstaller for freeze test env
cx_freeze doesn't seem to be very well supported in Python 3.5.

Using pyinstaller instead and rename environment to "freeze" which
is a more generic term for freezing python code into standalone
executables.

Fix #1769
2016-07-26 22:02:37 -03:00
Bruno Oliveira
9a68681719 Point doc links in README to docs.pytest.org 2016-07-26 20:25:55 -03:00
Bruno Oliveira
0b8a91b858 Fix pdf links in the documentation
Fix #1436
2016-07-26 20:20:22 -03:00
Bruno Oliveira
5565c1f4ae Sort link refs in CHANGELOG 2016-07-26 20:11:49 -03:00
Florian Bruhin
c40dcb3c18 Merge pull request #1768 from ioggstream/1609-fix-description
fix keep-duplicates help line.
2016-07-26 11:34:06 +02:00
Roberto Polli
05728d1317 fix keep-duplicates help line. 2016-07-26 09:53:12 +02:00
Florian Bruhin
b4ad4cc46e Merge pull request #1767 from nicoddemus/merge-master
Merge master into features
2016-07-26 08:44:11 +02:00
Bruno Oliveira
c2864aba3d Merge branch 'master' into merge-master
# Conflicts:
#	AUTHORS
#	CHANGELOG.rst
#	_pytest/monkeypatch.py
#	_pytest/python.py
2016-07-25 19:06:29 -03:00
Bruno Oliveira
9cf09cda7b Remove some comments and improved changelog 2016-07-25 18:41:03 -03:00
Bruno Oliveira
eb5b163698 Merge branch '1609-features' of https://github.com/ioggstream/pytest into features 2016-07-25 18:37:55 -03:00
Bruno Oliveira
d911bfcb8a Merge branch 'issue634-scopes' of https://github.com/Stranger6667/pytest
# Conflicts:
#	CHANGELOG.rst
2016-07-25 18:26:50 -03:00
Bruno Oliveira
8f29ce26e9 Merge branch 'mark_missing_fixture_error' of https://github.com/eolo999/pytest 2016-07-25 18:20:17 -03:00
Bruno Oliveira
6c8b0a28e1 Add deprecation module to centralize deprecation messages and bits of code 2016-07-25 18:14:39 -03:00
Dmitry Dygalo
d72afe7e08 Fixed scope override inside metafunc.parametrize. Fixes #634 2016-07-25 12:42:50 +02:00
Roberto Polli
ab6aef1d1f feature: default behavior now is to ignore duplicate paths specified from the command line. Use --keep-duplicates to retain duplicate paths. 2016-07-25 12:41:58 +02:00
Florian Bruhin
a2b04d02c2 Merge pull request #1759 from Stranger6667/issue1579-invalid-class
Fixed collection of classes with custom ``__new__`` method. Fixes #1579.
2016-07-25 12:27:51 +02:00
Dmitry Dygalo
f7ad173fee Fixed collection of classes with custom `__new__` method 2016-07-25 11:33:37 +02:00
Ronny Pfannschmidt
d37af20527 Merge pull request #1765 from The-Compiler/1763-cleanup
Cleanups for #1763
2016-07-25 10:31:06 +02:00
Florian Bruhin
a309a571d9 Cleanups for #1763 2016-07-25 10:17:46 +02:00
Edoardo Batini
e9d729bd46 drop parenthesis around GH issue number 2016-07-25 10:11:37 +02:00
Bruno Oliveira
c9a2e611ce Merge pull request #1763 from tomviner/issue1210-exit-msg
Fix #1210 display msg for early calls to exit
2016-07-24 13:05:44 -03:00
Bruno Oliveira
a24146dd3c Merge pull request #1757 from tramwaj29/improved-message-when-not-using-parametrized-variable
Improved message when not using parametrized variable
2016-07-24 13:02:03 -03:00
Bruno Oliveira
7862517c28 Merge pull request #1760 from blueyed/followup-pr1718-remove-newline
Followup to #1718: style/formatting
2016-07-24 13:00:14 -03:00
Tom Viner
42adaf5a61 Fix #1210 display msg for early calls to exit 2016-07-24 14:16:34 +02:00
JJ
4aede6faa6 fixed conflicts 2016-07-24 12:10:32 +02:00
JJ
d000f2536a added a test for when the indirect is just a string 2016-07-24 10:47:06 +02:00
Edoardo Batini
0ae77be9f0 Add new target links in CHANGELOG 2016-07-24 00:46:06 +02:00
Daniel Hahler
5c5d7e05f7 Followup to #1718: style/formatting 2016-07-24 00:21:42 +02:00
Edoardo Batini
f450e0a1db Thanks to Tom Viner for his guidance during EuroPython2016 sprint 2016-07-24 00:06:16 +02:00
Edoardo Batini
fabe8cda2f Thanking myself in CHANGELOG 2016-07-23 23:59:34 +02:00
Edoardo Batini
3c4158ac35 Add changelog entry for this bugfix branch 2016-07-23 23:51:11 +02:00
Edoardo Batini
e00199212c Add myself to the AUTHORS 2016-07-23 23:49:44 +02:00
Edoardo Batini
e9a67e6702 Adjust test involving FixtureLookupErrorRepr
I added a starting 'E' to the expected error messages.

The tests were still passing after the previous patch but I think it's
better to have stricter tests.
2016-07-23 23:45:07 +02:00
Edoardo Batini
6799a47c78 Start FixtureLookupErrorRepr with an 'E' 2016-07-23 23:43:34 +02:00
Bruno Oliveira
655df7f839 Merge pull request #1755 from diegorusso/master
Testcase for overriding autouse fixture with a parametrized fixture.
2016-07-23 12:53:24 -03:00
Bruno Oliveira
9891593413 Merge pull request #1754 from hartym/1749_doctest_report_format
Doctest report format option (#1749)
2016-07-23 12:52:54 -03:00
JJ
bbc7f3a631 updated changelog, resolve #1539 2016-07-23 16:57:49 +02:00
Diego Russo
1704b7d265 Test case for overriding autouse fixtures
Test case for overriding autouse fixture with a parametrized fixture.
The test covers the problem explained in the issue 1601
Adding Diego Russo to AUTHORS
2016-07-23 16:53:39 +02:00
JJ
3631719050 added myself to authors 2016-07-23 16:51:55 +02:00
JJ
f26fa5a441 changed error message for unused parametrize name 2016-07-23 16:49:20 +02:00
Romain Dorgueil
94731fc2a1 Changes variable name so it better describes what it does now. 2016-07-23 16:26:33 +02:00
Romain Dorgueil
51fa244650 Cleaner implementation of #1749. 2016-07-23 16:18:12 +02:00
Romain Dorgueil
d5a70acd48 Simplify test in test_doctest_report_none_or_only_first_failure. 2016-07-23 15:58:13 +02:00
Bruno Oliveira
018acc6bae Explain why thanks yourself in the CHANGELOG 2016-07-23 10:44:38 -03:00
Romain Dorgueil
f8f690de64 adds the versionadded flag in docs (#1749) 2016-07-23 15:30:06 +02:00
Romain Dorgueil
e229a27e8b using @pytest.mark.parametrize instead of calling one test many times from another as suggested by @nicoddemus in pr #1754 2016-07-23 15:21:59 +02:00
Romain Dorgueil
ec7695e15d adds a bit of doctest hint on why the key and value getters are separate functions. 2016-07-23 15:19:18 +02:00
Romain Dorgueil
1a33025a76 Refactors test to be in its own class, as discussed with @nicoddemus. 2016-07-23 15:16:23 +02:00
Romain Dorgueil
922a295729 fixes changelog, I think I got it 2016-07-23 15:15:17 +02:00
Romain Dorgueil
014ebc9202 Removed bug reference in changelog because it makes the linting fail. 2016-07-23 15:04:19 +02:00
Romain Dorgueil
87ca4b95fb Separate the option keys and value to avoid importing "doctest" (and tested things like "logging") for argument parsing (fixes #1749) 2016-07-23 14:50:24 +02:00
Romain Dorgueil
fd8e019cc1 Choose the doctest output format in case of failure, still work in progress as a few checks fail (related to #1749) 2016-07-23 14:40:46 +02:00
Romain Dorgueil
625b603f1f Implements an option to choose the doctest output format in case of failure. (fixes #1749) 2016-07-23 13:06:05 +02:00
Bruno Oliveira
38e0e08074 Merge pull request #1751 from javiromero/docstrings
Uppercase first word in docstrings. Change to an imperative form.
2016-07-22 10:33:58 -03:00
Javi Romero
1aab6e3bc2 Add changes to changelog. 2016-07-22 12:54:42 +02:00
Javi Romero
7e37497d5a Uppercase first word in docstrings. Change to an imperative form. Add name to authors. 2016-07-22 12:39:06 +02:00
Bruno Oliveira
ae0798522f Merge pull request #1711 from nicoddemus/invocation-scoped-fixtures
Invocation scoped fixtures
2016-07-21 19:48:52 -03:00
Florian Bruhin
832ada1b44 Merge pull request #1747 from nicoddemus/line-match-stringio
Log LineMatcher output in a stream instead of stderr
2016-07-21 09:38:11 +02:00
Bruno Oliveira
4c112401c5 Log LineMatcher output in a stream instead of stderr
This makes the match/nomatch output appear as part
of the fnmatch_lines() error on pytest's output instead
of globbered together with general stdout/stderr capture
2016-07-20 22:35:43 -03:00
Bruno Oliveira
05f3422d7c Make monkeypatch invocation-scoped 2016-07-20 22:05:49 -03:00
Bruno Oliveira
4f2bf965cb Merge remote-tracking branch 'upstream/features' into invocation-scoped-fixtures 2016-07-20 21:16:27 -03:00
Bruno Oliveira
eaa4ee3fdf Merge pull request #1746 from pytest-dev/conftest-exception-printing
Conftest exception printing
2016-07-20 21:03:39 -03:00
Bruno Oliveira
6aea164b6d Add more tests for invocation scoped fixtures 2016-07-20 21:02:36 -03:00
Bruno Oliveira
20f97c3041 Small documentation improvements 2016-07-20 20:22:28 -03:00
Bruno Oliveira
e0f08a73ab Merge branch 'features' into conftest-exception-printing 2016-07-20 19:33:36 -03:00
Bruno Oliveira
93aae987a2 Merge pull request #1744 from RonnyPfannschmidt/existfirst-override
allow --exitfirst/-x to be overridden by a following --maxfail
2016-07-20 18:16:07 -03:00
Bruno Oliveira
1204cbade4 Merge pull request #1745 from RonnyPfannschmidt/skip-compat
skipping plugin: remove python2.5 compat code
2016-07-20 18:14:20 -03:00
Ronny Pfannschmidt
9dadaa8a41 skipping plugin: remove python2.5 compat code 2016-07-20 17:45:20 +02:00
Ronny Pfannschmidt
0403266bf0 record --exitfirst change in changelog 2016-07-20 17:23:07 +02:00
Ronny Pfannschmidt
3fd8257c17 add test for --maxfail=NUM overiding -x 2016-07-20 17:20:10 +02:00
Ronny Pfannschmidt
2a05c311e9 implement exitfirst as store_const option
this makes it possible to override with a later maxfail
2016-07-20 17:15:29 +02:00
Bruno Oliveira
bcc58ec916 Merge pull request #1740 from RonnyPfannschmidt/float-argument
optparse compatibility - add float and complex
2016-07-19 19:17:35 -03:00
Ronny Pfannschmidt
9af872a230 update changelog 2016-07-19 20:11:47 +02:00
Ronny Pfannschmidt
61cc5c4d4e argument parsing: always warn for string types
fix #1741
2016-07-19 10:33:25 +02:00
Ronny Pfannschmidt
317b3f257d optparse compatibility - add float and complex
also documents the implementation quality
fixes #457
2016-07-19 10:20:41 +02:00
Floris Bruynooghe
2b9973846e Merge pull request #1736 from Avira/features
Add backwards compatibility docs
2016-07-18 11:17:48 +02:00
Oliver Bestwalter
58a8150bc5 add backwards compatibility policy 2016-07-17 21:14:16 +02:00
Bruno Oliveira
0ac3eaa1db Merge pull request #1735 from flub/reinterpret-docs
Document the re-writing of plugins
2016-07-17 12:48:33 -03:00
Floris Bruynooghe
0a53797fa3 Document the re-writing of plugins 2016-07-17 12:30:21 +01:00
Ronny Pfannschmidt
8a73a2ad60 Merge pull request #1734 from nicoddemus/issue-1728-inconsistent-setup-teardown
setup_* and teardown_* functions argument now optional
2016-07-15 14:59:22 +02:00
Floris Bruynooghe
fb21493856 Merge pull request #1733 from flub/remove-reinterpret
Remove assertion reinterpretation
2016-07-15 12:46:25 +01:00
Bruno Oliveira
ff8fb4950e setup_* and teardown_* functions argument now optional
setup_module, setup_function and setup_method
extra argument are now optional and may be omitted.

Fix #1728
2016-07-14 23:41:40 -03:00
Floris Bruynooghe
d1852a48b7 Remove assertion reinterpretation
The assertion reinterpretation is an old backwards compatibility
mode which was no longer being maintained on feature-parity with
the assertion rewriting mode.  It was also responsible for some
dubious patching of builtins and test with side-effects would
suddenly start passing.  Since re-writing has been the default for
a long time and plugins are now also re-written it is time to
retire reinterpretation.
2016-07-15 00:33:39 +01:00
Bruno Oliveira
ee374e3b80 Merge pull request #1731 from nicoddemus/improve-test-args-deprecated
Make assert in test_str_args_deprecated more resilient
2016-07-14 19:18:13 -03:00
Bruno Oliveira
3328cd2620 Make assert in test_str_args_deprecated more resilient
This attempts to fix CI which broke because of this test.

Other warnings introduced in the future could break
this test.
2016-07-14 18:37:59 -03:00
Bruno Oliveira
350ebc9167 Merge pull request #1730 from RedBeardCode/pytest-1536
Added confcutdir in testing/test_conftest.py::test_conftest_import_or…
2016-07-14 17:02:58 -03:00
Floris Bruynooghe
24fbbbef1f Merge pull request #1641 from flub/rewrite-plugins
Rewrite plugins
2016-07-14 19:39:15 +01:00
RedBeardCode
22bb43413f Added confcutdir in testing/test_conftest.py::test_conftest_import_order and
testing/python/fixture.py::TestAutouseManagement::()::
  test_class_function_parametrization_finalization to avoid problems with
  abandoned conftest.py files in /tmp dir.
  Fixes #1536
2016-07-14 18:15:38 +02:00
Florian Bruhin
691dc8bc68 Merge pull request #1727 from nicoddemus/deprecate-str-pytest-main
Deprecate support for passing command-line as string to pytest.main()
2016-07-14 14:42:14 +02:00
Florian Bruhin
14af12cb7b Merge pull request #1717 from nicoddemus/nose-yield-tests-docs
Document limitations for yield-tests in nose
2016-07-14 14:40:27 +02:00
Floris Bruynooghe
51ee7f8734 Fixup things after rebase
Some changes to make things work on top of current features branch.
2016-07-14 12:42:29 +01:00
Bruno Oliveira
9007e16cdf Document limitations for yield-tests in nose
Also add nose doc to the root toctree

Closes #1716
2016-07-14 08:20:01 -03:00
Bruno Oliveira
02dd7d612a Remove duplicated changelog entry and formatting fix 2016-07-14 08:16:27 -03:00
Bruno Oliveira
ab0b6faa5f Deprecate support for passing command-line as string to pytest.main()
Fixes #1723
2016-07-14 08:11:43 -03:00
Bruno Oliveira
1fb09d9dd5 Merge pull request #1726 from nicoddemus/warnings-displayed-by-default
Warnings displayed by default
2016-07-13 19:33:49 -03:00
Bruno Oliveira
1266ebec83 Merge remote-tracking branch 'upstream/features' into warnings-displayed-by-default
# Conflicts:
#	CHANGELOG.rst
#	testing/test_terminal.py
2016-07-13 18:45:15 -03:00
Bruno Oliveira
6e9ee2b766 Merge pull request #1724 from blueyed/followup-pr1718-remove-newline
funcarg_prefix_warning: remove newline
2016-07-13 15:46:16 -03:00
Daniel Hahler
3cfebdd7c5 funcarg_prefix_warning: remove newline
Followup to https://github.com/pytest-dev/pytest/pull/1718.
2016-07-13 18:33:24 +02:00
Floris Bruynooghe
743f59afb2 Introduce pytest.register_assert_rewrite()
Plugins can now explicitly mark modules to be re-written.  By default
only the modules containing the plugin entrypoint are re-written.
2016-07-13 17:31:09 +01:00
Floris Bruynooghe
944da5b98a Avoid rewrite warning for inline runs
When running pytest inline/inprocess we plugins have already been
imported and re-writen, so avoid the warning.
2016-07-13 17:29:19 +01:00
Floris Bruynooghe
a98e3cefc5 Enable re-writing of setuptools-installed plugins
Hook up the PEP 302 import hook very early in pytest startup so
that it gets installed before setuptools-installed plugins are
imported.  Also iterate over all installed plugins and mark them
for rewriting.  If an installed plugin is already imported then
a warning is issued, we can not break since that might break
existing plugins and the fallback will still be gracefull to
plain asserts.

Some existing tests are failing in this commit because of the new
warning triggered by inline pytest runs due to the hypothesis
plugin already being imported.  The tests will be fixed in the next
commit.
2016-07-13 17:29:19 +01:00
Bruno Oliveira
dd5ce96cd7 Merge pull request #1718 from blueyed/fix-funcarg_prefix_warning
Add punctuation to funcarg_prefix_warning
2016-07-13 12:53:54 -03:00
Florian Bruhin
aeccd6b4a2 Merge pull request #1720 from nicoddemus/changelog-formatting
Improve overall CHANGELOG formatting and consistency for 3.0
2016-07-13 15:58:38 +02:00
Bruno Oliveira
44c3055e79 Merge pull request #1721 from bronsen/patch-1
Docs: De-404 links in changelog
2016-07-13 10:05:14 -03:00
Bruno Oliveira
4a763accc5 Improve overall CHANGELOG formatting and consistency for 3.0 2016-07-13 08:52:36 -03:00
Kalle Bronsen
dfe1209d2c De-404 links in changelog 2016-07-13 11:41:27 +02:00
Florian Bruhin
54ea27c283 Merge pull request #1719 from nicoddemus/fix-2.10-versions-in-docs
Fix 2.10 -> 3.0 versions in docs
2016-07-13 08:10:13 +02:00
Bruno Oliveira
f827810fa8 Fix 2.10 -> 3.0 versions in docs 2016-07-12 21:02:40 -03:00
Daniel Hahler
15e97a7c78 Add punctuation to funcarg_prefix_warning 2016-07-12 23:49:09 +02:00
Ronny Pfannschmidt
c4f20a1834 Merge pull request #1712 from anntzer/custom-debugger
Allow passing a custom Pdb subclass via --pdbcls.
2016-07-12 16:45:07 +02:00
Ronny Pfannschmidt
4c56c95eb8 Merge pull request #1714 from nicoddemus/deprecate-yield-tests-funcarg-prefix
Deprecate yield tests funcarg prefix
2016-07-12 11:43:59 +02:00
Antony Lee
7ee3dd1cb5 Add tests for custom pdb class.
(and edit CHANGELOG)
2016-07-11 20:07:29 -07:00
Bruno Oliveira
458ecae1df Replace all usages of "pytest_funcarg__" for @pytest.fixture 2016-07-11 22:21:52 -03:00
Bruno Oliveira
ad4125dc0d Deprecate "pytest_funcarg__" prefix to declare fixtures
Fixes #1684
2016-07-11 22:21:50 -03:00
Bruno Oliveira
5506dc700c Deprecate yield tests
Closes #16
Closes #1324
2016-07-11 22:21:49 -03:00
Bruno Oliveira
0dd1c8bf14 Add test to ensure capsys and capfd error out when using "getfixturevalue" inside a test 2016-07-11 20:48:38 -03:00
Bruno Oliveira
0ca06962e9 Improve docs 2016-07-11 20:33:16 -03:00
Bruno Oliveira
2ffe354f21 Add CHANGELOG for invocation-scoped fixtures 2016-07-11 20:32:59 -03:00
Bruno Oliveira
fb4da00a32 Merge remote-tracking branch 'upstream/features' into invocation-scoped-fixtures 2016-07-11 20:09:13 -03:00
Bruno Oliveira
6f68dfcc47 Merge pull request #1710 from RonnyPfannschmidt/fixture-split
Fixture split 2nd attempt
2016-07-10 12:10:07 -03:00
Antony Lee
6383b53ad9 Allow passing a custom Pdb subclass via --pdbcls.
This obviates the need for plugins such as `pytest-ipdb`; instead one
can simply call `py.test --pdb=IPython.core.debugger:Pdb`
2016-07-09 21:10:52 -07:00
Bruno Oliveira
8ed055efd8 Add acceptance test for invocation-scoped fixtures 2016-07-09 22:52:07 -03:00
Bruno Oliveira
775100881a Implement invocation-scoped fixtures 2016-07-09 22:52:05 -03:00
Bruno Oliveira
29289b472f Add documentation for "invocation" scoped fixture 2016-07-09 16:51:25 -03:00
Ronny Pfannschmidt
8c49561470 split most fixture related code into own plugin 2016-07-09 20:36:00 +02:00
Florian Bruhin
7a2058e3db Merge pull request #1709 from The-Compiler/changelog
Clean up changelog
2016-07-08 18:52:28 +02:00
Florian Bruhin
668ebb102c Clean up changelog
- Merged 3.0 and 2.10 as much stuff from the sprint went to the 2.10
  section.
- Cleaned up mixture of link/text blocks
- Moved some entries to "Bug Fixes" and "Incompatible changes"
- Stop doing "Fixes (#123) ..." because it looks weird
- Add some new empty points for all sections
2016-07-08 18:51:26 +02:00
Bruno Oliveira
293351cfd0 Merge pull request #1705 from RonnyPfannschmidt/merge-master
Merge from master to features
2016-07-08 08:15:54 -03:00
Ronny Pfannschmidt
dad6aa8a16 fix duplicate target in changelog 2016-07-06 13:51:13 +02:00
Ronny Pfannschmidt
b9a91dc112 merge from master to features 2016-07-06 11:51:48 +02:00
Bruno Oliveira
f31c31a73c Merge pull request #1695 from sallner/feature-setup-show
Feature setup show
2016-07-05 21:29:01 -03:00
aostr
94e4a2dd67 * implemented changes recommended by nicoddemus 2016-07-05 15:22:27 +02:00
Javier Domingo Cansino
0171cfa30f Fixing link to issue and creating testcase that shows that it finds the line in the stderr lines 2016-07-05 10:39:12 +01:00
Javier Domingo Cansino
61e605f60b Making conftest import failures easier to debug 2016-07-05 10:04:42 +01:00
Ronny Pfannschmidt
cc0920ceb1 Merge pull request #1699 from nicoddemus/404-links-on-talks-docs
Fix links and removed 404 links from talks.rst
2016-07-05 08:44:23 +02:00
Florian Bruhin
067e044f97 Merge pull request #1700 from nicoddemus/split-appveyor
Split AppVeyor test runs in multiple jobs to avoid timeout issues
2016-07-05 06:43:39 +02:00
Bruno Oliveira
10c5e6fd9c Split AppVeyor test runs in multiple jobs to avoid timeout issues
Some of our builds have been timing out (over 1 hour),
on AppVeyor
2016-07-04 21:54:21 -03:00
Bruno Oliveira
8d39ce17da Fix links and removed 404 links from talks.rst
Fix #1696
2016-07-04 21:32:57 -03:00
Steffen Allner
6438895a23 Fix PEP-8. 2016-07-03 22:33:21 +02:00
Steffen Allner
b650c3c118 Implement --setup-show cli flag
to also be able to see fixture setup with normal test execution.
2016-07-03 22:30:51 +02:00
Steffen Allner
f7b5bb2f97 Merged branch features into features 2016-07-03 21:07:02 +02:00
Bruno Oliveira
f74dd8550f Merge pull request #1692 from pytest-dev/changelog
Add changelog to requirements for pytest-dev plugins
2016-06-30 17:39:14 -03:00
Florian Bruhin
e3c43a1462 Add changelog to requirements for pytest-dev plugins
Closes #1691
2016-06-30 22:25:09 +02:00
Florian Bruhin
7927dff8a1 Merge pull request #1678 from RonnyPfannschmidt/drop-python30-32
drop python 3.0-3.2 support code from setup.py
2016-06-30 11:15:49 +02:00
Ronny Pfannschmidt
1451a1ab00 remove unsupported python versions from code/source xfail 2016-06-30 10:03:40 +02:00
Bruno Oliveira
75ecd94294 Merge pull request #1689 from quodlibetor/autouse-docs
Document the interaction of autouse scopes
2016-06-29 18:08:06 -03:00
Brandon W Maister
771c4539fa Document the interaction of autouse scopes
I wouldn't have even attempted what I did to cause #1688 if this had
been there.
2016-06-29 16:52:13 -04:00
Ronny Pfannschmidt
2a43237527 docs: no longer include python 3.0-3.2 in the index page 2016-06-27 18:20:56 +02:00
Ronny Pfannschmidt
7dc8d1ab60 fix typo and remove python3.2 from readme 2016-06-27 18:19:00 +02:00
Florian Bruhin
1e60294188 Merge pull request #1679 from eli-b/patch-1
catched -> caught
2016-06-27 18:02:16 +02:00
Ronny Pfannschmidt
e877e25587 drop python 3.0-3.2 support code from setup.py
addresses #1627
2016-06-27 17:55:37 +02:00
Eli Boyarski
21d27784eb catched -> caught
Even though catch is a Python keyword, 'catched' just looks terrible in text.
If the text was supposed to reference the keyword, then 'catched' should be changed to "'catch'ed".
2016-06-27 15:41:40 +03:00
Bruno Oliveira
ccd395ffe0 Merge pull request #1659 from RonnyPfannschmidt/failtest-586
xfailing test for #568
2016-06-27 07:38:14 -03:00
Ronny Pfannschmidt
76756c0c0b mark tests: use better name of the test for #568 2016-06-27 11:57:21 +02:00
Bruno Oliveira
44695ae46c Fix CHANGELOG: obestwalter appearing twice due to mergig separate PRs 2016-06-26 23:44:07 +02:00
Bruno Oliveira
7e78965c79 Merge branch 'logic_brackets' 2016-06-26 21:34:37 +02:00
Bruno Oliveira
58e558141d Remove commented out code 2016-06-26 21:19:07 +02:00
Bruno Oliveira
22c2d87633 Fix bad merge in CHANGELOG 2016-06-26 21:18:01 +02:00
Bruno Oliveira
5891061ac1 Merge pull request #1675 from kvas-it/issue-1562
Add warning for assertions on tuples #1562
2016-06-26 16:09:15 -03:00
Bruno Oliveira
48ac1a0986 Merge branch 'remove-old-entry-points' into features 2016-06-26 20:38:59 +02:00
Bruno Oliveira
db9b3e9522 Merge pull request #1677 from nicoddemus/remove_cmd_options
Remove cmd options
2016-06-26 15:37:59 -03:00
Bruno Oliveira
b9536608c5 Add issue and obestwalter to CHANGELOG
Fix #1632
2016-06-26 20:36:04 +02:00
Bruno Oliveira
f7a2048e96 Merge branch 'features' of https://github.com/Avira/pytest into remove-old-entry-points 2016-06-26 20:32:38 +02:00
Bruno Oliveira
7239f36466 Improve formatting in CHANGELOG 2016-06-26 19:41:01 +02:00
RedBeardCode
1b0dbd8c40 Move the freezing function from genscript.py to a new module freeze_support.py 2016-06-26 19:37:24 +02:00
RedBeardCode
0e2ebc96ff Remove deprecated cmd options
Fixes #1657
2016-06-26 19:26:04 +02:00
aostr
b4e0fabf93 * added missing link to the referenced issue 2016-06-26 06:52:50 +02:00
aostr
1ce4670062 * removed tailing whitespaces 2016-06-26 06:51:57 +02:00
Vasily Kuznetsov
6d4cee2159 Add a test for indirect use of tuple in the assert that should not cause a warning 2016-06-26 02:21:51 +02:00
Vasily Kuznetsov
0db4ae15a9 Update changelog 2016-06-25 19:34:55 +02:00
Vasily Kuznetsov
c17027e576 Warn about asserts on tuples (fixes #1562) 2016-06-25 19:21:48 +02:00
aostr
e04d9ff80b * now showing pytest warnings summary by default.
* added ``--disable-pytest-warnings` flag to let users disable the warnings summary.
* extended/changed unit tests for the changes in the pytest core.
2016-06-25 18:16:13 +02:00
RedBeardCode
e2f550156e Improve of the test output for logical expression with brackets.
Fixes #925
2016-06-25 18:10:36 +02:00
holger krekel
68bed00d5b Merge pull request #1667 from fengxx/feature/override_ini_option
Add --overwrite-ini ININAME=INIVALUE cli option
2016-06-25 18:10:10 +02:00
Ted Xiao
856e6cab75 add --override-ini option to overrides ini values
Signed-off-by: Ted Xiao <xiao.xj@gmail.com>
2016-06-25 23:45:32 +08:00
holger krekel
13a188fe37 Merge pull request #1647 from sallner/features
Add new options to report fixture setup and teardown
2016-06-25 16:38:37 +02:00
Oliver Bestwalter
3a9e9fdf82 rephrase changes in CHANGELOG.rst 2016-06-25 16:04:23 +02:00
Oliver Bestwalter
72450408ed add changes in CHANGELOG.rst 2016-06-25 16:00:49 +02:00
Ronny Pfannschmidt
95b83958f4 add xfailing test for issue #568 2016-06-25 15:49:23 +02:00
Ronny Pfannschmidt
2af3a7a9d7 Merge pull request #1519 from omarkohl/pytest_skip_decorator
Raise CollectError if pytest.skip() is called during collection
2016-06-25 15:20:34 +02:00
Florian Bruhin
35cd12e4de Merge pull request #1660 from hackebrot/parametrize-with-fixtures
Proposal: Parametrize with fixtures
2016-06-25 15:05:27 +02:00
Raphael Pierzina
1b6bc4d606 Add feature proposal to changelog 2016-06-25 14:58:18 +02:00
Bruno Oliveira
c519b9517a Merge pull request #1663 from aostr/master
Rename the default plugin "pdb" into "debugging"
2016-06-25 09:56:54 -03:00
Raphael Pierzina
eb98a8eefb Change version in issues section to pytest 3.0 only 2016-06-25 14:52:57 +02:00
Raphael Pierzina
acfdd85dff Move document to proposals subfolder 2016-06-25 14:42:19 +02:00
Bruno Oliveira
e0242146ec Merge pull request #1666 from pytest-dev/1564-changelog
Add changelog entry for #1564
2016-06-25 09:34:21 -03:00
Bruno Oliveira
df17f862fa Merge pull request #1648 from blueyed/simplify-Argument-__repr__
Simplify Argument.__repr__
2016-06-25 09:26:50 -03:00
Bruno Oliveira
7eb1318db2 Merge pull request #1656 from pytest-dev/rm-indiegogo-links
Update website wrt indiegogo campaign
2016-06-25 09:22:07 -03:00
Florian Bruhin
ce603dc0ea Add changelog entry for #1564 2016-06-25 14:18:41 +02:00
Ronny Pfannschmidt
70ea3ce7f7 Merge pull request #1564 from The-Compiler/issue1479
Don't ignore ImportError when importing setuptools plugins
2016-06-25 14:09:48 +02:00
aostr
9a5224e2f8 Renamed the pdb module and changed unit tests accordingly 2016-06-25 12:37:31 +02:00
Danielle Jenkins
32ca5cdb09 Update changelog for new fixture hooks. 2016-06-25 12:33:31 +02:00
Oliver Bestwalter
891e1677b6 Remove all py.test-X* entry points.
The versioned, suffixed entry points are not documented and a leftover from a pre-virtualenv world. They also are broken for wheels.
2016-06-25 12:27:05 +02:00
Danielle Jenkins
9877bf47e3 Improve commenting for setupplan unittest. 2016-06-25 12:21:31 +02:00
Danielle Jenkins
7a3daac85b Add docs for setuponly and setupplan options. 2016-06-25 12:21:12 +02:00
Danielle Jenkins
da5c579d82 Move setupplan and setuponly options to their respective modules.
Also, changed their group from "general" to "debugconfig".
2016-06-25 12:20:56 +02:00
Danielle Jenkins
032ce8baf6 Switch setuponly and setupplan options to a hook-based implementation. 2016-06-25 12:19:46 +02:00
aostr
05b5554cac Renamed pytest pdb to debugging which conflicts with python pdb.
Combining multiple imports the "import pdb" imports the pytest module
as opposed to the python debugger.
2016-06-25 12:09:05 +02:00
Raphael Pierzina
5860c609ae Remove note on scoping 2016-06-25 11:09:46 +02:00
Raphael Pierzina
526c564576 Fix rst bullet point lists 2016-06-25 11:06:17 +02:00
Raphael Pierzina
693859210a Add yielded values to function example 2016-06-25 11:00:54 +02:00
Raphael Pierzina
4f8b8c8d31 Add alternative approach that uses wrappers 2016-06-25 10:55:08 +02:00
Raphael Pierzina
c6a711c2fc Add proposed solution using a module function 2016-06-25 10:50:14 +02:00
Raphael Pierzina
84f0dcecf8 Add issues section to proposal doc 2016-06-25 10:10:57 +02:00
Florian Bruhin
757f37f445 Don't ignore ImportError with setuptools plugins
This was added in b2d66b9e7b but is a bad
idea. When a plugin can't be imported, commandline options (optionally
set in pytest.ini) could be undefined, which means pytest bails out
much earlier before showing the warning, which is hard to debug.

Fixes #1479, also see #1307 and #1497
2016-06-25 09:56:22 +02:00
Daniel Hahler
939407ef63 Simplify Argument.__repr__
I have came across this when noticing that universal-ctags fails to parse
this correctly (https://github.com/universal-ctags/ctags/issues/997).
2016-06-25 09:31:31 +02:00
Omar Kohl
b3615ac29d Update CHANGELOG with #607 and add version 3.0.0.dev1 2016-06-24 20:56:21 +02:00
Omar Kohl
d81f23009b Raise CollectError if pytest.skip() is called during collection
pytest.skip() must not be used at module level because it can easily be
misunderstood and used as a decorator instead of pytest.mark.skip, causing the
whole module to be skipped instead of just the test being decorated.

This is unexpected for users used to the @unittest.skip decorator and therefore
it is best to bail out with a clean error when it happens.

The pytest equivalent of @unittest.skip is @pytest.mark.skip .

Adapt existing tests that were actually relying on this behaviour and add a
test that explicitly test that collection fails.

fix #607
2016-06-24 20:56:21 +02:00
Bruno Oliveira
0c63762d9c Merge pull request #1654 from tomviner/issue1503/remove_collapse_false
Fixes #1503 no longer collapse false explanations
2016-06-24 12:53:49 -03:00
Brianna Laugher
7612b650a0 update sprint page to be past tense 2016-06-24 17:24:06 +02:00
Brianna Laugher
62255d8000 rm global header 2016-06-24 17:12:41 +02:00
Brianna Laugher
ea5bda0898 remove links to funding campaign 2016-06-24 17:11:29 +02:00
Tom Viner
77689eb486 Fixes #1503 no longer collapse false explanations 2016-06-24 15:35:24 +02:00
Bruno Oliveira
3d263c64c3 Merge pull request #1626 from tomviner/issue1625/rename-getfuncargvalue
issue1625, rename getfuncargvalue to getfixturevalue
2016-06-24 08:58:32 -03:00
Raphael Pierzina
dc55551213 Start proposal for parametrize with fixtures 2016-06-24 12:08:57 +02:00
Tom Viner
df9918eda3 issue1625, name getfuncargvalue to getfixturevalue 2016-06-24 10:08:19 +02:00
Vasily Kuznetsov
c6af737d4e Fix fixture parameter display when ids is a function 2016-06-23 10:54:22 +02:00
Vasily Kuznetsov
1a5e530b98 Fix capturing with --setup-only/--setup-plan 2016-06-23 10:23:04 +02:00
Ronny Pfannschmidt
f2bb3df310 Merge pull request #1645 from userzimmermann/sprint/addoption-check
added check for already existing option names to OptionGroup.addoption()
2016-06-23 07:52:46 +02:00
Florian Bruhin
6359e75ff8 Trivial spelling fix in runtest_setup.py 2016-06-22 20:18:00 +02:00
Stefan Zimmermann
69bab4ab04 added check for already existing option names to OptionGroup.addoption() 2016-06-22 18:01:35 +02:00
Steffen Allner
ecc97aa3b9 Use correct links in changelog. 2016-06-22 17:52:13 +02:00
Steffen Allner
dd97a2e7c8 Merge from upstream 2016-06-22 17:51:48 +02:00
Steffen Allner
0dbf77e08e Add to changelog and authors. 2016-06-22 17:37:58 +02:00
Vasily Kuznetsov
f7d50dfa91 Add a test for handling of dynamic requests for fixtures from other fixtures 2016-06-22 17:24:55 +02:00
Ronny Pfannschmidt
7d60fcc098 Merge pull request #1643 from RonnyPfannschmidt/merge-master
Merge master
2016-06-22 17:05:59 +02:00
Vasily Kuznetsov
c8c32fd9c0 Merge with upstream 2016-06-22 17:00:35 +02:00
Vasily Kuznetsov
61992b4e22 Implement --setup-plan option 2016-06-22 16:45:36 +02:00
Vasily Kuznetsov
f59d8f7720 Fix the tests (#3)
* Fix the tests

* Fix .format string failures on python 2.6
2016-06-22 16:23:58 +02:00
Ronny Pfannschmidt
18ef7de96b merge from master again 2016-06-22 16:03:52 +02:00
Ronny Pfannschmidt
e96cd51a2a Merge remote-tracking branch 'upstream/features' into merge-master 2016-06-22 16:03:00 +02:00
Ronny Pfannschmidt
f7585c7549 Merge pull request #1635 from Avira/master
Add test for change in pull request #1631
2016-06-22 15:49:09 +02:00
Ronny Pfannschmidt
9cb851716d Merge pull request #1644 from KangarooCreativeTeam/patch-1
cache.rst: Fix wrong command used
2016-06-22 15:46:09 +02:00
Ronny Pfannschmidt
a2420ce051 Merge pull request #1640 from Avira/features
Add tests for entry points (#1629 )
2016-06-22 15:41:19 +02:00
HEAD KANGAROO
be1dabd6a9 cache.rst: Fix wrong command used
The "Inspecting Cache content" section was showing --cache-clear command,
  but should actually be using --cache-show command.

  Also; update AUTHORS
2016-06-22 14:04:02 +01:00
Vasily Kuznetsov
5e0d78f4f1 Fix .format string failures on python 2.6 2016-06-22 14:53:37 +02:00
Ronny Pfannschmidt
083f64100d merge master into features 2016-06-22 14:39:33 +02:00
Oliver Bestwalter
db79ed5c4d Add tests to make sure expected entry points exist (#1629) 2016-06-22 14:28:53 +02:00
Bruno Oliveira
fb79fa711b Merge branch 'issue1553/diff-final-newline' of https://github.com/tomviner/pytest 2016-06-22 14:21:30 +02:00
Vasily Kuznetsov
1a75139f72 Fix the tests 2016-06-22 13:25:46 +02:00
Steffen Allner
ee311e1eae Merge pull request #2 from kvas-it/features
Add printing of fixture dependencies
2016-06-22 13:04:23 +02:00
Vasily Kuznetsov
2c5c4f3f78 Add printing of fixture dependencies 2016-06-22 12:54:36 +02:00
Steffen Allner
2c6cfa42fa Disable capturing for setuponly output 2016-06-22 12:14:35 +02:00
Steffen Allner
de9ed5e3f4 Merge pull request #1 from kvas-it/features
Factor setuponly code out of runtestprotocol().
2016-06-22 12:04:45 +02:00
Steffen Allner
92bcc36266 Refactor logging of fixtures 2016-06-22 12:01:51 +02:00
Steffen Allner
7d19f83982 Add test for setuponly option 2016-06-22 12:00:45 +02:00
Oliver Bestwalter
7d87a1b127 Add test for failing assertion
Should contain function name that caused the failure (see pull request #1631).
2016-06-22 11:23:50 +02:00
Vasily Kuznetsov
6874c3a3cc Factor setuponly code out of runtestprotocol(). 2016-06-22 11:09:54 +02:00
Ronny Pfannschmidt
24179dc99f Merge pull request #1639 from tomviner/fix-changelog-links
fix changelog links
2016-06-22 10:49:35 +02:00
Tom Viner
ec25d398a5 fix changelog links 2016-06-22 10:06:14 +02:00
Tom Viner
98adf204b2 issue 1553: Include terminal newlines in diffs 2016-06-22 09:50:15 +02:00
Steffen Allner
499c9551c8 Implement working version of --setuponly 2016-06-22 09:42:45 +02:00
Bruno Oliveira
144dc12e55 Merge pull request #1638 from blueyed/fix-CONTRIBUTING
CONTRIBUTING.rst: spelling fixes
2016-06-22 04:28:15 -03:00
Daniel Hahler
09389d2b20 CONTRIBUTING.rst: spelling fixes
[ci skip]
2016-06-22 09:14:07 +02:00
Bruno Oliveira
c3ee1c17bc Merge pull request #1620 from tomviner/issue460/parameterized-subrequest
Issue 460: Fail on getfuncargvalue(<fixture with params>)
2016-06-21 13:43:06 -03:00
Bruno Oliveira
4350f499b2 Merge branch 'issue1629' of https://github.com/davehunt/pytest into features 2016-06-21 18:37:14 +02:00
Bruno Oliveira
61ede096a3 Merge pull request #1631 from Avira/master
help the user in the rare case this assertion actually fails
2016-06-21 13:17:52 -03:00
Bruno Oliveira
2f9d5c2586 Merge pull request #1623 from blueyed/ignore-hidden-files-in-test_pytest_collect_file
Ignore hidden files (.testmondata) in test_pytest_collect_file
2016-06-21 13:17:20 -03:00
Bruno Oliveira
f05d65dc42 Merge pull request #1622 from nicoddemus/issue-1619-conftest-assert-rewrite
Issue 1619 conftest assert rewrite
2016-06-21 13:15:52 -03:00
Bruno Oliveira
573866bfad Merge remote-tracking branch 'upstream/features' into issue-1619-conftest-assert-rewrite 2016-06-21 18:10:19 +02:00
Bruno Oliveira
2305d3271d Merge pull request #1628 from omarkohl/exit_on_collection_error
Exit pytest on collection error (without executing tests)
2016-06-21 13:03:21 -03:00
Bruno Oliveira
406355fd10 Merge pull request #1624 from blueyed/getexecutable-skip-non-zero-returncode
tests: getexecutable: call `--version` on all Pythons
2016-06-21 12:51:48 -03:00
Dave Hunt
393167b94f Update CHANGELOG and add Oliver Bestwalter to AUTHORS 2016-06-21 16:59:14 +02:00
Dave Hunt
ef9dd14963 Introduce pytest command as recommended entry point
Fixes #1629
2016-06-21 16:16:57 +02:00
Oliver Bestwalter
2b5c2f3ed5 help the user in the rare case this assertion actually fails 2016-06-21 14:57:48 +02:00
Omar Kohl
ede7478dcc Exit pytest on collection error (without executing tests)
Add --continue-on-collection-errors option to restore the previous behaviour:
Execute tests (that were successfully collected) even when collection errors
happen.

Some tests had to be modified e.g. because the return code changed to 2
(EXIT_INTERRUPTED) instead of 1 (EXIT_TESTSFAILED) because an Interrupted
exception is raised on collection error.

Implemented via pair programming with:
    Oleg Pidsadnyi <oleg.pidsadnyi@gmail.com>

closes #1421
2016-06-21 13:32:34 +02:00
Bruno Oliveira
819942e964 Return explicit None from rewrite hook's find_module 2016-06-21 12:28:36 +02:00
Bruno Oliveira
8b0fb47c79 Remove print left by accident 2016-06-21 12:23:12 +02:00
Tom Viner
5854a71ece Issue 460: getfuncargvalue fixture w. params err 2016-06-21 11:29:21 +02:00
Bruno Oliveira
5d8d1db4df Update repository transfer instructions 2016-06-21 09:40:22 +02:00
Floris Bruynooghe
9118c0222f Merge .set_config() into constructor 2016-06-21 09:28:10 +02:00
Daniel Hahler
e53e45b55c tests: getexecutable: call --version on all Pythons
This should prevent errors from pyenv:

    pyenv: python2.6: command not found

    The `python2.6' command exists in these Python versions:
      2.6.9

While the pyenv wrapper explicitly returns 127, I think it is better to
just check for non-zero?!
2016-06-21 08:36:02 +02:00
Bruno Oliveira
e0cb046885 Update AUTHORS and CHANGELOG 2016-06-20 23:16:06 +02:00
Bruno Oliveira
3a81d2e012 conftest files now use assertion rewriting
Fix #1619
2016-06-20 23:13:29 +02:00
Daniel Hahler
e9d7989140 Ignore hidden files (.testmondata) in test_pytest_collect_file
`test_pytest_collect_file` fails if you run the tests using `--testmon`,
because pytest-testmon will put its DB there as `.testmondata`.
2016-06-20 22:30:36 +02:00
Florian Bruhin
54872e94b4 Fix test name typo 2016-06-20 18:44:34 +02:00
Florian Bruhin
4f2db6c08d Merge pull request #1616 from palaviv/pytest.raises-message
Pytest.raises custom error message
2016-06-20 18:43:12 +02:00
Ronny Pfannschmidt
f3aead8e49 Merge pull request #1600 from nicoddemus/issue-1599-disable-cap-fixtures
Add disabled() method to capsys and capfd
2016-06-20 15:55:54 +02:00
palaviv
f8d4cadc3d Added versionchanged directives 2016-06-19 23:56:43 +03:00
palaviv
c29130d400 Updated documentation 2016-06-19 23:34:42 +03:00
palaviv
ca093673fb pytest.raises accept cutom message only when used as context manager 2016-06-19 21:24:47 +03:00
Bruno Oliveira
d81ee9acfb Merge pull request #1597 from taschini/pyargs-fix
Ensure that a module within a namespace package can be found by --pyargs
2016-06-19 14:20:52 -03:00
Bruno Oliveira
72bf11cbe9 Add disabled() method to capsys and capfd
Fix #1599
2016-06-19 19:14:36 +02:00
palaviv
e6ff01ada3 CR fixes 2016-06-16 21:09:15 +03:00
palaviv
8ddbca36c9 Add CHANGLOG entry 2016-06-16 20:21:03 +03:00
palaviv
d21886c005 pytest.raises accpets custom message 2016-06-16 20:15:32 +03:00
Bruno Oliveira
7f8e315285 Merge pull request #1615 from gnprice/deadcode
Cut a dead test helper function
2016-06-16 00:42:01 -03:00
Bruno Oliveira
c5424643f0 Merge pull request #1614 from gnprice/loop
Simplify default pytest_runtestloop
2016-06-16 00:29:03 -03:00
Greg Price
ab8b2e75a3 Simplify default pytest_runtestloop
The inner function and the explanatory comment it makes necessary can
all be removed if we switch to an if/else rather than try/except for
this condition.

Perhaps this bit comes from my fondness for C, but I think I would
find this style clearer and easier to understand even if it weren't
for the Python 2 quirk that makes the other style require us to add an
unnecessary-looking function abstraction.  In any case, given that the
alternative does require that abstraction this is definitely simpler.
2016-06-15 18:27:08 -07:00
Greg Price
2a3cbdf4d1 Cut a dead test helper function
This appears to have been unused since commit
320835d "split out pytest-xdist related reporting to the plugin"
in July 2010.  It's the only caller outside of _pytest/runner.py
of the `call_and_report` helper function there, so cutting it out
makes that more of a pure helper function and makes it slightly
easier to understand the code in _pytest/runner.py .
2016-06-15 18:26:10 -07:00
Bruno Oliveira
308396ae3c Merge pull request #1606 from hackebrot/show-fixtures-per-test
Show fixtures per test
2016-06-14 09:54:18 -03:00
Ronny Pfannschmidt
feeee2803e Merge pull request #1586 from nicoddemus/issue-1461-merge-yield-fixture
Make normal fixtures work with "yield"
2016-06-14 10:31:09 +02:00
taschini
1218392413 Added taschini to AUTHORS and #1597 to CHANGELOG.rst. 2016-06-14 07:16:20 +02:00
taschini
4d9e293b4d Incorporated feedback (#1597).
Fixed problem caused in a test on Windows by file left open by PyPy and not immediately garbage collected.
2016-06-14 07:12:40 +02:00
taschini
e2e6e31711 Ensure that a module within a namespace package can be found by --pyargs. 2016-06-14 07:12:40 +02:00
Raphael Pierzina
adc50ac72f Change format for test function locations 2016-06-12 15:58:32 +01:00
Ronny Pfannschmidt
66e66f61e8 Merge pull request #1605 from guyzmo/issue/1604
Fixed issue shadowing error when missing argument on teardown_method
2016-06-12 12:05:37 +02:00
Guyzmo
accd962c9f Fixed issue shadowing error when missing argument on teardown_method
When the method argument is missing on teardown_method, the traceback is
100% internal to pytest, which with default options get pruned. Then
that traceback is empty, leading to a new exception as a traceback shall
not be empty.

This PR fixes that issue by pushing back the last stack on the
traceback, when the stacktrace is empty after pruning. Then the output
is still pruned, but gives meaningful information with the item where it
failed on the stack.

* fixes issue #1604

Signed-off-by: Guyzmo <guyzmo+github@m0g.net>
2016-06-12 03:45:24 +02:00
Raphael Pierzina
b99aace8a9 Fix py26 by using indices in str.format 2016-06-12 00:52:03 +01:00
Raphael Pierzina
bbc6c18448 Add changelog entry for new cli flag 2016-06-12 00:26:32 +01:00
Raphael Pierzina
7eea168106 Implement show_fixtures_per_test and add cli flag 2016-06-12 00:20:06 +01:00
Raphael Pierzina
b47f155d74 Implement tests for --fixtures-per-test 2016-06-12 00:17:50 +01:00
Ronny Pfannschmidt
577cce2554 Merge pull request #1593 from marscher/fix_cwd_explosion
Fix cwd explosion
2016-06-10 07:24:18 +02:00
Bruno Oliveira
bdc29968b8 Remove dead code and simplify code in call_fixture_func 2016-06-08 21:07:56 -03:00
Bruno Oliveira
ed69424917 Remove most content from yieldfixture as it is now deprecated 2016-06-08 21:07:55 -03:00
Bruno Oliveira
371fbe4388 Update CHANGELOG (yield statements in normal fixtures) 2016-06-08 21:07:53 -03:00
Bruno Oliveira
fe4f23c1bf Update docs in prol of using yield statements 2016-06-08 21:07:52 -03:00
Bruno Oliveira
98acda426f Remove yieldctx variable being passed around 2016-06-08 21:07:50 -03:00
Bruno Oliveira
d712428d33 Fix custom name for yield_fixtures 2016-06-08 21:07:49 -03:00
Bruno Oliveira
366879db27 Make normal fixtures work with "yield" 2016-06-08 21:07:47 -03:00
Bruno Oliveira
92323895c9 Use same python which invoked tox for "doctesting" env
This will work for Travis and AppVeyor because both start tox using Python 3
2016-06-08 21:06:19 -03:00
marscher
09d163aa3a [exception handling] Fix case the current working directory (CWD) gets deleted during testing.
Fixes #1235.
2016-06-08 15:18:23 +02:00
Ronny Pfannschmidt
70fdab4cfa Merge pull request #1584 from mgedmin/patch-1
Docs: config.option is deprecated
2016-06-02 09:27:32 +02:00
Marius Gedminas
3ad5b9de86 Docs: config.option is deprecated
https://pytest.org/latest/writing_plugins.html#_pytest.config.Config says config.option is deprecated and one should use config.getoption() instead.
2016-06-02 09:52:56 +03:00
Ronny Pfannschmidt
9b6dc93496 Merge pull request #1583 from nicoddemus/fix-tox-doctesting
Use same python which invoked tox for "doctesting" env
2016-06-02 08:10:33 +02:00
Bruno Oliveira
2c4b76b754 Use same python which invoked tox for "doctesting" env
This will work for Travis and AppVeyor because both start tox using Python 3
2016-06-01 20:30:26 -03:00
Bruno Oliveira
63ced4d486 List contributors alphabetically in AUTHORS 2016-06-01 20:21:51 -03:00
Bruno Oliveira
97c89e6dc3 Merge branch 'fix-all-skipped-but-none-exist' 2016-06-01 20:20:50 -03:00
Bruno Oliveira
dd9c81ca26 Mention #1580 in the CHANGELOG and add Thomas Grainger to AUTHORS 2016-06-01 19:56:45 -03:00
Thomas Grainger
74862b8f2f Don't mark empty doctest files as skipped, fixes #1578 2016-06-01 19:19:14 +01:00
Florian Bruhin
057007fb52 Merge pull request #1582 from graingert/patch-1
Fix rst-lint CHANGELOG error
2016-06-01 19:25:18 +02:00
Thomas Grainger
2898dffb9e Fix rst-lint CHANGELOG error 2016-06-01 17:43:41 +01:00
Ronny Pfannschmidt
7305adfdba fix another copy&paste error in the announcement list 2016-06-01 08:55:44 +02:00
Ronny Pfannschmidt
fad6266a47 finish up the version bump in __init__ i forgot 2016-06-01 08:18:10 +02:00
Ronny Pfannschmidt
b5bd4d959d merge master to features 2016-06-01 08:13:26 +02:00
Ronny Pfannschmidt
f423f08b45 prepare cangelog for the next bugfix release 2016-06-01 08:04:21 +02:00
Ronny Pfannschmidt
5c8b0fb523 fix minor typos 2016-06-01 08:03:22 +02:00
Ronny Pfannschmidt
978bb190a1 add release announcement 2016-05-31 19:06:29 +02:00
Ronny Pfannschmidt
a2a904466c alter changelog header 2016-05-31 19:05:36 +02:00
Ronny Pfannschmidt
77c28825df regendoc and comment out a python2.7 example as per #1573 2016-05-31 19:05:36 +02:00
Ronny Pfannschmidt
d3dcc2b8f1 bump regendoc python version to 3.5 2016-05-31 19:05:36 +02:00
Ronny Pfannschmidt
85541113eb update version 2016-05-31 19:05:36 +02:00
Ronny Pfannschmidt
7ef06822cb ignore hypothesis temp folder 2016-05-31 19:05:36 +02:00
Ronny Pfannschmidt
289e0091de Merge pull request #1577 from pytest-dev/docs-hookwrapper-experimental
Remove "experimental" status from hookwrapper
2016-05-31 17:56:08 +02:00
Bruno Oliveira
28efdebfcd Remove "experimental" status from hookwrapper 2016-05-31 12:17:55 -03:00
Ronny Pfannschmidt
fb2e7cc727 Merge pull request #1575 from hackebrot/fix-showfixtures-for-multiple-fixturedefs
Fix showfixtures for multiple fixturedefs
2016-05-31 13:53:13 +02:00
Raphael Pierzina
fb8ad714b1 Implement a test for showfixtures to show fixtures with same name 2016-05-31 11:47:16 +01:00
Raphael Pierzina
945072b89a Update changelog with --fixtures fix 2016-05-31 11:47:16 +01:00
Raphael Pierzina
0d80a9c729 Change _showfixtures_main to loop over fixturedefs 2016-05-31 11:47:16 +01:00
Ronny Pfannschmidt
357a7c79ef Merge branch 'tomviner-issue-1496-xfail-cond-kw'
fixes  #1496
2016-05-31 11:25:15 +02:00
Ronny Pfannschmidt
158f3cfaea merge master 2016-05-31 11:24:53 +02:00
Bruno Oliveira
82c74fe7e6 Merge pull request #1530 from RonnyPfannschmidt/fix-510
fix #510 by adding a describing skip marker on empty parameterize
2016-05-30 10:54:33 -03:00
Ronny Pfannschmidt
afc5c7e4f6 better message for empty argument skip
include the argument names to help determining the fixture/parametrization
2016-05-30 14:42:55 +02:00
Ronny Pfannschmidt
03eb9203fd remove the old empty argument triggers
unlike the marker based one its not composable
2016-05-30 14:41:00 +02:00
Ronny Pfannschmidt
ae4dff0e0a add missing link to changelog 2016-05-30 14:34:38 +02:00
Ronny Pfannschmidt
d217b52508 fix #510 by adding a describing skip marker on empty parameterize 2016-05-30 14:34:38 +02:00
Bruno Oliveira
8c1be624a6 Merge pull request #1554 from RonnyPfannschmidt/merge-master
Merge master into features
2016-05-24 11:09:33 -03:00
Ronny Pfannschmidt
16794feaf6 Merge branch 'master' into merge-master 2016-05-24 08:15:10 +02:00
Ronny Pfannschmidt
436e13ac25 Merge pull request #1566 from nicoddemus/fix-win32-path
Fix shell argument split in win32
2016-05-24 08:14:01 +02:00
Bruno Oliveira
9fb5ddf778 Fix shell argument split in win32
This fixes the bug inserted by accident in #1523
2016-05-23 20:41:47 -03:00
Bruno Oliveira
5ab5a11544 Merge pull request #1565 from tomviner/issue1544/ignore-build-dist-dirs
Issue 1544: norecursedirs build & dist dirs
2016-05-23 19:30:20 -03:00
Ronny Pfannschmidt
26b526967e merge from master again 2016-05-23 22:33:00 +02:00
TomV
d6dfb1a393 issue 1544: norecursedirs build & dist dirs 2016-05-23 21:02:29 +01:00
Ronny Pfannschmidt
85393d34b6 Merge pull request #1561 from AbdealiJK/ajk/1558_feature
unittest.UnitTestCase: Allow __test__ for methods
2016-05-19 10:17:28 +02:00
Ronny Pfannschmidt
be7a86270c Merge pull request #1541 from RonnyPfannschmidt/document-1540
Document #1540
2016-05-19 10:15:33 +02:00
AbdealiJK
d4c9fa9f1a unittest.UnitTestCase: Allow __test__ for methods
__test__ needs to be checked for methods of a class too. Earlier,
this was not done, and all methods in a class was assumed to be
a test. This commit adds the appropriate condition to ensure that
if the __test__ is set to False, it does not collect that method.

Fixes https://github.com/pytest-dev/pytest/issues/1558
2016-05-19 08:19:57 +05:30
Ronny Pfannschmidt
ec5e05834f fix typo 2016-05-18 21:35:31 +02:00
Ronny Pfannschmidt
6f98cd6faa Merge pull request #1560 from nicoddemus/fix-py26-tox-comment
Move comment in tox.ini due to recent bug in pip
2016-05-18 21:31:56 +02:00
Bruno Oliveira
561a5fb558 Move comment in tox.ini due to recent bug in pip
As discussed in #1554

* https://bitbucket.org/hpk42/tox/issues/332/
* https://github.com/pypa/pip/issues/3667
2016-05-18 16:15:29 -03:00
Bruno Oliveira
47739291cf Merge pull request #1557 from adamchainz/readthedocs.io
Convert readthedocs link for their .org -> .io migration for hosted projects
2016-05-18 13:24:03 -03:00
Adam Chainz
8a39869347 Convert readthedocs link for their .org -> .io migration for hosted projects
As per their email ‘Changes to project subdomains’:

> Starting today, Read the Docs will start hosting projects from subdomains on the domain readthedocs.io, instead of on readthedocs.org. This change addresses some security concerns around site cookies while hosting user generated data on the same domain as our dashboard.

Test Plan: Manually visited all the links I’ve modified. One was not modified - `http://media.readthedocs.org/epub/pytest/latest/pytest.epub` - since it doesn't work on `readthedocs.io`.
2016-05-18 17:12:39 +01:00
Ronny Pfannschmidt
eab762ea99 Merge branch 'master' into merge-master 2016-05-13 19:37:41 +02:00
Ronny Pfannschmidt
c49863aa63 merge next chunk from master and fix changelog linting issue 2016-05-13 19:36:47 +02:00
Ronny Pfannschmidt
01d2ff804b Merge commit '56156bb119194014129ac08c4a2c370f0b893104' into merge-master 2016-05-13 17:55:02 +02:00
Ronny Pfannschmidt
68f658b6cc Merge commit '890c2fa555314a67a8d97a1b8ea4881a14be69c4' into merge-master 2016-05-13 17:52:59 +02:00
Ronny Pfannschmidt
4bde70d060 Merge commit 'ec62a3c9e47c3b5b07aa1656815145ffa2882a09' into merge-master 2016-05-13 17:40:14 +02:00
Ronny Pfannschmidt
8a94c66e68 Merge pull request #1551 from fushi/master
Fix #1549 - count skips in junit-xml
2016-05-05 22:03:30 +02:00
John Towler
0d07b64571 Fixes Issue 1549 2016-05-05 11:29:05 -07:00
Ronny Pfannschmidt
98dd2ce75c document reason for #1540 2016-04-28 16:22:31 +02:00
Ronny Pfannschmidt
308e76e19c add xfailing test for #1540 2016-04-28 16:11:30 +02:00
Florian Bruhin
60212e8831 Merge pull request #1537 from ben4ever/patch-1
Fix typo in doc
2016-04-27 22:13:51 -07:00
Benjamin Dopplinger
75abfbe8d4 Fix typo in doc 2016-04-28 14:40:17 +10:00
Ronny Pfannschmidt
6cc56b4a1b Merge pull request #1535 from palaviv/parametrize-test-ids-hook
introduce pytest_make_parametrize_id hook
2016-04-27 16:16:16 +02:00
palaviv
9733127951 pytest_make_parametrize_id receive config object 2016-04-26 10:23:57 +03:00
Bruno Oliveira
fdee88f086 Merge pull request #1520 from omarkohl/invalid_test_module_name
Raise CollectError if import test module fails
2016-04-25 21:42:41 -03:00
palaviv
53429ed8b8 Added hook to plugin docs and new CHANGELOG record 2016-04-25 18:03:34 +03:00
palaviv
b9faf78d51 Added test_pytest_make_parametrize_id 2016-04-25 17:48:28 +03:00
palaviv
79927428d1 Added pytest_make_parametrize_id hook 2016-04-25 17:11:47 +03:00
Omar Kohl
56855893ca Raise CollectError if import test module fails
One of the reasons for failing to import the test module is invalid Python
identifiers in the full package path of the test module.

fix #1426
2016-04-23 13:50:48 +02:00
Ronny Pfannschmidt
52babba33e Update sprint 2016 2016-04-23 08:56:28 +02:00
Bruno Oliveira
8552860a9b Merge pull request #1532 from RibeiroAna/features
Update sprint2016.rst :)
2016-04-23 01:05:25 -03:00
Ana Ribeiro
f02f72e651 Update sprint2016.rst 2016-04-23 00:11:44 -03:00
Ronny Pfannschmidt
6d661ace0a Merge pull request #1523 from MengJueM/master 2016-04-20 16:55:31 +02:00
MengJueM
f51c34ef31 Add changelog 2016-04-20 22:32:35 +08:00
Ronny Pfannschmidt
b220c96bf8 Merge pull request #1526 from The-Compiler/tracebackhide
Filter selectively with __tracebackhide__
2016-04-20 13:07:02 +02:00
Florian Bruhin
aa87395c39 Use py.builtin.callable
This restores compatibility with Python 3.0/3.1
2016-04-20 11:18:47 +02:00
Florian Bruhin
75160547f2 Use a callable __tracebackhide__ for filtering
While this leads to slightly more complicated user code for the common
case (checking if the exception is of a given type) it's easier to
implement and more flexible.
2016-04-20 11:09:27 +02:00
Florian Bruhin
4c552d4ef7 Fix tests for python 2.6 2016-04-20 10:36:13 +02:00
Florian Bruhin
b607f6728f Filter selectively with __tracebackhide__
When __tracebackhide__ gets set to an exception type or list/tuple of
exception types, only those exceptions get filtered, while the full
traceback is shown if another exception (e.g. a bug in a assertion
helper) happens.
2016-04-20 10:25:33 +02:00
Ronny Pfannschmidt
a986b8f945 Merge pull request #1525 from The-Compiler/traceback-item
Fix TracebackItem documentation in pytest.code
2016-04-20 09:38:03 +02:00
Florian Bruhin
c24e8e01b4 Fix TracebackItem documentation in pytest.code
The TracebackItem class does not exist, but it seems the docstrings refer to
TracebackEntry.
2016-04-20 08:35:17 +02:00
MengJueM
1a37035d71 Add test test_absolute_win32_path 2016-04-20 01:27:37 +08:00
TomV
99c4b6fdc3 issue 1496 - xfail with condition keyword 2016-04-19 18:12:37 +01:00
Meng Jue
dd2425675b Fix a small issue about shlex.split not working well with win32 path 2016-04-19 13:08:08 +08:00
Bruno Oliveira
6a3c943ce2 Merge pull request #1514 from The-Compiler/docfix
doc: Use ascii chars for file tree
2016-04-13 19:13:53 -03:00
Florian Bruhin
98430a17f2 doc: Use ascii chars for file tree
LaTeX doesn't like those particular unicode chars, so let's avoid them so the
PDF builds easily.
2016-04-13 23:38:58 +02:00
Bruno Oliveira
fe6e1b2059 Merge pull request #1506 from prusse-martin/fix-repr-tb-with-unicode
Fix `repr_traceback` to work with unicode errors
2016-04-09 13:03:55 -03:00
Martin Prusse
7ce5873da2 Perform a "unicode aware" check for maximum recursion depth error
Avoid errors `UnicodeErrosr`s due non maximum recursion depth errors
when checking for those errors.
2016-04-08 23:32:18 -03:00
Ronny Pfannschmidt
0eb80bcb5a Merge pull request #1504 from guettli/patch-1
Hudson -> Jenkins
2016-04-05 14:57:03 +02:00
Thomas Güttler
fb45f82840 Hudson -> Jenkins 2016-04-05 14:08:30 +02:00
Ronny Pfannschmidt
0f7aeafe7c Merge pull request #1486 from roolebo/fix-issue-138
Fix issue #138 - support chained exceptions
2016-04-03 19:21:57 +02:00
Bruno Oliveira
e3bc6faa2b Merge pull request #1470 from ceridwen/features
Escape both bytes and unicode strings for "ids" in Metafunc.parametrize
2016-04-03 13:48:30 -03:00
Bruno Oliveira
909d72b474 Merge pull request #1502 from omarkohl/excinfo_match
Implement ExceptionInfo.match() method
2016-04-03 13:48:12 -03:00
Omar Kohl
0c38aacc33 Add self to AUTHORS 2016-04-03 11:23:30 +02:00
Omar Kohl
c578226d43 Implement ExceptionInfo.match() to match regexp on str(exception)
This implements similar functionality to
unittest.TestCase.assertRegexpMatches()

closes #372
2016-04-03 11:22:44 +02:00
Ceridwen
23a8e2b469 Add .hypothesis to .gitignore and try an older version of Hypothesis for 2.6 2016-04-02 11:47:37 -04:00
Ceridwen
08671fcf4a Fix the changelog and dependencies for tox 2016-04-02 10:52:28 -04:00
Ceridwen
491b30c5d9 Add Hypothesis test for _idval and fix bug it found 2016-04-01 22:45:44 -04:00
Ceridwen
b631fc0bc1 Fix test_escaped_parametrized_names_xml 2016-04-01 21:30:45 -04:00
Bruno Oliveira
5af5ba11d3 Merge pull request #1500 from tgoodlet/lstrip-keywordexpr
Always lstrip() keyword expression
2016-04-01 17:48:58 -03:00
Tyler Goodlet
053c052190 Always lstrip() keyword expression 2016-04-01 13:10:05 -04:00
Ceridwen
9b438d56e8 Fix a test_unicode_idval_python2 (now test_unicode_idval) and associated string handling on Python 3 2016-04-01 12:27:17 -04:00
Bruno Oliveira
56156bb119 Merge pull request #1490 from omarkohl/get_issues
Adapt get_issues.py script for GitHub (instead of Bitbucket)
2016-03-28 20:15:29 -03:00
Omar Kohl
e048315d9b Adapt get_issues.py script for GitHub (instead of Bitbucket) 2016-03-28 20:00:57 +02:00
Roman Bolshakov
89df701ae9 Comment a workaround for #1485. 2016-03-27 13:15:56 +03:00
Bruno Oliveira
fed89ef549 Merge pull request #1474 from palaviv/improve-idmaker-duplicate-names
Improve idmaker name selection in case of duplicate ids in parametrize
2016-03-23 20:38:29 -03:00
palaviv
3ffce6ae4a Added thanks and PR links in changlog 2016-03-23 18:53:50 +02:00
palaviv
c66aedfa65 checking first there are duplciates ids before changing to unique names 2016-03-23 18:47:27 +02:00
Florian Bruhin
3155d0ca9c Merge pull request #1475 from nicoddemus/classifier-docs
Mention Pytest::Framework PyPI classifier on docs
2016-03-23 06:12:34 +01:00
Bruno Oliveira
53d319144d Mention Pytest::Framework PyPI classifier on docs 2016-03-22 20:42:52 -03:00
palaviv
412042d987 added entry to CHANGELOG 2016-03-23 00:21:24 +02:00
palaviv
b8c15a0215 improved idmaker name selection in case of duplicate ids 2016-03-23 00:20:58 +02:00
Ceridwen
1f46015de5 Merge remote-tracking branch 'upstream/features' into features 2016-03-22 16:22:00 -04:00
Ronny Pfannschmidt
6ddfd60ce7 Merge pull request #1472 from pquentin/master
Fix pytest.mark.skip mark when used in strict mode
2016-03-22 13:49:57 +01:00
Quentin Pradet
653a53226a Add strict parameter to xfail marker doc 2016-03-22 16:01:51 +04:00
Quentin Pradet
1fbd19b8cb Fix pytest.mark.skip mark when used in strict mode 2016-03-22 15:40:34 +04:00
Ceridwen
4405dd0ffe Escape both bytes and unicode strings for "ids" in Metafunc.parametrize 2016-03-22 01:31:48 -04:00
Ronny Pfannschmidt
890c2fa555 Merge pull request #1469 from omarkohl/doc-fixes
Doc fixes
2016-03-20 20:48:36 +01:00
Omar Kohl
725290a8ab Add 'Minor doc fixes' to CHANGELOG 2016-03-20 20:39:31 +01:00
Ronny Pfannschmidt
da1045151f Merge pull request #1468 from palaviv/allow-none-as-parametrized-test-id
None in paramtrized test id will use automatically generated id
2016-03-20 20:19:50 +01:00
Omar Kohl
98c707561c Document --full-trace option and KeyboardInterrupt
fix #513
2016-03-20 20:07:16 +01:00
Omar Kohl
a341dddc74 Replace --fulltrace with --full-trace in doc
Since 'py.test --help' shows --full-trace as an option (and not --fulltrace)
even though both forms are accepted I assume --full-trace is the preferred form
and should therefore be used in the documentation.
2016-03-20 19:51:23 +01:00
palaviv
dd384f7f78 Added changlog entries 2016-03-20 19:01:47 +02:00
palaviv
7885e43b78 Merge remote-tracking branch 'upstream/features' into allow-none-as-parametrized-test-id 2016-03-20 18:57:17 +02:00
palaviv
32f44ce2fd updated parametrize documentation 2016-03-20 18:54:48 +02:00
Omar Kohl
16e49d96d1 Replace --traceconfig with --trace-config in doc
Since 'py.test --help' shows --trace-config as an option (and not
--traceconfig) even though both forms are accepted I assume --trace-config is
the preferred form and should therefore be used in the documentation.
2016-03-20 17:12:50 +01:00
Omar Kohl
ec62a3c9e4 Fix minor typo in 'writing plugins' doc 2016-03-20 17:01:04 +01:00
Omar Kohl
f70ed83479 Fix 'test grouping by fixture instances' doc example
The fin() function was never added as a finalizer and did therefore not print
anything in the captured output.

In general improve the output by making it more verbose/explicit and extend the
final explanation.
2016-03-20 15:53:32 +01:00
Omar Kohl
dff914cadd Add short explanation and link to yield fixtures in fixture doc 2016-03-20 14:10:20 +01:00
Omar Kohl
3135463573 No longer refer to the 'yield fixture mechanism' as experimental (doc)
The feature has been there for a long time and in the 2.7.1 release notes it
says:

> fixed docs to remove the notion that yield-fixtures are experimental.

Therefore this one place was probably just missed.
2016-03-20 13:54:56 +01:00
Omar Kohl
266b53dfc2 Add Jenkins xUnit Plugin link to doc 2016-03-20 13:39:10 +01:00
Omar Kohl
bdb3581a52 Fix minor mistake in test discovery doc
The example output shown was for Python3 not Python2.

Add Python2 output and rephrase for clarity.
2016-03-20 13:24:43 +01:00
Omar Kohl
27b62740e3 Fix minor mistake in usage doc (pkg instead of pypkg) 2016-03-20 12:47:17 +01:00
Roman Bolshakov
52bc2f8616 Update authors & changelog 2016-03-20 01:06:53 +03:00
Roman Bolshakov
a736e26734 Merge remote-tracking branch 'pytest-dev/master' into fix-issue-138 2016-03-20 01:04:22 +03:00
Roman Bolshakov
fbc5ba08d9 Fix issue #138 2016-03-20 01:02:17 +03:00
palaviv
4b0237c8ee added test for unique names when recievieng identical ids in parametrize 2016-03-19 21:42:47 +02:00
palaviv
877ca5a0bf added test for None in paramtrized ids list 2016-03-19 21:38:24 +02:00
palaviv
a8cfd54871 added test for None in idmaker 2016-03-19 21:23:49 +02:00
palaviv
be1954afbc allow None to be passed in ids list for specific test and recieve idmaker name for test 2016-03-19 21:22:49 +02:00
Bruno Oliveira
2cfcf12d09 Merge pull request #1466 from nicoddemus/merge-master-into-features
Merge master into features after 2.9.1 release
2016-03-18 23:45:14 -03:00
Bruno Oliveira
5fcce8a7d6 Merge branch 'master' into merge-master-into-features 2016-03-18 18:26:56 -03:00
Bruno Oliveira
a70e92777f Bump version to 2.9.2.dev1 2016-03-18 18:24:24 -03:00
Bruno Oliveira
3c011c05db Merge pull request #1460 from nicoddemus/release-2.9.1
Release 2.9.1
2016-03-18 18:22:21 -03:00
nicoddemus
168daaa71f Regendocs 2016-03-17 17:13:41 -04:00
nicoddemus
43fc1b47c0 Add announce doc 2016-03-17 17:10:02 -04:00
nicoddemus
699f094b0c Finalize CHANGELOG for 2.9.1 2016-03-17 17:04:26 -04:00
nicoddemus
9bdf51fcc5 Bump version to 2.9.1 2016-03-17 17:03:46 -04:00
Ronny Pfannschmidt
1d23999033 Merge pull request #1458 from The-Compiler/talks
Update talks page
2016-03-17 09:09:35 +01:00
Florian Bruhin
1d35a03812 Update talks page 2016-03-17 06:37:49 +01:00
Bruno Oliveira
ceacc12b52 Merge pull request #1454 from tareqalayan/add-global-properties-node
junitxml: add properties node in testsuite level
2016-03-16 18:21:51 -03:00
Tareq Alayan
fa6acdcfd4 junitxml: add properties node in testsuite level
The commit allow users to add a properties node in testsuite level see
example below:

<testsuite errors="0" failures="0" name="pytest" skips="1" tests="1"
time="11.824">
  <properties>
    <property name="ARCH" value="PPC"/>
    <property name="OS" value="RHEL 7.2"/>
    <property name="TestPlanURL" value="https://url.."/>
    <property name="Automated" value="True"/>
  </properties>
  <testcase classname="git.....>
  </testcase>
</testsuite>

The current situation is that properties node can be added to every
testcase node. However, sometimes we need some global properties that
applies to all testcases and give better description for the testsuite
itself.
2016-03-16 13:24:33 +02:00
Ronny Pfannschmidt
d70596da91 Merge pull request #1452 from palaviv/specify-paramterized-node-in-command-line
Specify paramterized node in command line - fixes #649
2016-03-16 11:16:54 +01:00
palaviv
a1277aaf0e added TODO comment to remove the parametrized workaround 2016-03-15 23:42:25 +02:00
Ronny Pfannschmidt
5fd82078ad Merge pull request #1441 from kalekundert/features
Add a convenience function for floating-point comparisons
2016-03-15 07:45:07 +01:00
Kale Kundert
5ceee08590 Fix CHANGELOG merge conflicts. 2016-03-14 11:55:50 -07:00
Kale Kundert
0dcc862a56 Fix some typos in the documentation. 2016-03-14 11:38:00 -07:00
Kale Kundert
9e7206a1cf Fix a few stylistic issues. 2016-03-14 11:29:45 -07:00
Ronny Pfannschmidt
19cec79363 Merge pull request #1451 from blueyed/fix-doc-pytest_load_initial_conftests
docs: sort arguments for pytest_load_initial_conftests
the change is purely cosmetic, but its nice to have them ordered by name
2016-03-14 14:14:22 +01:00
Ronny Pfannschmidt
0cacdef6c5 Merge pull request #1444 from novas0x2a/fixture-custom-name
Allow custom fixture names for fixtures
2016-03-14 14:08:02 +01:00
palaviv
981fcb2798 added CHANGELOG and AUTHORS entry 2016-03-13 23:47:41 +02:00
palaviv
1ee3d40dbe allow parametrized nodes to be specified from command line 2016-03-13 23:37:21 +02:00
Kale Kundert
861265411f Add "thanks" line to the CHANGELOG. 2016-03-12 22:15:19 -08:00
Daniel Hahler
bdddc9c38b doc: fix argument order for pytest_load_initial_conftests 2016-03-12 17:35:27 +01:00
Kale Kundert
916c0a8b36 Fix Decimal() and __ne__() errors. 2016-03-11 16:29:18 -08:00
Kale Kundert
078448008c Discuss alternative float comparison algorithms. 2016-03-11 15:59:48 -08:00
Bruno Oliveira
b46c7dddaa Fix 'check' in markdown for github templates 2016-03-11 18:22:15 -03:00
Kale Kundert
42a7e0488d Properly handle inf, nan, and built-in numeric types.
This commit also:

- Dramatically increases the number of unit tests , mostly by borrowing
  from the standard  library's unit tests for math.isclose().

- Refactors approx() into two classes, one of which handles comparing
  individual numbers (ApproxNonIterable) and another which uses the
  first to compare individual numbers or sequences of numbers.
2016-03-11 08:49:26 -08:00
Ronny Pfannschmidt
4636bf6160 Merge pull request #1391 from malinoff/issue1342
LastFailed now creates .cache only when needed. Fixes #1342
2016-03-11 11:18:50 +01:00
Dmitry Malinovsky
52a5acda92 Use testscollected to make xdist happy 2016-03-11 14:48:17 +06:00
Florian Bruhin
2b0ad4630d Merge pull request #1443 from nicoddemus/improve-import-error-msg
Improve error message when a plugin fails to import
2016-03-11 06:10:58 +01:00
Bruno Oliveira
3ea987ef9d Copy over name and path attributes to the re-raised exception 2016-03-10 18:13:59 -03:00
Mike Lundy
9577120592 Allow custom fixture names for fixtures
When defining a fixture in the same module as where it is used, the
function argument shadows the fixture name, which a) annoys pylint and
b) can lead to bugs where you forget to request a fixture into a test
method.

This allows one to define fixtures with a different name than the name
of the function, bypassing that problem.
2016-03-09 14:58:54 -08:00
Bruno Oliveira
7a186df271 Improve error message when a plugin fails to import 2016-03-08 19:18:13 -03:00
Kale Kundert
7d155bd3cf Fix sys.version_info errors. 2016-03-08 10:12:31 -08:00
Kale Kundert
6a902924f8 Fix trailing whitespace errors. 2016-03-07 19:56:23 -08:00
Kale Kundert
c9c73b8d8e Fix zero-length field name error in python2.6 2016-03-07 19:54:43 -08:00
Kale Kundert
4d0f066db7 Add approx() to the CHANGELOG. 2016-03-07 18:29:22 -08:00
Kale Kundert
5dab0954a0 Add approx() to the Sphinx docs. 2016-03-07 18:14:49 -08:00
Kale Kundert
b8a8382c2c Reduce the default absolute error threshold to 1e-12. 2016-03-07 16:43:53 -08:00
Kale Kundert
bf97d5b817 Use the plus/minus unicode symbol in the repr string.
This was a challenge because it had to work in python2 and python3,
which have almost opposite unicode models, and I couldn't use the six
library.  I'm also not sure the solution I found would work in python3
before python3.3, because I use the u'' string prefix which I think was
initially not part of python3.
2016-03-07 16:40:41 -08:00
Kale Kundert
dd28e28b34 Make a few stylistic improvements. 2016-03-07 10:10:54 -08:00
Kale Kundert
6f5e1e386a Add a convenient and correct way to compare floats. 2016-03-07 10:10:54 -08:00
Ronny Pfannschmidt
6d4b14d7ee Merge pull request #1438 from Bachmann1234/issue-1437
Make a good faith effort to display a bytestring when one is provided…
2016-03-06 06:48:32 +01:00
Ronny Pfannschmidt
fd0010e6e9 Merge pull request #1439 from pytest-dev/fix-1178
Support pytest.fail with non-ascii characters

Fixes #1178
2016-03-06 06:42:35 +01:00
Matt Bachmann
8ce32b0795 When a regex pattern contains bytes instead of a string use escape_encode to turn it into a string before further processing. Thanks @nicoddemus for the review and tips! 2016-03-05 21:04:34 -05:00
Bruno Oliveira
5d4703852e Add test when using native strings with non-ascii chars 2016-03-05 19:34:15 -03:00
Ronny Pfannschmidt
9b51536a18 Merge pull request #1440 from nicoddemus/issue-578
Fix decoding issue while formatting SyntaxErrors during collection
2016-03-05 21:47:44 +01:00
Bruno Oliveira
d8403d793f Fix decoding issue while formatting SyntaxErrors during collection
This happens only in Python 2, as in Python 3 we receive
the "badline" in the exception is already properly encoded

Fix #578
2016-03-05 16:58:50 -03:00
Bruno Oliveira
24d3e01548 pytest.fail with non-ascii characters raises an internal pytest error
Fix #1178
2016-03-05 16:09:01 -03:00
Ronny Pfannschmidt
3884398055 Merge pull request #1433 from nicoddemus/issue-1427
Mention that pytest_addoption may be used from conftest files

fixes #1427
2016-03-04 10:48:43 +01:00
Bruno Oliveira
819e0ead44 Mention that pytest_addoption may be used from conftest files
fix #1427
2016-03-03 18:26:01 -03:00
Bruno Oliveira
c8ca1d12d7 Merge pull request #1432 from tomviner/issue469-junit-double-colon
issue469: junit parsing nodeid, add method test
2016-03-03 08:03:27 -03:00
TomV
3d2b7aeea5 issue469: junit parsing nodeid, add method test 2016-03-03 09:12:56 +00:00
Ronny Pfannschmidt
7aa7c6bbfd Merge pull request #1431 from tomviner/issue469-junit-double-colon
fix #469 - correctly mangle junit test names when double colons are in parameter id's
2016-03-03 08:45:30 +01:00
Bruno Oliveira
c2b9196a7c Merge remote-tracking branch 'upstream/master' into features 2016-03-02 23:41:56 -03:00
Bruno Oliveira
4a76b2e9b6 Merge branch 'doctest_namespace_inject' into features 2016-03-02 23:38:51 -03:00
Bruno Oliveira
28937a5cd9 Add versionadded directive to doctest_namespace section 2016-03-02 23:37:51 -03:00
Bruno Oliveira
2e02a1c370 Give proper credit for PR #1428 2016-03-02 23:30:42 -03:00
TomV
28530836c9 issue469: add fix junit double colon split issue 2016-03-02 22:18:57 +00:00
Bruno Oliveira
055f1dc9ea Merge pull request #1430 from vovanbo/patch-1
Reformat versions and header levels in CHANGELOG file
2016-03-02 16:23:55 -03:00
Vladimir Bolshakov
0cbd58e16a Reformat versions and header levels in CHANGELOG file 2016-03-02 22:07:30 +03:00
Bruno Oliveira
b7b863b7bf Merge pull request #1429 from Zearin/patch-1
Minor README tweaks (markup, phrasing)
2016-03-02 15:37:12 -03:00
Zearin
4bcc06362d Minor README tweaks (markup, phrasing) 2016-03-02 11:59:04 -05:00
Matt Williams
6dd2ff5332 Correct indentation in documentation 2016-03-02 13:02:15 +00:00
Matt Williams
891e029518 Add a new doctest_namespace fixture
This fixture can be used to inject names into the namespace in which
your doctests run.
2016-03-02 12:43:57 +00:00
Bruno Oliveira
316e39872a Add 2.9.1.dev1 to CHANGELOG 2016-03-01 18:55:53 -03:00
Bruno Oliveira
5a2500800d Add 2.10.0.dev1 to CHANGELOG 2016-03-01 18:54:08 -03:00
Bruno Oliveira
c8c5a416ef Bump version to 2.10.0.dev1 2016-03-01 18:48:13 -03:00
Bruno Oliveira
81af1c024a Bump version to 2.9.1.dev1 2016-03-01 18:46:17 -03:00
Bruno Oliveira
e656dbb602 Merge branch 'release-290' 2016-03-01 18:45:33 -03:00
Floris Bruynooghe
63b69326b8 Add company name to flub in sprint attendees 2016-03-01 10:17:31 +00:00
nicoddemus
19d05814d2 Fix reference to _CallOutcome in docs 2016-02-29 17:09:31 -05:00
nicoddemus
7d2b65813e Fix typo in CHANGELOG 2016-02-29 16:48:28 -05:00
nicoddemus
f82c03833f Regendocs 2016-02-29 15:52:56 -05:00
nicoddemus
486421fca2 Release announcement for 2.9.0 2016-02-29 15:47:23 -05:00
nicoddemus
2d7cfcd686 Finalize CHANGELOG 2016-02-29 15:42:15 -05:00
nicoddemus
623e786524 Bump version to 2.9.0 2016-02-29 15:39:00 -05:00
Bruno Oliveira
5c09b33150 Merge pull request #1423 from lukas-bednar/junit_properties
junit: allow multiple properties with same name
2016-02-29 15:35:03 -03:00
Lukas Bednar
7e758a9dc6 junit: allow multiple properties with same name
It might happen that test can be affected by two or more bugs.
I need to be able to track them all.
2016-02-29 16:00:26 +01:00
Bruno Oliveira
3445bdaca2 Merge pull request #1418 from hackebrot/update-sprint-info
Add company name sprint doc
2016-02-27 19:48:36 -03:00
Raphael Pierzina
89151b8c63 Add company name to @hackebrot in sprint attendees 2016-02-27 22:15:07 +00:00
Bruno Oliveira
4194ddd5b4 Merge pull request #1417 from hackebrot/fix-docs-on-traceback-styles
Fix docs on traceback styles
2016-02-27 18:28:57 -03:00
Raphael Pierzina
ab90043adc Update changelog with traceback style docs fix 2016-02-27 21:07:13 +00:00
Raphael Pierzina
a95fe3693b Add auto to tb styles (new default since v2.6) 2016-02-27 20:54:44 +00:00
Bruno Oliveira
b64aaac7ec Merge pull request #1416 from blubber/fix-mark-documentation
Fix a typo in the docstring for mark.MarkGenerator
2016-02-27 11:58:43 -03:00
Tiemo Kieft
424b46de1b Fix a typo in the docstring for mark.MarkGenerator 2016-02-27 14:15:42 +01:00
Florian Bruhin
c9927bb66f Merge pull request #1414 from rygwdn/indexerror
catch IndexError exceptions when getting exception source location
2016-02-26 18:53:10 +01:00
Florian Bruhin
cbb5d48fdd Merge pull request #1413 from nicoddemus/skip-if-parametrize
Fix skip/xfail markers in parametrized arguments
2016-02-26 18:41:37 +01:00
Ryan Wooden
d98d655094 Simplify IndexError test. 2016-02-26 08:25:49 -04:00
Anatoly Bubenkov
cf9a09e988 catch IndexError exceptions when getting exception source location 2016-02-26 08:18:12 -04:00
Bruno Oliveira
d9ede1bac2 Add test for unconditional skip with reason 2016-02-25 20:02:34 -03:00
Bruno Oliveira
5f90907509 Fix skip/xfail markers in parametrized arguments
Fix #1412
2016-02-25 19:13:09 -03:00
Bruno Oliveira
310bada6f5 Merge pull request #1409 from nicoddemus/builtin-fixtures-docs
Add reference to some builtin fixtures in "contents"
2016-02-25 15:46:33 -03:00
Bruno Oliveira
08b40396c9 Merge pull request #1400 from nicoddemus/contributing-improvements
Contributions to CONTRIBUTING.rst
2016-02-25 15:46:04 -03:00
holger krekel
a50209b29e add some more people, and preliminary company affiliations 2016-02-25 06:50:19 +01:00
Bruno Oliveira
a7b907d325 Add Raphael Pierzina to AUTHORS 2016-02-23 20:29:08 -03:00
Bruno Oliveira
c78a8b28dc Add reference to some builtin fixtures in "contents"
Fix #1408
2016-02-23 17:26:24 -03:00
Bruno Oliveira
3a6a0f1220 Merge pull request #1410 from milliams/master
Correct JUnit test invocation example
2016-02-23 08:06:21 -03:00
Matt Williams
fc4e240596 Correct JUnit test invocation example 2016-02-23 10:05:51 +00:00
holger krekel
5507a4d239 Merge pull request #1405 from nicoddemus/collection-atty
Display collect progress only when in a terminal
2016-02-21 08:17:35 +01:00
Bruno Oliveira
01479189a5 Merge pull request #1406 from lwm/fix-typo
fix typo
2016-02-20 20:49:58 -02:00
Luke Murphy
ddb7060535 fix typo 2016-02-20 23:44:55 +01:00
Bruno Oliveira
96a331e32f Display collect progress only when in a terminal
Fix #1397
2016-02-20 14:38:30 -02:00
Bruno Oliveira
688622f5cf Code review suggestions 2016-02-19 18:27:33 -02:00
Bruno Oliveira
fa7b0086a2 Move sections around (from easier to hardest) and added howto for repo transfers
#1282
2016-02-18 19:17:06 -02:00
Ronny Pfannschmidt
3874d53ee1 Merge pull request #1399 from nicoddemus/master
Add issue and PR GitHub templates
2016-02-18 21:38:50 +01:00
Bruno Oliveira
b76de91474 Add issue and PR GitHub templates 2016-02-18 18:26:38 -02:00
Bruno Oliveira
6940f82235 Merge pull request #1389 from nicoddemus/fix-strict-xfail
Fix bug in strict xfail: test was not being actually called
2016-02-17 17:58:49 -02:00
Bruno Oliveira
f6a2f779ae Merge pull request #1393 from hackebrot/add-license-section-to-homepage
Add license section to homepage
2016-02-17 17:53:49 -02:00
Raphael Pierzina
19536c9f05 Add full MIT license text to the docs section 2016-02-17 00:54:54 +00:00
Raphael Pierzina
e4c1b9c1c4 Add link to license page to index.rst 2016-02-17 00:47:49 +00:00
Raphael Pierzina
25aed0dca8 Add a license section to the docs toc 2016-02-16 19:42:16 +00:00
Raphael Pierzina
b2f837acd8 Add a reference to LICENSE file to README 2016-02-16 19:40:06 +00:00
Raphael Pierzina
3ef003f0ff Wrap lines at 79 characters 2016-02-16 19:14:55 +00:00
Raphael Pierzina
baabde76ae Insert copyright holders and year as mentioned in README 2016-02-16 19:13:39 +00:00
Raphael Pierzina
c805412d47 Grab official MIT license text from opensource.org 2016-02-16 19:12:22 +00:00
Dmitry Malinovsky
e4d361b093 LastFailed now creates .cache only when needed. Fixes #1342 2016-02-16 11:42:04 +06:00
Bruno Oliveira
bed56e504a Merge pull request #1390 from tomviner/bugfix/docs-typo-plugins
Fix usage of backticks in ReStructured Text files
2016-02-15 22:14:05 -02:00
TomV
3dd50d039d Fix rst syntax 2016-02-15 23:07:31 +00:00
Bruno Oliveira
0eeb466f11 Fix strict xfail: it should behave exactly like xfail when a test fails 2016-02-15 19:18:48 -02:00
Bruno Oliveira
ee88679c54 Fix bug in strict xfail: test was not being actually called 2016-02-15 18:43:45 -02:00
Bruno Oliveira
9af1f63ab6 Small typo in CHANGELOG 2016-02-14 23:36:17 -02:00
Bruno Oliveira
fb7bbf816c Merge branch 'strict-xpass' 2016-02-14 23:35:03 -02:00
Bruno Oliveira
9aae4b782b Add CHANGELOG entry for #1355 2016-02-14 23:31:31 -02:00
Ronny Pfannschmidt
1d190dc618 Merge pull request #1386 from nicoddemus/strict-xpass
Add a "strict" parameter to xfail
2016-02-15 02:29:43 +01:00
Bruno Oliveira
7823838e69 Add strict option to xfail, making tests which XPASS to actually fail the suite
Fix #1355
2016-02-14 20:52:27 -02:00
Bruno Oliveira
a965386b9e Add bool type to addini 2016-02-14 20:52:27 -02:00
Bruno Oliveira
6f0d90cd5a Merge pull request #1385 from RonnyPfannschmidt/release-process-update
update release process to ensure correct usage of base branches and p…
2016-02-14 00:54:25 -02:00
Ronny Pfannschmidt
48424a6bf6 update release process to ensure correct usage of base branches and propper finalization 2016-02-13 20:30:58 +01:00
holger krekel
2a8d58814a Merge pull request #1384 from hpk42/master
trying to settle the new layout
2016-02-13 16:56:44 +01:00
holger krekel
fa601de5c4 update participants 2016-02-13 16:55:16 +01:00
holger krekel
8284d14ec4 re-introduce topics 2016-02-13 16:54:06 +01:00
holger krekel
238dcd8bae some layout refinements 2016-02-13 14:30:10 +01:00
holger krekel
b95ff7104c Merge branch 'master' of https://github.com/pytest-dev/pytest
removed doc/en/announce/sprint-funding-2016.txt
because /doc/en/announnce/sprint2016.txt is the one which
we published.
2016-02-13 14:18:05 +01:00
holger krekel
03f8b50c8a Merge pull request #1383 from RonnyPfannschmidt/founding-header
give the founding header contrast
2016-02-13 14:10:44 +01:00
Ronny Pfannschmidt
dc7f76c276 adapt the header text based on a discussion with bruno 2016-02-13 13:40:59 +01:00
Ronny Pfannschmidt
20bd56f4b2 give the header contrast 2016-02-13 13:24:28 +01:00
Bruno Oliveira
89c75b2c91 Fix tox doc task 2016-02-13 02:09:25 -02:00
Bruno Oliveira
341bc33ff3 Merge pull request #1380 from biern/fix-utf8-explanation
Fix formatting utf-8 error explanation
2016-02-12 19:14:50 -02:00
Bruno Oliveira
fe10057c15 Merge pull request #1382 from RonnyPfannschmidt/founding-header
add links for the funding campaign in the header and sidebar
2016-02-12 18:45:32 -02:00
Ronny Pfannschmidt
48b62e4d89 add links for the funding campaign in the header and sidebar 2016-02-12 21:14:06 +01:00
Marcin Biernat
1b431d6644 fix formatting utf-8 error explanation 2016-02-12 20:28:06 +01:00
holger krekel
b1955c7f84 Merge pull request #1374 from RonnyPfannschmidt/fix-1366
fix issue #1366 by showing a note on the --fulltrace option
2016-02-11 10:45:12 +01:00
Ronny Pfannschmidt
bfa2fadac1 fix issue #1366 by showing a note on the --fulltrace option 2016-02-10 20:27:50 +01:00
holger krekel
48109b0e60 remove superflous file 2016-02-09 15:45:51 +01:00
holger krekel
fdce2306a7 fix names once again 2016-02-09 15:44:32 +01:00
Florian Bruhin
f00577f7c4 Also fix Brianna's name. 2016-02-09 15:37:45 +01:00
Florian Bruhin
569dbeb087 Fix names properly. 2016-02-09 15:36:59 +01:00
Bruno Oliveira
c6938221ab Merge branch 'issue1290-at-operator' 2016-02-06 09:38:45 -02:00
Bruno Oliveira
2b764a0e73 Fix CHANGELOG entry to new format 2016-02-06 09:37:13 -02:00
Bruno Oliveira
51694b8295 Merge branch 'master' into issue1290-at-operator 2016-02-06 09:31:42 -02:00
Bruno Oliveira
2e04771893 Merge pull request #1358 from RonnyPfannschmidt/features
merge features into master to begin the 2.9 line
2016-02-06 00:26:30 -02:00
TomV
7d107018e8 Fix #1290: Py3.5's @ operator/assertion rewriting. 2016-02-05 23:09:57 +00:00
holger krekel
05aad5c381 fix brianna's name once again 2016-02-05 14:12:35 +01:00
holger krekel
1e0088a949 fix EUR->USD 2016-02-05 14:11:30 +01:00
holger krekel
ba3b29e831 add a link to lieve indiegogo campaign in the pytest sprint page 2016-02-05 14:04:32 +01:00
holger krekel
6218e20e88 - preliminary sprint page, not yet linked through the header
- also removed plugins_index call from tox.ini "doc" env because it's not there
2016-02-05 11:34:40 +01:00
Ronny Pfannschmidt
190a52badb correct merge misstake in appveyor.yml 2016-02-05 01:18:11 +01:00
Ronny Pfannschmidt
7b2956e10b merge latest master into features as well 2016-02-05 00:13:48 +01:00
Ronny Pfannschmidt
de1a9f574c merge from master 2016-02-05 00:10:28 +01:00
Ronny Pfannschmidt
05a26d995b Merge pull request #1354 from gdyuldin/no_raise_message
Add expected exceptions to pytest.raises fail message
2016-02-03 13:54:24 +01:00
Georgy Dyuldin
79722ae89b Add expected exceptions to 'DID NOT RAISE' msg 2016-02-03 14:12:41 +03:00
Bruno Oliveira
b5dc7d9be1 Merge pull request #1350 from pytest-dev/appveyor-pypy
Test with pypy and enable coveralls in AppVeyor
2016-02-01 19:31:48 -02:00
Bruno Oliveira
30e61f2777 Test with pypy and enable coveralls in AppVeyor
* Install pypy using chocolatey
* Enable coveralls test environment in AppVeyor
* Suggest maintaining build matrix in .travis.yml by using "tox --listenvs"

 Fix #1254
2016-02-01 17:40:30 -02:00
holger krekel
58af604f82 Merge pull request #1346 from hpk42/master
merge sprint funding draft -- please feel free to commit directly.
2016-01-30 19:13:17 +01:00
holger krekel
c0024a723d fixed name 2016-01-30 19:12:41 +01:00
holger krekel
545bf0d5a1 a few refinements 2016-01-29 15:43:15 +01:00
holger krekel
70b5d5aee9 sprint funding draft 2016-01-29 14:52:07 +01:00
Bruno Oliveira
fde44f4f30 Merge branch 'better_flag_names' of https://github.com/MichaelAquilina/pytest into features 2016-01-27 20:02:50 -02:00
Bruno Oliveira
fa4d832507 Merge branch 'better_flag_names' into features 2016-01-27 19:57:23 -02:00
Bruno Oliveira
74a68b5ec6 Add CHANGELOG and docs for #1345 2016-01-27 19:57:11 -02:00
Michael Aquilina
e35ce98f89 Add explicit flag names for failed first and last failed 2016-01-27 21:28:38 +00:00
Bruno Oliveira
dd0062c177 Dummy change to test readthedocs hook 2016-01-27 08:59:26 -02:00
Bruno Oliveira
6c37a51f95 Fix version at the top of the CHANGELOG 2016-01-27 08:28:18 -02:00
Ronny Pfannschmidt
52ac6cd7a9 Merge pull request #1199 from nicoddemus/move-pycode-to-pytest
Copy py.code code to py.test
2016-01-26 23:29:09 +01:00
Bruno Oliveira
4825678e1a Add CHANGELOG entry for py.code merge 2016-01-26 20:24:08 -02:00
Bruno Oliveira
e43eaffd93 Remove unused import 2016-01-25 23:30:53 -02:00
Bruno Oliveira
9f85d4c952 mark test_comments as xfail on pypy
while migrating this code it was noticed that this test was failing even
on the original py repository, so it was decided to xfail it and investigate
later
2016-01-25 23:18:04 -02:00
Bruno Oliveira
7a6f902f6f Drop assertionnew and assertionold from _pytest._code 2016-01-25 23:18:04 -02:00
Bruno Oliveira
a912d3745b Moved py.code code over to py.test
Fix #103
2016-01-25 23:18:04 -02:00
Ronny Pfannschmidt
f23307b06d Merge release branch into mater 2016-01-25 00:01:43 +01:00
Ronny Pfannschmidt
6c3e6401d4 begin 2.8.8 cycle 2016-01-24 23:56:56 +01:00
Ronny Pfannschmidt
3315b3a12f finalize changelog for 2.8.7 2016-01-24 23:23:15 +01:00
Ronny Pfannschmidt
64d7d00218 Prepare 2.8.7 release 2016-01-24 17:59:48 +01:00
Ronny Pfannschmidt
7c747c97ec Merge pull request #1339 from RonnyPfannschmidt/fix-1338
Fix 1338
2016-01-24 17:51:00 +01:00
Ronny Pfannschmidt
56c5db6e12 add requests dependency to tox.ini to ensure all monkeypatch tests run 2016-01-24 12:30:38 +01:00
Ronny Pfannschmidt
2d05f831fe monkeypatch: unnest handling code
this avoid python3 nested exceptions
2016-01-24 12:28:14 +01:00
Ronny Pfannschmidt
cb6181255e changelog 2016-01-24 00:45:59 +01:00
Ronny Pfannschmidt
cd9e30b221 work around python 2/3 difference by using str(exception) 2016-01-24 00:40:27 +01:00
Ronny Pfannschmidt
d028fe1e66 remove unused import 2016-01-23 20:29:54 +01:00
Ronny Pfannschmidt
b825af2e66 pass trough annotated exceptions 2016-01-23 19:31:17 +01:00
Ronny Pfannschmidt
60e9698530 fix issue 1338 2016-01-23 19:12:51 +01:00
Ronny Pfannschmidt
9e6bb74d71 reformat monkeypatch core plugin/its tests 2016-01-23 19:12:51 +01:00
Bruno Oliveira
ed3c96ee58 Merge pull request #1336 from nicoddemus/merge-master-in-features
Merge master in features
2016-01-22 19:05:34 -02:00
Bruno Oliveira
199fcf93d4 Merge branch 'master' into 'features' 2016-01-22 18:32:45 -02:00
Bruno Oliveira
c8caa87759 Merge branch 'release-2.8.6' 2016-01-22 18:00:01 -02:00
Bruno Oliveira
b7de0401b8 Bump version to 2.8.7.dev1 2016-01-22 17:59:25 -02:00
Bruno Oliveira
01793ed8bc Use a full url to pytest logo on README
So it appers correctly in PyPI
2016-01-22 17:46:28 -02:00
Bruno Oliveira
82d00efa8d 2.8.6 release: version, CHANGELOG
Remove note about expected failing envs in tox, as tox now supports
skipping certain environments based on the platform.
2016-01-21 19:17:53 -02:00
Bruno Oliveira
61c569f960 Merge branch 'junit_stdout_err_on_error' 2016-01-20 19:06:50 -02:00
Bruno Oliveira
dd56d7b7fc Add CHANGELOG and AUTHORS entry for #1334 2016-01-20 19:00:52 -02:00
Bruno Oliveira
4de3d595c9 Merge pull request #1333 from lesteve/fix-practise-typo
Fix practise -> practice typo in documentation
2016-01-20 18:03:15 -02:00
Georgy Dyuldin
b28b3cc271 Add captured stdout to jUnit report on setup error 2016-01-20 20:13:01 +03:00
Loïc Estève
99072ea8c9 Fix practise -> practice typo in documentation 2016-01-20 16:35:27 +01:00
Ronny Pfannschmidt
11a7bcaaa5 Merge pull request #1322 from nicoddemus/missing-hooks-docs
Add a few missing hooks to the docs
2016-01-19 08:12:58 +01:00
Bruno Oliveira
0caee1a673 Add a few missing hooks to the docs 2016-01-18 19:27:35 -02:00
Bruno Oliveira
4c87a6aa09 Merge pull request #1330 from nicoddemus/fix-flakes
Fix flakes
2016-01-18 15:36:20 -02:00
Bruno Oliveira
7b13c4bec0 Fix flakes 2016-01-14 21:01:57 -02:00
Bruno Oliveira
aa8c352c10 Merge pull request #1323 from jeffwidman/patch-1
Change `input` to `test_input` in docs for clarity
2016-01-12 23:28:52 -02:00
Jeff Widman
ee75ecbda0 Change input to test_input in docs for clarity
Using `input` is confusing because it's also the name of a Python built-in function. So we use `test_input` instead. Fix #1321
2016-01-12 17:01:34 -08:00
Ronny Pfannschmidt
bc32e45bb6 Merge pull request #1314 from The-Compiler/ci-verbose
Always show full comparison output if on CI.
2016-01-11 10:05:15 +01:00
Florian Bruhin
3e5c9038ec Always show full comparison output if on CI.
When you don't get enough information with a test running on a CI, it's quite
frustrating, for various reasons:

- It's more likely to be a flaky test, so you might not be able to reproduce
  the failure.
- Passing -vv is quite bothersome (creating a temporary commit and reverting
  it)

For those reasons, if something goes wrong on CI, it's good to have as much
information as possible.
2016-01-11 08:45:04 +01:00
Ronny Pfannschmidt
b2c0864fbf Merge pull request #1318 from nicoddemus/doctest-unicode-error
Fix decode error in Python 2.7 when docstrings contain a non-ascii character
2016-01-11 08:37:24 +01:00
Florian Bruhin
a80efb038a Merge pull request #1320 from bionikspoon/patch-1
update docs plugin.rst typo
2016-01-11 07:37:46 +01:00
Manu Phatak
5b29f579c5 update docs plugin.rst typo 2016-01-11 00:11:46 -06:00
Bruno Oliveira
808cb8e3ad Merge branch 'stdout-pdb-capture' 2016-01-09 11:46:13 -02:00
Bruno Oliveira
8727503dd4 Add CHANGELOG entry for #1223 2016-01-09 11:45:56 -02:00
foxx
f46de68804 Fixes bug with stdout/stderr capture on pdb 2016-01-09 12:04:26 +00:00
Bruno Oliveira
3c19cfcd9a Fix decode error in Python 2.7 when docstrings contain a non-ascii character
Fix #628
2016-01-08 23:10:02 -02:00
Bruno Oliveira
b8784c28c9 Merge branch 'master' into 'features' 2016-01-08 21:51:34 -02:00
Bruno Oliveira
29b05c8391 Merge pull request #1309 from k4rtik/patch-1
Correct platform name osx -> darwin
2016-01-05 23:29:33 -02:00
Kartik Singhal
26c835eea5 Correct platform name osx -> darwin 2016-01-05 18:43:03 -05:00
Florian Bruhin
eebf5c1d2c Merge pull request #1304 from nicoddemus/rst-changelog
Changelog now in rst format (2.9.0 and onward) and add rst-lint check
2016-01-05 14:05:53 -08:00
Bruno Oliveira
3daa0756eb Add CHANGELOG.rst to MANIFEST and small format fix 2016-01-05 20:01:41 -02:00
Bruno Oliveira
3e34db50fb Rename "flakes" testenv to "linting" as requested in review 2016-01-05 18:18:29 -02:00
Ronny Pfannschmidt
e2603d7050 Merge pull request #1306 from nicoddemus/summary-warnings
pytest warnings emitted during ``pytest_terminal_summary`` are now properly displayed.
2016-01-04 11:16:33 +01:00
Bruno Oliveira
369d9ecaa5 pytest warnings emitted during `pytest_terminal_summary` are now properly displayed.
Fix #1305
2016-01-04 00:07:45 -02:00
Bruno Oliveira
02dd6df6e6 Changelog now in rst format (2.9.0 and onward) and add rst-lint check
Fix #1274
2016-01-03 23:09:24 -02:00
Ronny Pfannschmidt
6c170201d6 Merge branch 'master' into features 2016-01-02 23:56:01 +01:00
Ronny Pfannschmidt
bf4de4bd68 Merge pull request #1294 from nicoddemus/doctest-bytes-literals
Doctest bytes literals
2016-01-01 18:18:08 +01:00
Bruno Oliveira
80d6d94635 Merge pull request #1298 from aktech/patch-1
Update copyright in README
2016-01-01 12:06:21 -02:00
AMiT Kumar
63cba1ed0d Update copyright in README 2016-01-01 18:52:56 +05:30
Ronny Pfannschmidt
71ab6b8b05 Merge pull request #1295 from nicoddemus/monkeypatch-perf
Make monkeypatch calls O(1)
2015-12-30 22:21:16 +01:00
Ronny Pfannschmidt
c367180ab2 Merge pull request #1297 from nicoddemus/multi-doctest-glob
Multiple --doctest-glob arguments
2015-12-30 22:18:46 +01:00
Bruno Oliveira
1bdf71730a Complement #1255 by adding tests and docs
Fix #1242
2015-12-30 18:24:59 -02:00
jab
0ea8dc0d40 make --doctest-glob multi-allowed 2015-12-30 17:32:14 -02:00
Bruno Oliveira
638b3f5e39 Make monkeypatch calls O(1)
Fix #1292
2015-12-29 22:04:35 -02:00
Bruno Oliveira
309ecf7ab3 Rename "BugFixes/Adjustments" to just "Bug Fixes" as commented elsewhere 2015-12-29 21:09:15 -02:00
Bruno Oliveira
719d63085d Add CHANGELOG entry for ALLOW_BYTES doctest option 2015-12-29 21:08:25 -02:00
Bruno Oliveira
5a5b732fe1 Add docs for ALLOW_BYTES doctest option
Fix #1287
2015-12-29 21:05:11 -02:00
Bruno Oliveira
a0edbb75a4 Implement ALLOW_BYTES doctest option
Fix #1287
2015-12-29 20:55:19 -02:00
Bruno Oliveira
0ef73ed3e0 Small typo on README 2015-12-28 18:56:14 -02:00
Bruno Oliveira
7cfb750d7f Small wording on README 2015-12-28 18:55:20 -02:00
Bruno Oliveira
70f72229c6 Merge pull request #1291 from ulope/master
Make monkeypatch differentiate ImportError sources
2015-12-28 13:18:25 -02:00
Ulrich Petri
2e02579437 Add CHANGELOG entry for #900 fix 2015-12-28 10:53:38 +01:00
Ulrich Petri
8d49abb0d1 Make monkeypatch differentiate ImportError sources
Previously `monkeypatch` assumed that any `ImportError` was caused by
a mistake in the specified import path. However this assumption is false 
in case the import target itself causes an `ImportError`.

Fixes: #900
2015-12-27 22:44:23 +01:00
Ronny Pfannschmidt
c5631b6567 Merge pull request #1284 from nicoddemus/pyversions-badge
Add badge of supported python versions to README
2015-12-27 16:05:43 +01:00
Ronny Pfannschmidt
522224ee7c Merge pull request #1285 from nicoddemus/readme-changes-logo
Add logo and some readme changes
2015-12-27 15:47:29 +01:00
Bruno Oliveira
015e8e574a Merge pull request #1289 from WoLpH/patch-1
Updated out of date link
2015-12-27 07:22:41 -02:00
Rick van Hattem
87ff7ee232 Updated out of date link 2015-12-27 02:35:02 +01:00
Bruno Oliveira
b5490b289d Add logo and update readme
* Show pytest logo
* Show assertion introspection in the example
* Use separate sections for change-log, docs, license, etc.
2015-12-26 12:47:22 -02:00
Ronny Pfannschmidt
46039f8687 Merge pull request #1286 from nicoddemus/changelog-sections
Separate 2.9.0 CHANGELOG into sections
2015-12-26 11:09:45 +01:00
Bruno Oliveira
6b25fb4d64 Separate 2.9.0 CHANGELOG into sections
Fix #1275
2015-12-25 20:44:03 -02:00
Bruno Oliveira
99a5067edb Merge branch 'pyreadline-workaround' 2015-12-25 18:03:25 -02:00
Bruno Oliveira
5afb61ad26 Fix trailing white-space 2015-12-25 17:51:55 -02:00
Bruno Oliveira
fbfab6778c Give proper thanks for the PR in the CHANGELOG 2015-12-25 17:48:03 -02:00
Bruno Oliveira
57bc14caa0 Apply readline workaround during initial conftest loading 2015-12-25 17:46:19 -02:00
Bruno Oliveira
df3f21afb6 Add badge of supported python versions to README 2015-12-25 16:28:50 -02:00
Ronny Pfannschmidt
1a87bb2416 Merge pull request #1280 from nicoddemus/del-index-from-overview
Remove "index" entry from overview.rst
2015-12-25 07:33:15 +01:00
Erik M. Bray
6e170a4a1c * Moved workaround to its own function, mostly for the sake of adding
a more descriptive docstring (the workaround itself is just to import
  readline earlier).  I removed the conditional on targetfd from the
  workaround since it doesn't really matter.

* Added # noqa marker.

* Added changelog entry, and self to authors.
2015-12-24 16:43:34 -05:00
Erik M. Bray
924a9667e1 Make sure readline has been imported before duping any stdio handles--otherwise pyreadline fails to connect to the correct handle for the console's stdout/in. 2015-12-24 14:56:57 -05:00
Bruno Oliveira
319f6310f8 Remove "index" entry from overview.rst
"index" is already displayed in the main docs, repeating it here breaks the reading flow
2015-12-24 16:08:43 -02:00
Bruno Oliveira
cd3a441304 Merge pull request #1277 from peterdemin/patch-1
doc typo
2015-12-24 15:57:01 -02:00
Peter Demin
8180165229 doc typo 2015-12-24 08:56:54 -05:00
Ronny Pfannschmidt
ec5a429c77 junitxml tests: extend with extra items 2015-12-17 22:30:27 +01:00
Ronny Pfannschmidt
713069ebd4 implement review comments for #1266 2015-12-17 22:27:01 +01:00
Ronny Pfannschmidt
f7af08d309 Merge pull request #1268 from nicoddemus/merge-newinterpret
Merge newinterpret.py into reinterpret.py
2015-12-17 07:10:47 +01:00
Bruno Oliveira
943099ddd1 Merge newinterpret into reinterpret.py 2015-12-16 18:31:43 -02:00
Bruno Oliveira
379562107e Merge pull request #1267 from nicoddemus/remove-pre-2.6
Remove pre-2.6 support code and docs (including obsolete oldinterpret module)
2015-12-16 18:30:53 -02:00
Bruno Oliveira
25c392196f Mention #1226 in the CHANGELOG 2015-12-16 16:48:49 -02:00
Bruno Oliveira
ec597e81a4 Remove references to python pre-2.6 from docs 2015-12-16 16:16:22 -02:00
Bruno Oliveira
81588d7f63 Remove obsolete "oldinterpret" module 2015-12-16 16:16:22 -02:00
Bruno Oliveira
af893aab26 Remove code related to support python <= 2.5
Fix #1226
2015-12-16 16:16:22 -02:00
Ronny Pfannschmidt
8bf7e7cc4b fixes #1259 - take finalized nodes out of the mapping
this allows double node id usage for file based items
2015-12-16 19:09:44 +01:00
Ronny Pfannschmidt
7b20288c2b Merge pull request #1264 from nicoddemus/exception-interact-deprecated
Remove experimental status from pytest_exception_interact
2015-12-16 18:32:58 +01:00
Bruno Oliveira
2b2bec6b97 Remove experimental status from pytest_exception_interact 2015-12-16 14:29:39 -02:00
Ronny Pfannschmidt
fcc20d4181 Merge pull request #1257 from nicoddemus/merge-master-into-features
Merge master into features after 2.8.5
2015-12-12 08:15:55 +01:00
Bruno Oliveira
6ac31088c5 Merge branch 'master' into merge-master-into-features 2015-12-11 23:13:50 -02:00
Bruno Oliveira
7eea6b3b02 Add 2.8.6.dev1 to CHANGELOG 2015-12-11 23:11:36 -02:00
Bruno Oliveira
e87facfb22 Bump master to 2.8.6.dev1 2015-12-11 23:07:30 -02:00
Bruno Oliveira
855b115dab Remove plugins_index generation from HOWTORELEASE 2015-12-11 22:35:44 -02:00
Bruno Oliveira
4263b8b407 Restore regen-doc result 2015-12-11 22:34:16 -02:00
Florian Bruhin
7d150c20cf Regenerate 2.8.5 docs. 2015-12-11 22:28:23 -02:00
Bruno Oliveira
a124163425 Prepare for 2.8.5: bump version, CHANGELOG, announce 2015-12-11 19:20:07 -02:00
Ronny Pfannschmidt
2382546112 Merge pull request #1252 from nicoddemus/optimize-app-veyor
Optimize appveyor build
2015-12-11 16:10:45 +01:00
Bruno Oliveira
946bb08da5 Tyding up the CHANGELOG 2015-12-11 00:36:26 -02:00
Bruno Oliveira
85d1f0404a Merge pull request #1243 from aselus-hub/master
Update python.py
2015-12-11 00:33:46 -02:00
Bruno Oliveira
1d60f61ba8 Optimize appveyor build
- AppVeyor does not run matrix builds in parallel, so creating a matrix with the intent to
  speed up the build will actually result in longer build times, as each matrix will execute
  in a brand new VM.
- tox does not detect 64 bit installations in AppVeyor, it always installs interpreters
  from C:\PythonX.Y, so there's no point to have 64bit builds
- No need for the auxiliary script "install.ps1" because all python versions we are interested
  in are already pre-installed in AppVeyor
2015-12-11 00:20:20 -02:00
aselus-hub
ad05cbe6da fixed meesage. 2015-12-10 15:39:31 -08:00
aselus-hub
1216a27b44 added docstrign to inection collection test. 2015-12-10 15:19:08 -08:00
aselus-hub
2b2240e904 added myself to authors, added changelog entry. 2015-12-10 15:15:09 -08:00
aselus-hub
74f7efd2a3 added line comparison that is pytest-sugar agnostic. 2015-12-10 15:10:55 -08:00
aselus-hub
34db8aed34 added verification that test actually passed. 2015-12-10 15:02:57 -08:00
Bruno Oliveira
926c6028bb Merge pull request #1250 from nicoddemus/merge-master-into-features
Merge master into features
2015-12-10 20:56:10 -02:00
aselus-hub
af54e09759 nit: fixed newline 2015-12-10 14:46:51 -08:00
aselus-hub
dfaeefd692 added test to verify injection. 2015-12-10 14:45:36 -08:00
Bruno Oliveira
86b6ce5042 Merge remote-tracking branch 'upstream/master' into merge-master-into-features 2015-12-10 19:41:14 -02:00
Bruno Oliveira
8f880e1625 Fix CHANGELOG merge 2015-12-10 19:40:45 -02:00
Bruno Oliveira
46c85bc352 Merge pull request #1249 from nicoddemus/remove-plugins-index
Remove plugins_index from the docs
2015-12-10 19:11:32 -02:00
Bruno Oliveira
8b61a332ba Merge remote-tracking branch 'bukzor/features-merge-master' into features 2015-12-10 19:03:55 -02:00
Bruno Oliveira
139c97930b Remove plugins_index from the docs
Fix #1229
2015-12-10 19:00:01 -02:00
Ronny Pfannschmidt
9cfee82f9b Merge pull request #1247 from alex/patch-1
Use https for images in readme
2015-12-10 00:02:47 +01:00
Alex Gaynor
c0a5f3df10 Use https for images in readme 2015-12-09 18:01:36 -05:00
Bruno Oliveira
8220c05b01 Merge pull request #1245 from RonnyPfannschmidt/howtorelease
add a reminder of the features branch merge to HOWTORELEASE.rst
2015-12-09 18:34:41 -02:00
Ronny Pfannschmidt
d0f5f6676b add a reminder of the features branch merge to HOWTORELEASE.rst 2015-12-09 21:20:54 +01:00
aselus-hub
ec02f694ef Update python.py
updated dictionary itteration to create a list for generation, so that tests can be added in the generator functions under python3. This works fine as-is in python2 because python 2 already creates a list, whereas python3 returns an itterator. Forcing a list format for the return fixes python3 to work the same way as python2
2015-12-09 11:32:19 -08:00
Ronny Pfannschmidt
6351e2846c Merge pull request #1232 from codewarrior0/report-passing-option
Add -rp and -rP options to report passing tests.
2015-12-09 06:57:42 +01:00
Ronny Pfannschmidt
1c70827f33 Merge pull request #1241 from nicoddemus/fix-deprecated-call-args
Fix deprecated_call regression introduced in 2.8.4
2015-12-09 06:48:43 +01:00
David Vierra
ccfd962170 Add "no -rP" case to test_pass_output_reporting 2015-12-08 17:33:03 -10:00
David Vierra
b417d7cb79 Add tests to test_terminal.py for -rp and -rP 2015-12-08 15:54:23 -10:00
Bruno Oliveira
1c46462991 Fix deprecated_call regression introduced in 2.8.4
Fix #1238
2015-12-08 22:40:05 -02:00
Buck Golemon
5ccb7b1ced update test_recwarn to new style 2015-12-08 11:08:33 -08:00
Buck Golemon
eabf2f9091 Merge branch 'master' into features
Conflicts:
	AUTHORS
	_pytest/__init__.py
	_pytest/hookspec.py
	_pytest/recwarn.py
	testing/test_recwarn.py
2015-12-07 14:28:59 -08:00
David Vierra
1db4cbcc9f Update AUTHORS and CHANGELOG 2015-12-07 12:17:30 -10:00
David Vierra
fbac936596 Add -rp and -rP options to report passing tests.
-rP is an alternative to `-s` for viewing the output of passing tests.
This causes the captured stdout/stderr of passing tests to be output in
the same way as that of failing tests.

-rp adds a simple one-line-per-test summary for passing tests.

Neither option is included by -ra.

Additional changes to `pytest_capturelog` and `pytest_catchlog` are
needed for this option to also output captured logs: They must be
changed to use `rep.sections.add` instead of `rep.longrepr.addsection`,
and to add these additional sections even if the test passes, since
passing tests don't seem to have a `longrepr` at report time.
2015-12-07 11:32:56 -10:00
Ronny Pfannschmidt
ffa572531a Merge pull request #1091 from RonnyPfannschmidt/fix-1074
fix issue 1074 and clean up junitxml
2015-12-07 22:13:16 +01:00
Ronny Pfannschmidt
fde2a6f5fd add changelog entry 2015-12-07 21:58:34 +01:00
Ronny Pfannschmidt
7b7737bf96 handle duplicate test ids via collection and xdist each reporting 2015-12-07 21:54:25 +01:00
Ronny Pfannschmidt
04e9ae75c8 add xfailing test for double test id failure 2015-12-07 21:54:25 +01:00
Ronny Pfannschmidt
9ea7826427 Junitxml: correct node reporter attribute names 2015-12-07 21:54:25 +01:00
Ronny Pfannschmidt
09cc45b0c5 junitxml: correct docstring of make_properties_node 2015-12-07 21:54:25 +01:00
Ronny Pfannschmidt
0aa54101c9 junitxml: follow Bruno's attribute/method naming hint from the review 2015-12-07 21:54:25 +01:00
Ronny Pfannschmidt
5eef6a2821 junitxml: fix python3 compat of the tests 2015-12-07 21:54:25 +01:00
Ronny Pfannschmidt
518c88f149 finalize nodereporters by throwing away the intermediate xml nodes, fixes issue #1074 2015-12-07 21:54:25 +01:00
Ronny Pfannschmidt
5f5a7995b9 reintroduce junitxml report order and debug cleanups 2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
0528e5b45f junitxml: intermediate, move testcase generation to NodeReporter 2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
9b04958303 junitxml: keep track of custom property insert order
+ review: should we allow the same key multile times
2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
faed54d6c7 junitxml: use node.warn to ensure fslocations 2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
1f609f96e6 junitxml: introduce nodereporter and track durations/properties there 2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
0664ae137c junitxml: remove debug print 2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
d0107c898e junitxml restrucutre stat generation - use node tags 2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
9128fec4c4 junitxml: simplify the api used for testing junitml 2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
80bcf8d624 junitxml: simplify tests by creating a api wrapper 2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
b8df5446c0 junitxml: yapf clean the tests 2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
2a31df072b junitxml: reverse the if/else logic for failure appending 2015-12-07 21:54:24 +01:00
Ronny Pfannschmidt
02f5defd89 yapf junitxml 2015-12-07 21:54:24 +01:00
Bruno Oliveira
efb5332023 Merge pull request #1186 from RonnyPfannschmidt/fix-manifest
fix #1185 - ensure MANIFEST.in exactly matches what should go to a sdist
2015-12-07 13:48:39 -02:00
Ronny Pfannschmidt
b9908cc036 Merge pull request #1228 from pytest-dev/pytest-2.8.4
finish the release process of pytest 2.8.4
2015-12-06 20:32:52 +01:00
Ronny Pfannschmidt
c727860241 bump to 2.8.5.dev 2015-12-06 20:31:14 +01:00
Ronny Pfannschmidt
8c17c7cd12 correct copy&paste error in the release announcement version number 2015-12-06 17:44:08 +01:00
Ronny Pfannschmidt
b7459b8a64 finish release announcement 2015-12-06 16:46:44 +01:00
Ronny Pfannschmidt
b920f09a95 doc regen for release 2.8.4 2015-12-06 16:14:23 +01:00
Ronny Pfannschmidt
a3353c49fd prepare release 2.8.4 - changelog updates + version bump 2015-12-06 16:13:55 +01:00
Ronny Pfannschmidt
a4a12b8356 Merge pull request #1227 from nicoddemus/warn-deprecated-call
Add a note about how DeprecationWarning and PendingDeprecationWarning are treated differently
2015-12-06 10:52:58 +01:00
Ronny Pfannschmidt
13ae2fe28b adopt review comment of #1186 2015-12-06 10:24:24 +01:00
Ronny Pfannschmidt
141a463fed fix #1185 - ensure MANIFEST.in exactly matches what should go to a sdist 2015-12-06 10:24:24 +01:00
Ronny Pfannschmidt
f508a52ca9 Merge pull request #1225 from pytest-dev/skipping-docs-inconsistency
Fix inconsistency in skipif example
2015-12-05 20:44:01 +01:00
Bruno Oliveira
b48a02fdb1 Add a note about how DeprecationWarning and PendingDeprecationWarning are treated differently
Fix #1026
2015-12-05 13:53:58 -02:00
Bruno Oliveira
382efc6363 Fix same inconsistency in next example 2015-12-05 00:43:06 -02:00
Bruno Oliveira
1bed514eb6 Fix inconsistency in skipif example
Fix #1224
2015-12-05 00:35:31 -02:00
Bruno Oliveira
41f19796e8 Merge pull request #1212 from nicoddemus/goodpractices
Goodpractises docs reorganization/review
2015-12-05 00:27:28 -02:00
Ronny Pfannschmidt
427e6c3b4d Merge pull request #1222 from nicoddemus/pastebin-unicode
Fix #1222 - pastebin when captured output contains non-ascii characters
2015-12-04 07:10:49 +01:00
Bruno Oliveira
14bc3c4009 Fix pastebin when captured output contains non-ascii characters
Fix #1219
2015-12-03 20:07:18 -02:00
Florian Bruhin
7e063eec08 Merge pull request #1221 from jeffwidman/patch-1
Fix typo: previosuly --> previously
2015-12-03 21:25:40 +01:00
Jeff Widman
61934ae82d Fix typo: previosuly --> previously 2015-12-03 11:56:18 -08:00
Bruno Oliveira
8c74bb0d25 Improve description on how pytest starts test collection in goodpractises 2015-12-03 01:01:34 -02:00
Bruno Oliveira
bb4771cedf Remove promise about documenting how to create a zipped pytest 2015-12-03 00:13:16 -02:00
Bruno Oliveira
9475cd3fb8 Replace "--assertmode=off" by "--assert=plain"
Fix #1214
2015-12-02 18:39:32 -02:00
Bruno Oliveira
464e16deca Removed incorrect note about genscript requiring wheels 2015-12-02 18:33:53 -02:00
Bruno Oliveira
d9b78f2a95 Remove reference to distutils 2015-12-02 18:30:12 -02:00
Ronny Pfannschmidt
7232b45f25 Merge pull request #1213 from nicoddemus/pastebin-py3
merge Pastebin py3 support

 also closes #1202 and fixes #1198
2015-12-02 09:08:50 +01:00
Bruno Oliveira
a54e4e64cd Merge remote-tracking branch 'upstream/master' into pastebin-py3 2015-12-01 23:51:14 -02:00
Bruno Oliveira
edfb567091 Add #1198 fix to CHANGELOG 2015-12-01 23:37:16 -02:00
Bruno Oliveira
6a2ebddc7c Decode urlopen response in pastebin
Fix #1198
2015-12-01 23:33:37 -02:00
Bruno Oliveira
5040dde0c5 Fix genscript deprecation version and document reasons for such 2015-12-01 23:09:15 -02:00
Bruno Oliveira
095abfd035 Fix formatting errors 2015-12-01 22:52:22 -02:00
Bruno Oliveira
69ef0ab189 Merged virtual env into the Tox section
Nowadays virtualenv use is widespread so we don't need to
devote a how-to section in pytest's docs
2015-12-01 22:47:36 -02:00
Bruno Oliveira
d851a8fd07 Fixed some formatting 2015-12-01 22:43:11 -02:00
Bruno Oliveira
0704fcacd7 Removed setuptools/genscript session 2015-12-01 22:32:07 -02:00
Bruno Oliveira
4f17d56ecb Move deprecated genscript method to the bottom of the document 2015-12-01 22:30:08 -02:00
Bruno Oliveira
b1f6dc23da Moved "conventions for Python test discovery to the top" 2015-12-01 22:28:20 -02:00
Bruno Oliveira
c6f90c25e3 Remove finalize_options override from goodpractices
This is not required in latest versions of `setuptools`, and
`self.test_args` is a read-only attribute in some of the
versions of the 18.X series.

Fix #1134
2015-12-01 22:20:40 -02:00
Florian Bruhin
f0e5cb362e Merge pull request #1211 from nchammas/patch-1
Update xdist newhooks.py link; BitBucket -> GitHub
2015-12-01 20:15:40 +01:00
Nicholas Chammas
c7cf4adfd0 Update xdist link; BitBucket -> GitHub
xdist is now hosted on GitHub.
2015-12-01 13:20:55 -05:00
Ronny Pfannschmidt
def543924b Merge pull request #1209 from jeffwidman/master
Fix spelling: explicitely --> explicitly
2015-12-01 10:51:26 +01:00
Jeff Widman
6be6798cdf Fix spelling: explicitely --> explicitly 2015-12-01 01:41:47 -08:00
Ronny Pfannschmidt
ce4eb51ee0 Merge pull request #1208 from The-Compiler/no-tests-run-spelling
Fix spelling mistake in #1207.
2015-11-30 17:40:26 +01:00
Florian Bruhin
0d2668017d Fix spelling mistake in #1207. 2015-11-30 17:33:34 +01:00
Ronny Pfannschmidt
e7e4860ded Merge pull request #1207 from The-Compiler/no-tests-run
Fix terminal output if no tests were run.
2015-11-30 17:26:47 +01:00
Florian Bruhin
aba55a0fb2 Fix terminal output if no tests were run.
Before:
====  in 0.00 seconds ====

After:
==== no tests run in 0.00 seconds ====
2015-11-30 17:24:40 +01:00
Ronny Pfannschmidt
b5d65e5139 Merge pull request #1206 from The-Compiler/collect-getattr
Don't collect classes with truthy __getattr__.
2015-11-30 17:23:47 +01:00
Ronny Pfannschmidt
3a3f0f5c56 Merge pull request #1205 from The-Compiler/reportinfo-getattr
Fix getting line number with nasty __getattr__. fixes #1204
2015-11-30 17:23:05 +01:00
Florian Bruhin
ba9146c131 Don't collect classes with truthy __getattr__.
When we have a metaclass which returns something truthy (like a method) in its
__getattr__, we collected the class because pytest thought its __test__
attribute was set to True.

We can work around this to some degree by assuming __test__ will always be set
to an explicit True if that's what the user has intended, and if it's something
other than that, this is probably a mistake.

Fixes #1204.
2015-11-30 16:41:13 +01:00
Florian Bruhin
c790f7475e Fix getting line number with nasty __getattr__.
When an object has a custom __getattr__ which always returns a non-int, we
tried to get compat_co_firstlineno from it and checked it was a integer, which
caused an exception if such a class is mistakenly collected.

If we still mistakenly collect such a class (which is likely to be something
other than a test), we now skip it with a warning (because it probably has an
__init__) instead of producing an error.

See #1204.
2015-11-30 16:13:15 +01:00
mehdy
f9b1e39b8a fix #1198 - decoding monkeypatched data to unicode 2015-11-29 19:42:50 +03:30
mehdy
81ad1689b9 fix #1198 - removed docoding the result 2015-11-29 19:20:37 +03:30
mehdy
44f60ba141 fixed #1198 issue by encoding the unicode parameters to bytes and decoding the
bytes response to unicode
2015-11-29 18:27:05 +03:30
Ronny Pfannschmidt
bced5a3f81 Merge pull request #1200 from macrotim/master
Merge #1200 - correct various documentation spelling misstakes
2015-11-28 08:00:24 +01:00
Tim Chan
a8d7e513f4 Fixed docs 2015-11-27 22:46:45 -08:00
Ronny Pfannschmidt
604a021a2a Merge pull request #1196 from nicoddemus/deprecated-call-1190
Make deprecated_call() use monkey-patching again , fixes #1190
2015-11-27 22:09:09 +01:00
Bruno Oliveira
603d81ef2f deprecated_call now uses monkey patching strategy to capture warnings
similar to what we had in 2.7, with a few enhancements

Fix #1190
2015-11-26 16:48:58 -02:00
Bruno Oliveira
6378cdf7a9 Restored 2.7 implentation of deprecated_call 2015-11-26 15:54:57 -02:00
Bruno Oliveira
84eacf3e3c Small changelog formatting fix 2015-11-26 14:37:55 -02:00
Bruno Oliveira
320c95ca43 Fix formatting in HOWTORELEASE.rst 2015-11-24 12:05:41 -02:00
Bruno Oliveira
b20803f0a6 Mention pytest_enter_pdb in the docs 2015-11-23 18:00:02 -02:00
Ronny Pfannschmidt
df767cca8f Merge pull request #1188 from nicoddemus/pytest_enter_pdb
Pass pytest config object to pytest_enter_pdb
2015-11-23 20:55:33 +01:00
Bruno Oliveira
b3166a538c Pass pytest's config object to pytest_enter_pdb 2015-11-23 14:42:21 -02:00
Bruno Oliveira
1f148a93ec Mention pytest_enter_pdb in the docs 2015-11-23 13:02:15 -02:00
Ronny Pfannschmidt
af46ffe021 bump to 2.8.4.dev 2015-11-19 22:01:34 +01:00
Ronny Pfannschmidt
e4a000bb00 refer more explicit to osx el cap in the changelogs 2015-11-18 17:57:41 +01:00
Ronny Pfannschmidt
d04505553e update authors list for 2.8.3 and add a log command to the howto 2015-11-18 17:55:18 +01:00
Ronny Pfannschmidt
2b5c46b2ab correct drop in version in announcement 2015-11-18 17:48:35 +01:00
Ronny Pfannschmidt
063f90f0d2 run regendoc 2015-11-18 17:47:17 +01:00
Ronny Pfannschmidt
6096cae3dd release announcements for 2.8.3 2015-11-18 17:38:31 +01:00
Ronny Pfannschmidt
3dc57d99f2 Changelog groming and release preps for 2.8.3 2015-11-18 17:34:30 +01:00
Florian Bruhin
3cc5a4ecb0 Merge pull request #1175 from gabehollombe/add-pyconsg2015-talk
Add 'Improve your testing with Pytest and Mock' video from PyCon SG 2015
2015-11-11 06:16:46 +01:00
Gabe Hollombe
ac0b7b9803 Add 'Improve your testing with Pytest and Mock' video from PyCon SG 2015 2015-11-11 11:28:59 +08:00
Bruno Oliveira
a1d226b751 Merge pull request #1168 from hackebrot/write-docs-on-ignore-cli-option
Write docs on ignore cli option
2015-11-07 12:38:21 -02:00
Raphael Pierzina
d667259e31 Change pytest ignore invocation as suggested by @nicoddemus 2015-11-04 23:45:29 +01:00
Bruno Oliveira
98668c943d Merge pull request #1171 from nicoddemus/fix-1169
Allow @unittest.skip decorators in Python 2.7
2015-11-04 20:27:00 -02:00
Bruno Oliveira
a7a470b56f Give credit where it is due 2015-11-04 19:55:05 -02:00
Bruno Oliveira
7d6edb9ca5 Fix unittest.skip decorator test and separate the fix into a different, self-doc function 2015-11-04 19:54:18 -02:00
Lee Kamentsky
313050b15b Suggested edits by Bruno.
Moved fix to TestCaseFunction.setup. Added myself to AUTHORS and added entry to CHANGELOG
2015-11-04 15:30:16 -05:00
Lee Kamentsky
1833547936 Added test for issue #1169
(I undid my fix, checked for failure, redid my fix and it passes)
2015-11-04 14:24:22 -05:00
LeeKamentsky
8de2c035e2 Fixes #1169
The unittest.skip decorator runs @functools.wraps on self._testcase. functools.wraps expects a "__name__" attribute and this patch adds one. It might not be the correct fix, but it works for me.
2015-11-04 13:52:40 -05:00
Raphael Pierzina
a2d07bfa93 Add pytest invocation along with result 2015-11-04 15:34:18 +01:00
Raphael Pierzina
586fdbcbbd Add example tests directory structure 2015-11-04 15:00:37 +01:00
Raphael Pierzina
04079f9ae5 Start doc section on `--ignore` in pytestcollection.rst 2015-11-04 14:49:02 +01:00
Bruno Oliveira
af2d391903 Merge pull request #1166 from Toilal/pytest-runner
Use pytest-runner for setuptools integration
2015-11-02 12:50:21 -02:00
Toilal
8abf85e96c Use pytest-runner for setuptools integration 2015-11-02 12:22:40 +01:00
Ronny Pfannschmidt
9013cb1b4c Merge pull request #1144 from The-Compiler/elcapitan-sip
Handle EPERM when writing rewritten bytecode.
2015-11-01 08:20:00 +01:00
Florian Bruhin
2eb345f9b7 Merge pull request #1159 from zoidbergwill/patch-1
Fix typo in parametrize.rst
2015-10-30 09:02:29 +01:00
William Martin Stewart
1376d75fbe Fix typo in parametrize.rst 2015-10-30 09:58:41 +02:00
Bruno Oliveira
4fe7cca44e Merge pull request #1157 from gabrielcnr/master
Color highlight on the name of the failed tests
2015-10-28 17:36:47 -02:00
gabriel.reis
a83d5c0f08 Updated entries on CHANGELOG and AUTHORS. Ref: #1157 2015-10-28 19:35:04 +00:00
Gabriel Reis
f3f61fb5d1 Color highlight on the name of the failed tests 2015-10-28 08:12:57 +00:00
Bruno Oliveira
8e54d07c40 Fix link in FAQ about parametrizing tests
Fix #1154
2015-10-26 22:46:35 -02:00
Florian Bruhin
bd36e00174 Merge pull request #1153 from b-jazz/patch-2
Update usage.rst
2015-10-24 15:41:24 +02:00
Ronny Pfannschmidt
da6b1557f0 Merge pull request #1152 from b-jazz/patch-1
Update CONTRIBUTING.rst
2015-10-24 12:00:33 +02:00
b-jazz
f174026f53 Update usage.rst
Remove double "the" in usage comments
2015-10-24 02:36:02 -07:00
b-jazz
390e1c93ed Update CONTRIBUTING.rst
Clean up the grammar of one of the lines.
2015-10-24 02:21:22 -07:00
Bruno Oliveira
8f31a1a64b Merge pull request #1147 from jayvdb/remove-extrainit
Remove commented out extrainit
2015-10-20 10:25:54 -02:00
John Vandenberg
9a04879129 Remove commented out extrainit
Unused since 2012, and the docstring syntax is incorrect with
four quotes.
2015-10-20 21:08:21 +11:00
Bruno Oliveira
7469b5591e Update plugins_index.rst 2015-10-17 13:37:38 -03:00
Bruno Oliveira
75932a92d0 Make pytest-version mandatory
Fix #1118
2015-10-17 13:37:01 -03:00
Bruno Oliveira
cf56f59f58 Merge pull request #1145 from htgoebel/patch-1
Add link to unittest2pytest
2015-10-17 13:16:55 -03:00
Hartmut Goebel
4fba20e544 Add link to unittest2pytest
Closes #991.
2015-10-17 18:14:52 +02:00
Florian Bruhin
2956627b8b Handle EPERM when writing rewritten bytecode.
Fixes #1143.
2015-10-17 11:55:55 +02:00
Ronny Pfannschmidt
3404d2a99b Merge pull request #1142 from nicoddemus/issue-1133-str-relto
Fix situation where a traceback entry "path" returns a str object
2015-10-17 08:58:48 +02:00
Bruno Oliveira
311b0a9683 Fix situation where a traceback entry "path" returns a str object
Fix #1133
2015-10-16 20:18:14 -03:00
Ronny Pfannschmidt
3b11995dbe Merge pull request #1053 from mbirtwell/issue_331_failure_for_test_with_no_name
Prevent non-function callables from being collected
2015-10-13 23:35:32 +02:00
Michael Birtwell
a3bda59a30 collection: Prevent non-function callables from being collected
Fixes issue 331
previously to this change the collection code would issue a warning for
when ever it encountered a variable that looked like a test but wasn't a
function saying that it wouldn't collect it because it wasn't a function.
This fixes the logic so that if that warning is issued it really isn't
collected.
However previously special cases existed to support tests that were
created using functools.wraps and functools.partial. So the condition for
issuing that warning has been updated to take that in to account

Also try the old way of detecting functions just for proper integration
with mock.path in python 2.7 the get_real_func returned the unbound method
2015-10-12 22:23:18 +01:00
Bruno Oliveira
0c21533cc5 Merge pull request #1130 from The-Compiler/pytest_doc_fix
Use a string for pytest_plugins in docs.
2015-10-12 10:58:39 -03:00
Florian Bruhin
dadf03baea Use a string for pytest_plugins in docs. 2015-10-12 06:57:43 +02:00
Ronny Pfannschmidt
1525cc78f6 Merge pull request #1127 from michael-k/indentation
[doc] Fixed indentation
2015-10-10 14:22:18 +02:00
Ronny Pfannschmidt
db077555f6 Merge pull request #1102 from nicoddemus/doctest-fixtures-fix
Fix autouse fixtures and doctest modules
2015-10-10 14:21:53 +02:00
Michael K
37e96c9335 [doc] Fixed indentation 2015-10-10 13:29:22 +02:00
Bruno Oliveira
b052becba9 Merge pull request #1121 from tomviner/issue1035-getattr
Issue1035 getattr
2015-10-09 16:45:52 -03:00
TomV
88c8dd96f9 issue1035 Override inspect.isclass for python 2.6 2015-10-09 19:44:47 +01:00
Bruno Oliveira
cee828130c Merge pull request #1124 from bukzor/unit-test-config-fromdictargs
tests of (and fixes for) Config.fromdictargs (2)
2015-10-09 15:10:40 -03:00
Buck Golemon
67236d6de3 strengthen the ini assertion 2015-10-09 09:58:12 -07:00
Buck Golemon
470e4f9e91 changelog entry 2015-10-09 09:58:12 -07:00
Buck Golemon
0e55a8793f all tests pass 2015-10-09 09:58:12 -07:00
Buck Golemon
49d46a0059 an ugly patch to fix all but the most important part =/ 2015-10-08 10:44:58 -07:00
Buck Golemon
616d8251f3 unit tests of Config.fromdictargs. currently failing 2015-10-08 10:44:58 -07:00
TomV
707226298a issue1035 add test for classes setting __getattr__ 2015-10-08 09:08:32 +01:00
Florian Bruhin
1f6988bdec Add empty 2.8.3.dev section to CHANGELOG. 2015-10-07 22:47:22 +02:00
Florian Bruhin
ec74a8deb8 Fix contents.rst.
This was broken in 787c866191.
2015-10-07 18:10:13 +02:00
Florian Bruhin
b5b53b6aec start 2.8.3 development 2015-10-07 17:56:05 +02:00
Florian Bruhin
7c529e0afe Merge branch '2.8.2-release' 2015-10-07 17:51:34 +02:00
Florian Bruhin
b955473533 Add 2.8.2 release annoucement. 2015-10-06 22:37:59 +02:00
Florian Bruhin
2026ce0ed2 Update plugin_index. 2015-10-06 22:35:16 +02:00
Florian Bruhin
42937d4bb6 Prepare 2.8.2 release. 2015-10-06 21:06:25 +02:00
Bruno Oliveira
cfd259ae6f Merge pull request #1113 from demianbrecht/typo_fix
typo fix, changed position of context manager notes
2015-10-05 17:21:59 -03:00
Demian Brecht
493530ec6d typo fix, changed position of context manager notes 2015-10-05 12:13:25 -07:00
Florian Bruhin
4dea0892cb Merge pull request #1108 from nicoddemus/plugins_index
plugins_index was still generating ".txt" files, so it was effectively being ignored
2015-10-05 09:37:31 -07:00
Bruno Oliveira
a14c77aeba Fix problems when mixing autouse fixtures and doctest modules
The main problem was that previously DoctestModule was setting
up its fixtures during collection, instead of letting
each DoctestItem make its own fixture setup

Fix #1100
Fix #1057
2015-10-03 16:07:14 -03:00
Bruno Oliveira
a24126effb Add credit for pytest.mark.skip to the CHANGELOG 2015-10-03 14:15:22 -03:00
Michael Aquilina
8984177448 TestXFail also shouldnt explicitly inherit from object 2015-10-03 17:12:44 +01:00
Michael Aquilina
750442909c Add unconditional skip entry to CHANGELOG 2015-10-03 17:04:06 +01:00
Michael Aquilina
df874db817 Update default reason to "unconditional skip" 2015-10-03 17:02:18 +01:00
Michael Aquilina
00d0c74657 Update reason in test to prevent confusing with test_no_reason 2015-10-03 17:01:21 +01:00
Michael Aquilina
122980ecad Add myself to AUTHORS 2015-10-03 17:01:11 +01:00
Michael Aquilina
fc0bd9412c Test that "unconditional skip" is the default reason if none given 2015-10-03 17:00:16 +01:00
Michael Aquilina
5ff9a0ff54 Remove redundant comments 2015-10-03 16:59:27 +01:00
Michael Aquilina
25d74a5919 Dont explicitly inherit from object 2015-10-03 16:55:04 +01:00
Michael Aquilina
213dbe7a5f newlines 2015-10-03 16:42:15 +01:00
Michael Aquilina
9e57954b03 First argument in pytest.mark.skip is a reason 2015-10-03 16:42:15 +01:00
Michael Aquilina
1b5aa2868d Check no reason displayed if none specified 2015-10-03 16:42:15 +01:00
Michael Aquilina
eee24138b0 Fix failing test 2015-10-03 16:42:15 +01:00
Michael Aquilina
04545f8a54 classes inherit from object 2015-10-03 16:42:15 +01:00
Michael Aquilina
d1628944a6 Update skippings tests for better coverage 2015-10-03 16:42:15 +01:00
Michael Aquilina
abc27f56fc Update skipping.rst with correct version marker 2015-10-03 16:42:15 +01:00
Michael Aquilina
771aef9ddb Add a test_skip_class test 2015-10-03 16:42:15 +01:00
Michael Aquilina
dc7153e33c Spelling and grammar fixes 2015-10-03 16:42:15 +01:00
Michael Aquilina
5ec08d3081 Delete trailing whitespace 2015-10-03 16:42:15 +01:00
Michael Aquilina
61b8443723 Update docs with new skip marker 2015-10-03 16:42:14 +01:00
Michael Aquilina
ad0b8e31b8 Fix case where skip is assigned to as an attribute directly 2015-10-03 16:42:14 +01:00
Michael Aquilina
f144666f8b Work towards test coverage of mark.skip 2015-10-03 16:42:14 +01:00
Michael Aquilina
4e94135d36 Remove incorrect use of pytest.mark.skip 2015-10-03 16:42:14 +01:00
Michael Aquilina
b71add27da Add MarkEvaluator for skip 2015-10-03 16:42:14 +01:00
Bruno Oliveira
9deab6c0fd Add a reminder on HOWTORELEASE to update plugins_index 2015-10-02 19:44:00 -03:00
Bruno Oliveira
f9e9413f52 plugins_index was still generating ".txt" files, so it was effectively being ignored
Fix #1105
2015-10-02 19:21:55 -03:00
Bruno Oliveira
5171d167ce Move "note" to the end of the main text
Fix #1097
2015-10-02 18:14:17 -03:00
Demian Brecht
2981bece55 pyflakes fix 2015-10-02 13:03:43 -07:00
Demian Brecht
fd211bf490 Add a note about usage of the context manager
Addesses #1097
2015-10-02 12:40:58 -07:00
Ronny Pfannschmidt
9263b3a051 Merge pull request #1096 from hackebrot/update-docs-skip-with-cli-option
Update docs skip with cli option
2015-10-01 18:31:55 +02:00
holger krekel
88209c6ac6 Merge pull request #1092 from nicoddemus/param-ids-fix
Param ids fix
2015-10-01 15:09:11 +02:00
Ronny Pfannschmidt
688f955f5e Merge pull request #1058 from nicoddemus/doc-how-disable-cache
Add docs on how to disable cache provider
2015-10-01 13:06:02 +02:00
Bruno Oliveira
f3cee8f0b5 Merge remote-tracking branch 'upstream/master' into param-ids-fix 2015-10-01 07:58:55 -03:00
Ronny Pfannschmidt
b7fd3f0031 Merge pull request #1093 from nicoddemus/relto-bug
Fix internal error when filtering tracebacks where one entry was generated by an exec() statement
Fixes #995
2015-10-01 06:00:40 +02:00
Bruno Oliveira
d1e00f6e19 Detect dynamic code explicitly in filter_traceback 2015-09-30 17:32:49 -03:00
Bruno Oliveira
c9480c5b8b Move imports outside _escape_bytes as suggested in review 2015-09-30 17:02:19 -03:00
Raphael Pierzina
4829eac1e1 Use a variable for the skipif marker as suggested by @nicoddemus 2015-09-30 21:53:34 +02:00
Raphael Pierzina
a10da0e540 Implement skipif marker for slow test based on pytest.config 2015-09-30 19:41:47 +02:00
Raphael Pierzina
7ac8a88a05 Remove pytest_runtest_setup from conftest.py 2015-09-30 19:25:57 +02:00
Bruno Oliveira
639ae0cfe0 Merge pull request #1095 from ionelmc/fix-hook-docs
Correct hook examples in docs.
2015-09-30 11:28:43 -03:00
Ionel Cristian Mărieș
c8f5a40fd9 Edit examples again to use hookimpl. 2015-09-30 16:58:12 +03:00
Ionel Cristian Mărieș
f4f23e8e09 Correct hook examples in docs. 2015-09-30 16:12:33 +03:00
Florian Bruhin
dc9ad12182 Merge pull request #1094 from nicoddemus/cache-fixture-docstring-fix
fix docstring for cache fixture regarding ``/`` on keys
2015-09-30 06:02:38 +02:00
Bruno Oliveira
a808e09204 fix docstring for cache fixture regarding `/` on keys 2015-09-30 00:27:52 -03:00
Bruno Oliveira
6ae16eba36 add entries for #1085 and #1087 to the CHANGELOG 2015-09-29 22:37:11 -03:00
Bruno Oliveira
11f100813e Fix internal error when filtering tracebacks where one entry was generated by an exec() statement
Fix #995
2015-09-29 22:29:43 -03:00
Bruno Oliveira
b64470443f Fix SystemError when using unicode_escape on Python 3
Fix #1087
2015-09-29 18:20:30 -03:00
Bruno Oliveira
8633c4cefd Fix encoding errors for parametrized tests with unicode parameters in py2
Fix #1085
2015-09-29 17:57:49 -03:00
Florian Bruhin
e9240f7eee Merge pull request #1090 from RonnyPfannschmidt/fix-flaky-getusertest
fix flaky get_user fallback tests
2015-09-29 21:35:45 +02:00
Ronny Pfannschmidt
04deea3c6d fix flaky get_user fallback tests 2015-09-29 21:00:12 +02:00
Bruno Oliveira
6ca8923ec7 Merge pull request #1088 from hpk42/docfix
remove unclear todo that irritates in the online docs
2015-09-29 13:26:54 -03:00
holger krekel
e3562be530 remove unclear todo that irritates in the online docs 2015-09-29 18:23:44 +02:00
holger krekel
cb58eaa611 Merge remote-tracking branch 'upstream/master' into features
Conflicts:
	_pytest/__init__.py
	testing/test_recwarn.py
2015-09-29 15:56:41 +02:00
holger krekel
c5fd42b699 start 2.8.2 development 2015-09-29 15:32:33 +02:00
holger krekel
afdbb6b17a Merge pull request #1084 from hpk42/branch-281
2.8.1 release
2015-09-29 15:19:07 +02:00
holger krekel
a0076460db avoid pullrequest picture and fix bugfix/feature target info.
I could not get the pullrequest picture to be included correctly
in both latex and html sphinx builders due to the "include" directive
from doc/en/contributing.rst
2015-09-29 13:48:38 +02:00
holger krekel
787c866191 hide some parts from generating latexpdf 2015-09-29 13:37:30 +02:00
holger krekel
95245b935c - fix a flaky test on py35-xdist by calling
importlib.invalidate_caches()

- bump version to 2.8.1

- regen docs

- amend changelog, authors
2015-09-29 13:10:59 +02:00
holger krekel
f61f39efdd Merge pull request #1052 from The-Compiler/no-std-prefix
Don't hardcode 'std' for captured stdout/stderr.
2015-09-29 09:19:40 +02:00
holger krekel
a73d517bee Merge pull request #1080 from vodik/master
fix #1034: Add missing nodeid on pytest_logwarning call in addhook.  Thanks Simon Gomizelj for the PR.
2015-09-29 09:07:43 +02:00
Simon Gomizelj
b3727438d6 Add missing nodeid on pytest_logwarning call in addhook.
Otherwise KeyError: 'nodeid' gets thrown, killing pytest. This may fix
issue 1034, but the details of it may be caused by something similar
somewhere else.
2015-09-28 20:23:54 -04:00
Bruno Oliveira
b184f391c6 Show known environment variables in py.test --help 2015-09-28 18:34:16 -03:00
Bruno Oliveira
5f860181b6 Remove print left by accident 2015-09-28 18:25:20 -03:00
Bruno Oliveira
6caa7083db Moved more detailed options on how to disable a plugin to plugins.rst 2015-09-28 18:23:08 -03:00
holger krekel
839909f3f6 Merge pull request #1081 from hunse/fix-pendingdep
`deprecated_call` detects pending warnings again
2015-09-28 19:05:44 +02:00
Eric Hunsberger
4194c9cce2 Check deprecated_call specific to deprecation
`deprecated_call` used to accept any warning. As of #897, it
is now specific to DeprecationWarnings, and another commit in
this PR extends this to PendingDeprecationWarnings. This commit
makes sure this stays the case.
2015-09-28 12:35:24 -04:00
Eric Hunsberger
e8261e0c77 deprecated_call detects pending warnings again
`deprecated_call` now looks for PendingDeprecationWarnings,
as it did previously but was broken by #897. Fixes #1037.

Also added a test so this does not happen again.
2015-09-28 12:11:52 -04:00
Ronny Pfannschmidt
22e1f4946e Merge pull request #1079 from hpk42/issue1073
fix issue #1073 -- shortcut plugin hook lookup if the attrname is not prefixed with pytest_.
2015-09-28 16:15:42 +02:00
holger krekel
971ebcbd77 simplify by removing the single-call "exclude_pytest_names" function 2015-09-28 15:43:55 +02:00
holger krekel
03aca9ea79 add changelog entry for fix #1073 2015-09-28 14:17:58 +02:00
holger krekel
1c0ffc5caf seems like pypy's callable builtin calls __getattr__ so we do the check
later.
2015-09-28 14:02:30 +02:00
holger krekel
4e3a807733 fix issue #1073 -- shortcut plugin hook lookup if the attrname is not
prefixed with pytest_.
2015-09-28 13:34:28 +02:00
holger krekel
d29084ec2c add changelog note for fix #704 2015-09-28 11:45:51 +02:00
holger krekel
c5faa00ace Merge pull request #1077 from nicoddemus/pluggy-0.3.1
Vendor pluggy-0.3.1
2015-09-28 11:44:07 +02:00
Bruno Oliveira
910b25d416 Vendor pluggy-0.3.1
Fix #704
2015-09-27 16:04:29 -03:00
holger krekel
0c05ca1fd5 Merge branch 'master' into features 2015-09-26 10:03:42 +02:00
Ronny Pfannschmidt
cb4b5bd684 Merge pull request #1072 from nicoddemus/use-more-py35-tox
Use py35 as preferred py3 interpreter for special test environments
2015-09-26 09:26:16 +02:00
Ronny Pfannschmidt
842aa5746f Merge pull request #1069 from nicoddemus/docs-contents-reorg
Reorganize "Contents" page
2015-09-26 09:18:42 +02:00
Ronny Pfannschmidt
c2c2451788 Merge pull request #1071 from nicoddemus/xml-xdist
Wrong xml report when used with pytest-xdist
2015-09-26 09:05:25 +02:00
Bruno Oliveira
cd7ca3de68 Test py27-xdist and py35 environments on AppVeyor 2015-09-26 03:46:03 -03:00
Bruno Oliveira
d52d0251b2 Test py35 on AppVeyor 2015-09-26 03:44:12 -03:00
Bruno Oliveira
cdead1a991 Update travis with new tox environments 2015-09-26 03:43:37 -03:00
Bruno Oliveira
031a20699c Use py35 as preferred py3 interpreter for special test environments 2015-09-26 03:37:21 -03:00
Bruno Oliveira
e4b18ea5c3 Update CHANGELOG 2015-09-26 03:28:30 -03:00
Bruno Oliveira
b72c3310bc Add note on docs about record_xml_property not working with xdist 2015-09-26 03:24:07 -03:00
Bruno Oliveira
748da0e5d7 Fix xml generation when used with pytest-xdist
pytest_runtest_logreport must be careful to not depend on setup/call/teardown
being called sequentially in that order, as xdist will call them as they are reported
from the slaves

Fix #1064
2015-09-26 03:21:24 -03:00
Bruno Oliveira
bc501a28af Merge pull request #1070 from oleg-alexandrov/master
Documentation clarification
2015-09-26 03:16:44 -03:00
Oleg Alexandrov
9d2d2d17af Clarify documentation
Fix doc markup
2015-09-25 21:46:06 -07:00
Bruno Oliveira
b403395cdb Reorganize "Contents" page
Change the organization in a more logical way to a newcomer
2015-09-26 01:09:50 -03:00
Bruno Oliveira
fbce3bb48f Small format fixes in HOWTORELEASE 2015-09-25 23:10:35 -03:00
Ronny Pfannschmidt
bf23a0f4b8 Merge pull request #1065 from The-Compiler/doc-fixes
Doc fixes
2015-09-25 19:18:09 +02:00
Florian Bruhin
448ec8b740 Mark sources correctly in parametrize.rst.
Sphinx didn't pick this up as monospace text.
2015-09-25 18:43:33 +02:00
Florian Bruhin
272f987b0c Fix test_time in parametrize doc.
The source was indented with a mixture of tabs and spaces, causing syntax
errors when executed.
2015-09-25 18:42:06 +02:00
Florian Bruhin
0ebac22bb2 Regenerate fixture list doc with cache docstring. 2015-09-25 18:41:07 +02:00
Bruno Oliveira
c55e42f856 Merge pull request #1063 from timstaley/docs-module-level-fixtures-pytestmark
Docs: Fixtures page - clarify usage of module-level pytestmark.
2015-09-25 12:42:35 -03:00
Tim Staley
eb2caa554c Docs: Fixtures page - clarify usage of module-level pytestmark.
It certainly wasn't clear to me that the variable assigned by
pytest.mark.usefixtures should also be called pytestmark,
so I was confused when::

  foo = pytest.mark.usefixtures('fixture_bar')

wasn't behaving as expected; correct usage is of course::

  pytestmark = pytest.mark.usefixtures('fixture_bar')

I assume this is by design, otherwise that's a separate issue, at
least current behaviour should be documented.
2015-09-25 14:57:08 +01:00
Florian Bruhin
7c5d2ea81d Merge pull request #1046 from RonnyPfannschmidt/docs
fix documentation regeneration, kill Makefile
2015-09-25 08:35:18 +02:00
Bruno Oliveira
b09d3724a0 Add docs on how to disable cache provider 2015-09-23 19:15:44 -03:00
holger krekel
4867554eec Merge branch 'master' into features 2015-09-23 16:42:42 +02:00
Ronny Pfannschmidt
acb6b186f2 Merge pull request #1056 from icemac/patch-1
Remove duplicate line.
2015-09-23 09:10:20 +02:00
Ronny Pfannschmidt
a3fdcd9b17 Merge pull request #1031 from pytest-dev/unmarshable-parametrize
Parametrized values containing non-ascii bytes break cache
2015-09-23 09:03:51 +02:00
Ronny Pfannschmidt
e5c76cb22d Merge pull request #1054 from nicoddemus/cache-fixture-docstring
Add docstring to cache fixture
2015-09-23 09:00:01 +02:00
Michael Howitz
730114d088 Remove duplicate line. 2015-09-23 08:53:13 +02:00
Florian Bruhin
c0c685a5de Merge pull request #1055 from nicoddemus/fix-help-pytest-warnings
(w)warnings -> (w)pytest-warnings in "-r chars" help
2015-09-23 06:53:46 +02:00
Bruno Oliveira
79ebca3f30 (w)warnings -> (w)pytest-warnings in "-r chars" help 2015-09-23 01:09:09 -03:00
Bruno Oliveira
25d2cc4604 Add docstring to cache fixture
Fixes #1049
2015-09-22 23:46:05 -03:00
Bruno Oliveira
716fa97fa1 Update CHANGELOG 2015-09-22 23:21:36 -03:00
Bruno Oliveira
e1063678f1 escape bytes when creating ids for parametrized values 2015-09-22 23:18:09 -03:00
Bruno Oliveira
661495e5c5 Write failing test for parametrized tests with unmarshable parameters
Related to #1030; committing directly to pytest repository to
get feedback from others on how to proceed.
2015-09-22 23:18:07 -03:00
Bruno Oliveira
9d1ae0a149 Merge pull request #1048 from RonnyPfannschmidt/pytest-1029
fixes #1029 by handling access errors for cache dirs as pytest warning
2015-09-22 19:04:04 -03:00
Ronny Pfannschmidt
7f776fe19a skip chmod using cache access warning tests on windows 2015-09-22 20:49:11 +02:00
Florian Bruhin
c10f483b9f Don't hardcode 'std' for captured stdout/stderr.
This will make Item.add_report_sect more usable for plugins.
See https://github.com/eisensheng/pytest-catchlog/pull/7
2015-09-22 20:29:16 +02:00
Ronny Pfannschmidt
ea9a491fb3 add an acceptance test for cache write errors 2015-09-22 20:24:37 +02:00
holger krekel
ca460e11e6 Merge pull request #1051 from Akasurde/issue_1027
Added minor documentation change in python.py
2015-09-22 17:09:25 +02:00
Ronny Pfannschmidt
c3588b545f generate docs on python3.4 2015-09-22 16:52:35 +02:00
Abhijeet Kasurde
dc1ce51ac2 Added minor documentation change
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2015-09-22 20:15:49 +05:30
Ronny Pfannschmidt
6e51918353 update changelog 2015-09-22 16:33:27 +02:00
Bruno Oliveira
1d2afada83 Minor typo in CHANGELOG 2015-09-22 11:30:00 -03:00
Ronny Pfannschmidt
29f4da93d4 handle access errors when writing cache files silently as pytest warning, fixes #1039 2015-09-22 16:28:19 +02:00
Bruno Oliveira
5acbd7bc86 Fix git checkout command in CONTRIBUTING.rst 2015-09-22 10:54:37 -03:00
Ronny Pfannschmidt
36924b59bd Merge branch '653-deprecated-context-manager' of https://github.com/chiller/pytest into features 2015-09-22 15:14:06 +02:00
Ronny Pfannschmidt
5ff75a41ea fix erroring doc example 2015-09-22 15:05:56 +02:00
Ronny Pfannschmidt
89badfec0c update regendoc, substitutes PYTHON_PREFIX 2015-09-22 14:48:04 +02:00
Ronny Pfannschmidt
662d755974 fix documentation gegeneration, kill Makefile 2015-09-22 14:22:37 +02:00
holger krekel
7c088d1104 remove nonsense line 2015-09-22 11:23:24 +02:00
holger krekel
48df2f6842 Merge branch 'master' into features 2015-09-22 11:23:05 +02:00
holger krekel
bf9b94595c fix changelog 2015-09-22 11:18:19 +02:00
holger krekel
41d61ed221 Merge pull request #1023 from RonnyPfannschmidt/fix-877
Fix 877
2015-09-22 11:17:02 +02:00
holger krekel
79587d4b70 Merge branch 'master' into features
Conflicts:
	_pytest/__init__.py
2015-09-22 11:06:21 +02:00
holger krekel
8a4517fd17 re-add 2.8.x changelog so that MASTER can be merged into features wrt
to the changelog
2015-09-22 11:05:19 +02:00
holger krekel
97f7815feb also change pytest version to target 2.9.0 2015-09-22 11:01:33 +02:00
holger krekel
d8fbb0b8e3 start features branch 2015-09-22 11:00:55 +02:00
holger krekel
e2f72ffed8 start bugfix changelog on master 2015-09-22 10:59:23 +02:00
Florian Bruhin
79c2abf531 Merge pull request #1038 from hpk42/newbranching
adapt contributing to new versioning and to python3.5 as latest.
2015-09-22 10:55:30 +02:00
holger krekel
a5ff345f7b fix another occurence of "macro" to "major" 2015-09-22 10:45:55 +02:00
holger krekel
f19ba6c2b1 fix naming 2015-09-22 10:29:12 +02:00
holger krekel
745cd26850 Merge branch 'master' into newbranching 2015-09-22 10:22:05 +02:00
holger krekel
71c5883d52 update according to discussion on pytest-dev and in PR 2015-09-22 10:21:01 +02:00
Galaczi Endre
9f77a8507e removed mutation of global state, changed filter addition in WarningsRecorder 2015-09-21 19:01:23 +01:00
Galaczi Endre
beaa8e55bd Fixes #653 use deprecated_call as context_manager 2015-09-21 19:01:23 +01:00
Floris Bruynooghe
c30eafa254 Update changelog for merged PR. 2015-09-21 14:59:48 +01:00
Floris Bruynooghe
7c3be72ac7 Merge pull request #1042 from Bjwebb/issue411
Add __eq__ method to assertion comparison example
2015-09-21 14:57:59 +01:00
Ben Webb
622e64320a Add __eq__ method to assertion comparison example
This makes the example make more sense, because now Foo(1) == Foo(1) is
true. Fixes #411
2015-09-21 14:23:26 +01:00
holger krekel
0efcfeed17 adapt contributing to new versioning and to python3.5 as latest. 2015-09-21 14:04:30 +02:00
Floris Bruynooghe
65de43e67d Mention fix for issue 766 in changelog
Fixes issue #766.
2015-09-21 12:21:24 +01:00
Floris Bruynooghe
cd4557cce8 Merge pull request #1036 from russel/rlw_766
Remove references to distutils as per Issue 766.
2015-09-21 12:19:14 +01:00
Russel Winder
714a97e452 Remove references to distutils as per Issue 766. 2015-09-21 12:00:48 +01:00
Floris Bruynooghe
80897f62a6 Merge pull request #974 from nicoddemus/addoption-conftest
Add warning about implementing pytest_addoption in conftest files
2015-09-21 11:28:31 +01:00
Floris Bruynooghe
dfd83b59f8 Merge pull request #1033 from mbirtwell/changes_to_contributing_rst
contributing: Add instructions from PyCon
2015-09-21 11:13:14 +01:00
Michael Birtwell
bb42e43ee7 contributing: Add instructions from PyCon
At PyCon we realised that the virtualenv created in the make file wasn't
used in the subsequent steps in CONTRIBUTING.rst. This change removes the
reference the make and suggesting installing tox directly.
Also changed the explanation that follows to make more sense with this
change
2015-09-21 10:56:05 +01:00
Bruno Oliveira
8fe5c704e3 Merge pull request #1024 from rouge8/tmpdir-uid-not-found
Make tmpdir resiliant to user ids that do not exist
2015-09-18 22:53:17 -03:00
Andy Freeland
b1c9b8b415 Make tmpdir resiliant to user ids that do not exist
Previously, the tmpdir fixture would fail if the current process's user
id does not correspond to a valid user (e.g. running pytest in a Docker
container with 'docker run -u').
2015-09-18 21:26:19 -04:00
Ronny Pfannschmidt
7658f60146 #877 - reencoding causes typeerrors on python2 2015-09-19 00:30:01 +02:00
Ronny Pfannschmidt
49c99a41ea reencode non-ascii python2 assertion reprs, fixes #877
i decided against using a warning since the problem goes away with python3
the support code can be removed once we drop python2 in 10 years or so
2015-09-19 00:30:01 +02:00
Bruno Oliveira
f02d9425f9 Bump version to 2.8.0 2015-09-18 19:04:20 -03:00
Ronny Pfannschmidt
1aca998f3f Merge pull request #1012 from lukas-bednar/junitxml_plugin
junitxml: align custom properties with junit format
2015-09-18 16:01:22 +02:00
holger krekel
2ba0fe2876 Merge pull request #1022 from nicoddemus/cxfreeze-tmpdir
Use temporary directory for cx_freeze testing
2015-09-18 09:28:33 +02:00
Bruno Oliveira
546093175e White list rm for cxfreeze env 2015-09-17 23:34:09 -03:00
Bruno Oliveira
e4d5f88257 Fix install cx_freeze 2015-09-17 23:32:27 -03:00
Bruno Oliveira
3a8e375efe Fix import 2015-09-17 14:52:51 -03:00
Bruno Oliveira
f5f3a2a928 Fix flaky failure about unused shutil 2015-09-17 12:54:02 -03:00
Bruno Oliveira
6bca5a1c25 Use temporary directory for cx_freeze testing 2015-09-17 11:54:44 -03:00
Lukas Bednar
02a2272cfe junitxml: move custom properties to properties element
<testsuite>
  <testcase>
    <properties>
      <property name="ABC" value="XYZ" />
      <property name="DEF" value="ZYX" />
    </properties>
  </testcase>
</testsuite>
2015-09-17 15:56:41 +02:00
Florian Bruhin
fe8def98e4 Merge pull request #1020 from hpk42/pluggy031
re-vendor pluggy to 0.3.1 release and also fix the README
2015-09-17 14:41:32 +02:00
holger krekel
f4bfd571ee re-vendor pluggy to 0.3.1 release and also fix the README 2015-09-17 13:54:23 +02:00
holger krekel (rather uses bitbucket/hpk42)
f32f3f1980 Merge pull request #1019 from mdboom/python3.5-docs
Various updates to the docs to mention support for Python 3.5
2015-09-17 13:45:35 +02:00
holger krekel
baf5b5d005 update changelog/author info, bump version number 2015-09-17 13:43:39 +02:00
holger krekel (rather uses bitbucket/hpk42)
3bcda48ba4 Merge pull request #1009 from mdboom/deprecation-warnings
avoid deprecation warnings, introduce helpers.
2015-09-17 13:37:26 +02:00
Michael Droettboom
16f90ffc92 Various Python 3.5 documentation mentions 2015-09-17 07:32:52 -04:00
Ronny Pfannschmidt
6520cf00e9 Merge pull request #1018 from hpk42/no_scm
revert setuptools_scm addition
2015-09-17 13:25:48 +02:00
holger krekel
7eb1211192 revert setuptools_scm addition introduced with f22d14b105 2015-09-17 12:58:04 +02:00
Florian Bruhin
f978b545c5 Merge pull request #1016 from hpk42/importappend3
revert importing test module behaviour to prepend by default
2015-09-17 12:41:28 +02:00
holger krekel
6192e74f03 remove __init__.py as advised by ronny 2015-09-17 10:51:03 +02:00
Michael Droettboom
7f71ce0ab2 Reorganize tests 2015-09-16 16:52:37 -04:00
holger krekel
a62d12634c revert importing test module behaviour to prepend by default 2015-09-16 22:12:20 +02:00
holger krekel (rather uses bitbucket/hpk42)
886ac82c43 Merge pull request #1013 from nicoddemus/issue1010
Make tmpdir more resilient in case environment variables required by getpass are missing
2015-09-16 21:57:44 +02:00
Florian Bruhin
2575053697 Merge pull request #1015 from hpk42/cache-integration
refined pytest-cache integration
2015-09-16 21:46:46 +02:00
Bruno Oliveira
130e6cf8a2 Use temproot as a fallback if the current user couldn't be obtained 2015-09-16 16:42:07 -03:00
holger krekel
3841e99720 avoid oldstyle funcarg usage 2015-09-16 21:06:44 +02:00
holger krekel
79d22bf334 some more doc refinements 2015-09-16 20:44:41 +02:00
holger krekel
45065e4e2e refine command line option naming and docs 2015-09-16 20:41:22 +02:00
Bruno Oliveira
558e5406e8 test_get_user should execute on windows only 2015-09-16 13:06:39 -03:00
Bruno Oliveira
1150e87e31 Extract get_user logic into a separate function 2015-09-16 12:47:50 -03:00
Bruno Oliveira
6676aeda5a Make tmpdir more resilient in case environment variables required by getpass are missing
Fix #1010
2015-09-16 12:20:07 -03:00
holger krekel
9a90aaca96 improve and integrate docs 2015-09-16 17:15:31 +02:00
Michael Droettboom
bf74401fd3 Use __code__.co_argcount 2015-09-16 11:05:54 -04:00
Michael Droettboom
9a84c9edb6 Add tests for argument formatting 2015-09-16 11:02:48 -04:00
Michael Droettboom
08a572086b Fix lookup of special values 2015-09-16 11:02:36 -04:00
Bruno Oliveira
2093889ac2 Merge pull request #1011 from hpk42/master
merge latest pytest-2.7 changes
2015-09-16 11:22:05 -03:00
Michael Droettboom
9c19728d2b Fix checking for args 2015-09-16 06:45:51 -04:00
Michael Droettboom
859259ddae Simplify 2015-09-16 06:43:16 -04:00
Michael Droettboom
a0cefb3213 Use inspect.signature instead of inspect.getargspec 2015-09-16 06:33:53 -04:00
holger krekel
fdd23878ec Merge latest changes from branch 'pytest-2.7'
Conflicts:
	_pytest/__init__.py
	doc/en/fixture.rst
	setup.cfg
	testing/test_runner.py
2015-09-16 09:26:55 +02:00
Bruno Oliveira
b2b003dcac Merge pull request #1001 from RonnyPfannschmidt/exitcode-refactor
restrucure pytest.main.wrap_session to allow for non-testrun wraps
2015-09-14 15:56:04 -03:00
Ronny Pfannschmidt
c5bf148ed7 Merge pull request #959 from nicoddemus/vendor-pluggy
Vendor pluggy
2015-09-14 18:37:52 +02:00
Ronny Pfannschmidt
81018f1996 restrucure pytest.main.wrap_session to allow for non-testrun wraps 2015-09-14 18:34:29 +02:00
Bruno Oliveira
a13f23d218 Merge branch 'master' into vendor-pluggy 2015-09-14 12:22:18 -03:00
Anatoly Bubenkov
6d5641afce Merge pull request #999 from nicoddemus/fix-appveyor
Use pip and tox from py27 in appveyor
2015-09-14 17:20:46 +02:00
Bruno Oliveira
9396489b4c Remove unused run_with_env script 2015-09-14 11:28:07 -03:00
Ronny Pfannschmidt
2eb3bdf132 Merge pull request #998 from nicoddemus/py35
Use python "3.5" on travis
2015-09-14 16:16:42 +02:00
Bruno Oliveira
a0dd478637 Use pip and tox from py27 in appveyor 2015-09-14 10:59:10 -03:00
Bruno Oliveira
1d1eac4c6b Use python "3.5" on travis 2015-09-14 10:36:20 -03:00
Bruno Oliveira
d6bb5cb6c1 Ignore vendored_packages folder for coverage purposes 2015-09-14 10:30:58 -03:00
Bruno Oliveira
d79c89beba Merge pull request #997 from RonnyPfannschmidt/monkeypatch-cleanup
monkeypatch: ensure the internal _savesyspath attribute always exists
2015-09-14 10:25:09 -03:00
Ronny Pfannschmidt
2cfc183029 monkeypatch: ensure the internal _savesyspath attribute always exists 2015-09-14 07:42:23 +02:00
Ronny Pfannschmidt
e0645564fe more pep8 fixes 2015-09-13 21:49:01 +02:00
Ronny Pfannschmidt
cd475c7b27 minor flake8 fixes 2015-09-13 19:55:44 +02:00
Ronny Pfannschmidt
c06ff2a992 update docs on the json usage of builtin cache 2015-09-13 19:55:44 +02:00
Ronny Pfannschmidt
1e107e6bd1 restrucure pytest.main.wrap_session to allow for non-testrun wraps 2015-09-13 19:55:44 +02:00
Ronny Pfannschmidt
3d843edc69 minor doc reference fixes 2015-09-13 19:55:44 +02:00
Ronny Pfannschmidt
2e87cf4a62 create the previously missing cache fixture
there was a disabled test
2015-09-13 19:55:44 +02:00
Ronny Pfannschmidt
1de38a25fc use flake8 in the flakes testenv
and extend the ignored errors list so pytest is clean
we def have to trim down that one
2015-09-13 19:55:44 +02:00
Ronny Pfannschmidt
e035f57535 s/--cache/--show-cache/ 2015-09-13 19:55:44 +02:00
Ronny Pfannschmidt
e20216a1a8 merge the pytest-cache plugin into core 2015-09-13 19:55:44 +02:00
Bruno Oliveira
c7888d1d97 Add note in changelog about issue 960 2015-09-12 11:17:50 -03:00
Bruno Oliveira
41d2faccea Merge branch 'issue_960' of https://github.com/Akasurde/pytest 2015-09-12 10:57:23 -03:00
Abhijeet Kasurde
dd69394598 Added testcase and help for report option
Fix added to show help of new reporting option 'a'.
Also, added testcase for checking reporting functionality
with option 'a'.

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2015-09-11 12:24:45 +05:30
Abhijeet Kasurde
c40947e651 Added fix for specifying every option for reporting
The fix will add option 'a' to reporting which will ease task of
adding all options or reporting at once.

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2015-09-10 15:43:43 +05:30
Bruno Oliveira
b6f876e721 Fix --target parameter for pip install 2015-09-07 14:13:41 -03:00
Bruno Oliveira
5a1c679f78 Keep *dist-info directory on vendored_packages 2015-09-07 14:09:59 -03:00
Bruno Oliveira
0b3f1b4a7c Create _pytest.vendored_packages and _pytest._pluggy
- Replace imports from "pluggy" to "_pytest._pluggy"
- Fallback to import "pluggy" from global namespace if
  not found in _pytest.vendored_packges
2015-09-07 13:01:54 -03:00
Bruno Oliveira
e622975ffd Merge pull request #987 from benauthor/master
Document single-method usage
2015-09-04 17:24:15 -03:00
Evan Bender
6ffb659282 Document single-method usage
It is possible to run a single test method in a class, but the syntax is
not glaringly obvious and documentation would help people out.
2015-09-04 15:11:57 -04:00
Bruno Oliveira
8625eb643e Merge pull request #986 from RonnyPfannschmidt/early-logging
replay initial warnings when terminalreporter is loaded
2015-09-02 19:10:53 -03:00
Ronny Pfannschmidt
76f0988551 turn the pytest_logwarning hook historic 2015-09-02 18:49:49 +02:00
Ronny Pfannschmidt
348e519437 Merge pull request #962 from nicoddemus/doctest-skip
Make doctest SKIP option register doctests as SKIPPED rather than PASSED
2015-09-01 12:31:35 +02:00
Ronny Pfannschmidt
7292212d5a Merge pull request #976 from nicoddemus/ren-warnings-on-terminal
Rename "warnings" to "pytest-warnings" in terminal output
2015-09-01 07:56:42 +02:00
Bruno Oliveira
4ad56e84a8 Make doctest SKIP option register doctests as SKIPPED rather than PASSED
Fix 957
2015-08-31 21:25:11 -03:00
Bruno Oliveira
e3734ef337 Add CHANGELOG entry about renaming "warnings" to "pytest-warnings" 2015-08-31 21:21:29 -03:00
Bruno Oliveira
06a70b6d6d Merge pull request #982 from codewarrior0/patch-1
Add notes to docstring of `monkeypatch.undo()`
2015-08-31 21:18:53 -03:00
Ronny Pfannschmidt
3fa261564b replay initial warnings when terminalreporter is loaded 2015-08-31 21:54:12 +02:00
Anatoly Bubenkov
18d175708c Merge pull request #983 from The-Compiler/issue-979
Fix overriding of fixtures with parametrization.
2015-08-31 15:21:45 +02:00
Florian Bruhin
19791546da Add docstring. 2015-08-31 15:11:57 +02:00
Florian Bruhin
885e461ae3 Fix overriding of fixtures with parametrization.
Fixes #979, see #926.
2015-08-31 14:38:39 +02:00
David Vierra
3a27cd87ce Adjust phrasing in monkeypatch.undo docstring
s/test invocation/test function invocation/
2015-08-29 19:00:00 -10:00
David Vierra
6380e19f07 Add notes to docstring of monkeypatch.undo()
Note that calling `undo()` is generally not needed, and describe the "gotcha" discovered in #981.
2015-08-29 16:53:57 -10:00
Bruno Oliveira
c0eec5d61c Merge pull request #975 from nicoddemus/fix-regression-parse-known-args
Fix regression caused by changing the signature for parse_known_args
2015-08-29 23:44:32 -03:00
Brianna Laugher
c493f263b6 Merge branch 'Elizaveta239-master' closes #908 2015-08-29 17:34:35 +10:00
Floris Bruynooghe
553aef57aa Merge pull request #978 from nicoddemus/string-diff
Show a few diff lines when truncating string diffs
2015-08-28 09:04:39 +01:00
Florian Bruhin
9f30ae9850 Merge pull request #977 from nicoddemus/marks-fixtures-note
Add note that using marks on fixtures is not supported
2015-08-28 06:16:49 +02:00
Bruno Oliveira
dd7112d5ea Show a few diff lines when truncating string diffs
Fix #934
2015-08-27 22:20:13 -03:00
Brianna Laugher
b49bedcf0c Merge branch 'master' of git://github.com/Elizaveta239/pytest into Elizaveta239-master 2015-08-28 11:10:22 +10:00
Bruno Oliveira
87cb5bc5b7 Add note that using marks on fixtures is not supported
Fix #964
2015-08-27 20:11:18 -03:00
Bruno Oliveira
e59471766a Rename "warnings" to "pytest-warnings" in terminal output
Fix #970
2015-08-27 19:59:52 -03:00
Bruno Oliveira
4533a50542 Fix regression caused by changing the signature for parse_known_args
Fix #973
2015-08-27 19:35:32 -03:00
Bruno Oliveira
ccf7584fac Add warning about implementing pytest_addoption from conftest files 2015-08-27 19:14:56 -03:00
Bruno Oliveira
06b1b69fb7 Merge pull request #963 from nicoddemus/cookiecutter-docs
Mention cookie-cutter in the docs and fix broken links to <extplugin>
2015-08-26 16:41:56 -03:00
Bruno Oliveira
333cb27272 Merge pull request #961 from nicoddemus/args-after-options
Paths after normal options are now properly used to discover rootdir and ini files
2015-08-26 12:50:19 -03:00
Bruno Oliveira
d988d2006f Mention cookie-cutter in the docs and fix broken links to <extplugin> 2015-08-25 23:59:18 -03:00
Bruno Oliveira
42b43a7d7b Paths after normal options are now properly used to discover rootdir and ini files
Fix #949
2015-08-25 22:08:05 -03:00
elizabeth
e67d66a5d4 Merge branch 'pytest-dev'
# Conflicts:
#	AUTHORS
2015-08-24 22:55:11 +03:00
Ronny Pfannschmidt
b25e41e348 Merge pull request #956 from nicoddemus/record-xml-property
add preliminary support for extended junit xml properties
2015-08-24 09:13:04 +02:00
Bruno Oliveira
70da93145d Improve docs and using warning system for record_xml_property fixture 2015-08-23 11:56:27 -03:00
Bruno Oliveira
a20c6d072d Fix getdoctarget to ignore comment lines 2015-08-23 11:20:34 -03:00
elizabeth
06585f5bdd Always report error about parametrize data that doesn't correspond to fixtures in test functions. 2015-08-23 13:42:40 +03:00
David Diaz
44d9365da0 Add warning of "preliminary feature" to record_xml_property 2015-08-21 15:21:12 -06:00
David Diaz
2ddbac1f98 Correcting implementation based on pull request feed back 2015-08-21 14:31:53 -06:00
Ronny Pfannschmidt
287df16c9c Merge pull request #817 from nicoddemus/non-collection-exit-error
return non-zero exit code if no tests are collected
2015-08-21 18:30:57 +02:00
Bruno Oliveira
5f0e92a432 Merge pull request #942 from RonnyPfannschmidt/adapt-print
Adapt plugin name printing
2015-08-21 12:02:58 -03:00
Bruno Oliveira
d7d418cd47 Fix forked_run_report in pytest.xdist 1.13 2015-08-20 21:17:27 -04:00
David Diaz
24212fd97f Add support to record custom properties on xml output 2015-08-20 17:55:38 -06:00
Bruno Oliveira
3e41c3cbb3 Using packages from pypi 2015-08-18 09:19:51 -03:00
Bruno Oliveira
359f248729 Force to use xdist >= 1.13 2015-08-18 07:35:03 -03:00
Bruno Oliveira
f730291904 Make testsfailed and testscollected public Session attributes
As suggested by @flub in review
2015-08-18 07:35:02 -03:00
Bruno Oliveira
2ffd37b816 return non-zero exit code if no tests are collected
Fix #812
Fix #500
2015-08-18 07:35:02 -03:00
Ronny Pfannschmidt
7758bcd141 terminalwriter: extract plugin printing logic and add positive unittests 2015-08-17 09:10:01 +02:00
Ronny Pfannschmidt
740a97a8cc terinalwriter: use dash between plugin name and version 2015-08-17 08:48:38 +02:00
Ronny Pfannschmidt
2c42f15e00 adapt plugin printing
* print each distribution only once(xdist now has 3 entrypoints)
* include the distribution version
2015-08-17 08:41:24 +02:00
Ronny Pfannschmidt
37ed391cc2 Merge pull request #938 from nicoddemus/doctest-unicode
New ALLOW_UNICODE doctest option
2015-08-16 11:35:10 +02:00
Floris Bruynooghe
f22d14b105 Merge pull request #879 from RonnyPfannschmidt/setuptools-scm
use setuptools_scm to determine the version
2015-08-15 00:56:16 +01:00
Bruno Oliveira
d749021a31 Fix coverage
Also make sure a test that doesn't set ALLOW_UNICODE fails
on Python 2 and passes Python 3.
2015-08-12 22:49:41 -03:00
Bruno Oliveira
93aee0f814 Add docs and CHANGELOG for ALLOW_UNICODE option 2015-08-12 22:17:15 -03:00
Bruno Oliveira
420823070b Add ALLOW_UNICODE doctest option
When enabled, the ``u`` prefix is stripped from unicode strings in
expected doctest output. This allows doctests which use unicode
to run in Python 2 and 3 unchanged.

Fix #710
2015-08-12 22:16:44 -03:00
Ronny Pfannschmidt
ddbdcab522 Merge pull request #937 from ctheune/patch-1
Fix accidental inversion in skip example.
2015-08-12 07:51:59 +02:00
Christian Theune
2174f3ce37 Fix accidental inversion in skip example. 2015-08-12 07:38:04 +02:00
Bruno Oliveira
73fdda0e45 Merge pull request #926 from untitaker/multifixture
Don't skip fixtures that are substrings of params
2015-08-10 21:12:51 -03:00
Markus Unterwaditzer
1d5215ab4f Add myself to authors 2015-08-11 00:47:18 +02:00
Markus Unterwaditzer
cafd71eb29 Update changelog for #926
Also fix some inconsistencies in the changelog on the way.
2015-08-11 00:47:18 +02:00
Markus Unterwaditzer
41cef6f5f2 Don't skip fixtures that are substrings of params
Bug introduced with
https://bitbucket.org/pytest-dev/pytest/pull-requests/257/allow-to-override-parametrized-fixtures

Fix #736
2015-08-11 00:41:21 +02:00
Bruno Oliveira
681e502c12 Use "union" merge strategy for CHANGELOG
Credits: @The-Compiler 😄
2015-08-10 19:27:22 -03:00
Ronny Pfannschmidt
bc509b42e8 Merge pull request #933 from nicoddemus/hasplugin
Reintroduce hasplugin to PytestPluginManager
2015-08-10 09:40:52 +02:00
Bruno Oliveira
e103932aad Reintroduce hasplugin to PytestPluginManager
Fix #932
2015-08-09 19:30:49 -03:00
Ronny Pfannschmidt
1c680210c2 Merge pull request #931 from nicoddemus/docs-hookwrapper
Change docs to use hookwraper instead of __multicall__
2015-08-09 09:22:31 +02:00
Ronny Pfannschmidt
eb989c8257 Merge pull request #921 from tomviner/issue562-noseistest
Issue #562 - Ensure @nose.tools.istest is respected
2015-08-09 07:54:19 +02:00
TomV
14625907ae update changelog 2015-08-09 00:11:16 +01:00
TomV
353360dbe5 use local isclass 2015-08-09 00:11:15 +01:00
TomV
3497aa0766 check nose.istest __test__ attr issue526 2015-08-09 00:11:15 +01:00
Bruno Oliveira
d49fb8a2d5 Change cx_freeze example to not use regendoc 2015-08-08 19:17:50 -03:00
Bruno Oliveira
e8583f01a0 Replaced __multicall__ examples in docs by hookwrapper
Fix #929
2015-08-08 19:07:27 -03:00
TomV
e130a0257d add test for @nose.tools.istest 2015-08-08 21:08:05 +01:00
Bruno Oliveira
729b5e9b2f Merge pull request #923 from The-Compiler/parametrize-idfunc
Generate parametrize IDs for enum/re/class objects.
2015-08-08 15:09:54 -03:00
Brianna Laugher
36b86af4b9 Added more test cases 2015-08-08 19:20:09 +02:00
Brianna Laugher
40fa7b25c5 Merge branch 'master' of git://github.com/Elizaveta239/pytest into Elizaveta239-master
Fixed merge conflict in CHANGELOG
2015-08-08 18:54:53 +02:00
Florian Bruhin
4e21d1d77b Move enum import and adjust comments. 2015-08-08 15:25:10 +02:00
Florian Bruhin
84fdba129a More style changes. 2015-08-08 12:57:54 +02:00
Bruno Oliveira
9ae40e393a Fix PR image link 2015-08-07 22:32:22 -03:00
Florian Bruhin
18125c7d1f Clean up type comparisons. 2015-08-07 23:10:22 +02:00
Florian Bruhin
03d8a6c05d Update CHANGELOG. 2015-08-07 23:08:22 +02:00
Brianna Laugher
fd4d35d9a2 Merge pull request #924 from The-Compiler/parametrise
Alert user about other parametrize spellings.
2015-08-07 13:32:04 +02:00
Florian Bruhin
91a29932a6 Add CHANGELOG entry. 2015-08-07 07:58:13 +02:00
Florian Bruhin
b59376bea4 Alert user about other parametrize spellings. 2015-08-07 07:51:59 +02:00
Florian Bruhin
13c5456868 Generate parametrize IDs for enum/re/class objects. 2015-08-07 07:37:59 +02:00
Bruno Oliveira
4f83586f55 Give credit where it is due in CHANGELOG 😄
Related to #890
2015-08-06 22:51:32 -03:00
Bruno Oliveira
77f54dbdae Merge pull request #915 from Akasurde/issue-890
Converted docs from txt to rst
2015-08-06 22:47:53 -03:00
Bruno Oliveira
2bbe709bce Use testdir fixture in test_double_test to ensure controlled environment for execution
Because the test relies that two subsequent tests try to use pytest.warns to capture
the exact same warning, it is better to use testdir to ensure test execution
occurs in the order we expect (which might be different with pytest-xdist or
pytest-random for example)
2015-08-06 22:30:01 -03:00
Eric Hunsberger
39f1471e93 Warnings always raised in WarningsRecorder
This ensures that if tests for warnings are run more than once,
the warning is still raised as expected.
2015-08-06 15:05:01 -04:00
Abhijeet Kasurde
ab9befb197 Updated CHANGELOG and AUTHORS 2015-08-05 15:21:37 +05:30
Abhijeet Kasurde
6d446e7167 Converted documentation from txt to rst 2015-08-05 10:24:14 +05:30
Bruno Oliveira
02e742b7a6 Move WarningsChecker import in test to a local import to workaround flakes issue
See #897 for discussion
2015-08-04 19:27:13 -03:00
Abhijeet Kasurde
185e730feb Added makefile changes for docs
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2015-08-04 18:44:52 +05:30
Abhijeet Kasurde
e79413acc4 Updated documentation from txt to rst
Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
2015-08-04 16:41:02 +05:30
Bruno Oliveira
d761bfffd7 Merge pull request #897 from hunse/warns
Warns
2015-08-03 22:48:20 -03:00
elizabeth
f7bacd169e Update docs 2015-08-04 00:48:41 +03:00
Bruno Oliveira
8fca4781f1 Merge pull request #910 from oleksmarkh/patch-1
fix docs folder name in HOWTORELEASE
2015-08-03 18:12:14 -03:00
elizabeth
657ca97dbd Some refactorings after code review 2015-08-04 00:02:03 +03:00
Oleksii Markhovskyi
3868b61443 fix docs folder name in HOWTORELEASE 2015-08-03 23:01:03 +02:00
Bruno Oliveira
c605cf92f9 Merge pull request #909 from flub/assertdoc
Update docs to represent reality
2015-08-02 18:53:47 -03:00
Floris Bruynooghe
b097d8c0a6 Update docs to represent reality
This was changed after EuroPython 2014, now both the message and the
introspection is presented.
2015-08-02 22:36:19 +01:00
elizabeth
db9809d6dc Update test for error in 'indirect' parameter 2015-08-02 23:53:44 +03:00
elizabeth
63bac67fb5 Add test for bad value in argument 'indirect' 2015-08-02 23:06:24 +03:00
elizabeth
54a3d6210b Update CHANGELOG and AUTHORS 2015-08-02 20:39:31 +03:00
elizabeth
15b865f502 Rewrite test using @pytest.fixture 2015-08-02 20:30:23 +03:00
elizabeth
9846953597 Support for python 2.6 2015-08-02 17:28:27 +03:00
elizabeth
2fc7aede0b Request #714: Apply indirect=True on particular argnames 2015-08-02 16:40:40 +03:00
Eric Hunsberger
52b4eb6c46 Added warns to assert warnings are thrown
Works in a similar manner to `raises`, but for warnings instead
of exceptions. Also refactored `recwarn.py` so that all the
warning recording and checking use the same core code.
2015-07-30 23:28:32 -04:00
Eric Hunsberger
aac371cf07 Added myself to AUTHORS 2015-07-30 23:28:32 -04:00
Ronny Pfannschmidt
0b83b4076a Merge pull request #898 from nicoddemus/tmpdir-factory-new-name
Use pytest-of-$user as base directory for tmpdir_factory
2015-07-29 13:58:42 +02:00
Bruno Oliveira
4302972c23 Use pytest-of-$user as base directory for tmpdir_factory
Before tmpdir_factory, pytest used to create a link named "pytest-$user" to the current numbered directory. Use
 a different name so there's no conflict when running different pytest versions.

Fix #894
2015-07-28 20:57:48 -03:00
Ronny Pfannschmidt
235f9da432 special-case _pytest.__init__ in genscript to avoid a python3 bug 2015-07-27 11:33:27 +02:00
Bruno Oliveira
9cf9900721 Merge pull request #892 from The-Compiler/multi-parametrize
Document and test stacking of parametrize.
2015-07-26 21:00:29 -03:00
Bruno Oliveira
2035c5f8be Merge pull request #893 from pfctdayelise/dupereleaseguides
Delete duplicate release guide
2015-07-26 20:59:07 -03:00
Brianna Laugher
5ebad5c96d Delete release.txt from docs, merge extra comments to HOWTORELEASE.rst 2015-07-26 15:20:32 +02:00
Florian Bruhin
2ab4bf13ab Document and test stacking of parametrize.
Closes #815.
2015-07-26 14:39:13 +02:00
Ronny Pfannschmidt
5098e5fc47 fix version import 2015-07-26 14:04:52 +02:00
Brianna Laugher
017ceffb76 minor tweaks to CONTRIBUTING 2015-07-26 12:19:39 +02:00
Floris Bruynooghe
e69e785b23 Mention fix for issue #683 2015-07-26 12:15:29 +02:00
jakubo
e8f4819876 Test file run twice fails if it contains marked class #683 2015-07-26 12:15:29 +02:00
Brianna Laugher
985fd0cc2b Mention Contributors team by name in CONTRIBUTING 2015-07-26 12:07:50 +02:00
Floris Bruynooghe
97e5f7d7e9 Merge merge branch
I suspect I don't yet know how to use git...  Surely I don't need two
merges to merge a contribution.
2015-07-26 11:49:42 +02:00
Floris Bruynooghe
011565ca10 Add changelog entry for capture improvement 2015-07-26 11:42:33 +02:00
Floris Bruynooghe
e68fa641ff Merge reset-capgture-on-reeadouterr-errors
Merge branch 'reset-capture-on-readouterr-errors' of github.com:davidszotten/pytest into merge-capmerge
2015-07-26 11:39:03 +02:00
David Szotten
3e6bee2fc6 fail if snap is removed in the future 2015-07-26 01:28:00 +02:00
David Szotten
983d249680 reset capture even if readouterr throws
otherwise that exception (and all following output) end up in /dev/null
2015-07-26 01:15:51 +02:00
Floris Bruynooghe
8338c692a3 Merge pull request #887 from maartenq/753content_of
changed contents -> content but still #753 did not solved, might be i…
2015-07-25 19:11:53 +02:00
Floris Bruynooghe
f64d5f1209 Merge pull request #884 from cpommranz/deprecate_genscript
Deprecate and warn about --genscript, fixes #730
2015-07-25 19:09:52 +02:00
Floris Bruynooghe
f38c632635 Merge branch 'jb-fix-751' 2015-07-25 19:04:59 +02:00
Floris Bruynooghe
251fc68ef9 Merge fix for #751
Merge branch 'fix-751' of github.com:JanBednarik/pytest into jb-fix-751
2015-07-25 19:03:44 +02:00
Maarten
df8a83b2a1 changed contents -> content but still #753 did not solved, might be issues with regendoc 2015-07-25 17:48:12 +02:00
Jan Bednařík
0b92650494 Update changelog. 2015-07-25 16:25:29 +02:00
Jan Bednařík
9906a19e29 Issue #751 - fix. 2015-07-25 15:38:27 +02:00
Jan Bednařík
f78d87ee38 Issue #751 - test. 2015-07-25 15:38:11 +02:00
Christian Pommranz
00e1a2122a Deprecate and warn about --genscript, fixes #730 2015-07-25 15:10:22 +02:00
Floris Bruynooghe
80ee620459 Merge pull request #881 from maartenq/master
setuptools not present issue deprecating gentest
2015-07-25 15:03:50 +02:00
Floris Bruynooghe
023687d8d0 Merge pull request #872 from nicoddemus/confcutdir-inifile
Avoid detecting conftest files upwards from setup.cfg/pytest.ini/tox.ini by default
2015-07-25 14:03:24 +02:00
Maarten
e3d60024aa setuptools not present issue deprecating gentest 2015-07-25 13:50:40 +02:00
Ronny Pfannschmidt
a060b8ff73 use setuptools_scm to determine the version 2015-07-25 10:44:18 +02:00
Bruno Oliveira
ae28e4ba0f Merge remote-tracking branch 'upstream/pytest-2.7'
Conflicts:
	.travis.yml
2015-07-24 20:02:12 -03:00
Bruno Oliveira
033def0a7a Workaround for cmdexec bug on Windows
This bug fails the entire pytest suite when executed with the
--lsof option in Python 2 on Windows.
2015-07-24 19:24:31 -03:00
Bruno Oliveira
9f94e443ff Merge remote-tracking branch 'upstream/pytest-2.7'
Conflicts:
	testing/conftest.py
2015-07-24 19:24:21 -03:00
Bruno Oliveira
ab9e246ab0 Avoid detecting conftest files upwards from setup.cfg/pytest.ini/tox.ini files by default
As discussed in #82
2015-07-23 23:21:07 -03:00
Bruno Oliveira
df29120abe Merge branch 'pytest-2.7'
Conflicts:
	_pytest/config.py
	_pytest/genscript.py
	_pytest/mark.py
	tox.ini
2015-07-23 22:35:51 -03:00
Bruno Oliveira
77844ec5f3 Fixed typo in CHANGELOG: "testdirs" -> "testpaths" 2015-07-22 12:14:49 -03:00
Anatoly Bubenkov
045274e647 remove merge artifact 2015-07-19 15:49:43 +02:00
Anatoly Bubenkov
6af7172204 Merge branch 'pytest-2.7' 2015-07-19 15:25:04 +02:00
Bruno Oliveira
604a39f5ef Allow py35 to fail on Travis until it is properly supported (fix2) 2015-07-18 15:30:16 -03:00
Bruno Oliveira
a5bc98136d Allow py35 to fail on Travis until it is properly supported (fix) 2015-07-18 15:18:57 -03:00
Bruno Oliveira
7dab2e1efe Allow py35 to fail on Travis until it is properly supported 2015-07-18 14:46:36 -03:00
Floris Bruynooghe
5e0235946b Merge pull request #801 from Carreau/test-35
Support Python 3.5
2015-07-18 11:30:36 +01:00
Bruno Oliveira
30e7104b05 Merge pull request #845 from nicoddemus/tmpdir-improvements
Introduce tmpdir_factory session fixture
2015-07-16 20:02:08 -03:00
Thomas Kluyver
4462b83258 Style fix 2015-07-16 11:04:36 -07:00
Bruno Oliveira
74bc50e97c Fix flakes 2015-07-15 20:45:35 -03:00
Bruno Oliveira
0f52856f99 Use a subdirectory in the TEMP directory to speed up tmpdir creation
Fix #105
2015-07-15 20:03:58 -03:00
Thomas Kluyver
077f0d3d66 Match .travis.yml env list to tox envs 2015-07-15 16:03:14 -07:00
Thomas Kluyver
37a09a6c30 No more failures 2015-07-15 15:58:42 -07:00
Thomas Kluyver
4e98d2b7f1 OK, try running flakes with 2.7 2015-07-15 15:52:28 -07:00
Thomas Kluyver
d73c8e6a5e Try running flakes tests with Python 3.4 2015-07-15 15:49:15 -07:00
Thomas Kluyver
195422f9c0 Fix AST rewriting with starred expressions in function calls 2015-07-15 15:31:35 -07:00
Thomas Kluyver
62ca4ae963 Move Interrupted exception class out of Session 2015-07-15 14:28:43 -07:00
Thomas Kluyver
35bea86c9f No Starred node type on Python 2 2015-07-15 14:11:21 -07:00
Matthias Bussonnier
d774f3ca86 generify 2015-07-15 13:49:40 -07:00
Matthias Bussonnier
167625d24d simplify + fix 2015-07-15 13:49:40 -07:00
Matthias Bussonnier
3bc6c0f936 a test 2015-07-15 13:49:40 -07:00
Matthias Bussonnier
3cf82c6594 nigh 2015-07-15 13:49:40 -07:00
Matthias Bussonnier
71a00c3223 try isntall 35 on tox 2015-07-15 13:49:40 -07:00
Matthias Bussonnier
e2e29284f0 allow faillure on 35 2015-07-15 13:49:40 -07:00
Matthias Bussonnier
26e64fc45c Ast Call signature changed on 3.5
fix issue 744 on bitbucket

port of merge request 296

https://bitbucket.org/pytest-dev/pytest/pull-request/296/astcall-signature-changed-on-35
https://bitbucket.org/pytest-dev/pytest/issue/744/
2015-07-15 13:49:40 -07:00
Bruno Oliveira
8f4f2c665d Mention pytest-runner in the docs
Fix #147
2015-07-13 21:59:37 -03:00
holger krekel (rather uses bitbucket/hpk42)
8910ec2870 Merge pull request #836 from nicoddemus/doctest-modules-fixtures
Consider session fixtures for doctest docstrings in modules
2015-07-13 18:02:51 +02:00
Bruno Oliveira
d6033037ac Consider session fixtures for doctest docstrings in modules
Fixes #768
2015-07-13 12:29:09 -03:00
holger krekel (rather uses bitbucket/hpk42)
194581ab5f Merge pull request #829 from nicoddemus/pep302-get-data-support
Add support for PEP302 get_data API
2015-07-13 16:55:16 +02:00
Bruno Oliveira
7445c5bd70 Add support for PEP302 get_data API
Fix #808
2015-07-11 14:13:43 -03:00
Bruno Oliveira
1baa1a4d01 Merge pull request #822 from nicoddemus/extra-usage-info
Print inifile and rootdir when there's usage errors
2015-07-11 13:43:20 -03:00
Bruno Oliveira
40ec0ec97d Merge pull request #823 from nicoddemus/testdirs-option
Add new testdirs ini option
2015-07-11 13:42:54 -03:00
Bruno Oliveira
8a6aa5e17e Print inifile and rootdir when there's usage errors
Related to #821
2015-07-10 21:56:12 -03:00
Bruno Oliveira
854e603f84 Add new testdirs ini option
Fix #694
2015-07-10 21:52:47 -03:00
Bruno Oliveira
65c56d4c00 Pinning mock module to < 1.1 fo py26
It has been announced that mock>=1.1 will be
supported for python 2.7 only.
2015-07-10 19:57:48 -03:00
holger krekel (rather uses bitbucket/hpk42)
e7374c39ba Merge pull request #825 from nicoddemus/syntax-highlight-docs
Add syntax highlighting to missing snippets in the documentation and other fixes
2015-07-10 13:02:52 +02:00
Bruno Oliveira
0ee3ee7333 Add syntax highlighting to missing snippets in the documentation and other fixes
- Add explicit "code-block" for sessions without syntax highlight
- Moved Metafunc documentation to the class docstring and reused that in the
   docs;
2015-07-09 21:50:38 -03:00
Bruno Oliveira
0624a69964 Merge pull request #824 from hpk42/devpiupload
configure a plain "devpi upload" to create sdist and universal wheel
2015-07-09 12:08:52 -03:00
holger krekel
fe897c81be configure a plain "devpi upload" to create sdist and universal wheel 2015-07-09 14:56:56 +02:00
Bruno Oliveira
ae4c8b8635 Merge pull request #787 from pytest-dev/pluggy-bc-fix
Reintroduce get_plugin_manager() for backward-compatibility
2015-07-08 19:28:01 -03:00
Bruno Oliveira
d70a31168b Merge pull request #820 from jeffwidman/patch-1
Fix typo + grammar
2015-07-07 21:13:50 -03:00
Jeff Widman
4fa64a962e Fix typo + grammar 2015-07-07 16:35:21 -07:00
Bruno Oliveira
438ea86137 Fix flaky test_timing_function in Windows
This tests fails consistently on Windows due to small time
difference:

>       assert float(val) >= 0.03
E       assert 0.0299999713898 >= 0.03
E        +  where 0.0299999713898 = float('0.0299999713898')

Windows time.time() function is not as accurate as linux's,
so relaxed the test a bit.
2015-07-04 15:05:45 -03:00
Bruno Oliveira
d773c7498f Reword entry in the changelog to show case the new status bar colors better 2015-07-03 18:36:15 -03:00
Bruno Oliveira
4ef6cdfb68 Add small thanks note to Eric Siegerman 2015-07-03 18:31:15 -03:00
Bruno Oliveira
d10054a38d Merge branch 'esiegerman/summary_colors' of github.com:esiegerman/pytest 2015-07-03 18:29:17 -03:00
Bruno Oliveira
9293062221 Merge pull request #809 from kevincox/junitxml-file-attribute
Add `file` and `line` attributes to junit-xml output.
2015-07-03 08:24:36 -03:00
Kevin Cox
7fa27af408 Add file and line attributes to junit-xml output.
This adds the `file` and `line` attributes to the junit-xml output
which can be used by tooling to identify where tests come from. This can be
used for many things such as IDEs jumping to failures and test
runners evenly balancing tests among multiple executors.

Update test_junitxml.py

Foo.
2015-07-02 18:41:52 -04:00
Eric Siegerman
2c419c4790 Add CHANGELOG and AUTHORS entries 2015-07-02 15:47:03 -04:00
Eric Siegerman
afcad74be8 PEP8ify parametrized-test parameters 2015-07-02 13:39:05 -04:00
Eric Siegerman
6c395cb58c Default color is now yellow
Passing tests override that default, making the color green; but several other
"boring" statuses (xfailed, xpassed, deselected, skipped) have no effect.

Net effect: if only "boring" tests are seen, or no tests at all, the summary
bar is yellow.
2015-07-02 13:39:05 -04:00
Eric Siegerman
044d874c5b If there are warnings, make the status bar yellow
Also if we see any statuses the code doesn't know about.
2015-07-02 13:39:05 -04:00
Eric Siegerman
cb21d844d9 Add missing "error" status to the list 2015-07-02 13:39:05 -04:00
Eric Siegerman
0282da9ddf Refactor slightly
Check for the empty-key special case in the first loop,
not the second.
2015-07-02 13:39:05 -04:00
Eric Siegerman
e07144aeb4 Add tests for the empty-key special case 2015-07-02 13:39:05 -04:00
Eric Siegerman
7993afae46 test_summary_stats() now prints its parameter values
This makes it easier to identify failing tests.
2015-07-02 13:39:05 -04:00
Eric Siegerman
bfc3e48fd5 Factor out build_summary_stats_line(), and add tests
--HG--
branch : esiegerman/summary_colors
2015-07-02 13:39:04 -04:00
Bruno Oliveira
76497c2542 Fix plugins_index script and update plugins_index.txt 2015-06-30 19:01:28 -03:00
Bruno Oliveira
3c2fd833ca Reintroduce get_plugin_manager() for backward-compatibility
PyCharm pytest runner depends on this function existing (see #787).

Added reference to get_plugin_manager() and PluginManager/PytestPluginManager to docs
2015-06-25 00:48:47 -03:00
holger krekel
01f5913826 try to fix coveralls env 2015-06-23 23:25:19 +02:00
holger krekel
0998170a01 check webhook again 2015-06-23 17:22:37 +02:00
holger krekel
28cf4c3226 small fix to test webhook 2015-06-23 17:14:08 +02:00
holger krekel (rather uses bitbucket/hpk42)
08613b621e Merge pull request #799 from pytest-dev/noconftest
Add a --noconftest option.
2015-06-23 16:53:22 +02:00
holger krekel
ee40ea5f6d Merge branch 'pytest-2.7'
Conflicts:
	AUTHORS
	_pytest/__init__.py
	setup.py
	testing/conftest.py
	tox.ini
2015-06-23 16:49:05 +02:00
Florian Bruhin
f78b6df8bc Return an empty list directly. 2015-06-23 14:05:44 +02:00
Florian Bruhin
8e0589af69 Add changelog entry. 2015-06-23 09:47:07 +02:00
Florian Bruhin
8664fc4102 Add a --noconftest option. 2015-06-23 09:38:54 +02:00
holger krekel (rather uses bitbucket/hpk42)
755d7b3787 Merge pull request #798 from radarhere/patch-1
Fixed typo
2015-06-23 09:00:42 +02:00
Andrew Murray
cba1ca6244 Fixed typo 2015-06-23 10:29:37 +10:00
Anatoly Bubenkov
e947732bde Merge pull request #791 from pytest-dev/coverage-config
Improve coverage score by tweaking options
2015-06-21 00:54:25 +02:00
Bruno Oliveira
b0491e1a5e Merge pull request #792 from iKevinY/svg-badges
Use SVGs for all README badges
2015-06-20 16:10:55 -03:00
Kevin Yap
190326c186 Use SVGs for all README badges 2015-06-20 10:58:38 -07:00
Bruno Oliveira
0008bcb877 Add coveragerc file for coverage options 2015-06-20 00:58:41 -03:00
Bruno Oliveira
80b5ebc398 Merge pull request #790 from pytest-dev/irc-notifications
Adjust IRC notifications to use #pytest.
2015-06-19 07:31:50 -03:00
Florian Bruhin
94332ed1d8 Adjust IRC notifications to use #pytest.
It seems #pytest-dev is quite dead. Also I set it to only send notifications on
changes (i.e. success -> failure and vice-versa).
2015-06-19 11:37:10 +02:00
holger krekel
13c01193d6 Merge remote-tracking branch 'origin/pytest-2.7' 2015-06-19 10:03:37 +02:00
Anatoly Bubenkov
4d6fef36f4 Merge branch 'pytest-2.7' 2015-06-17 13:42:41 +02:00
Bruno Oliveira
a0da7b9774 Mention issue 713 in the test's docstring 2015-06-16 20:42:49 -03:00
Punyashloka Biswal
0b0406fa85 Handle reports that don't have a reprcrash
Closes #713 (which happens because ReprFailDoctest
doesn't have a reprcrash)
2015-06-16 18:53:20 -04:00
Anatoly Bubenkov
f1245b094f Merge pull request #779 from pytest-dev/coveralls-shields-badge
Use shields.io badge for coveralls
2015-06-16 04:09:49 +02:00
Bruno Oliveira
c840e5c06e Use shields.io badge for coveralls
All badges have a similar look
2015-06-15 23:08:17 -03:00
Anatoly Bubenkov
c7573a92b2 Merge pull request #778 from pytest-dev/pypi-badge
Use pypi version badge from shields.io
2015-06-16 04:05:30 +02:00
Bruno Oliveira
84a476af87 Use pypi version badge from shields.io
The old one from pypip.in seems to always be broken as of late
2015-06-15 23:03:53 -03:00
Anatoly Bubenkov
e890d60459 appveyor badge 2015-06-16 03:28:12 +02:00
Anatoly Bubenkov
5dbe565b6d Merge branch 'master' of github.com:pytest-dev/pytest 2015-06-16 03:25:39 +02:00
Anatoly Bubenkov
8f09904c06 appveyor scripts 2015-06-16 03:25:28 +02:00
Anatoly Bubenkov
c0db143d4a Merge pull request #777 from bubenkoff/appveyor-integration
appveyor integration
2015-06-16 03:05:14 +02:00
Anatoly Bubenkov
534dbacc80 appveyor integration 2015-06-16 02:58:07 +02:00
Anatoly Bubenkov
af439e7d74 Merge pull request #775 from bubenkoff/pass-coveralls-env
pass coveralls env
2015-06-16 02:39:17 +02:00
Anatoly Bubenkov
b38cadbecd pass coveralls env 2015-06-16 02:38:52 +02:00
Anatoly Bubenkov
edfadf3a7c pass coveralls env 2015-06-16 01:12:24 +02:00
Anatoly Bubenkov
ae66683998 Merge pull request #773 from pytest-dev/remove-hg-files
Remove hgignore and hgtags files
2015-06-16 01:06:47 +02:00
Bruno Oliveira
4a8a4cb21b Merge pull request #770 from bubenkoff/add-travis-badge
add travis badge
2015-06-15 20:04:32 -03:00
Anatoly Bubenkov
ccebf8e1d6 add travis badge 2015-06-16 01:03:38 +02:00
Bruno Oliveira
8663be34b4 Remove hgignore and hgtags files 2015-06-15 20:02:41 -03:00
Bruno Oliveira
502a372405 Merge pull request #771 from pytest-dev/use-travis-containers
use travis containers
2015-06-15 19:56:34 -03:00
Bruno Oliveira
088ead2477 Merge pull request #772 from bubenkoff/split-travis-jobs
split travis jobs
2015-06-15 19:56:20 -03:00
Anatoly Bubenkov
f2494ecb3d split travis jobs 2015-06-16 00:49:55 +02:00
Anatoly Bubenkov
e9e01f2c9c use travis containers 2015-06-16 00:22:16 +02:00
Bruno Oliveira
d4e77faea7 Update sidebar links from Bitbucket to GitHub 2015-06-15 19:18:03 -03:00
Bruno Oliveira
ff58ae66c0 Update CONTRIBUTING documentation with GitHub instructions 2015-06-15 18:54:44 -03:00
Bruno Oliveira
b40f760cc3 Change links from bitbucket to GitHub 2015-06-15 18:28:31 -03:00
Floris Bruynooghe
42e7456780 Merged in RonnyPfannschmidt/pytest/regendoc-upgrade (pull request #303)
use regendoc normalization and regenerate docs
2015-06-10 10:44:38 +01:00
Ronny Pfannschmidt
43d27ec7ed use regendoc normalization and regenerate docs
--HG--
branch : regendoc-upgrade
2015-06-06 23:30:49 +02:00
Ronny Pfannschmidt
645ddc917f make regendoc a direct requirement 2015-06-06 14:15:23 +02:00
Ronny Pfannschmidt
33a7f03ccc sort AUTHORS and add Janne 2015-06-06 13:38:25 +02:00
Ronny Pfannschmidt
8b53a72dde add Janne`s changes to CHANGELOG 2015-06-06 11:53:34 +02:00
Ronny Pfannschmidt
8ee73e028f Merged in jpvanhal/pytest/include-setup-teardown-duration-in-junitxml (pull request #287)
Include setup and teardown in junitxml test durations
2015-06-06 11:50:37 +02:00
holger krekel
304fc4f222 Merged in issue735 (pull request #302)
use NameConstant node when it exists (fixes #735)
2015-06-04 07:48:53 +02:00
holger krekel
09edb813bc Close branch issue735
--HG--
branch : issue735
2015-06-04 07:48:53 +02:00
Benjamin Peterson
f3ad2e4ad2 use NameConstant node when it exists (fixes #735)
--HG--
branch : issue735
2015-06-03 18:07:10 -05:00
holger krekel
a2bb2ff164 port typo fix 2015-06-03 23:43:12 +02:00
holger krekel
c037f52878 fix issue741: make running output from testdir.run copy/pasteable 2015-06-03 23:40:42 +02:00
holger krekel
584cccf7ec Merged in nicoddemus/pytest/issue-741-pytester-output (pull request #293)
Make "running" output from testdir.run copy/pastable
2015-06-03 23:40:08 +02:00
holger krekel
c92467df2f add changelog for latest merge 2015-06-03 23:39:00 +02:00
holger krekel
ad08bf79e7 Merged in The-Compiler/pytest (pull request #298)
Fix monkeypatch.setenv with string and raising=False.
2015-06-03 23:37:26 +02:00
holger krekel
22c62dbd90 Merged in flub/pytest (pull request #299)
Ignore emacs' .dir-locals.el file
2015-06-03 23:34:13 +02:00
Floris Bruynooghe
d220be8468 Use platform.python_version() to show Python version number
This results in something like "3.5.0b2" for non-final releases
while still being "3.5.0" for final releases.
2015-05-31 20:31:31 +01:00
Floris Bruynooghe
b09be4e3ef Merged in flub/pytest (pull request #297)
Merge 2.7.1 release changes into default
2015-05-31 20:27:13 +01:00
Darren Yin
efce2ababa add in missing finalizer to doc example 2015-05-21 19:15:52 -07:00
Floris Bruynooghe
773b8b69dd Ignore emacs' .dir-locals.el file
This can be used to e.g. automatically set a specific syntax
checker or virtualenv to activate.
2015-05-20 10:33:13 +01:00
Florian Bruhin
ff8d787cd5 Fix monkeypatch.setenv with string and raising=False.
Fixes #746.
2015-05-19 22:59:49 +02:00
Floris Bruynooghe
d299f0d99f Merge changes from 2.7.1 release
This is mostly doc examples regeneration, other changes are:
- Add 2.7.1 tag to .hgtags
- Update changelog to use real versions
- Update HOWTORELEASE.rst
- Fix rst in doc/en/adopt.txt
- Fix CHANGELOG and release-2.7.0 rst formatting
2015-05-19 21:43:50 +01:00
holger krekel
3401049dea remove adopt pytest note 2015-05-12 13:36:43 +02:00
Bruno Oliveira
a7f880fa1f Make "running" output from testdir.run copy/pastable
fix 741

--HG--
branch : issue-741-pytester-output
2015-05-09 10:24:33 -03:00
holger krekel
c4bd3c672b another try at ignoring cx_freeze during other tox envs 2015-05-07 12:19:35 +02:00
holger krekel
52354b9ab5 try to ignore cx_freeze from regular pytest runs and see if travis is happy 2015-05-07 12:02:14 +02:00
holger krekel
3c187c844e make default depend on just published py/pluggy releases 2015-05-07 11:50:08 +02:00
Ronny Pfannschmidt
45ed4c726e Merged in hpk42/pytest-patches/plug30 (pull request #291)
use new pluggy api (now at 0.3.0) for adding hookcall monitoring
2015-05-07 11:24:39 +02:00
holger krekel
d9a44098ce use new pluggy api (now at 0.3.0) for adding hookcall monitoring
and reraise real keyboard interrupts during inline pytest runs
to allow for better stopping of the pytest tests.

--HG--
branch : plug30
2015-05-07 11:02:55 +02:00
holger krekel
b93abfb3d1 Merged in hpk42/pytest-patches/pluggy1 (pull request #290)
integrate pluggy as external plugin manager
2015-05-06 15:02:05 +02:00
holger krekel
bb8141e27c - make sure sub pytest runs use the same basetemp
- depend on pluggy < 0.3

--HG--
branch : pluggy1
2015-05-06 14:58:46 +02:00
holger krekel
bddc88f09e adapt to pluggy naming, rename pytest.hookspec_opts to pytest.hookspec,s ame with hookimpl_opts
--HG--
branch : pluggy1
2015-05-06 10:08:08 +02:00
holger krekel
5ea7f0342b Merged default into pluggy1
--HG--
branch : pluggy1
2015-05-05 22:29:53 +02:00
holger krekel
13db045fc4 merge 2015-05-05 21:55:39 +02:00
holger krekel
23538bcd31 - some more adaptation to most recent pluggy API
- avoid using pluggin underscore api
- show pluggy version in header

--HG--
branch : pluggy1
2015-05-05 21:53:04 +02:00
holger krekel
a4f2236b36 merge default
--HG--
branch : pluggy1
2015-05-05 14:52:16 +02:00
holger krekel
88538f13ba adapt for current API changes of pluggy
--HG--
branch : pluggy1
2015-05-04 15:08:41 +02:00
holger krekel
920b5afe45 now that we are going to have wheels, py source code might be not be installed
and the resulting genscript is useless

--HG--
branch : pluggy1
2015-05-04 14:42:01 +02:00
holger krekel
e4b9603fa8 Merged in famousgarkin/pytest/famousgarkin/monkeypatchchdir-docstring-punctuation-1430453576841 (pull request #288)
monkeypatch.chdir docstring punctuation
2015-05-04 14:28:32 +02:00
holger krekel
ef7f627573 merging pytest-2.7 2015-05-04 14:27:09 +02:00
Janne Vanhala
93628fc0eb Include setup and teardown in junitxml test durations
--HG--
branch : include-setup-teardown-duration-in-junitxml
2015-05-01 14:55:52 +03:00
famousgarkin
47936643c9 monkeypatch.chdir docstring punctuation
--HG--
branch : famousgarkin/monkeypatchchdir-docstring-punctuation-1430453576841
2015-05-01 04:13:06 +00:00
Floris Bruynooghe
aa2ffb9805 Merge fix for issue 731 from pytest-2.7 2015-04-30 21:13:03 +01:00
holger krekel
25963e0544 adapt pytest to pluggy's decoratorclass branch
--HG--
branch : pluggy1
2015-04-29 16:40:52 +02:00
holger krekel
5ee7ee0850 adapt pytest to using pluggy (current master)
--HG--
branch : pluggy1
2015-04-29 16:40:51 +02:00
holger krekel
d6670bd6a8 Merged in hpk42/pytest-patches/testrefactor (pull request #284)
majorly refactor pytester and speed/streamline  tests
2015-04-29 16:32:28 +02:00
holger krekel
9aec5cd52d use runpytest() instead of runpytest_inprocess if a test can run as subprocess as well
--HG--
branch : testrefactor
2015-04-28 12:05:08 +02:00
holger krekel
4d5161444c merge
--HG--
branch : testrefactor
2015-04-28 11:56:57 +02:00
holger krekel
db5649ec6a streamline pytester API majorly:
- integrate conftest into pytester plugin
- introduce runpytest() to either call runpytest_inline (default) or
  runpytest_subprocess (python -m pytest)
- move testdir.inline_runsource1 to pdb tests
- strike some unneccessary methods.
- a new section "writing plugins" and some better pytester docs

--HG--
branch : testrefactor
2015-04-28 11:54:53 +02:00
holger krekel
a8afba054a - refine lsof checking
- make runpytest() create an inline testing process instead of
  a subprocess one

--HG--
branch : testrefactor
2015-04-28 11:54:46 +02:00
holger krekel
d3e363b97a - make API between runpytest() and inline_run() more similar
- shift a number of tests to become inline_run() tests

--HG--
branch : testrefactor
2015-04-28 11:54:45 +02:00
holger krekel
2e3e1e9b7e Merged in hpk42/pytest-patches/plugtestfix (pull request #283)
make test suite more tolerable against xdist causing warnings itself
2015-04-28 11:52:53 +02:00
holger krekel
424e5d1394 make test suite more tolerable against xdist causing warnings itself (which it does
currently)

--HG--
branch : plugtestfix
2015-04-27 15:06:47 +02:00
Floris Bruynooghe
2d8f115d8c Merged in hpk42/pytest-patches/more_plugin (pull request #282)
another major pluginmanager refactor and docs
2015-04-27 13:17:40 +01:00
holger krekel
b2d66b9e7b simplify load_setuptools_entrypoints and refine comments/docstrings
--HG--
branch : more_plugin
2015-04-27 14:10:33 +02:00
holger krekel
c54afbe42e deprecate and warn about __multicall__ usage in hooks, refine docs about hook ordering,
make hookwrappers respect tryfirst/trylast

--HG--
branch : more_plugin
2015-04-27 12:50:34 +02:00
holger krekel
dea1c96031 actually revert back to using older simpler method for subset hook
calling.  It is slightly more inefficient but easier to implement and
read.

--HG--
branch : more_plugin
2015-04-26 17:17:59 +02:00
holger krekel
16c922bf53 merge contribution fix 2015-04-26 01:06:17 +02:00
holger krekel
d2ea7387f2 re-add tryfirst/trylast marker documentation, mark it as to be removed
--HG--
branch : more_plugin
2015-04-26 00:47:24 +02:00
holger krekel
8e009ee31c move consider_setuptools_entrypoints to core pluginmanager
--HG--
branch : more_plugin
2015-04-26 00:41:29 +02:00
holger krekel
0c961deeaa fix some doc strings
--HG--
branch : more_plugin
2015-04-26 00:22:34 +02:00
holger krekel
32165d82b1 introduce a new subset_hook_caller instead of remove make_hook_caller
and adapat and refine conftest/global plugin management accordingly

--HG--
branch : more_plugin
2015-04-26 00:10:52 +02:00
holger krekel
d422247433 specialize make_hook_caller to work with a subset of the registered plugins.
--HG--
branch : more_plugin
2015-04-25 22:13:42 +02:00
holger krekel
a042c57227 ensure proper get_name references
--HG--
branch : more_plugin
2015-04-25 20:42:41 +02:00
holger krekel
3a1374e69c simplify plugins bookkeeping further, refine API
--HG--
branch : more_plugin
2015-04-25 20:17:32 +02:00
holger krekel
1c0582eaa7 simplify addition of method and scanning of plugins
--HG--
branch : more_plugin
2015-04-25 18:15:42 +02:00
holger krekel
1e883f5979 simplify tracing mechanics by simply going through an indirection
--HG--
branch : more_plugin
2015-04-25 18:15:39 +02:00
holger krekel
9c5495832c avoid direct circular reference between config and pluginmanager
--HG--
branch : more_plugin
2015-04-25 18:14:41 +02:00
holger krekel
7364647f2f fix issue732: make sure removed plugins remove all hook callers.
--HG--
branch : more_plugin
2015-04-25 18:14:39 +02:00
holger krekel
4e116ed503 make pytest_plugin_registered a historic hook
--HG--
branch : more_plugin
2015-04-25 13:38:30 +02:00
holger krekel
e7a2e53108 Streamline data structures
--HG--
branch : more_plugin
2015-04-25 13:38:29 +02:00
holger krekel
2f8a1aed6e properly perform hook calls with extra methods
--HG--
branch : more_plugin
2015-04-25 11:29:11 +02:00
holger krekel
a63585dcab introduce historic hook spec which will memorize calls to a hook
in order to call them on later registered plugins

--HG--
branch : more_plugin
2015-04-25 11:29:11 +02:00
holger krekel
ea50ef1588 split plugin documentation into "using" and "writing plugins",
referencing each other.  Also add tryfirst/trylast examples.

--HG--
branch : more_plugin
2015-04-25 11:29:11 +02:00
holger krekel
d2a5c7f99b add documented hookimpl_opts and hookspec_opts decorators
so that one doesn't have to use pytest.mark or function-attribute setting anymore

--HG--
branch : more_plugin
2015-04-25 11:29:11 +02:00
holger krekel
bbbb6dc2e3 remove _do_register indirection between PluginManager and PytestPluginManager
--HG--
branch : more_plugin
2015-04-25 11:29:11 +02:00
holger krekel
f41528433b also incrementally remove plugins from hook callers
--HG--
branch : more_plugin
2015-04-25 11:29:11 +02:00
holger krekel
02a4042dca incrementally update hook call lists instead of regenerating the whole
list on each registered plugin

--HG--
branch : more_plugin
2015-04-25 11:29:11 +02:00
holger krekel
b03c1342ac allow to register plugins with hooks that are only added later
--HG--
branch : more_plugin
2015-04-25 11:29:11 +02:00
holger krekel
d8e91d9fee Merged in hpk42/pytest-patches/plugin_no_pytest (pull request #278)
Refactor pluginmanagement
2015-04-25 09:08:21 +02:00
holger krekel
9020bf48b7 remove useless check
--HG--
branch : plugin_no_pytest
2015-04-24 14:09:57 +02:00
holger krekel
237ac8562f minimize HookCaller attributes: avoid passing in hookrelay to HookCallers
--HG--
branch : plugin_no_pytest
2015-04-24 13:02:49 +02:00
holger krekel
feb4b2249a remove some redundancy when parsing import spec
--HG--
branch : plugin_no_pytest
2015-04-23 13:15:34 +02:00
holger krekel
95dd2eb1da streamline and document handling of builtin module special casing.
--HG--
branch : plugin_no_pytest
2015-04-23 12:39:11 +02:00
holger krekel
8fde2f98ae merge default
--HG--
branch : plugin_no_pytest
2015-04-23 12:35:15 +02:00
holger krekel
2b80caf1af merge cxfreeze fix 2015-04-23 12:07:12 +02:00
Floris Bruynooghe
e450218daa Merge _pytest fixture reintroduction from pytest-2.7 branch
This was accidentally removed while some plugins depend on it.
2015-04-23 00:55:58 +01:00
holger krekel
27589eb7e1 reshuffle pluginmanager methods and add some docstrings.
--HG--
branch : plugin_no_pytest
2015-04-22 16:42:41 +02:00
holger krekel
d5db9faba8 shuffle PluginManager method order to first have the public API
and then the internal.

--HG--
branch : plugin_no_pytest
2015-04-22 16:34:42 +02:00
holger krekel
715a235b45 remove shutdown logic from PluginManager and add a add_cleanup() API
for the already existing cleanup logic of the config object.
This simplifies lifecycle management as we don't keep two
layers of shutdown functions and also simplifies the pluginmanager
interface.

also add some docstrings.

--HG--
branch : plugin_no_pytest
2015-04-22 16:33:20 +02:00
holger krekel
f746c190ac slight cleanup of plugin register() functionality
--HG--
branch : plugin_no_pytest
2015-04-22 14:54:28 +02:00
holger krekel
d632a0d5c2 merge conftest management into PytestPluginManager
--HG--
branch : plugin_no_pytest
2015-04-22 14:15:42 +02:00
holger krekel
894d7dca22 avoid undocumented special casing of "pytest_" prefix
--HG--
branch : plugin_no_pytest
2015-04-22 13:44:37 +02:00
holger krekel
20d6c0b560 simplify exception capturing
--HG--
branch : plugin_no_pytest
2015-04-22 13:37:42 +02:00
holger krekel
c08dfdc330 move bookkeeping of conftest plugins in core pluginmanager to PytestPluginManager
--HG--
branch : plugin_no_pytest
2015-04-22 13:33:01 +02:00
holger krekel
7049ebe4e2 avoid prepend to register api as it's redundant wrt to hooks
--HG--
branch : plugin_no_pytest
2015-04-22 13:31:46 +02:00
holger krekel
1ef49ac5ab minimize HookRelay to become a pure container, refactor initialization and
tests of plugin management to be a bit better split between pytest
and pytest-independent bits

--HG--
branch : plugin_no_pytest
2015-04-22 13:31:46 +02:00
holger krekel
db650de372 remove redundant py check as our setup.py excludes py <=1.4 already
--HG--
branch : plugin_no_pytest
2015-04-22 10:04:13 +02:00
Floris Bruynooghe
d9885388d0 Merge pull request #277 from pytest-2.7 branch
This removes the drone.io badge from the README as it doesn't make
sense to have it on the cheeseshop status page.

Fixes issue #726.
2015-04-21 15:04:08 +01:00
Floris Bruynooghe
240cd1f28d Merge cleaning of sys.modules after pytester.inline_run()
Merged in schettino72/pytest/pytester-inline-run-clean-sys-modules
(pull request #278).
2015-04-21 11:00:32 +01:00
Floris Bruynooghe
31af381c56 Merged in hpk42/pytest-patches/prefer_installed (pull request #275)
change test module importing behaviour to append to sys.path
2015-04-21 10:47:33 +01:00
Eduardo Schettino
bc0ecd1d06 pytester: add method `TmpTestdir.delete_loaded_modules()`
, and call it from ``inline_run()`` to allow temporary modules to be reloaded.

--HG--
branch : pytester-inline-run-clean-sys-modules
2015-04-21 10:18:04 +08:00
Eduardo Schettino
c792ab8aed fix regendoc repository location on requirements-docs.txt.
--HG--
branch : pytester-inline-run-clean-sys-modules
2015-04-21 10:16:04 +08:00
holger krekel
bac1ccd5b3 merge fix of issue553 on pytest-2.7 2015-04-17 22:32:49 +02:00
holger krekel
5c8e5acf9d change test module importing behaviour to append to sys.path
instead of prepending.  This better allows to run test modules
against installated versions of a package even if the package
under test has the same import root.  In this example::

   testing/__init__.py
   testing/test_pkg_under_test.py
   pkg_under_test/

the tests will preferrably run against the installed version
of pkg_under_test whereas before they would always pick
up the local version.

--HG--
branch : prefer_installed
2015-04-17 22:25:35 +02:00
Floris Bruynooghe
fb07a09964 Merge pull request #274 from pytest-2.7
fixed regression to 2.6.4 which surfaced e.g. in lost stdout capture printing
2015-04-17 11:10:47 +01:00
Floris Bruynooghe
c7a60af666 Use capital Y as the tests look for that 2015-04-13 09:08:10 +01:00
Floris Bruynooghe
09dff73607 Merge pytest-2.7 for issue660 fix 2015-04-13 00:04:53 +01:00
Floris Bruynooghe
ddffa9d1cc Merge wheel support from pytest-2.7 branch
Merged in pytest-2.7 (pull request #269).
2015-04-12 23:47:10 +01:00
Floris Bruynooghe
bf0b70aa66 Some docstrings for the pytester plugin
These aren't quite complete but are a jolly good start anyway.  It
seems better to commit this now then leave it lingering until it
gets lost.
2015-04-11 17:07:37 +01:00
holger krekel
74019025b9 shift default to 2.8.0.dev 2015-04-04 16:32:25 +02:00
holger krekel
1ab93a5f1d Merged in release-checklist (pull request #266)
add a release checklist
2015-04-04 16:27:07 +02:00
holger krekel
d9d932aef5 Merged in yield-experimental-docs (pull request #267)
Removed note about yield fixtures being experimental
2015-04-04 16:25:24 +02:00
holger krekel
421c43a873 Close branch yield-experimental-docs
--HG--
branch : yield-experimental-docs
2015-04-04 16:25:24 +02:00
Bruno Oliveira
6558c7245f Brought back discussion session
Reworded it a bit to bring it to par with the current status

--HG--
branch : yield-experimental-docs
2015-04-03 19:44:06 -03:00
Bruno Oliveira
b3d646455a Fixed straightforward spelling
--HG--
branch : yield-experimental-docs
2015-04-03 17:06:51 -03:00
Bruno Oliveira
161d9e5971 Removed "discussion" session
Kept a note about exceptions after yield not being reraised

--HG--
branch : yield-experimental-docs
2015-04-03 16:59:33 -03:00
Bruno Oliveira
30260361dd Reviewed wording about yield being a "new" feature
--HG--
branch : yield-experimental-docs
2015-04-03 16:55:10 -03:00
Bruno Oliveira
c1b935adbd Removed note about yield fixtures being experimental
--HG--
branch : yield-experimental-docs
2015-04-03 16:28:20 -03:00
278 changed files with 22987 additions and 11240 deletions

7
.coveragerc Normal file
View File

@@ -0,0 +1,7 @@
[run]
omit =
# standlonetemplate is read dynamically and tested by test_genscript
*standalonetemplate.py
# oldinterpret could be removed, as it is no longer used in py26+
*oldinterpret.py
vendored_packages

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
CHANGELOG merge=union

8
.github/ISSUE_TEMPLATE.md vendored Normal file
View File

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

11
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,11 @@
Thanks for submitting a PR, your contribution is really appreciated!
Here's a quick checklist that should be present in PRs:
- [ ] Target: for bug or doc fixes, target `master`; for new features, target `features`;
- [ ] Make sure to include one or more tests for your change;
- [ ] Add yourself to `AUTHORS`;
- [ ] Add a new entry to `CHANGELOG.rst`
* Choose any open position to avoid merge conflicts with other PRs.
* Add a link to the issue you are fixing (if any) using RST syntax.
* The pytest team likes to have people to acknowledged in the `CHANGELOG`, so please add a thank note to yourself ("Thanks @user for the PR") and a link to your GitHub profile. It may sound weird thanking yourself, but otherwise a maintainer would have to do it manually before or after merging instead of just using GitHub's merge button. This makes it easier on the maintainers to merge PRs.

6
.gitignore vendored
View File

@@ -16,6 +16,9 @@ include/
*.class
*.orig
*~
.hypothesis/
.eggs/
doc/*/_build
build/
@@ -23,10 +26,11 @@ dist/
*.egg-info
issue/
env/
.env/
3rdparty/
.tox
.cache
.coverage
.ropeproject
.idea
.hypothesis

View File

@@ -1,39 +0,0 @@
# Automatically generated by `hgimportsvn`
syntax:glob
.svn
.hgsvn
# Ignore local virtualenvs
syntax:glob
lib/
bin/
include/
.Python/
.env/
# These lines are suggested according to the svn:ignore property
# Feel free to enable them by uncommenting them
syntax:glob
*.pyc
*.pyo
*.swp
*.html
*.class
*.orig
*~
doc/*/_build
build/
dist/
testing/cx_freeze/build
testing/cx_freeze/cx_freeze_source
*.egg-info
issue/
env/
env3/
3rdparty/
.tox
.cache
.coverage
.ropeproject
*.sublime-*

77
.hgtags
View File

@@ -1,77 +0,0 @@
52c6d9e78777a5a34e813123997dfc614a1a4767 1.0.0b3
1c7aaa8c61f3b0945921a9acc7beb184201aed4b 1.0.0b4
1c7aaa8c61f3b0945921a9acc7beb184201aed4b 1.0.0b4
0000000000000000000000000000000000000000 1.0.0b4
0000000000000000000000000000000000000000 1.0.0b4
8cd6eb91eba313b012d6e568f37d844dc0751f2e 1.0.0b4
8cd6eb91eba313b012d6e568f37d844dc0751f2e 1.0.0b4
0000000000000000000000000000000000000000 1.0.0b4
2cc0507f117ffe721dff7ee026648cfce00ec92f 1.0.0b6
86f1e1b6e49bf5882a809f11edd1dbb08162cdad 1.0.0b8
86f1e1b6e49bf5882a809f11edd1dbb08162cdad 1.0.0b8
c63f35c266cbb26dad6b87b5e115d65685adf448 1.0.0b8
c63f35c266cbb26dad6b87b5e115d65685adf448 1.0.0b8
0eaa0fdf2ba0163cf534dc2eff4ba2e5fc66c261 1.0.0b8
e2a60653cb490aeed81bbbd83c070b99401c211c 1.0.0b9
5ea0cdf7854c3d4278d36eda94a2b68483a0e211 1.0.0
5ea0cdf7854c3d4278d36eda94a2b68483a0e211 1.0.0
7acde360d94b6a2690ce3d03ff39301da84c0a2b 1.0.0
6bd221981ac99103002c1cb94fede400d23a96a1 1.0.1
4816e8b80602a3fd3a0a120333ad85fbe7d8bab4 1.0.2
60c44bdbf093285dc69d5462d4dbb4acad325ca6 1.1.0
319187fcda66714c5eb1353492babeec3d3c826f 1.1.1
4fc5212f7626a56b9eb6437b5c673f56dd7eb942 1.2.0
c143a8c8840a1c68570890c8ac6165bbf92fd3c6 1.2.1
eafd3c256e8732dfb0a4d49d051b5b4339858926 1.3.0
d5eacf390af74553227122b85e20345d47b2f9e6 1.3.1
d5eacf390af74553227122b85e20345d47b2f9e6 1.3.1
8b8e7c25a13cf863f01b2dd955978285ae9daf6a 1.3.1
3bff44b188a7ec1af328d977b9d39b6757bb38df 1.3.2
c59d3fa8681a5b5966b8375b16fccd64a3a8dbeb 1.3.3
79ef6377705184c55633d456832eea318fedcf61 1.3.4
79ef6377705184c55633d456832eea318fedcf61 1.3.4
90fffd35373e9f125af233f78b19416f0938d841 1.3.4
e9e127acd6f0497324ef7f40cfb997cad4c4cd17 2.0.0
e4497c2aed358c1988cf7be83ca9394c3c707fa2 2.0.1
84e5c54b72448194a0f6f815da7e048ac8019d50 2.0.2
2ef82d82daacb72733a3a532a95c5a37164e5819 2.0.3
2ef82d82daacb72733a3a532a95c5a37164e5819 2.0.3
c777dcad166548b7499564cb49ae5c8b4b07f935 2.0.3
c777dcad166548b7499564cb49ae5c8b4b07f935 2.0.3
49f11dbff725acdcc5fe3657cbcdf9ae04e25bbc 2.0.3
49f11dbff725acdcc5fe3657cbcdf9ae04e25bbc 2.0.3
363e5a5a59c803e6bc176a6f9cc4bf1a1ca2dab0 2.0.3
e5e1746a197f0398356a43fbe2eebac9690f795d 2.1.0
5864412c6f3c903384243bd315639d101d7ebc67 2.1.2
12a05d59249f80276e25fd8b96e8e545b1332b7a 2.1.3
1522710369337d96bf9568569d5f0ca9b38a74e0 2.2.0
3da8cec6c5326ed27c144c9b6d7a64a648370005 2.2.1
92b916483c1e65a80dc80e3f7816b39e84b36a4d 2.2.2
3c11c5c9776f3c678719161e96cc0a08169c1cb8 2.2.3
ad9fe504a371ad8eb613052d58f229aa66f53527 2.2.4
c27a60097767c16a54ae56d9669a77925b213b9b 2.3.0
acf0e1477fb19a1d35a4e40242b77fa6af32eb17 2.3.1
8738b828dec53937765db71951ef955cca4c51f6 2.3.2
7fe44182c434f8ac89149a3c340479872a5d5ccb 2.3.3
ef299e57f24218dbdd949498d7e660723636bcc3 2.3.4
fc3a793e87ec907000a47ea0d3a372a2fe218c0a 2.3.5
b93ac0cdae02effaa3c136a681cc45bba757fe46 1.4.14
b93ac0cdae02effaa3c136a681cc45bba757fe46 1.4.14
0000000000000000000000000000000000000000 1.4.14
0000000000000000000000000000000000000000 1.4.14
0000000000000000000000000000000000000000 1.4.14
af860de70cc3f157ac34ca1d4bf557a057bff775 2.4.0
8828c924acae0b4cad2e2cb92943d51da7cb744a 2.4.1
8d051f89184bfa3033f5e59819dff9f32a612941 2.4.2
a064ad64d167508a8e9e73766b1a4e6bd10c85db 2.5.0
039d543d1ca02a716c0b0de9a7131beb8021e8a2 2.5.1
421d3b4d150d901de24b1cbeb8955547b1420483 2.5.2
60725b17a9d1af4100abb8be3f9f4ddf6262bf34 2.6.0
60725b17a9d1af4100abb8be3f9f4ddf6262bf34 2.6.0
88af949b9611494e2c65d528f9e565b00fb7e8ca 2.6.0
a4f9639702baa3eb4f3b16e162f74f7b69f3f9e1 2.6.1
a4f25c5e649892b5cc746d21be971e4773478af9 2.6.2
2967aa416a4f3cdb65fc75073a2a148e1f372742 2.6.3
f03b6de8325f5b6c35cea7c3de092f134ea8ef07 2.6.4
7ed701fa2fb554bfc0618d447dfec700cc697407 2.7.0
edc1d080bab5a970da8f6c776be50768829a7b09 2.7.1

View File

@@ -1,13 +1,16 @@
sudo: false
language: python
python:
- '3.5.0b3'
- '3.5'
# command to install dependencies
install: "pip install -U tox"
# # command to run tests
env:
matrix:
- TESTENV=flakes
# coveralls is not listed in tox's envlist, but should run in travis
- TESTENV=coveralls
# note: please use "tox --listenvs" to populate the build matrix below
- TESTENV=linting
- TESTENV=py26
- TESTENV=py27
- TESTENV=py33
@@ -15,23 +18,24 @@ env:
- TESTENV=py35
- TESTENV=pypy
- TESTENV=py27-pexpect
- TESTENV=py34-pexpect
- TESTENV=py27-nobyte
- TESTENV=py27-xdist
- TESTENV=py34-xdist
- TESTENV=py27-trial
- TESTENV=py33
- TESTENV=py34-trial
# inprocess tests by default were introduced in 2.8 only;
# this TESTENV should be enabled when merged back to master
#- TESTENV=py27-subprocess
- TESTENV=py35-pexpect
- TESTENV=py35-xdist
- TESTENV=py35-trial
- TESTENV=py27-nobyte
- TESTENV=doctesting
- TESTENV=py27-cxfreeze
- TESTENV=coveralls
script: tox --recreate -i ALL=https://devpi.net/hpk/dev/ -e $TESTENV
- TESTENV=freeze
- TESTENV=docs
script: tox --recreate -e $TESTENV
notifications:
irc:
- "chat.freenode.net#pytest-dev"
channels:
- "chat.freenode.net#pytest"
on_success: change
on_failure: change
skip_join: true
email:
- pytest-commit@python.org

76
AUTHORS
View File

@@ -3,52 +3,128 @@ merlinux GmbH, Germany, office at merlinux eu
Contributors include::
Abdeali JK
Abhijeet Kasurde
Ahn Ki-Wook
Alexei Kozlenok
Anatoly Bubenkoff
Andreas Zeidler
Andrzej Ostrowski
Andy Freeland
Anthon van der Neut
Antony Lee
Armin Rigo
Aron Curzon
Aviv Palivoda
Ben Webb
Benjamin Peterson
Bernard Pratz
Bob Ippolito
Brian Dorsey
Brian Okken
Brianna Laugher
Bruno Oliveira
Cal Leeming
Carl Friedrich Bolz
Charles Cloud
Charnjit SiNGH (CCSJ)
Chris Lamb
Christian Boelsen
Christian Theunert
Christian Tismer
Christopher Gilling
Daniel Grana
Daniel Hahler
Daniel Nuri
Danielle Jenkins
Dave Hunt
David Díaz-Barquero
David Mohr
David Vierra
Diego Russo
Dmitry Dygalo
Edison Gustavo Muenz
Edoardo Batini
Eduardo Schettino
Elizaveta Shashkova
Endre Galaczi
Eric Hunsberger
Eric Siegerman
Erik M. Bray
Feng Ma
Florian Bruhin
Floris Bruynooghe
Gabriel Reis
Georgy Dyuldin
Graham Horler
Greg Price
Grig Gheorghiu
Guido Wesdorp
Harald Armin Massa
Ian Bicking
Jaap Broekhuizen
Jan Balster
Janne Vanhala
Jason R. Coombs
Javier Domingo Cansino
Javier Romero
John Towler
Jon Sonesen
Jordan Guymon
Joshua Bronson
Jurko Gospodnetić
Justyna Janczyszyn
Kale Kundert
Katarzyna Jachim
Kevin Cox
Lee Kamentsky
Lukas Bednar
Maciek Fijalkowski
Maho
Marc Schlaich
Marcin Bachry
Mark Abramowitz
Markus Unterwaditzer
Martijn Faassen
Martin K. Scherer
Martin Prusse
Matt Bachmann
Matt Williams
Matthias Hafner
mbyt
Michael Aquilina
Michael Birtwell
Michael Droettboom
Mike Lundy
Nicolas Delaby
Oleg Pidsadnyi
Oliver Bestwalter
Omar Kohl
Pieter Mulder
Piotr Banaszkiewicz
Punyashloka Biswal
Quentin Pradet
Ralf Schmitt
Raphael Pierzina
Roberto Polli
Romain Dorgueil
Roman Bolshakov
Ronny Pfannschmidt
Ross Lawley
Russel Winder
Ryan Wooden
Samuele Pedroni
Simon Gomizelj
Stefan Farmbauer
Stefan Zimmermann
Stefano Taschini
Steffen Allner
Stephan Obermann
Tareq Alayan
Ted Xiao
Thomas Grainger
Tom Viner
Trevor Bekolay
Vasily Kuznetsov
Wouter van Ackooy
Xuecong Liao

File diff suppressed because it is too large Load Diff

View File

@@ -9,46 +9,18 @@ so do not hesitate!
:depth: 2
.. _submitplugin:
.. _submitfeedback:
Submit a plugin, co-develop pytest
----------------------------------
Feature requests and feedback
-----------------------------
Pytest development of the core, some plugins and support code happens
in repositories living under:
Do you like pytest? Share some love on Twitter or in your blog posts!
- `the pytest-dev github organisation <https://github.com/pytest-dev>`_
We'd also like to hear about your propositions and suggestions. Feel free to
`submit them as issues <https://github.com/pytest-dev/pytest/issues>`_ and:
- `the pytest-dev bitbucket team <https://bitbucket.org/pytest-dev>`_
All pytest-dev team members have write access to all contained
repositories. pytest core and plugins are generally developed
using `pull requests`_ to respective repositories.
You can submit your plugin by subscribing to the `pytest-dev mail list
<https://mail.python.org/mailman/listinfo/pytest-dev>`_ and writing a
mail pointing to your existing pytest plugin repository which must have
the following:
- PyPI presence with a ``setup.py`` that contains a license, ``pytest-``
prefixed, version number, authors, short and long description.
- a ``tox.ini`` for running tests using `tox <http://tox.testrun.org>`_.
- a ``README.txt`` describing how to use the plugin and on which
platforms it runs.
- a ``LICENSE.txt`` file or equivalent containing the licensing
information, with matching info in ``setup.py``.
- an issue tracker unless you rather want to use the core ``pytest``
issue tracker.
If no contributor strongly objects and two agree, the repo will be
transferred to the ``pytest-dev`` organisation and you'll become a
member of the ``pytest-dev`` team, with commit rights to all projects.
We recommend that each plugin has at least three people who have the
right to release to pypi.
* Explain in detail how they should work.
* Keep the scope as narrow as possible. This will make it easier to implement.
.. _reportbugs:
@@ -56,7 +28,7 @@ right to release to pypi.
Report bugs
-----------
Report bugs for pytest at https://github.com/pytest-dev/pytest/issues
Report bugs for pytest in the `issue tracker <https://github.com/pytest-dev/pytest/issues>`_.
If you are reporting a bug, please include:
@@ -66,40 +38,29 @@ If you are reporting a bug, please include:
installed libraries and pytest version.
* Detailed steps to reproduce the bug.
.. _submitfeedback:
If you can write a demonstration test that currently fails but should pass (xfail),
that is a very useful commit to make as well, even if you can't find how
to fix the bug yet.
Submit feedback for developers
------------------------------
Do you like pytest? Share some love on Twitter or in your blog posts!
We'd also like to hear about your propositions and suggestions. Feel free to
`submit them as issues <https://github.com/pytest-dev/pytest/issues>`__ and:
* Set the "kind" to "enhancement" or "proposal" so that we can quickly find
about them.
* Explain in detail how they should work.
* Keep the scope as narrow as possible. This will make it easier to implement.
* If you have required skills and/or knowledge, we are very happy for
:ref:`pull requests <pull-requests>`.
.. _fixbugs:
Fix bugs
--------
Look through the GitHub issues for bugs. Here is sample filter you can use:
Look through the GitHub issues for bugs. Here is a filter you can use:
https://github.com/pytest-dev/pytest/labels/bug
:ref:`Talk <contact>` to developers to find out how you can fix specific bugs.
Don't forget to check the issue trackers of your favourite plugins, too!
.. _writeplugins:
Implement features
------------------
Look through the GitHub issues for enhancements. Here is sample filter you
can use:
Look through the GitHub issues for enhancements. Here is a filter you can use:
https://github.com/pytest-dev/pytest/labels/enhancement
:ref:`Talk <contact>` to developers to find out how you can implement specific
@@ -108,13 +69,82 @@ features.
Write documentation
-------------------
pytest could always use more documentation. What exactly is needed?
Pytest could always use more documentation. What exactly is needed?
* More complementary documentation. Have you perhaps found something unclear?
* Documentation translations. We currently have English and Japanese versions.
* Docstrings. There's never too much of them.
* Documentation translations. We currently have only English.
* Docstrings. There can never be too many of them.
* Blog posts, articles and such -- they're all very appreciated.
You can also edit documentation files directly in the GitHub web interface,
without using a local copy. This can be convenient for small fixes.
.. _submitplugin:
Submitting Plugins to pytest-dev
--------------------------------
Pytest development of the core, some plugins and support code happens
in repositories living under the ``pytest-dev`` organisations:
- `pytest-dev on GitHub <https://github.com/pytest-dev>`_
- `pytest-dev on Bitbucket <https://bitbucket.org/pytest-dev>`_
All pytest-dev Contributors team members have write access to all contained
repositories. Pytest core and plugins are generally developed
using `pull requests`_ to respective repositories.
The objectives of the ``pytest-dev`` organisation are:
* Having a central location for popular pytest plugins
* Sharing some of the maintenance responsibility (in case a maintainer no
longer wishes to maintain a plugin)
You can submit your plugin by subscribing to the `pytest-dev mail list
<https://mail.python.org/mailman/listinfo/pytest-dev>`_ and writing a
mail pointing to your existing pytest plugin repository which must have
the following:
- PyPI presence with a ``setup.py`` that contains a license, ``pytest-``
prefixed name, version number, authors, short and long description.
- a ``tox.ini`` for running tests using `tox <http://tox.testrun.org>`_.
- a ``README.txt`` describing how to use the plugin and on which
platforms it runs.
- a ``LICENSE.txt`` file or equivalent containing the licensing
information, with matching info in ``setup.py``.
- an issue tracker for bug reports and enhancement requests.
- a `changelog <http://keepachangelog.com/>`_
If no contributor strongly objects and two agree, the repository can then be
transferred to the ``pytest-dev`` organisation.
Here's a rundown of how a repository transfer usually proceeds
(using a repository named ``joedoe/pytest-xyz`` as example):
* ``joedoe`` transfers repository ownership to ``pytest-dev`` administrator ``calvin``.
* ``calvin`` creates ``pytest-xyz-admin`` and ``pytest-xyz-developers`` teams, inviting ``joedoe`` to both as **maintainer**.
* ``calvin`` transfers repository to ``pytest-dev`` and configures team access:
- ``pytest-xyz-admin`` **admin** access;
- ``pytest-xyz-developers`` **write** access;
The ``pytest-dev/Contributors`` team has write access to all projects, and
every project administrator is in it. We recommend that each plugin has at least three
people who have the right to release to PyPI.
Repository owners can rest assured that no ``pytest-dev`` administrator will ever make
releases of your repository or take ownership in any way, except in rare cases
where someone becomes unresponsive after months of contact attempts.
As stated, the objective is to share maintenance and avoid "plugin-abandon".
.. _`pull requests`:
.. _pull-requests:
@@ -125,7 +155,7 @@ Preparing Pull Requests on GitHub
What is a "pull request"? It informs project's core developers about the
changes you want to review and merge. Pull requests are stored on
`GitHub servers <https://github.com/pytest-dev/pytest/pulls>`_.
Once you send pull request, we can discuss it's potential modifications and
Once you send a pull request, we can discuss its potential modifications and
even add more commits to it later on.
There's an excellent tutorial on how Pull Requests work in the
@@ -141,59 +171,71 @@ but here is a simple overview:
$ git clone git@github.com:YOUR_GITHUB_USERNAME/pytest.git
$ cd pytest
$ git checkout pytest-2.7 # if you want to fix a bug for the pytest-2.7 series
$ git checkout master # if you want to add a feature bound for the next minor release
$ git branch your-branch-name # your feature/bugfix branch
# now, to fix a bug create your own branch off "master":
$ git checkout -b your-bugfix-branch-name master
# or to instead add a feature create your own branch off "features":
$ git checkout -b your-feature-branch-name features
Given we have "major.minor.micro" version numbers, bugfixes will usually
be released in micro releases whereas features will be released in
minor releases and incompatible changes in major releases.
If you need some help with Git, follow this quick start
guide: https://git.wiki.kernel.org/index.php/QuickStart
#. Create a development environment
#. Install tox
Tox is used to run all the tests and will automatically setup virtualenvs
to run the tests in.
(will implicitly use http://www.virtualenv.org/en/latest/)::
$ make develop
$ source .env/bin/activate
$ pip install tox
#. Run all the tests
You need to have Python 2.7 and 3.5 available in your system. Now
running tests is as simple as issuing this command::
$ python3 runtox.py -e linting,py27,py35
This command will run tests via the "tox" tool against Python 2.7 and 3.5
and also perform "lint" coding-style checks. ``runtox.py`` is
a thin wrapper around ``tox`` which installs from a development package
index where newer (not yet released to PyPI) versions of dependencies
(especially ``py``) might be present.
#. You can now edit your local working copy.
You need to have Python 2.7 and 3.4 available in your system. Now
running tests is as simple as issuing this command::
You can now make the changes you want and run the tests again as necessary.
$ python runtox.py -e py27,py34,flakes
To run tests on Python 2.7 and pass options to pytest (e.g. enter pdb on
failure) to pytest you can do::
This command will run tests via the "tox" tool against Python 2.7 and 3.4
and also perform "flakes" coding-style checks. ``runtox.py`` is
a thin wrapper around ``tox`` which installs from a development package
index where newer (not yet released to pypi) versions of dependencies
(especially ``py``) might be present.
$ python3 runtox.py -e py27 -- --pdb
To run tests on py27 and pass options (e.g. enter pdb on failure)
to pytest you can do::
Or to only run tests in a particular test module on Python 3.5::
$ python runtox.py -e py27 -- --pdb
or to only run tests in a particular test module on py34::
$ python runtox.py -e py34 -- testing/test_config.py
$ python3 runtox.py -e py35 -- testing/test_config.py
#. Commit and push once your tests pass and you are happy with your change(s)::
$ git commit -a -m "<commit message>"
$ git push -u
#. Finally, submit a pull request through the GitHub website:
Make sure you add a message to ``CHANGELOG.rst`` and add yourself to
``AUTHORS``. If you are unsure about either of these steps, submit your
pull request and we'll help you fix it up.
.. image:: img/pullrequest.png
:width: 700px
:align: center
::
#. Finally, submit a pull request through the GitHub website using this data::
head-fork: YOUR_GITHUB_USERNAME/pytest
compare: your-branch-name
base-fork: pytest-dev/pytest
base: master # if it's a feature
base: pytest-VERSION # if it's a bugfix
base: master # if it's a bugfix
base: features # if it's a feature

View File

@@ -1,59 +1,85 @@
How to release pytest (draft)
How to release pytest
--------------------------------------------
1. bump version numbers in _pytest/__init__.py (setup.py reads it)
Note: this assumes you have already registered on pypi.
2. check and finalize CHANGELOG
1. Bump version numbers in ``_pytest/__init__.py`` (``setup.py`` reads it).
3. write doc/en/announce/release-VERSION.txt and include
it in doc/en/announce/index.txt
2. Check and finalize ``CHANGELOG.rst``.
4. use devpi for uploading a release tarball to a staging area:
- ``devpi use https://devpi.net/USER/dev``
- ``devpi upload --formats sdist,bdist_wheel``
3. Write ``doc/en/announce/release-VERSION.txt`` and include
it in ``doc/en/announce/index.txt``. Run this command to list names of authors involved::
5. run from multiple machines:
- ``devpi use https://devpi.net/USER/dev``
- ``devpi test pytest==VERSION``
git log $(git describe --abbrev=0 --tags)..HEAD --format='%aN' | sort -u
6. check that tests pass for relevant combinations with
``devpi list pytest``
or look at failures with "devpi list -f pytest".
There will be some failed environments like e.g. the py33-trial
or py27-pexpect tox environments on Win32 platforms
which is ok (tox does not support skipping on
per-platform basis yet).
4. Regenerate the docs examples using tox::
7. Regenerate the docs examples using tox::
# Create and activate a virtualenv with regendoc installed
# (currently needs revision 4a9ec1035734)
tox -e regen
8. Build the docs, you need a virtualenv with, py and sphinx
installed::
cd docs/en
make html
5. At this point, open a PR named ``release-X`` so others can help find regressions or provide suggestions.
9. Tag the release::
hg tag VERSION
6. Use devpi for uploading a release tarball to a staging area::
10. Upload the docs using docs/en/Makefile::
cd docs/en
make install # or "installall" if you have LaTeX installed
This requires ssh-login permission on pytest.org because it uses
rsync.
Note that the "install" target of doc/en/Makefile defines where the
rsync goes to, typically to the "latest" section of pytest.org.
devpi use https://devpi.net/USER/dev
devpi upload --formats sdist,bdist_wheel
11. publish to pypi "devpi push pytest-VERSION pypi:NAME" where NAME
is the name of pypi.python.org as configured in your
~/.pypirc file -- it's the same you would use with
"setup.py upload -r NAME"
7. Run from multiple machines::
12. send release announcement to mailing lists:
devpi use https://devpi.net/USER/dev
devpi test pytest==VERSION
Alternatively, you can use `devpi-cloud-tester <https://github.com/nicoddemus/devpi-cloud-tester>`_ to test
the package on AppVeyor and Travis (follow instructions on the ``README``).
8. Check that tests pass for relevant combinations with::
devpi list pytest
or look at failures with "devpi list -f pytest".
9. Feeling confident? Publish to pypi::
devpi push pytest==VERSION pypi:NAME
where NAME is the name of pypi.python.org as configured in your ``~/.pypirc``
file `for devpi <http://doc.devpi.net/latest/quickstart-releaseprocess.html?highlight=pypirc#devpi-push-releasing-to-an-external-index>`_.
10. Tag the release::
git tag VERSION <hash>
git push origin VERSION
Make sure ``<hash>`` is **exactly** the git hash at the time the package was created.
11. Send release announcement to mailing lists:
- pytest-dev@python.org
- testing-in-python@lists.idyll.org
- python-announce-list@python.org
And announce the release on Twitter, making sure to add the hashtag ``#pytest``.
12. **After the release**
a. **patch release (2.8.3)**:
1. Checkout ``master``.
2. Update version number in ``_pytest/__init__.py`` to ``"2.8.4.dev"``.
3. Create a new section in ``CHANGELOG.rst`` titled ``2.8.4.dev`` and add a few bullet points as placeholders for new entries.
4. Commit and push.
b. **minor release (2.9.0)**:
1. Merge ``features`` into ``master``.
2. Checkout ``master``.
3. Follow the same steps for a **patch release** above, using the next patch release: ``2.9.1.dev``.
4. Commit ``master``.
5. Checkout ``features`` and merge with ``master`` (should be a fast-forward at this point).
6. Update version number in ``_pytest/__init__.py`` to the next minor release: ``"2.10.0.dev"``.
7. Create a new section in ``CHANGELOG.rst`` titled ``2.10.0.dev``, above ``2.9.1.dev``, and add a few bullet points as placeholders for new entries.
8. Commit ``features``.
9. Push ``master`` and ``features``.
c. **major release (3.0.0)**: same steps as that of a **minor release**
pytest-dev
testing-in-python
python-announce-list@python.org

View File

@@ -1,364 +0,0 @@
recorder = monkeypatch.function(".......")
-------------------------------------------------------------
tags: nice feature
Like monkeypatch.replace but sets a mock-like call recorder:
recorder = monkeypatch.function("os.path.abspath")
recorder.set_return("/hello")
os.path.abspath("hello")
call, = recorder.calls
assert call.args.path == "hello"
assert call.returned == "/hello"
...
Unlike mock, "args.path" acts on the parsed auto-spec'ed ``os.path.abspath``
so it's independent from if the client side called "os.path.abspath(path=...)"
or "os.path.abspath('positional')".
refine parametrize API
-------------------------------------------------------------
tags: critical feature
extend metafunc.parametrize to directly support indirection, example:
def setupdb(request, config):
# setup "resource" based on test request and the values passed
# in to parametrize. setupfunc is called for each such value.
# you may use request.addfinalizer() or request.cached_setup ...
return dynamic_setup_database(val)
@pytest.mark.parametrize("db", ["pg", "mysql"], setupfunc=setupdb)
def test_heavy_functional_test(db):
...
There would be no need to write or explain funcarg factories and
their special __ syntax.
The examples and improvements should also show how to put the parametrize
decorator to a class, to a module or even to a directory. For the directory
part a conftest.py content like this::
pytestmark = [
@pytest.mark.parametrize_setup("db", ...),
]
probably makes sense in order to keep the declarative nature. This mirrors
the marker-mechanism with respect to a test module but puts it to a directory
scale.
When doing larger scoped parametrization it probably becomes necessary
to allow parametrization to be ignored if the according parameter is not
used (currently any parametrized argument that is not present in a function will cause a ValueError). Example:
@pytest.mark.parametrize("db", ..., mustmatch=False)
means to not raise an error but simply ignore the parametrization
if the signature of a decorated function does not match. XXX is it
not sufficient to always allow non-matches?
allow parametrized attributes on classes
--------------------------------------------------
tags: wish 2.4
example:
@pytest.mark.parametrize_attr("db", setupfunc, [1,2,3], scope="class")
@pytest.mark.parametrize_attr("tmp", setupfunc, scope="...")
class TestMe:
def test_hello(self):
access self.db ...
this would run the test_hello() function three times with three
different values for self.db. This could also work with unittest/nose
style tests, i.e. it leverages existing test suites without needing
to rewrite them. Together with the previously mentioned setup_test()
maybe the setupfunc could be omitted?
optimizations
---------------------------------------------------------------
tags: 2.4 core
- look at ihook optimization such that all lookups for
hooks relating to the same fspath are cached.
fix start/finish partial finailization problem
---------------------------------------------------------------
tags: bug core
if a configure/runtest_setup/sessionstart/... hook invocation partially
fails the sessionfinishes is not called. Each hook implementation
should better be repsonsible for registering a cleanup/finalizer
appropriately to avoid this issue. Moreover/Alternatively, we could
record which implementations of a hook succeeded and only call their
teardown.
relax requirement to have tests/testing contain an __init__
----------------------------------------------------------------
tags: feature
bb: http://bitbucket.org/hpk42/py-trunk/issue/64
A local test run of a "tests" directory may work
but a remote one fail because the tests directory
does not contain an "__init__.py". Either give
an error or make it work without the __init__.py
i.e. port the nose-logic of unloading a test module.
customize test function collection
-------------------------------------------------------
tags: feature
- introduce pytest.mark.nocollect for not considering a function for
test collection at all. maybe also introduce a pytest.mark.test to
explicitely mark a function to become a tested one. Lookup JUnit ways
of tagging tests.
introduce pytest.mark.importorskip
-------------------------------------------------------
tags: feature
in addition to the imperative pytest.importorskip also introduce
a pytest.mark.importorskip so that the test count is more correct.
introduce pytest.mark.platform
-------------------------------------------------------
tags: feature
Introduce nice-to-spell platform-skipping, examples:
@pytest.mark.platform("python3")
@pytest.mark.platform("not python3")
@pytest.mark.platform("win32 and not python3")
@pytest.mark.platform("darwin")
@pytest.mark.platform("not (jython and win32)")
@pytest.mark.platform("not (jython and win32)", xfail=True)
etc. Idea is to allow Python expressions which can operate
on common spellings for operating systems and python
interpreter versions.
pytest.mark.xfail signature change
-------------------------------------------------------
tags: feature
change to pytest.mark.xfail(reason, (optional)condition)
to better implement the word meaning. It also signals
better that we always have some kind of an implementation
reason that can be formualated.
Compatibility? how to introduce a new name/keep compat?
allow to non-intrusively apply skipfs/xfail/marks
---------------------------------------------------
tags: feature
use case: mark a module or directory structures
to be skipped on certain platforms (i.e. no import
attempt will be made).
consider introducing a hook/mechanism that allows to apply marks
from conftests or plugins. (See extended parametrization)
explicit referencing of conftest.py files
-----------------------------------------
tags: feature
allow to name conftest.py files (in sub directories) that should
be imported early, as to include command line options.
improve central pytest ini file
-------------------------------
tags: feature
introduce more declarative configuration options:
- (to-be-collected test directories)
- required plugins
- test func/class/file matching patterns
- skip/xfail (non-intrusive)
- pytest.ini and tox.ini and setup.cfg configuration in the same file
new documentation
----------------------------------
tags: feature
- logo pytest
- examples for unittest or functional testing
- resource management for functional testing
- patterns: page object
have imported module mismatch honour relative paths
--------------------------------------------------------
tags: bug
With 1.1.1 pytest fails at least on windows if an import
is relative and compared against an absolute conftest.py
path. Normalize.
consider globals: pytest.ensuretemp and config
--------------------------------------------------------------
tags: experimental-wish
consider deprecating pytest.ensuretemp and pytest.config
to further reduce pytest globality. Also consider
having pytest.config and ensuretemp coming from
a plugin rather than being there from the start.
consider pytest_addsyspath hook
-----------------------------------------
tags: wish
pytest could call a new pytest_addsyspath() in order to systematically
allow manipulation of sys.path and to inhibit it via --no-addsyspath
in order to more easily run against installed packages.
Alternatively it could also be done via the config object
and pytest_configure.
deprecate global pytest.config usage
----------------------------------------------------------------
tags: feature
pytest.ensuretemp and pytest.config are probably the last
objects containing global state. Often using them is not
necessary. This is about trying to get rid of them, i.e.
deprecating them and checking with PyPy's usages as well
as others.
remove deprecated bits in collect.py
-------------------------------------------------------------------
tags: feature
In an effort to further simplify code, review and remove deprecated bits
in collect.py. Probably good:
- inline consider_file/dir methods, no need to have them
subclass-overridable because of hooks
implement fslayout decorator
---------------------------------
tags: feature
Improve the way how tests can work with pre-made examples,
keeping the layout close to the test function:
@pytest.mark.fslayout("""
conftest.py:
# empty
tests/
test_%(NAME)s: # becomes test_run1.py
def test_function(self):
pass
""")
def test_run(pytester, fslayout):
p = fslayout.findone("test_*.py")
result = pytester.runpytest(p)
assert result.ret == 0
assert result.passed == 1
Another idea is to allow to define a full scenario including the run
in one content string::
runscenario("""
test_{TESTNAME}.py:
import pytest
@pytest.mark.xfail
def test_that_fails():
assert 0
@pytest.mark.skipif("True")
def test_hello():
pass
conftest.py:
import pytest
def pytest_runsetup_setup(item):
pytest.skip("abc")
runpytest -rsxX
*SKIP*{TESTNAME}*
*1 skipped*
""")
This could be run with at least three different ways to invoke pytest:
through the shell, through "python -m pytest" and inlined. As inlined
would be the fastest it could be run first (or "--fast" mode).
Create isolate plugin
---------------------
tags: feature
The idea is that you can e.g. import modules in a test and afterwards
sys.modules, sys.meta_path etc would be reverted. It can go further
then just importing however, e.g. current working directory, file
descriptors, ...
This would probably be done by marking::
@pytest.mark.isolate(importing=True, cwd=True, fds=False)
def test_foo():
...
With the possibility of doing this globally in an ini-file.
fnmatch for test names
----------------------
tags: feature-wish
various testsuites use suffixes instead of prefixes for test classes
also it lends itself to bdd style test names::
class UserBehaviour:
def anonymous_should_not_have_inbox(user):
...
def registred_should_have_inbox(user):
..
using the following in pytest.ini::
[pytest]
python_classes = Test *Behaviour *Test
python_functions = test *_should_*
mechanism for running named parts of tests with different reporting behaviour
------------------------------------------------------------------------------
tags: feature-wish-incomplete
a few use-cases come to mind:
* fail assertions and record that without stopping a complete test
* this is in particular hepfull if a small bit of a test is known to fail/xfail::
def test_fun():
with pytest.section('fdcheck, marks=pytest.mark.xfail_if(...)):
breaks_on_windows()
* divide functional/acceptance tests into sections
* provide a different mechanism for generators, maybe something like::
def pytest_runtest_call(item)
if not generator:
...
prepare_check = GeneratorCheckprepare()
gen = item.obj(**fixtures)
for check in gen
id, call = prepare_check(check)
# bubble should only prevent exception propagation after a failure
# the whole test should still fail
# there might be need for a lower level api and taking custom markers into account
with pytest.section(id, bubble=False):
call()

36
LICENSE
View File

@@ -1,19 +1,21 @@
The MIT License (MIT)
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 the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Copyright (c) 2004-2016 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
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,7 +1,32 @@
include CHANGELOG
include README.rst
include setup.py
include tox.ini
include CHANGELOG.rst
include LICENSE
graft doc
include AUTHORS
include README.rst
include CONTRIBUTING.rst
include HOWTORELEASE.rst
include tox.ini
include setup.py
include .coveragerc
include plugin-test.sh
include requirements-docs.txt
include runtox.py
recursive-include bench *.py
recursive-include extra *.py
graft testing
graft doc
exclude _pytest/impl
graft _pytest/vendored_packages
recursive-exclude * *.pyc *.pyo
exclude appveyor/install.ps1
exclude appveyor.yml
exclude appveyor

View File

@@ -1,25 +0,0 @@
# Set of targets useful for development/release process
PYTHON = python2.7
PATH := $(PWD)/.env/bin:$(PATH)
# prepare virtual python environment
.env:
virtualenv .env -p $(PYTHON)
# install all needed for development
develop: .env
pip install -e . tox -r requirements-docs.txt
# clean the development envrironment
clean:
-rm -rf .env
# generate documentation
docs: develop
find doc/en -name '*.txt' -not -path 'doc/en/_build/*' | xargs .env/bin/regendoc
cd doc/en; make html
# upload documentation
upload-docs: develop
find doc/en -name '*.txt' -not -path 'doc/en/_build/*' | xargs .env/bin/regendoc --update
cd doc/en; make install

View File

@@ -1,53 +1,102 @@
.. image:: https://pypip.in/v/pytest/badge.png
.. image:: http://docs.pytest.org/en/latest/_static/pytest1.png
:target: http://docs.pytest.org
:align: center
:alt: pytest
------
.. image:: https://img.shields.io/pypi/v/pytest.svg
:target: https://pypi.python.org/pypi/pytest
.. image:: https://img.shields.io/pypi/pyversions/pytest.svg
:target: https://pypi.python.org/pypi/pytest
.. image:: https://img.shields.io/coveralls/pytest-dev/pytest/master.svg
:target: https://coveralls.io/r/pytest-dev/pytest
.. image:: https://travis-ci.org/pytest-dev/pytest.svg?branch=master
:target: https://travis-ci.org/pytest-dev/pytest
.. image:: https://ci.appveyor.com/api/projects/status/mrgbjaua7t33pg6b?svg=true
:target: https://ci.appveyor.com/project/pytestbot/pytest
Documentation: http://pytest.org/latest/
The ``pytest`` framework makes it easy to write small tests, yet
scales to support complex functional testing for applications and libraries.
Changelog: http://pytest.org/latest/changelog.html
An example of a simple test:
Issues: https://bitbucket.org/pytest-dev/pytest/issues?status=open
.. code-block:: python
CI: https://drone.io/bitbucket.org/pytest-dev/pytest
# content of test_sample.py
def func(x):
return x + 1
The ``pytest`` testing tool makes it easy to write small tests, yet
scales to support complex functional testing. It provides
- `auto-discovery
<http://pytest.org/latest/goodpractises.html#python-test-discovery>`_
of test modules and functions,
- detailed info on failing `assert statements <http://pytest.org/latest/assert.html>`_ (no need to remember ``self.assert*`` names)
- `modular fixtures <http://pytest.org/latest/fixture.html>`_ for
managing small or parametrized long-lived test resources.
- multi-paradigm support: you can use ``pytest`` to run test suites based
on `unittest <http://pytest.org/latest/unittest.html>`_ (or trial),
`nose <http://pytest.org/latest/nose.html>`_
- single-source compatibility from Python2.6 all the way up to
Python3.4, PyPy-2.3, (jython-2.5 untested)
def test_answer():
assert func(3) == 5
- many `external plugins <http://pytest.org/latest/plugins.html#installing-external-plugins-searching>`_.
To execute it::
A simple example for a test::
$ pytest
======= test session starts ========
collected 1 items
# content of test_module.py
def test_function():
i = 4
assert i == 3
test_sample.py F
which can be run with ``py.test test_module.py``. See `getting-started <http://pytest.org/latest/getting-started.html#our-first-test-run>`_ for more examples.
======= FAILURES ========
_______ test_answer ________
For much more info, including PDF docs, see
def test_answer():
> assert func(3) == 5
E assert 4 == 5
E + where 4 = func(3)
http://pytest.org
and report bugs at:
http://bitbucket.org/pytest-dev/pytest/issues/
and checkout or fork repo at:
http://bitbucket.org/pytest-dev/pytest/
test_sample.py:5: AssertionError
======= 1 failed in 0.12 seconds ========
Copyright Holger Krekel and others, 2004-2014
Licensed under the MIT license.
Due to ``pytest``'s detailed assertion introspection, only plain ``assert`` statements are used. See `getting-started <http://docs.pytest.org/en/latest/getting-started.html#our-first-test-run>`_ for more examples.
Features
--------
- Detailed info on failing `assert statements <http://docs.pytest.org/en/latest/assert.html>`_ (no need to remember ``self.assert*`` names);
- `Auto-discovery
<http://docs.pytest.org/en/latest/goodpractices.html#python-test-discovery>`_
of test modules and functions;
- `Modular fixtures <http://docs.pytest.org/en/latest/fixture.html>`_ for
managing small or parametrized long-lived test resources;
- Can run `unittest <http://docs.pytest.org/en/latest/unittest.html>`_ (or trial),
`nose <http://docs.pytest.org/en/latest/nose.html>`_ test suites out of the box;
- Python2.6+, Python3.3+, PyPy-2.3, Jython-2.5 (untested);
- Rich plugin architecture, with over 150+ `external plugins <http://docs.pytest.org/en/latest/plugins.html#installing-external-plugins-searching>`_ and thriving community;
Documentation
-------------
For full documentation, including installation, tutorials and PDF documents, please see http://docs.pytest.org.
Bugs/Requests
-------------
Please use the `GitHub issue tracker <https://github.com/pytest-dev/pytest/issues>`_ to submit bugs or request features.
Changelog
---------
Consult the `Changelog <http://docs.pytest.org/en/latest/changelog.html>`_ page for fixes and enhancements of each version.
License
-------
Copyright Holger Krekel and others, 2004-2016.
Distributed under the terms of the `MIT`_ license, pytest is free and open source software.
.. _`MIT`: https://github.com/pytest-dev/pytest/blob/master/LICENSE

View File

@@ -1,2 +1,2 @@
#
__version__ = '2.7.3'
__version__ = '3.0.2'

View File

@@ -88,9 +88,6 @@ class FastFilesCompleter:
return completion
if os.environ.get('_ARGCOMPLETE'):
# argcomplete 0.5.6 is not compatible with python 2.5.6: print/with/format
if sys.version_info[:2] < (2, 6):
sys.exit(1)
try:
import argcomplete.completers
except ImportError:

View File

@@ -0,0 +1,9 @@
""" python inspection/code generation API """
from .code import Code # noqa
from .code import ExceptionInfo # noqa
from .code import Frame # noqa
from .code import Traceback # noqa
from .code import getrawcode # noqa
from .source import Source # noqa
from .source import compile_ as compile # noqa
from .source import getfslineno # noqa

View File

@@ -0,0 +1,81 @@
# copied from python-2.7.3's traceback.py
# CHANGES:
# - some_str is replaced, trying to create unicode strings
#
import types
def format_exception_only(etype, value):
"""Format the exception part of a traceback.
The arguments are the exception type and value such as given by
sys.last_type and sys.last_value. The return value is a list of
strings, each ending in a newline.
Normally, the list contains a single string; however, for
SyntaxError exceptions, it contains several lines that (when
printed) display detailed information about where the syntax
error occurred.
The message indicating which exception occurred is always the last
string in the list.
"""
# An instance should not have a meaningful value parameter, but
# sometimes does, particularly for string exceptions, such as
# >>> raise string1, string2 # deprecated
#
# Clear these out first because issubtype(string1, SyntaxError)
# would throw another exception and mask the original problem.
if (isinstance(etype, BaseException) or
isinstance(etype, types.InstanceType) or
etype is None or type(etype) is str):
return [_format_final_exc_line(etype, value)]
stype = etype.__name__
if not issubclass(etype, SyntaxError):
return [_format_final_exc_line(stype, value)]
# It was a syntax error; show exactly where the problem was found.
lines = []
try:
msg, (filename, lineno, offset, badline) = value.args
except Exception:
pass
else:
filename = filename or "<string>"
lines.append(' File "%s", line %d\n' % (filename, lineno))
if badline is not None:
if isinstance(badline, bytes): # python 2 only
badline = badline.decode('utf-8', 'replace')
lines.append(u' %s\n' % badline.strip())
if offset is not None:
caretspace = badline.rstrip('\n')[:offset].lstrip()
# non-space whitespace (likes tabs) must be kept for alignment
caretspace = ((c.isspace() and c or ' ') for c in caretspace)
# only three spaces to account for offset1 == pos 0
lines.append(' %s^\n' % ''.join(caretspace))
value = msg
lines.append(_format_final_exc_line(stype, value))
return lines
def _format_final_exc_line(etype, value):
"""Return a list of a single line -- normal case for format_exception_only"""
valuestr = _some_str(value)
if value is None or not valuestr:
line = "%s\n" % etype
else:
line = "%s: %s\n" % (etype, valuestr)
return line
def _some_str(value):
try:
return unicode(value)
except Exception:
try:
return str(value)
except Exception:
pass
return '<unprintable %s object>' % type(value).__name__

848
_pytest/_code/code.py Normal file
View File

@@ -0,0 +1,848 @@
import sys
from inspect import CO_VARARGS, CO_VARKEYWORDS
import re
import py
builtin_repr = repr
reprlib = py.builtin._tryimport('repr', 'reprlib')
if sys.version_info[0] >= 3:
from traceback import format_exception_only
else:
from ._py2traceback import format_exception_only
class Code(object):
""" wrapper around Python code objects """
def __init__(self, rawcode):
if not hasattr(rawcode, "co_filename"):
rawcode = getrawcode(rawcode)
try:
self.filename = rawcode.co_filename
self.firstlineno = rawcode.co_firstlineno - 1
self.name = rawcode.co_name
except AttributeError:
raise TypeError("not a code object: %r" %(rawcode,))
self.raw = rawcode
def __eq__(self, other):
return self.raw == other.raw
def __ne__(self, other):
return not self == other
@property
def path(self):
""" return a path object pointing to source code (note that it
might not point to an actually existing file). """
try:
p = py.path.local(self.raw.co_filename)
# maybe don't try this checking
if not p.check():
raise OSError("py.path check failed.")
except OSError:
# XXX maybe try harder like the weird logic
# in the standard lib [linecache.updatecache] does?
p = self.raw.co_filename
return p
@property
def fullsource(self):
""" return a _pytest._code.Source object for the full source file of the code
"""
from _pytest._code import source
full, _ = source.findsource(self.raw)
return full
def source(self):
""" return a _pytest._code.Source object for the code object's source only
"""
# return source only for that part of code
import _pytest._code
return _pytest._code.Source(self.raw)
def getargs(self, var=False):
""" return a tuple with the argument names for the code object
if 'var' is set True also return the names of the variable and
keyword arguments when present
"""
# handfull shortcut for getting args
raw = self.raw
argcount = raw.co_argcount
if var:
argcount += raw.co_flags & CO_VARARGS
argcount += raw.co_flags & CO_VARKEYWORDS
return raw.co_varnames[:argcount]
class Frame(object):
"""Wrapper around a Python frame holding f_locals and f_globals
in which expressions can be evaluated."""
def __init__(self, frame):
self.lineno = frame.f_lineno - 1
self.f_globals = frame.f_globals
self.f_locals = frame.f_locals
self.raw = frame
self.code = Code(frame.f_code)
@property
def statement(self):
""" statement this frame is at """
import _pytest._code
if self.code.fullsource is None:
return _pytest._code.Source("")
return self.code.fullsource.getstatement(self.lineno)
def eval(self, code, **vars):
""" evaluate 'code' in the frame
'vars' are optional additional local variables
returns the result of the evaluation
"""
f_locals = self.f_locals.copy()
f_locals.update(vars)
return eval(code, self.f_globals, f_locals)
def exec_(self, code, **vars):
""" exec 'code' in the frame
'vars' are optiona; additional local variables
"""
f_locals = self.f_locals.copy()
f_locals.update(vars)
py.builtin.exec_(code, self.f_globals, f_locals )
def repr(self, object):
""" return a 'safe' (non-recursive, one-line) string repr for 'object'
"""
return py.io.saferepr(object)
def is_true(self, object):
return object
def getargs(self, var=False):
""" return a list of tuples (name, value) for all arguments
if 'var' is set True also include the variable and keyword
arguments when present
"""
retval = []
for arg in self.code.getargs(var):
try:
retval.append((arg, self.f_locals[arg]))
except KeyError:
pass # this can occur when using Psyco
return retval
class TracebackEntry(object):
""" a single entry in a traceback """
_repr_style = None
exprinfo = None
def __init__(self, rawentry, excinfo=None):
self._excinfo = excinfo
self._rawentry = rawentry
self.lineno = rawentry.tb_lineno - 1
def set_repr_style(self, mode):
assert mode in ("short", "long")
self._repr_style = mode
@property
def frame(self):
import _pytest._code
return _pytest._code.Frame(self._rawentry.tb_frame)
@property
def relline(self):
return self.lineno - self.frame.code.firstlineno
def __repr__(self):
return "<TracebackEntry %s:%d>" %(self.frame.code.path, self.lineno+1)
@property
def statement(self):
""" _pytest._code.Source object for the current statement """
source = self.frame.code.fullsource
return source.getstatement(self.lineno)
@property
def path(self):
""" path to the source code """
return self.frame.code.path
def getlocals(self):
return self.frame.f_locals
locals = property(getlocals, None, None, "locals of underlaying frame")
def getfirstlinesource(self):
# on Jython this firstlineno can be -1 apparently
return max(self.frame.code.firstlineno, 0)
def getsource(self, astcache=None):
""" return failing source code. """
# we use the passed in astcache to not reparse asttrees
# within exception info printing
from _pytest._code.source import getstatementrange_ast
source = self.frame.code.fullsource
if source is None:
return None
key = astnode = None
if astcache is not None:
key = self.frame.code.path
if key is not None:
astnode = astcache.get(key, None)
start = self.getfirstlinesource()
try:
astnode, _, end = getstatementrange_ast(self.lineno, source,
astnode=astnode)
except SyntaxError:
end = self.lineno + 1
else:
if key is not None:
astcache[key] = astnode
return source[start:end]
source = property(getsource)
def ishidden(self):
""" return True if the current frame has a var __tracebackhide__
resolving to True
If __tracebackhide__ is a callable, it gets called with the
ExceptionInfo instance and can decide whether to hide the traceback.
mostly for internal use
"""
try:
tbh = self.frame.f_locals['__tracebackhide__']
except KeyError:
try:
tbh = self.frame.f_globals['__tracebackhide__']
except KeyError:
return False
if py.builtin.callable(tbh):
return tbh(self._excinfo)
else:
return tbh
def __str__(self):
try:
fn = str(self.path)
except py.error.Error:
fn = '???'
name = self.frame.code.name
try:
line = str(self.statement).lstrip()
except KeyboardInterrupt:
raise
except:
line = "???"
return " File %r:%d in %s\n %s\n" %(fn, self.lineno+1, name, line)
def name(self):
return self.frame.code.raw.co_name
name = property(name, None, None, "co_name of underlaying code")
class Traceback(list):
""" Traceback objects encapsulate and offer higher level
access to Traceback entries.
"""
Entry = TracebackEntry
def __init__(self, tb, excinfo=None):
""" initialize from given python traceback object and ExceptionInfo """
self._excinfo = excinfo
if hasattr(tb, 'tb_next'):
def f(cur):
while cur is not None:
yield self.Entry(cur, excinfo=excinfo)
cur = cur.tb_next
list.__init__(self, f(tb))
else:
list.__init__(self, tb)
def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):
""" return a Traceback instance wrapping part of this Traceback
by provding any combination of path, lineno and firstlineno, the
first frame to start the to-be-returned traceback is determined
this allows cutting the first part of a Traceback instance e.g.
for formatting reasons (removing some uninteresting bits that deal
with handling of the exception/traceback)
"""
for x in self:
code = x.frame.code
codepath = code.path
if ((path is None or codepath == path) and
(excludepath is None or not hasattr(codepath, 'relto') or
not codepath.relto(excludepath)) and
(lineno is None or x.lineno == lineno) and
(firstlineno is None or x.frame.code.firstlineno == firstlineno)):
return Traceback(x._rawentry, self._excinfo)
return self
def __getitem__(self, key):
val = super(Traceback, self).__getitem__(key)
if isinstance(key, type(slice(0))):
val = self.__class__(val)
return val
def filter(self, fn=lambda x: not x.ishidden()):
""" return a Traceback instance with certain items removed
fn is a function that gets a single argument, a TracebackEntry
instance, and should return True when the item should be added
to the Traceback, False when not
by default this removes all the TracebackEntries which are hidden
(see ishidden() above)
"""
return Traceback(filter(fn, self), self._excinfo)
def getcrashentry(self):
""" return last non-hidden traceback entry that lead
to the exception of a traceback.
"""
for i in range(-1, -len(self)-1, -1):
entry = self[i]
if not entry.ishidden():
return entry
return self[-1]
def recursionindex(self):
""" return the index of the frame/TracebackEntry where recursion
originates if appropriate, None if no recursion occurred
"""
cache = {}
for i, entry in enumerate(self):
# id for the code.raw is needed to work around
# the strange metaprogramming in the decorator lib from pypi
# which generates code objects that have hash/value equality
#XXX needs a test
key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno
#print "checking for recursion at", key
l = cache.setdefault(key, [])
if l:
f = entry.frame
loc = f.f_locals
for otherloc in l:
if f.is_true(f.eval(co_equal,
__recursioncache_locals_1=loc,
__recursioncache_locals_2=otherloc)):
return i
l.append(entry.frame.f_locals)
return None
co_equal = compile('__recursioncache_locals_1 == __recursioncache_locals_2',
'?', 'eval')
class ExceptionInfo(object):
""" wraps sys.exc_info() objects and offers
help for navigating the traceback.
"""
_striptext = ''
def __init__(self, tup=None, exprinfo=None):
import _pytest._code
if tup is None:
tup = sys.exc_info()
if exprinfo is None and isinstance(tup[1], AssertionError):
exprinfo = getattr(tup[1], 'msg', None)
if exprinfo is None:
exprinfo = py._builtin._totext(tup[1])
if exprinfo and exprinfo.startswith('assert '):
self._striptext = 'AssertionError: '
self._excinfo = tup
#: the exception class
self.type = tup[0]
#: the exception instance
self.value = tup[1]
#: the exception raw traceback
self.tb = tup[2]
#: the exception type name
self.typename = self.type.__name__
#: the exception traceback (_pytest._code.Traceback instance)
self.traceback = _pytest._code.Traceback(self.tb, excinfo=self)
def __repr__(self):
return "<ExceptionInfo %s tblen=%d>" % (self.typename, len(self.traceback))
def exconly(self, tryshort=False):
""" return the exception as a string
when 'tryshort' resolves to True, and the exception is a
_pytest._code._AssertionError, only the actual exception part of
the exception representation is returned (so 'AssertionError: ' is
removed from the beginning)
"""
lines = format_exception_only(self.type, self.value)
text = ''.join(lines)
text = text.rstrip()
if tryshort:
if text.startswith(self._striptext):
text = text[len(self._striptext):]
return text
def errisinstance(self, exc):
""" return True if the exception is an instance of exc """
return isinstance(self.value, exc)
def _getreprcrash(self):
exconly = self.exconly(tryshort=True)
entry = self.traceback.getcrashentry()
path, lineno = entry.frame.code.raw.co_filename, entry.lineno
return ReprFileLocation(path, lineno+1, exconly)
def getrepr(self, showlocals=False, style="long",
abspath=False, tbfilter=True, funcargs=False):
""" return str()able representation of this exception info.
showlocals: show locals per traceback entry
style: long|short|no|native traceback style
tbfilter: hide entries (where __tracebackhide__ is true)
in case of style==native, tbfilter and showlocals is ignored.
"""
if style == 'native':
return ReprExceptionInfo(ReprTracebackNative(
py.std.traceback.format_exception(
self.type,
self.value,
self.traceback[0]._rawentry,
)), self._getreprcrash())
fmt = FormattedExcinfo(showlocals=showlocals, style=style,
abspath=abspath, tbfilter=tbfilter, funcargs=funcargs)
return fmt.repr_excinfo(self)
def __str__(self):
entry = self.traceback[-1]
loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
return str(loc)
def __unicode__(self):
entry = self.traceback[-1]
loc = ReprFileLocation(entry.path, entry.lineno + 1, self.exconly())
return unicode(loc)
def match(self, regexp):
"""
Match the regular expression 'regexp' on the string representation of
the exception. If it matches then True is returned (so that it is
possible to write 'assert excinfo.match()'). If it doesn't match an
AssertionError is raised.
"""
__tracebackhide__ = True
if not re.search(regexp, str(self.value)):
assert 0, "Pattern '{0!s}' not found in '{1!s}'".format(
regexp, self.value)
return True
class FormattedExcinfo(object):
""" presenting information about failing Functions and Generators. """
# for traceback entries
flow_marker = ">"
fail_marker = "E"
def __init__(self, showlocals=False, style="long", abspath=True, tbfilter=True, funcargs=False):
self.showlocals = showlocals
self.style = style
self.tbfilter = tbfilter
self.funcargs = funcargs
self.abspath = abspath
self.astcache = {}
def _getindent(self, source):
# figure out indent for given source
try:
s = str(source.getstatement(len(source)-1))
except KeyboardInterrupt:
raise
except:
try:
s = str(source[-1])
except KeyboardInterrupt:
raise
except:
return 0
return 4 + (len(s) - len(s.lstrip()))
def _getentrysource(self, entry):
source = entry.getsource(self.astcache)
if source is not None:
source = source.deindent()
return source
def _saferepr(self, obj):
return py.io.saferepr(obj)
def repr_args(self, entry):
if self.funcargs:
args = []
for argname, argvalue in entry.frame.getargs(var=True):
args.append((argname, self._saferepr(argvalue)))
return ReprFuncArgs(args)
def get_source(self, source, line_index=-1, excinfo=None, short=False):
""" return formatted and marked up source lines. """
import _pytest._code
lines = []
if source is None or line_index >= len(source.lines):
source = _pytest._code.Source("???")
line_index = 0
if line_index < 0:
line_index += len(source)
space_prefix = " "
if short:
lines.append(space_prefix + source.lines[line_index].strip())
else:
for line in source.lines[:line_index]:
lines.append(space_prefix + line)
lines.append(self.flow_marker + " " + source.lines[line_index])
for line in source.lines[line_index+1:]:
lines.append(space_prefix + line)
if excinfo is not None:
indent = 4 if short else self._getindent(source)
lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))
return lines
def get_exconly(self, excinfo, indent=4, markall=False):
lines = []
indent = " " * indent
# get the real exception information out
exlines = excinfo.exconly(tryshort=True).split('\n')
failindent = self.fail_marker + indent[1:]
for line in exlines:
lines.append(failindent + line)
if not markall:
failindent = indent
return lines
def repr_locals(self, locals):
if self.showlocals:
lines = []
keys = [loc for loc in locals if loc[0] != "@"]
keys.sort()
for name in keys:
value = locals[name]
if name == '__builtins__':
lines.append("__builtins__ = <builtins>")
else:
# This formatting could all be handled by the
# _repr() function, which is only reprlib.Repr in
# disguise, so is very configurable.
str_repr = self._saferepr(value)
#if len(str_repr) < 70 or not isinstance(value,
# (list, tuple, dict)):
lines.append("%-10s = %s" %(name, str_repr))
#else:
# self._line("%-10s =\\" % (name,))
# # XXX
# py.std.pprint.pprint(value, stream=self.excinfowriter)
return ReprLocals(lines)
def repr_traceback_entry(self, entry, excinfo=None):
import _pytest._code
source = self._getentrysource(entry)
if source is None:
source = _pytest._code.Source("???")
line_index = 0
else:
# entry.getfirstlinesource() can be -1, should be 0 on jython
line_index = entry.lineno - max(entry.getfirstlinesource(), 0)
lines = []
style = entry._repr_style
if style is None:
style = self.style
if style in ("short", "long"):
short = style == "short"
reprargs = self.repr_args(entry) if not short else None
s = self.get_source(source, line_index, excinfo, short=short)
lines.extend(s)
if short:
message = "in %s" %(entry.name)
else:
message = excinfo and excinfo.typename or ""
path = self._makepath(entry.path)
filelocrepr = ReprFileLocation(path, entry.lineno+1, message)
localsrepr = None
if not short:
localsrepr = self.repr_locals(entry.locals)
return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style)
if excinfo:
lines.extend(self.get_exconly(excinfo, indent=4))
return ReprEntry(lines, None, None, None, style)
def _makepath(self, path):
if not self.abspath:
try:
np = py.path.local().bestrelpath(path)
except OSError:
return path
if len(np) < len(str(path)):
path = np
return path
def repr_traceback(self, excinfo):
traceback = excinfo.traceback
if self.tbfilter:
traceback = traceback.filter()
recursionindex = None
if is_recursion_error(excinfo):
recursionindex = traceback.recursionindex()
last = traceback[-1]
entries = []
extraline = None
for index, entry in enumerate(traceback):
einfo = (last == entry) and excinfo or None
reprentry = self.repr_traceback_entry(entry, einfo)
entries.append(reprentry)
if index == recursionindex:
extraline = "!!! Recursion detected (same locals & position)"
break
return ReprTraceback(entries, extraline, style=self.style)
def repr_excinfo(self, excinfo):
if sys.version_info[0] < 3:
reprtraceback = self.repr_traceback(excinfo)
reprcrash = excinfo._getreprcrash()
return ReprExceptionInfo(reprtraceback, reprcrash)
else:
repr_chain = []
e = excinfo.value
descr = None
while e is not None:
reprtraceback = self.repr_traceback(excinfo)
reprcrash = excinfo._getreprcrash()
repr_chain += [(reprtraceback, reprcrash, descr)]
if e.__cause__ is not None:
e = e.__cause__
excinfo = ExceptionInfo((type(e), e, e.__traceback__))
descr = 'The above exception was the direct cause of the following exception:'
elif e.__context__ is not None:
e = e.__context__
excinfo = ExceptionInfo((type(e), e, e.__traceback__))
descr = 'During handling of the above exception, another exception occurred:'
else:
e = None
repr_chain.reverse()
return ExceptionChainRepr(repr_chain)
class TerminalRepr(object):
def __str__(self):
s = self.__unicode__()
if sys.version_info[0] < 3:
s = s.encode('utf-8')
return s
def __unicode__(self):
# FYI this is called from pytest-xdist's serialization of exception
# information.
io = py.io.TextIO()
tw = py.io.TerminalWriter(file=io)
self.toterminal(tw)
return io.getvalue().strip()
def __repr__(self):
return "<%s instance at %0x>" %(self.__class__, id(self))
class ExceptionRepr(TerminalRepr):
def __init__(self):
self.sections = []
def addsection(self, name, content, sep="-"):
self.sections.append((name, content, sep))
def toterminal(self, tw):
for name, content, sep in self.sections:
tw.sep(sep, name)
tw.line(content)
class ExceptionChainRepr(ExceptionRepr):
def __init__(self, chain):
super(ExceptionChainRepr, self).__init__()
self.chain = chain
# reprcrash and reprtraceback of the outermost (the newest) exception
# in the chain
self.reprtraceback = chain[-1][0]
self.reprcrash = chain[-1][1]
def toterminal(self, tw):
for element in self.chain:
element[0].toterminal(tw)
if element[2] is not None:
tw.line("")
tw.line(element[2], yellow=True)
super(ExceptionChainRepr, self).toterminal(tw)
class ReprExceptionInfo(ExceptionRepr):
def __init__(self, reprtraceback, reprcrash):
super(ReprExceptionInfo, self).__init__()
self.reprtraceback = reprtraceback
self.reprcrash = reprcrash
def toterminal(self, tw):
self.reprtraceback.toterminal(tw)
super(ReprExceptionInfo, self).toterminal(tw)
class ReprTraceback(TerminalRepr):
entrysep = "_ "
def __init__(self, reprentries, extraline, style):
self.reprentries = reprentries
self.extraline = extraline
self.style = style
def toterminal(self, tw):
# the entries might have different styles
for i, entry in enumerate(self.reprentries):
if entry.style == "long":
tw.line("")
entry.toterminal(tw)
if i < len(self.reprentries) - 1:
next_entry = self.reprentries[i+1]
if entry.style == "long" or \
entry.style == "short" and next_entry.style == "long":
tw.sep(self.entrysep)
if self.extraline:
tw.line(self.extraline)
class ReprTracebackNative(ReprTraceback):
def __init__(self, tblines):
self.style = "native"
self.reprentries = [ReprEntryNative(tblines)]
self.extraline = None
class ReprEntryNative(TerminalRepr):
style = "native"
def __init__(self, tblines):
self.lines = tblines
def toterminal(self, tw):
tw.write("".join(self.lines))
class ReprEntry(TerminalRepr):
localssep = "_ "
def __init__(self, lines, reprfuncargs, reprlocals, filelocrepr, style):
self.lines = lines
self.reprfuncargs = reprfuncargs
self.reprlocals = reprlocals
self.reprfileloc = filelocrepr
self.style = style
def toterminal(self, tw):
if self.style == "short":
self.reprfileloc.toterminal(tw)
for line in self.lines:
red = line.startswith("E ")
tw.line(line, bold=True, red=red)
#tw.line("")
return
if self.reprfuncargs:
self.reprfuncargs.toterminal(tw)
for line in self.lines:
red = line.startswith("E ")
tw.line(line, bold=True, red=red)
if self.reprlocals:
#tw.sep(self.localssep, "Locals")
tw.line("")
self.reprlocals.toterminal(tw)
if self.reprfileloc:
if self.lines:
tw.line("")
self.reprfileloc.toterminal(tw)
def __str__(self):
return "%s\n%s\n%s" % ("\n".join(self.lines),
self.reprlocals,
self.reprfileloc)
class ReprFileLocation(TerminalRepr):
def __init__(self, path, lineno, message):
self.path = str(path)
self.lineno = lineno
self.message = message
def toterminal(self, tw):
# filename and lineno output for each entry,
# using an output format that most editors unterstand
msg = self.message
i = msg.find("\n")
if i != -1:
msg = msg[:i]
tw.write(self.path, bold=True, red=True)
tw.line(":%s: %s" % (self.lineno, msg))
class ReprLocals(TerminalRepr):
def __init__(self, lines):
self.lines = lines
def toterminal(self, tw):
for line in self.lines:
tw.line(line)
class ReprFuncArgs(TerminalRepr):
def __init__(self, args):
self.args = args
def toterminal(self, tw):
if self.args:
linesofar = ""
for name, value in self.args:
ns = "%s = %s" %(name, value)
if len(ns) + len(linesofar) + 2 > tw.fullwidth:
if linesofar:
tw.line(linesofar)
linesofar = ns
else:
if linesofar:
linesofar += ", " + ns
else:
linesofar = ns
if linesofar:
tw.line(linesofar)
tw.line("")
def getrawcode(obj, trycall=True):
""" return code object for given function. """
try:
return obj.__code__
except AttributeError:
obj = getattr(obj, 'im_func', obj)
obj = getattr(obj, 'func_code', obj)
obj = getattr(obj, 'f_code', obj)
obj = getattr(obj, '__code__', obj)
if trycall and not hasattr(obj, 'co_firstlineno'):
if hasattr(obj, '__call__') and not py.std.inspect.isclass(obj):
x = getrawcode(obj.__call__, trycall=False)
if hasattr(x, 'co_firstlineno'):
return x
return obj
if sys.version_info[:2] >= (3, 5): # RecursionError introduced in 3.5
def is_recursion_error(excinfo):
return excinfo.errisinstance(RecursionError) # noqa
else:
def is_recursion_error(excinfo):
if not excinfo.errisinstance(RuntimeError):
return False
try:
return "maximum recursion depth exceeded" in str(excinfo.value)
except UnicodeError:
return False

421
_pytest/_code/source.py Normal file
View File

@@ -0,0 +1,421 @@
from __future__ import generators
from bisect import bisect_right
import sys
import inspect, tokenize
import py
from types import ModuleType
cpy_compile = compile
try:
import _ast
from _ast import PyCF_ONLY_AST as _AST_FLAG
except ImportError:
_AST_FLAG = 0
_ast = None
class Source(object):
""" a immutable object holding a source code fragment,
possibly deindenting it.
"""
_compilecounter = 0
def __init__(self, *parts, **kwargs):
self.lines = lines = []
de = kwargs.get('deindent', True)
rstrip = kwargs.get('rstrip', True)
for part in parts:
if not part:
partlines = []
if isinstance(part, Source):
partlines = part.lines
elif isinstance(part, (tuple, list)):
partlines = [x.rstrip("\n") for x in part]
elif isinstance(part, py.builtin._basestring):
partlines = part.split('\n')
if rstrip:
while partlines:
if partlines[-1].strip():
break
partlines.pop()
else:
partlines = getsource(part, deindent=de).lines
if de:
partlines = deindent(partlines)
lines.extend(partlines)
def __eq__(self, other):
try:
return self.lines == other.lines
except AttributeError:
if isinstance(other, str):
return str(self) == other
return False
def __getitem__(self, key):
if isinstance(key, int):
return self.lines[key]
else:
if key.step not in (None, 1):
raise IndexError("cannot slice a Source with a step")
return self.__getslice__(key.start, key.stop)
def __len__(self):
return len(self.lines)
def __getslice__(self, start, end):
newsource = Source()
newsource.lines = self.lines[start:end]
return newsource
def strip(self):
""" return new source object with trailing
and leading blank lines removed.
"""
start, end = 0, len(self)
while start < end and not self.lines[start].strip():
start += 1
while end > start and not self.lines[end-1].strip():
end -= 1
source = Source()
source.lines[:] = self.lines[start:end]
return source
def putaround(self, before='', after='', indent=' ' * 4):
""" return a copy of the source object with
'before' and 'after' wrapped around it.
"""
before = Source(before)
after = Source(after)
newsource = Source()
lines = [ (indent + line) for line in self.lines]
newsource.lines = before.lines + lines + after.lines
return newsource
def indent(self, indent=' ' * 4):
""" return a copy of the source object with
all lines indented by the given indent-string.
"""
newsource = Source()
newsource.lines = [(indent+line) for line in self.lines]
return newsource
def getstatement(self, lineno, assertion=False):
""" return Source statement which contains the
given linenumber (counted from 0).
"""
start, end = self.getstatementrange(lineno, assertion)
return self[start:end]
def getstatementrange(self, lineno, assertion=False):
""" return (start, end) tuple which spans the minimal
statement region which containing the given lineno.
"""
if not (0 <= lineno < len(self)):
raise IndexError("lineno out of range")
ast, start, end = getstatementrange_ast(lineno, self)
return start, end
def deindent(self, offset=None):
""" return a new source object deindented by offset.
If offset is None then guess an indentation offset from
the first non-blank line. Subsequent lines which have a
lower indentation offset will be copied verbatim as
they are assumed to be part of multilines.
"""
# XXX maybe use the tokenizer to properly handle multiline
# strings etc.pp?
newsource = Source()
newsource.lines[:] = deindent(self.lines, offset)
return newsource
def isparseable(self, deindent=True):
""" return True if source is parseable, heuristically
deindenting it by default.
"""
try:
import parser
except ImportError:
syntax_checker = lambda x: compile(x, 'asd', 'exec')
else:
syntax_checker = parser.suite
if deindent:
source = str(self.deindent())
else:
source = str(self)
try:
#compile(source+'\n', "x", "exec")
syntax_checker(source+'\n')
except KeyboardInterrupt:
raise
except Exception:
return False
else:
return True
def __str__(self):
return "\n".join(self.lines)
def compile(self, filename=None, mode='exec',
flag=generators.compiler_flag,
dont_inherit=0, _genframe=None):
""" return compiled code object. if filename is None
invent an artificial filename which displays
the source/line position of the caller frame.
"""
if not filename or py.path.local(filename).check(file=0):
if _genframe is None:
_genframe = sys._getframe(1) # the caller
fn,lineno = _genframe.f_code.co_filename, _genframe.f_lineno
base = "<%d-codegen " % self._compilecounter
self.__class__._compilecounter += 1
if not filename:
filename = base + '%s:%d>' % (fn, lineno)
else:
filename = base + '%r %s:%d>' % (filename, fn, lineno)
source = "\n".join(self.lines) + '\n'
try:
co = cpy_compile(source, filename, mode, flag)
except SyntaxError:
ex = sys.exc_info()[1]
# re-represent syntax errors from parsing python strings
msglines = self.lines[:ex.lineno]
if ex.offset:
msglines.append(" "*ex.offset + '^')
msglines.append("(code was compiled probably from here: %s)" % filename)
newex = SyntaxError('\n'.join(msglines))
newex.offset = ex.offset
newex.lineno = ex.lineno
newex.text = ex.text
raise newex
else:
if flag & _AST_FLAG:
return co
lines = [(x + "\n") for x in self.lines]
if sys.version_info[0] >= 3:
# XXX py3's inspect.getsourcefile() checks for a module
# and a pep302 __loader__ ... we don't have a module
# at code compile-time so we need to fake it here
m = ModuleType("_pycodecompile_pseudo_module")
py.std.inspect.modulesbyfile[filename] = None
py.std.sys.modules[None] = m
m.__loader__ = 1
py.std.linecache.cache[filename] = (1, None, lines, filename)
return co
#
# public API shortcut functions
#
def compile_(source, filename=None, mode='exec', flags=
generators.compiler_flag, dont_inherit=0):
""" compile the given source to a raw code object,
and maintain an internal cache which allows later
retrieval of the source code for the code object
and any recursively created code objects.
"""
if _ast is not None and isinstance(source, _ast.AST):
# XXX should Source support having AST?
return cpy_compile(source, filename, mode, flags, dont_inherit)
_genframe = sys._getframe(1) # the caller
s = Source(source)
co = s.compile(filename, mode, flags, _genframe=_genframe)
return co
def getfslineno(obj):
""" Return source location (path, lineno) for the given object.
If the source cannot be determined return ("", -1)
"""
import _pytest._code
try:
code = _pytest._code.Code(obj)
except TypeError:
try:
fn = (py.std.inspect.getsourcefile(obj) or
py.std.inspect.getfile(obj))
except TypeError:
return "", -1
fspath = fn and py.path.local(fn) or None
lineno = -1
if fspath:
try:
_, lineno = findsource(obj)
except IOError:
pass
else:
fspath = code.path
lineno = code.firstlineno
assert isinstance(lineno, int)
return fspath, lineno
#
# helper functions
#
def findsource(obj):
try:
sourcelines, lineno = py.std.inspect.findsource(obj)
except py.builtin._sysex:
raise
except:
return None, -1
source = Source()
source.lines = [line.rstrip() for line in sourcelines]
return source, lineno
def getsource(obj, **kwargs):
import _pytest._code
obj = _pytest._code.getrawcode(obj)
try:
strsrc = inspect.getsource(obj)
except IndentationError:
strsrc = "\"Buggy python version consider upgrading, cannot get source\""
assert isinstance(strsrc, str)
return Source(strsrc, **kwargs)
def deindent(lines, offset=None):
if offset is None:
for line in lines:
line = line.expandtabs()
s = line.lstrip()
if s:
offset = len(line)-len(s)
break
else:
offset = 0
if offset == 0:
return list(lines)
newlines = []
def readline_generator(lines):
for line in lines:
yield line + '\n'
while True:
yield ''
it = readline_generator(lines)
try:
for _, _, (sline, _), (eline, _), _ in tokenize.generate_tokens(lambda: next(it)):
if sline > len(lines):
break # End of input reached
if sline > len(newlines):
line = lines[sline - 1].expandtabs()
if line.lstrip() and line[:offset].isspace():
line = line[offset:] # Deindent
newlines.append(line)
for i in range(sline, eline):
# Don't deindent continuing lines of
# multiline tokens (i.e. multiline strings)
newlines.append(lines[i])
except (IndentationError, tokenize.TokenError):
pass
# Add any lines we didn't see. E.g. if an exception was raised.
newlines.extend(lines[len(newlines):])
return newlines
def get_statement_startend2(lineno, node):
import ast
# flatten all statements and except handlers into one lineno-list
# AST's line numbers start indexing at 1
l = []
for x in ast.walk(node):
if isinstance(x, _ast.stmt) or isinstance(x, _ast.ExceptHandler):
l.append(x.lineno - 1)
for name in "finalbody", "orelse":
val = getattr(x, name, None)
if val:
# treat the finally/orelse part as its own statement
l.append(val[0].lineno - 1 - 1)
l.sort()
insert_index = bisect_right(l, lineno)
start = l[insert_index - 1]
if insert_index >= len(l):
end = None
else:
end = l[insert_index]
return start, end
def getstatementrange_ast(lineno, source, assertion=False, astnode=None):
if astnode is None:
content = str(source)
if sys.version_info < (2,7):
content += "\n"
try:
astnode = compile(content, "source", "exec", 1024) # 1024 for AST
except ValueError:
start, end = getstatementrange_old(lineno, source, assertion)
return None, start, end
start, end = get_statement_startend2(lineno, astnode)
# we need to correct the end:
# - ast-parsing strips comments
# - there might be empty lines
# - we might have lesser indented code blocks at the end
if end is None:
end = len(source.lines)
if end > start + 1:
# make sure we don't span differently indented code blocks
# by using the BlockFinder helper used which inspect.getsource() uses itself
block_finder = inspect.BlockFinder()
# if we start with an indented line, put blockfinder to "started" mode
block_finder.started = source.lines[start][0].isspace()
it = ((x + "\n") for x in source.lines[start:end])
try:
for tok in tokenize.generate_tokens(lambda: next(it)):
block_finder.tokeneater(*tok)
except (inspect.EndOfBlock, IndentationError):
end = block_finder.last + start
except Exception:
pass
# the end might still point to a comment or empty line, correct it
while end:
line = source.lines[end - 1].lstrip()
if line.startswith("#") or not line:
end -= 1
else:
break
return astnode, start, end
def getstatementrange_old(lineno, source, assertion=False):
""" return (start, end) tuple which spans the minimal
statement region which containing the given lineno.
raise an IndexError if no such statementrange can be found.
"""
# XXX this logic is only used on python2.4 and below
# 1. find the start of the statement
from codeop import compile_command
for start in range(lineno, -1, -1):
if assertion:
line = source.lines[start]
# the following lines are not fully tested, change with care
if 'super' in line and 'self' in line and '__init__' in line:
raise IndexError("likely a subclass")
if "assert" not in line and "raise" not in line:
continue
trylines = source.lines[start:lineno+1]
# quick hack to prepare parsing an indented line with
# compile_command() (which errors on "return" outside defs)
trylines.insert(0, 'def xxx():')
trysource = '\n '.join(trylines)
# ^ space here
try:
compile_command(trysource)
except (SyntaxError, OverflowError, ValueError):
continue
# 2. find the end of the statement
for end in range(lineno+1, len(source)+1):
trysource = source[start:end]
if trysource.isparseable():
return start, end
raise SyntaxError("no valid source range around line %d " % (lineno,))

11
_pytest/_pluggy.py Normal file
View File

@@ -0,0 +1,11 @@
"""
imports symbols from vendored "pluggy" if available, otherwise
falls back to importing "pluggy" from the default namespace.
"""
try:
from _pytest.vendored_packages.pluggy import * # noqa
from _pytest.vendored_packages.pluggy import __version__ # noqa
except ImportError:
from pluggy import * # noqa
from pluggy import __version__ # noqa

View File

@@ -2,9 +2,11 @@
support for presenting detailed information in failing assertions.
"""
import py
import os
import sys
from _pytest.monkeypatch import monkeypatch
from _pytest.assertion import util
from _pytest.assertion import rewrite
def pytest_addoption(parser):
@@ -12,25 +14,49 @@ def pytest_addoption(parser):
group.addoption('--assert',
action="store",
dest="assertmode",
choices=("rewrite", "reinterp", "plain",),
choices=("rewrite", "plain",),
default="rewrite",
metavar="MODE",
help="""control assertion debugging tools. 'plain'
performs no assertion debugging. 'reinterp'
reinterprets assert statements after they failed
to provide assertion expression information.
'rewrite' (the default) rewrites assert
statements in test modules on import to
provide assert expression information. """)
group.addoption('--no-assert',
action="store_true",
default=False,
dest="noassert",
help="DEPRECATED equivalent to --assert=plain")
group.addoption('--nomagic', '--no-magic',
action="store_true",
default=False,
help="DEPRECATED equivalent to --assert=plain")
help="""Control assertion debugging tools. 'plain'
performs no assertion debugging. 'rewrite'
(the default) rewrites assert statements in
test modules on import to provide assert
expression information.""")
def pytest_namespace():
return {'register_assert_rewrite': register_assert_rewrite}
def register_assert_rewrite(*names):
"""Register a module name to be rewritten on import.
This function will make sure that this module or all modules inside
the package will get their assert statements rewritten.
Thus you should make sure to call this before the module is
actually imported, usually in your __init__.py if you are a plugin
using a package.
:raise TypeError: if the given module names are not strings.
"""
for name in names:
if not isinstance(name, str):
msg = 'expected module names as *args, got {0} instead'
raise TypeError(msg.format(repr(names)))
for hook in sys.meta_path:
if isinstance(hook, rewrite.AssertionRewritingHook):
importhook = hook
break
else:
importhook = DummyRewriteHook()
importhook.mark_rewrite(*names)
class DummyRewriteHook(object):
"""A no-op import hook for when rewriting is disabled."""
def mark_rewrite(self, *names):
pass
class AssertionState:
@@ -39,52 +65,43 @@ class AssertionState:
def __init__(self, config, mode):
self.mode = mode
self.trace = config.trace.root.get("assertion")
self.hook = None
def pytest_configure(config):
mode = config.getvalue("assertmode")
if config.getvalue("noassert") or config.getvalue("nomagic"):
mode = "plain"
if mode == "rewrite":
try:
import ast # noqa
except ImportError:
mode = "reinterp"
else:
# Both Jython and CPython 2.6.0 have AST bugs that make the
# assertion rewriting hook malfunction.
if (sys.platform.startswith('java') or
sys.version_info[:3] == (2, 6, 0)):
mode = "reinterp"
if mode != "plain":
_load_modules(mode)
m = monkeypatch()
config._cleanup.append(m.undo)
m.setattr(py.builtin.builtins, 'AssertionError',
reinterpret.AssertionError) # noqa
hook = None
if mode == "rewrite":
hook = rewrite.AssertionRewritingHook() # noqa
sys.meta_path.insert(0, hook)
warn_about_missing_assertion(mode)
config._assertstate = AssertionState(config, mode)
config._assertstate.hook = hook
config._assertstate.trace("configured with mode set to %r" % (mode,))
def install_importhook(config):
"""Try to install the rewrite hook, raise SystemError if it fails."""
# Both Jython and CPython 2.6.0 have AST bugs that make the
# assertion rewriting hook malfunction.
if (sys.platform.startswith('java') or
sys.version_info[:3] == (2, 6, 0)):
raise SystemError('rewrite not supported')
def pytest_unconfigure(config):
hook = config._assertstate.hook
if hook is not None and hook in sys.meta_path:
sys.meta_path.remove(hook)
config._assertstate = AssertionState(config, 'rewrite')
config._assertstate.hook = hook = rewrite.AssertionRewritingHook(config)
sys.meta_path.insert(0, hook)
config._assertstate.trace('installed rewrite import hook')
def undo():
hook = config._assertstate.hook
if hook is not None and hook in sys.meta_path:
sys.meta_path.remove(hook)
config.add_cleanup(undo)
return hook
def pytest_collection(session):
# this hook is only called when test modules are collected
# so for example not in the master process of pytest-xdist
# (which does not collect test modules)
hook = session.config._assertstate.hook
if hook is not None:
hook.set_session(session)
assertstate = getattr(session.config, '_assertstate', None)
if assertstate:
if assertstate.hook is not None:
assertstate.hook.set_session(session)
def _running_on_ci():
"""Check if we're currently running on a CI system."""
env_vars = ['CI', 'BUILD_NUMBER']
return any(var in os.environ for var in env_vars)
def pytest_runtest_setup(item):
@@ -100,7 +117,8 @@ def pytest_runtest_setup(item):
This uses the first result from the hook and then ensures the
following:
* Overly verbose explanations are dropped unles -vv was used.
* Overly verbose explanations are dropped unless -vv was used or
running on a CI.
* Embedded newlines are escaped to help util.format_explanation()
later.
* If the rewrite mode is used embedded %-characters are replaced
@@ -113,10 +131,14 @@ def pytest_runtest_setup(item):
config=item.config, op=op, left=left, right=right)
for new_expl in hook_result:
if new_expl:
if (sum(len(p) for p in new_expl[1:]) > 80*8
and item.config.option.verbose < 2):
new_expl[1:] = [py.builtin._totext(
'Detailed information truncated, use "-vv" to show')]
if (sum(len(p) for p in new_expl[1:]) > 80*8 and
item.config.option.verbose < 2 and
not _running_on_ci()):
show_max = 10
truncated_lines = len(new_expl) - show_max
new_expl[show_max:] = [py.builtin._totext(
'Detailed information truncated (%d more lines)'
', use "-vv" to show' % truncated_lines)]
new_expl = [line.replace("\n", "\\n") for line in new_expl]
res = py.builtin._totext("\n~").join(new_expl)
if item.config.getvalue("assertmode") == "rewrite":
@@ -130,35 +152,10 @@ def pytest_runtest_teardown(item):
def pytest_sessionfinish(session):
hook = session.config._assertstate.hook
if hook is not None:
hook.session = None
def _load_modules(mode):
"""Lazily import assertion related code."""
global rewrite, reinterpret
from _pytest.assertion import reinterpret # noqa
if mode == "rewrite":
from _pytest.assertion import rewrite # noqa
def warn_about_missing_assertion(mode):
try:
assert False
except AssertionError:
pass
else:
if mode == "rewrite":
specifically = ("assertions which are not in test modules "
"will be ignored")
else:
specifically = "failing tests may report as passing"
sys.stderr.write("WARNING: " + specifically +
" because assert statements are not executed "
"by the underlying Python interpreter "
"(are you using python -O?)\n")
assertstate = getattr(session.config, '_assertstate', None)
if assertstate:
if assertstate.hook is not None:
assertstate.hook.set_session(None)
# Expose this plugin's implementation for the pytest_assertrepr_compare hook

View File

@@ -1,365 +0,0 @@
"""
Find intermediate evalutation results in assert statements through builtin AST.
This should replace oldinterpret.py eventually.
"""
import sys
import ast
import py
from _pytest.assertion import util
from _pytest.assertion.reinterpret import BuiltinAssertionError
if sys.platform.startswith("java"):
# See http://bugs.jython.org/issue1497
_exprs = ("BoolOp", "BinOp", "UnaryOp", "Lambda", "IfExp", "Dict",
"ListComp", "GeneratorExp", "Yield", "Compare", "Call",
"Repr", "Num", "Str", "Attribute", "Subscript", "Name",
"List", "Tuple")
_stmts = ("FunctionDef", "ClassDef", "Return", "Delete", "Assign",
"AugAssign", "Print", "For", "While", "If", "With", "Raise",
"TryExcept", "TryFinally", "Assert", "Import", "ImportFrom",
"Exec", "Global", "Expr", "Pass", "Break", "Continue")
_expr_nodes = set(getattr(ast, name) for name in _exprs)
_stmt_nodes = set(getattr(ast, name) for name in _stmts)
def _is_ast_expr(node):
return node.__class__ in _expr_nodes
def _is_ast_stmt(node):
return node.__class__ in _stmt_nodes
else:
def _is_ast_expr(node):
return isinstance(node, ast.expr)
def _is_ast_stmt(node):
return isinstance(node, ast.stmt)
try:
_Starred = ast.Starred
except AttributeError:
# Python 2. Define a dummy class so isinstance() will always be False.
class _Starred(object): pass
class Failure(Exception):
"""Error found while interpreting AST."""
def __init__(self, explanation=""):
self.cause = sys.exc_info()
self.explanation = explanation
def interpret(source, frame, should_fail=False):
mod = ast.parse(source)
visitor = DebugInterpreter(frame)
try:
visitor.visit(mod)
except Failure:
failure = sys.exc_info()[1]
return getfailure(failure)
if should_fail:
return ("(assertion failed, but when it was re-run for "
"printing intermediate values, it did not fail. Suggestions: "
"compute assert expression before the assert or use --assert=plain)")
def run(offending_line, frame=None):
if frame is None:
frame = py.code.Frame(sys._getframe(1))
return interpret(offending_line, frame)
def getfailure(e):
explanation = util.format_explanation(e.explanation)
value = e.cause[1]
if str(value):
lines = explanation.split('\n')
lines[0] += " << %s" % (value,)
explanation = '\n'.join(lines)
text = "%s: %s" % (e.cause[0].__name__, explanation)
if text.startswith('AssertionError: assert '):
text = text[16:]
return text
operator_map = {
ast.BitOr : "|",
ast.BitXor : "^",
ast.BitAnd : "&",
ast.LShift : "<<",
ast.RShift : ">>",
ast.Add : "+",
ast.Sub : "-",
ast.Mult : "*",
ast.Div : "/",
ast.FloorDiv : "//",
ast.Mod : "%",
ast.Eq : "==",
ast.NotEq : "!=",
ast.Lt : "<",
ast.LtE : "<=",
ast.Gt : ">",
ast.GtE : ">=",
ast.Pow : "**",
ast.Is : "is",
ast.IsNot : "is not",
ast.In : "in",
ast.NotIn : "not in"
}
unary_map = {
ast.Not : "not %s",
ast.Invert : "~%s",
ast.USub : "-%s",
ast.UAdd : "+%s"
}
class DebugInterpreter(ast.NodeVisitor):
"""Interpret AST nodes to gleam useful debugging information. """
def __init__(self, frame):
self.frame = frame
def generic_visit(self, node):
# Fallback when we don't have a special implementation.
if _is_ast_expr(node):
mod = ast.Expression(node)
co = self._compile(mod)
try:
result = self.frame.eval(co)
except Exception:
raise Failure()
explanation = self.frame.repr(result)
return explanation, result
elif _is_ast_stmt(node):
mod = ast.Module([node])
co = self._compile(mod, "exec")
try:
self.frame.exec_(co)
except Exception:
raise Failure()
return None, None
else:
raise AssertionError("can't handle %s" %(node,))
def _compile(self, source, mode="eval"):
return compile(source, "<assertion interpretation>", mode)
def visit_Expr(self, expr):
return self.visit(expr.value)
def visit_Module(self, mod):
for stmt in mod.body:
self.visit(stmt)
def visit_Name(self, name):
explanation, result = self.generic_visit(name)
# See if the name is local.
source = "%r in locals() is not globals()" % (name.id,)
co = self._compile(source)
try:
local = self.frame.eval(co)
except Exception:
# have to assume it isn't
local = None
if local is None or not self.frame.is_true(local):
return name.id, result
return explanation, result
def visit_Compare(self, comp):
left = comp.left
left_explanation, left_result = self.visit(left)
for op, next_op in zip(comp.ops, comp.comparators):
next_explanation, next_result = self.visit(next_op)
op_symbol = operator_map[op.__class__]
explanation = "%s %s %s" % (left_explanation, op_symbol,
next_explanation)
source = "__exprinfo_left %s __exprinfo_right" % (op_symbol,)
co = self._compile(source)
try:
result = self.frame.eval(co, __exprinfo_left=left_result,
__exprinfo_right=next_result)
except Exception:
raise Failure(explanation)
try:
if not self.frame.is_true(result):
break
except KeyboardInterrupt:
raise
except:
break
left_explanation, left_result = next_explanation, next_result
if util._reprcompare is not None:
res = util._reprcompare(op_symbol, left_result, next_result)
if res:
explanation = res
return explanation, result
def visit_BoolOp(self, boolop):
is_or = isinstance(boolop.op, ast.Or)
explanations = []
for operand in boolop.values:
explanation, result = self.visit(operand)
explanations.append(explanation)
if result == is_or:
break
name = is_or and " or " or " and "
explanation = "(" + name.join(explanations) + ")"
return explanation, result
def visit_UnaryOp(self, unary):
pattern = unary_map[unary.op.__class__]
operand_explanation, operand_result = self.visit(unary.operand)
explanation = pattern % (operand_explanation,)
co = self._compile(pattern % ("__exprinfo_expr",))
try:
result = self.frame.eval(co, __exprinfo_expr=operand_result)
except Exception:
raise Failure(explanation)
return explanation, result
def visit_BinOp(self, binop):
left_explanation, left_result = self.visit(binop.left)
right_explanation, right_result = self.visit(binop.right)
symbol = operator_map[binop.op.__class__]
explanation = "(%s %s %s)" % (left_explanation, symbol,
right_explanation)
source = "__exprinfo_left %s __exprinfo_right" % (symbol,)
co = self._compile(source)
try:
result = self.frame.eval(co, __exprinfo_left=left_result,
__exprinfo_right=right_result)
except Exception:
raise Failure(explanation)
return explanation, result
def visit_Call(self, call):
func_explanation, func = self.visit(call.func)
arg_explanations = []
ns = {"__exprinfo_func" : func}
arguments = []
for arg in call.args:
arg_explanation, arg_result = self.visit(arg)
if isinstance(arg, _Starred):
arg_name = "__exprinfo_star"
ns[arg_name] = arg_result
arguments.append("*%s" % (arg_name,))
arg_explanations.append("*%s" % (arg_explanation,))
else:
arg_name = "__exprinfo_%s" % (len(ns),)
ns[arg_name] = arg_result
arguments.append(arg_name)
arg_explanations.append(arg_explanation)
for keyword in call.keywords:
arg_explanation, arg_result = self.visit(keyword.value)
if keyword.arg:
arg_name = "__exprinfo_%s" % (len(ns),)
keyword_source = "%s=%%s" % (keyword.arg)
arguments.append(keyword_source % (arg_name,))
arg_explanations.append(keyword_source % (arg_explanation,))
else:
arg_name = "__exprinfo_kwds"
arguments.append("**%s" % (arg_name,))
arg_explanations.append("**%s" % (arg_explanation,))
ns[arg_name] = arg_result
if getattr(call, 'starargs', None):
arg_explanation, arg_result = self.visit(call.starargs)
arg_name = "__exprinfo_star"
ns[arg_name] = arg_result
arguments.append("*%s" % (arg_name,))
arg_explanations.append("*%s" % (arg_explanation,))
if getattr(call, 'kwargs', None):
arg_explanation, arg_result = self.visit(call.kwargs)
arg_name = "__exprinfo_kwds"
ns[arg_name] = arg_result
arguments.append("**%s" % (arg_name,))
arg_explanations.append("**%s" % (arg_explanation,))
args_explained = ", ".join(arg_explanations)
explanation = "%s(%s)" % (func_explanation, args_explained)
args = ", ".join(arguments)
source = "__exprinfo_func(%s)" % (args,)
co = self._compile(source)
try:
result = self.frame.eval(co, **ns)
except Exception:
raise Failure(explanation)
pattern = "%s\n{%s = %s\n}"
rep = self.frame.repr(result)
explanation = pattern % (rep, rep, explanation)
return explanation, result
def _is_builtin_name(self, name):
pattern = "%r not in globals() and %r not in locals()"
source = pattern % (name.id, name.id)
co = self._compile(source)
try:
return self.frame.eval(co)
except Exception:
return False
def visit_Attribute(self, attr):
if not isinstance(attr.ctx, ast.Load):
return self.generic_visit(attr)
source_explanation, source_result = self.visit(attr.value)
explanation = "%s.%s" % (source_explanation, attr.attr)
source = "__exprinfo_expr.%s" % (attr.attr,)
co = self._compile(source)
try:
try:
result = self.frame.eval(co, __exprinfo_expr=source_result)
except AttributeError:
# Maybe the attribute name needs to be mangled?
if not attr.attr.startswith("__") or attr.attr.endswith("__"):
raise
source = "getattr(__exprinfo_expr.__class__, '__name__', '')"
co = self._compile(source)
class_name = self.frame.eval(co, __exprinfo_expr=source_result)
mangled_attr = "_" + class_name + attr.attr
source = "__exprinfo_expr.%s" % (mangled_attr,)
co = self._compile(source)
result = self.frame.eval(co, __exprinfo_expr=source_result)
except Exception:
raise Failure(explanation)
explanation = "%s\n{%s = %s.%s\n}" % (self.frame.repr(result),
self.frame.repr(result),
source_explanation, attr.attr)
# Check if the attr is from an instance.
source = "%r in getattr(__exprinfo_expr, '__dict__', {})"
source = source % (attr.attr,)
co = self._compile(source)
try:
from_instance = self.frame.eval(co, __exprinfo_expr=source_result)
except Exception:
from_instance = None
if from_instance is None or self.frame.is_true(from_instance):
rep = self.frame.repr(result)
pattern = "%s\n{%s = %s\n}"
explanation = pattern % (rep, rep, explanation)
return explanation, result
def visit_Assert(self, assrt):
test_explanation, test_result = self.visit(assrt.test)
explanation = "assert %s" % (test_explanation,)
if not self.frame.is_true(test_result):
try:
raise BuiltinAssertionError
except Exception:
raise Failure(explanation)
return explanation, test_result
def visit_Assign(self, assign):
value_explanation, value_result = self.visit(assign.value)
explanation = "... = %s" % (value_explanation,)
name = ast.Name("__exprinfo_expr", ast.Load(),
lineno=assign.value.lineno,
col_offset=assign.value.col_offset)
new_assign = ast.Assign(assign.targets, name, lineno=assign.lineno,
col_offset=assign.col_offset)
mod = ast.Module([new_assign])
co = self._compile(mod, "exec")
try:
self.frame.exec_(co, __exprinfo_expr=value_result)
except Exception:
raise Failure(explanation)
return explanation, value_result

View File

@@ -1,566 +0,0 @@
import traceback
import types
import py
import sys, inspect
from compiler import parse, ast, pycodegen
from _pytest.assertion.util import format_explanation, BuiltinAssertionError
passthroughex = py.builtin._sysex
class Failure:
def __init__(self, node):
self.exc, self.value, self.tb = sys.exc_info()
self.node = node
class View(object):
"""View base class.
If C is a subclass of View, then C(x) creates a proxy object around
the object x. The actual class of the proxy is not C in general,
but a *subclass* of C determined by the rules below. To avoid confusion
we call view class the class of the proxy (a subclass of C, so of View)
and object class the class of x.
Attributes and methods not found in the proxy are automatically read on x.
Other operations like setting attributes are performed on the proxy, as
determined by its view class. The object x is available from the proxy
as its __obj__ attribute.
The view class selection is determined by the __view__ tuples and the
optional __viewkey__ method. By default, the selected view class is the
most specific subclass of C whose __view__ mentions the class of x.
If no such subclass is found, the search proceeds with the parent
object classes. For example, C(True) will first look for a subclass
of C with __view__ = (..., bool, ...) and only if it doesn't find any
look for one with __view__ = (..., int, ...), and then ..., object,...
If everything fails the class C itself is considered to be the default.
Alternatively, the view class selection can be driven by another aspect
of the object x, instead of the class of x, by overriding __viewkey__.
See last example at the end of this module.
"""
_viewcache = {}
__view__ = ()
def __new__(rootclass, obj, *args, **kwds):
self = object.__new__(rootclass)
self.__obj__ = obj
self.__rootclass__ = rootclass
key = self.__viewkey__()
try:
self.__class__ = self._viewcache[key]
except KeyError:
self.__class__ = self._selectsubclass(key)
return self
def __getattr__(self, attr):
# attributes not found in the normal hierarchy rooted on View
# are looked up in the object's real class
return getattr(object.__getattribute__(self, '__obj__'), attr)
def __viewkey__(self):
return self.__obj__.__class__
def __matchkey__(self, key, subclasses):
if inspect.isclass(key):
keys = inspect.getmro(key)
else:
keys = [key]
for key in keys:
result = [C for C in subclasses if key in C.__view__]
if result:
return result
return []
def _selectsubclass(self, key):
subclasses = list(enumsubclasses(self.__rootclass__))
for C in subclasses:
if not isinstance(C.__view__, tuple):
C.__view__ = (C.__view__,)
choices = self.__matchkey__(key, subclasses)
if not choices:
return self.__rootclass__
elif len(choices) == 1:
return choices[0]
else:
# combine the multiple choices
return type('?', tuple(choices), {})
def __repr__(self):
return '%s(%r)' % (self.__rootclass__.__name__, self.__obj__)
def enumsubclasses(cls):
for subcls in cls.__subclasses__():
for subsubclass in enumsubclasses(subcls):
yield subsubclass
yield cls
class Interpretable(View):
"""A parse tree node with a few extra methods."""
explanation = None
def is_builtin(self, frame):
return False
def eval(self, frame):
# fall-back for unknown expression nodes
try:
expr = ast.Expression(self.__obj__)
expr.filename = '<eval>'
self.__obj__.filename = '<eval>'
co = pycodegen.ExpressionCodeGenerator(expr).getCode()
result = frame.eval(co)
except passthroughex:
raise
except:
raise Failure(self)
self.result = result
self.explanation = self.explanation or frame.repr(self.result)
def run(self, frame):
# fall-back for unknown statement nodes
try:
expr = ast.Module(None, ast.Stmt([self.__obj__]))
expr.filename = '<run>'
co = pycodegen.ModuleCodeGenerator(expr).getCode()
frame.exec_(co)
except passthroughex:
raise
except:
raise Failure(self)
def nice_explanation(self):
return format_explanation(self.explanation)
class Name(Interpretable):
__view__ = ast.Name
def is_local(self, frame):
source = '%r in locals() is not globals()' % self.name
try:
return frame.is_true(frame.eval(source))
except passthroughex:
raise
except:
return False
def is_global(self, frame):
source = '%r in globals()' % self.name
try:
return frame.is_true(frame.eval(source))
except passthroughex:
raise
except:
return False
def is_builtin(self, frame):
source = '%r not in locals() and %r not in globals()' % (
self.name, self.name)
try:
return frame.is_true(frame.eval(source))
except passthroughex:
raise
except:
return False
def eval(self, frame):
super(Name, self).eval(frame)
if not self.is_local(frame):
self.explanation = self.name
class Compare(Interpretable):
__view__ = ast.Compare
def eval(self, frame):
expr = Interpretable(self.expr)
expr.eval(frame)
for operation, expr2 in self.ops:
if hasattr(self, 'result'):
# shortcutting in chained expressions
if not frame.is_true(self.result):
break
expr2 = Interpretable(expr2)
expr2.eval(frame)
self.explanation = "%s %s %s" % (
expr.explanation, operation, expr2.explanation)
source = "__exprinfo_left %s __exprinfo_right" % operation
try:
self.result = frame.eval(source,
__exprinfo_left=expr.result,
__exprinfo_right=expr2.result)
except passthroughex:
raise
except:
raise Failure(self)
expr = expr2
class And(Interpretable):
__view__ = ast.And
def eval(self, frame):
explanations = []
for expr in self.nodes:
expr = Interpretable(expr)
expr.eval(frame)
explanations.append(expr.explanation)
self.result = expr.result
if not frame.is_true(expr.result):
break
self.explanation = '(' + ' and '.join(explanations) + ')'
class Or(Interpretable):
__view__ = ast.Or
def eval(self, frame):
explanations = []
for expr in self.nodes:
expr = Interpretable(expr)
expr.eval(frame)
explanations.append(expr.explanation)
self.result = expr.result
if frame.is_true(expr.result):
break
self.explanation = '(' + ' or '.join(explanations) + ')'
# == Unary operations ==
keepalive = []
for astclass, astpattern in {
ast.Not : 'not __exprinfo_expr',
ast.Invert : '(~__exprinfo_expr)',
}.items():
class UnaryArith(Interpretable):
__view__ = astclass
def eval(self, frame, astpattern=astpattern):
expr = Interpretable(self.expr)
expr.eval(frame)
self.explanation = astpattern.replace('__exprinfo_expr',
expr.explanation)
try:
self.result = frame.eval(astpattern,
__exprinfo_expr=expr.result)
except passthroughex:
raise
except:
raise Failure(self)
keepalive.append(UnaryArith)
# == Binary operations ==
for astclass, astpattern in {
ast.Add : '(__exprinfo_left + __exprinfo_right)',
ast.Sub : '(__exprinfo_left - __exprinfo_right)',
ast.Mul : '(__exprinfo_left * __exprinfo_right)',
ast.Div : '(__exprinfo_left / __exprinfo_right)',
ast.Mod : '(__exprinfo_left % __exprinfo_right)',
ast.Power : '(__exprinfo_left ** __exprinfo_right)',
}.items():
class BinaryArith(Interpretable):
__view__ = astclass
def eval(self, frame, astpattern=astpattern):
left = Interpretable(self.left)
left.eval(frame)
right = Interpretable(self.right)
right.eval(frame)
self.explanation = (astpattern
.replace('__exprinfo_left', left .explanation)
.replace('__exprinfo_right', right.explanation))
try:
self.result = frame.eval(astpattern,
__exprinfo_left=left.result,
__exprinfo_right=right.result)
except passthroughex:
raise
except:
raise Failure(self)
keepalive.append(BinaryArith)
class CallFunc(Interpretable):
__view__ = ast.CallFunc
def is_bool(self, frame):
source = 'isinstance(__exprinfo_value, bool)'
try:
return frame.is_true(frame.eval(source,
__exprinfo_value=self.result))
except passthroughex:
raise
except:
return False
def eval(self, frame):
node = Interpretable(self.node)
node.eval(frame)
explanations = []
vars = {'__exprinfo_fn': node.result}
source = '__exprinfo_fn('
for a in self.args:
if isinstance(a, ast.Keyword):
keyword = a.name
a = a.expr
else:
keyword = None
a = Interpretable(a)
a.eval(frame)
argname = '__exprinfo_%d' % len(vars)
vars[argname] = a.result
if keyword is None:
source += argname + ','
explanations.append(a.explanation)
else:
source += '%s=%s,' % (keyword, argname)
explanations.append('%s=%s' % (keyword, a.explanation))
if self.star_args:
star_args = Interpretable(self.star_args)
star_args.eval(frame)
argname = '__exprinfo_star'
vars[argname] = star_args.result
source += '*' + argname + ','
explanations.append('*' + star_args.explanation)
if self.dstar_args:
dstar_args = Interpretable(self.dstar_args)
dstar_args.eval(frame)
argname = '__exprinfo_kwds'
vars[argname] = dstar_args.result
source += '**' + argname + ','
explanations.append('**' + dstar_args.explanation)
self.explanation = "%s(%s)" % (
node.explanation, ', '.join(explanations))
if source.endswith(','):
source = source[:-1]
source += ')'
try:
self.result = frame.eval(source, **vars)
except passthroughex:
raise
except:
raise Failure(self)
if not node.is_builtin(frame) or not self.is_bool(frame):
r = frame.repr(self.result)
self.explanation = '%s\n{%s = %s\n}' % (r, r, self.explanation)
class Getattr(Interpretable):
__view__ = ast.Getattr
def eval(self, frame):
expr = Interpretable(self.expr)
expr.eval(frame)
source = '__exprinfo_expr.%s' % self.attrname
try:
try:
self.result = frame.eval(source, __exprinfo_expr=expr.result)
except AttributeError:
# Maybe the attribute name needs to be mangled?
if (not self.attrname.startswith("__") or
self.attrname.endswith("__")):
raise
source = "getattr(__exprinfo_expr.__class__, '__name__', '')"
class_name = frame.eval(source, __exprinfo_expr=expr.result)
mangled_attr = "_" + class_name + self.attrname
source = "__exprinfo_expr.%s" % (mangled_attr,)
self.result = frame.eval(source, __exprinfo_expr=expr.result)
except passthroughex:
raise
except:
raise Failure(self)
self.explanation = '%s.%s' % (expr.explanation, self.attrname)
# if the attribute comes from the instance, its value is interesting
source = ('hasattr(__exprinfo_expr, "__dict__") and '
'%r in __exprinfo_expr.__dict__' % self.attrname)
try:
from_instance = frame.is_true(
frame.eval(source, __exprinfo_expr=expr.result))
except passthroughex:
raise
except:
from_instance = True
if from_instance:
r = frame.repr(self.result)
self.explanation = '%s\n{%s = %s\n}' % (r, r, self.explanation)
# == Re-interpretation of full statements ==
class Assert(Interpretable):
__view__ = ast.Assert
def run(self, frame):
test = Interpretable(self.test)
test.eval(frame)
# print the result as 'assert <explanation>'
self.result = test.result
self.explanation = 'assert ' + test.explanation
if not frame.is_true(test.result):
try:
raise BuiltinAssertionError
except passthroughex:
raise
except:
raise Failure(self)
class Assign(Interpretable):
__view__ = ast.Assign
def run(self, frame):
expr = Interpretable(self.expr)
expr.eval(frame)
self.result = expr.result
self.explanation = '... = ' + expr.explanation
# fall-back-run the rest of the assignment
ass = ast.Assign(self.nodes, ast.Name('__exprinfo_expr'))
mod = ast.Module(None, ast.Stmt([ass]))
mod.filename = '<run>'
co = pycodegen.ModuleCodeGenerator(mod).getCode()
try:
frame.exec_(co, __exprinfo_expr=expr.result)
except passthroughex:
raise
except:
raise Failure(self)
class Discard(Interpretable):
__view__ = ast.Discard
def run(self, frame):
expr = Interpretable(self.expr)
expr.eval(frame)
self.result = expr.result
self.explanation = expr.explanation
class Stmt(Interpretable):
__view__ = ast.Stmt
def run(self, frame):
for stmt in self.nodes:
stmt = Interpretable(stmt)
stmt.run(frame)
def report_failure(e):
explanation = e.node.nice_explanation()
if explanation:
explanation = ", in: " + explanation
else:
explanation = ""
sys.stdout.write("%s: %s%s\n" % (e.exc.__name__, e.value, explanation))
def check(s, frame=None):
if frame is None:
frame = sys._getframe(1)
frame = py.code.Frame(frame)
expr = parse(s, 'eval')
assert isinstance(expr, ast.Expression)
node = Interpretable(expr.node)
try:
node.eval(frame)
except passthroughex:
raise
except Failure:
e = sys.exc_info()[1]
report_failure(e)
else:
if not frame.is_true(node.result):
sys.stderr.write("assertion failed: %s\n" % node.nice_explanation())
###########################################################
# API / Entry points
# #########################################################
def interpret(source, frame, should_fail=False):
module = Interpretable(parse(source, 'exec').node)
#print "got module", module
if isinstance(frame, types.FrameType):
frame = py.code.Frame(frame)
try:
module.run(frame)
except Failure:
e = sys.exc_info()[1]
return getfailure(e)
except passthroughex:
raise
except:
traceback.print_exc()
if should_fail:
return ("(assertion failed, but when it was re-run for "
"printing intermediate values, it did not fail. Suggestions: "
"compute assert expression before the assert or use --assert=plain)")
else:
return None
def getmsg(excinfo):
if isinstance(excinfo, tuple):
excinfo = py.code.ExceptionInfo(excinfo)
#frame, line = gettbline(tb)
#frame = py.code.Frame(frame)
#return interpret(line, frame)
tb = excinfo.traceback[-1]
source = str(tb.statement).strip()
x = interpret(source, tb.frame, should_fail=True)
if not isinstance(x, str):
raise TypeError("interpret returned non-string %r" % (x,))
return x
def getfailure(e):
explanation = e.node.nice_explanation()
if str(e.value):
lines = explanation.split('\n')
lines[0] += " << %s" % (e.value,)
explanation = '\n'.join(lines)
text = "%s: %s" % (e.exc.__name__, explanation)
if text.startswith('AssertionError: assert '):
text = text[16:]
return text
def run(s, frame=None):
if frame is None:
frame = sys._getframe(1)
frame = py.code.Frame(frame)
module = Interpretable(parse(s, 'exec').node)
try:
module.run(frame)
except Failure:
e = sys.exc_info()[1]
report_failure(e)
if __name__ == '__main__':
# example:
def f():
return 5
def g():
return 3
def h(x):
return 'never'
check("f() * g() == 5")
check("not f()")
check("not (f() and g() or 0)")
check("f() == g()")
i = 4
check("i == f()")
check("len(f()) == 0")
check("isinstance(2+3+4, float)")
run("x = i")
check("x == 5")
run("assert not f(), 'oops'")
run("a, b, c = 1, 2")
run("a, b, c = f()")
check("max([f(),g()]) == 4")
check("'hello'[g()] == 'h'")
run("'guk%d' % h(f())")

View File

@@ -1,52 +0,0 @@
import sys
import py
from _pytest.assertion.util import BuiltinAssertionError
u = py.builtin._totext
class AssertionError(BuiltinAssertionError):
def __init__(self, *args):
BuiltinAssertionError.__init__(self, *args)
if args:
# on Python2.6 we get len(args)==2 for: assert 0, (x,y)
# on Python2.7 and above we always get len(args) == 1
# with args[0] being the (x,y) tuple.
if len(args) > 1:
toprint = args
else:
toprint = args[0]
try:
self.msg = u(toprint)
except Exception:
self.msg = u(
"<[broken __repr__] %s at %0xd>"
% (toprint.__class__, id(toprint)))
else:
f = py.code.Frame(sys._getframe(1))
try:
source = f.code.fullsource
if source is not None:
try:
source = source.getstatement(f.lineno, assertion=True)
except IndexError:
source = None
else:
source = str(source.deindent()).strip()
except py.error.ENOENT:
source = None
# this can also occur during reinterpretation, when the
# co_filename is set to "<run>".
if source:
self.msg = reinterpret(source, f, should_fail=True)
else:
self.msg = "<could not determine information>"
if not self.args:
self.args = (self.msg,)
if sys.version_info > (3, 0):
AssertionError.__module__ = "builtins"
if sys.version_info >= (2, 6) or sys.platform.startswith("java"):
from _pytest.assertion.newinterpret import interpret as reinterpret
else:
from _pytest.assertion.oldinterpret import interpret as reinterpret

View File

@@ -1,6 +1,7 @@
"""Rewrite assertion AST to produce nice error messages"""
import ast
import _ast
import errno
import itertools
import imp
@@ -10,6 +11,7 @@ import re
import struct
import sys
import types
from fnmatch import fnmatch
import py
from _pytest.assertion import util
@@ -44,20 +46,19 @@ else:
class AssertionRewritingHook(object):
"""PEP302 Import hook which rewrites asserts."""
def __init__(self):
def __init__(self, config):
self.config = config
self.fnpats = config.getini("python_files")
self.session = None
self.modules = {}
self._register_with_pkg_resources()
self._must_rewrite = set()
def set_session(self, session):
self.fnpats = session.config.getini("python_files")
self.session = session
def find_module(self, name, path=None):
if self.session is None:
return None
sess = self.session
state = sess.config._assertstate
state = self.config._assertstate
state.trace("find_module called for: %s" % name)
names = name.rsplit(".", 1)
lastname = names[-1]
@@ -86,24 +87,11 @@ class AssertionRewritingHook(object):
return None
else:
fn = os.path.join(pth, name.rpartition(".")[2] + ".py")
fn_pypath = py.path.local(fn)
# Is this a test file?
if not sess.isinitpath(fn):
# We have to be very careful here because imports in this code can
# trigger a cycle.
self.session = None
try:
for pat in self.fnpats:
if fn_pypath.fnmatch(pat):
state.trace("matched test file %r" % (fn,))
break
else:
return None
finally:
self.session = sess
else:
state.trace("matched test file (was specified on cmdline): %r" %
(fn,))
if not self._should_rewrite(name, fn_pypath, state):
return None
# The requested module looks like a test file, so rewrite it. This is
# the most magical part of the process: load the source, rewrite the
# asserts, and load the rewritten source. We also cache the rewritten
@@ -128,7 +116,7 @@ class AssertionRewritingHook(object):
# One of the path components was not a directory, likely
# because we're in a zip file.
write = False
elif e in [errno.EACCES, errno.EROFS]:
elif e in [errno.EACCES, errno.EROFS, errno.EPERM]:
state.trace("read only directory: %r" % fn_pypath.dirname)
write = False
else:
@@ -140,7 +128,7 @@ class AssertionRewritingHook(object):
co = _read_pyc(fn_pypath, pyc, state.trace)
if co is None:
state.trace("rewriting %r" % (fn,))
source_stat, co = _rewrite_test(state, fn_pypath)
source_stat, co = _rewrite_test(self.config, fn_pypath)
if co is None:
# Probably a SyntaxError in the test.
return None
@@ -151,6 +139,54 @@ class AssertionRewritingHook(object):
self.modules[name] = co, pyc
return self
def _should_rewrite(self, name, fn_pypath, state):
# always rewrite conftest files
fn = str(fn_pypath)
if fn_pypath.basename == 'conftest.py':
state.trace("rewriting conftest file: %r" % (fn,))
return True
if self.session is not None:
if self.session.isinitpath(fn):
state.trace("matched test file (was specified on cmdline): %r" %
(fn,))
return True
# modules not passed explicitly on the command line are only
# rewritten if they match the naming convention for test files
for pat in self.fnpats:
# use fnmatch instead of fn_pypath.fnmatch because the
# latter might trigger an import to fnmatch.fnmatch
# internally, which would cause this method to be
# called recursively
if fnmatch(fn_pypath.basename, pat):
state.trace("matched test file %r" % (fn,))
return True
for marked in self._must_rewrite:
if name.startswith(marked):
state.trace("matched marked file %r (from %r)" % (name, marked))
return True
return False
def mark_rewrite(self, *names):
"""Mark import names as needing to be re-written.
The named module or package as well as any nested modules will
be re-written on import.
"""
already_imported = set(names).intersection(set(sys.modules))
if already_imported:
self._warn_already_imported(already_imported)
self._must_rewrite.update(names)
def _warn_already_imported(self, names):
self.config.warn(
'P1',
'Modules are already imported so can not be re-written: %s' %
','.join(names))
def load_module(self, name):
# If there is an existing module object named 'fullname' in
# sys.modules, the loader must use that existing module. (Otherwise,
@@ -203,6 +239,12 @@ class AssertionRewritingHook(object):
# DefaultProvider is appropriate.
pkg_resources.register_loader_type(cls, pkg_resources.DefaultProvider)
def get_data(self, pathname):
"""Optional PEP302 get_data API.
"""
with open(pathname, 'rb') as f:
return f.read()
def _write_pyc(state, co, source_stat, pyc):
# Technically, we don't have to have the same pyc format as
@@ -235,8 +277,9 @@ N = "\n".encode("utf-8")
cookie_re = re.compile(r"^[ \t\f]*#.*coding[:=][ \t]*[-\w.]+")
BOM_UTF8 = '\xef\xbb\xbf'
def _rewrite_test(state, fn):
def _rewrite_test(config, fn):
"""Try to read and rewrite *fn* and return the code object."""
state = config._assertstate
try:
stat = fn.stat()
source = fn.read("rb")
@@ -281,7 +324,7 @@ def _rewrite_test(state, fn):
# Let this pop up again in the real import.
state.trace("failed to parse: %r" % (fn,))
return None, None
rewrite_asserts(tree)
rewrite_asserts(tree, fn, config)
try:
co = compile(tree, fn.strpath, "exec")
except SyntaxError:
@@ -337,9 +380,9 @@ def _read_pyc(source, pyc, trace=lambda x: None):
return co
def rewrite_asserts(mod):
def rewrite_asserts(mod, module_path=None, config=None):
"""Rewrite the assert statements in mod."""
AssertionRewriter().run(mod)
AssertionRewriter(module_path, config).run(mod)
def _saferepr(obj):
@@ -447,6 +490,11 @@ binop_map = {
ast.In: "in",
ast.NotIn: "not in"
}
# Python 3.5+ compatibility
try:
binop_map[ast.MatMult] = "@"
except AttributeError:
pass
# Python 3.4+ compatibility
if hasattr(ast, "NameConstant"):
@@ -521,6 +569,11 @@ class AssertionRewriter(ast.NodeVisitor):
"""
def __init__(self, module_path, config):
super(AssertionRewriter, self).__init__()
self.module_path = module_path
self.config = config
def run(self, mod):
"""Find all assert statements in *mod* and rewrite them."""
if not mod.body:
@@ -661,6 +714,10 @@ class AssertionRewriter(ast.NodeVisitor):
the expression is false.
"""
if isinstance(assert_.test, ast.Tuple) and self.config is not None:
fslocation = (self.module_path, assert_.lineno)
self.config.warn('R1', 'assertion is always true, perhaps '
'remove parentheses?', fslocation=fslocation)
self.statements = []
self.variables = []
self.variable_counter = itertools.count()
@@ -844,6 +901,8 @@ class AssertionRewriter(ast.NodeVisitor):
def visit_Compare(self, comp):
self.push_format_context()
left_res, left_expl = self.visit(comp.left)
if isinstance(comp.left, (_ast.Compare, _ast.BoolOp)):
left_expl = "({0})".format(left_expl)
res_variables = [self.variable() for i in range(len(comp.ops))]
load_names = [ast.Name(v, ast.Load()) for v in res_variables]
store_names = [ast.Name(v, ast.Store()) for v in res_variables]
@@ -853,6 +912,8 @@ class AssertionRewriter(ast.NodeVisitor):
results = [left_res]
for i, op, next_operand in it:
next_res, next_expl = self.visit(next_operand)
if isinstance(next_operand, (_ast.Compare, _ast.BoolOp)):
next_expl = "({0})".format(next_expl)
results.append(next_res)
sym = binop_map[op.__class__]
syms.append(ast.Str(sym))

View File

@@ -1,6 +1,7 @@
"""Utilities for assertion debugging"""
import pprint
import _pytest._code
import py
try:
from collections import Sequence
@@ -17,6 +18,15 @@ u = py.builtin._totext
_reprcompare = None
# the re-encoding is needed for python2 repr
# with non-ascii characters (see issue 877 and 1379)
def ecu(s):
try:
return u(s, 'utf-8', 'replace')
except TypeError:
return s
def format_explanation(explanation):
"""This formats an explanation
@@ -27,44 +37,12 @@ def format_explanation(explanation):
for when one explanation needs to span multiple lines, e.g. when
displaying diffs.
"""
explanation = _collapse_false(explanation)
explanation = ecu(explanation)
lines = _split_explanation(explanation)
result = _format_lines(lines)
return u('\n').join(result)
def _collapse_false(explanation):
"""Collapse expansions of False
So this strips out any "assert False\n{where False = ...\n}"
blocks.
"""
where = 0
while True:
start = where = explanation.find("False\n{False = ", where)
if where == -1:
break
level = 0
prev_c = explanation[start]
for i, c in enumerate(explanation[start:]):
if prev_c + c == "\n{":
level += 1
elif prev_c + c == "\n}":
level -= 1
if not level:
break
prev_c = c
else:
raise AssertionError("unbalanced braces: %r" % (explanation,))
end = start + i
where = end
if explanation[end - 1] == '\n':
explanation = (explanation[:start] + explanation[start+15:end-1] +
explanation[end+1:])
where -= 17
return explanation
def _split_explanation(explanation):
"""Return a list of individual lines in the explanation
@@ -129,10 +107,11 @@ def assertrepr_compare(config, op, left, right):
width = 80 - 15 - len(op) - 2 # 15 chars indentation, 1 space around op
left_repr = py.io.saferepr(left, maxsize=int(width/2))
right_repr = py.io.saferepr(right, maxsize=width-len(left_repr))
summary = u('%s %s %s') % (left_repr, op, right_repr)
issequence = lambda x: (isinstance(x, (list, tuple, Sequence))
and not isinstance(x, basestring))
summary = u('%s %s %s') % (ecu(left_repr), op, ecu(right_repr))
issequence = lambda x: (isinstance(x, (list, tuple, Sequence)) and
not isinstance(x, basestring))
istext = lambda x: isinstance(x, basestring)
isdict = lambda x: isinstance(x, dict)
isset = lambda x: isinstance(x, (set, frozenset))
@@ -170,7 +149,7 @@ def assertrepr_compare(config, op, left, right):
explanation = [
u('(pytest_assertion plugin: representation of details failed. '
'Probably an object has a faulty __repr__.)'),
u(py.code.ExceptionInfo())]
u(_pytest._code.ExceptionInfo())]
if not explanation:
return None
@@ -213,9 +192,10 @@ def _diff_text(left, right, verbose=False):
'characters in diff, use -v to show') % i]
left = left[:-i]
right = right[:-i]
keepends = True
explanation += [line.strip('\n')
for line in ndiff(left.splitlines(),
right.splitlines())]
for line in ndiff(left.splitlines(keepends),
right.splitlines(keepends))]
return explanation
@@ -254,8 +234,7 @@ def _compare_eq_sequence(left, right, verbose=False):
explanation += [
u('Right contains more items, first extra item: %s') %
py.io.saferepr(right[len(left)],)]
return explanation # + _diff_text(pprint.pformat(left),
# pprint.pformat(right))
return explanation
def _compare_eq_set(left, right, verbose=False):

245
_pytest/cacheprovider.py Executable file
View File

@@ -0,0 +1,245 @@
"""
merged implementation of the cache provider
the name cache was not choosen to ensure pluggy automatically
ignores the external pytest-cache
"""
import py
import pytest
import json
from os.path import sep as _sep, altsep as _altsep
class Cache(object):
def __init__(self, config):
self.config = config
self._cachedir = config.rootdir.join(".cache")
self.trace = config.trace.root.get("cache")
if config.getvalue("cacheclear"):
self.trace("clearing cachedir")
if self._cachedir.check():
self._cachedir.remove()
self._cachedir.mkdir()
def makedir(self, name):
""" return a directory path object with the given name. If the
directory does not yet exist, it will be created. You can use it
to manage files likes e. g. store/retrieve database
dumps across test sessions.
:param name: must be a string not containing a ``/`` separator.
Make sure the name contains your plugin or application
identifiers to prevent clashes with other cache users.
"""
if _sep in name or _altsep is not None and _altsep in name:
raise ValueError("name is not allowed to contain path separators")
return self._cachedir.ensure_dir("d", name)
def _getvaluepath(self, key):
return self._cachedir.join('v', *key.split('/'))
def get(self, key, default):
""" return cached value for the given key. If no value
was yet cached or the value cannot be read, the specified
default is returned.
:param key: must be a ``/`` separated value. Usually the first
name is the name of your plugin or your application.
:param default: must be provided in case of a cache-miss or
invalid cache values.
"""
path = self._getvaluepath(key)
if path.check():
try:
with path.open("r") as f:
return json.load(f)
except ValueError:
self.trace("cache-invalid at %s" % (path,))
return default
def set(self, key, value):
""" save value for the given key.
:param key: must be a ``/`` separated value. Usually the first
name is the name of your plugin or your application.
:param value: must be of any combination of basic
python types, including nested types
like e. g. lists of dictionaries.
"""
path = self._getvaluepath(key)
try:
path.dirpath().ensure_dir()
except (py.error.EEXIST, py.error.EACCES):
self.config.warn(
code='I9', message='could not create cache path %s' % (path,)
)
return
try:
f = path.open('w')
except py.error.ENOTDIR:
self.config.warn(
code='I9', message='cache could not write path %s' % (path,))
else:
with f:
self.trace("cache-write %s: %r" % (key, value,))
json.dump(value, f, indent=2, sort_keys=True)
class LFPlugin:
""" Plugin which implements the --lf (run last-failing) option """
def __init__(self, config):
self.config = config
active_keys = 'lf', 'failedfirst'
self.active = any(config.getvalue(key) for key in active_keys)
if self.active:
self.lastfailed = config.cache.get("cache/lastfailed", {})
else:
self.lastfailed = {}
def pytest_report_header(self):
if self.active:
if not self.lastfailed:
mode = "run all (no recorded failures)"
else:
mode = "rerun last %d failures%s" % (
len(self.lastfailed),
" first" if self.config.getvalue("failedfirst") else "")
return "run-last-failure: %s" % mode
def pytest_runtest_logreport(self, report):
if report.failed and "xfail" not in report.keywords:
self.lastfailed[report.nodeid] = True
elif not report.failed:
if report.when == "call":
self.lastfailed.pop(report.nodeid, None)
def pytest_collectreport(self, report):
passed = report.outcome in ('passed', 'skipped')
if passed:
if report.nodeid in self.lastfailed:
self.lastfailed.pop(report.nodeid)
self.lastfailed.update(
(item.nodeid, True)
for item in report.result)
else:
self.lastfailed[report.nodeid] = True
def pytest_collection_modifyitems(self, session, config, items):
if self.active and self.lastfailed:
previously_failed = []
previously_passed = []
for item in items:
if item.nodeid in self.lastfailed:
previously_failed.append(item)
else:
previously_passed.append(item)
if not previously_failed and previously_passed:
# running a subset of all tests with recorded failures outside
# of the set of tests currently executing
pass
elif self.config.getvalue("failedfirst"):
items[:] = previously_failed + previously_passed
else:
items[:] = previously_failed
config.hook.pytest_deselected(items=previously_passed)
def pytest_sessionfinish(self, session):
config = self.config
if config.getvalue("cacheshow") or hasattr(config, "slaveinput"):
return
prev_failed = config.cache.get("cache/lastfailed", None) is not None
if (session.testscollected and prev_failed) or self.lastfailed:
config.cache.set("cache/lastfailed", self.lastfailed)
def pytest_addoption(parser):
group = parser.getgroup("general")
group.addoption(
'--lf', '--last-failed', action='store_true', dest="lf",
help="rerun only the tests that failed "
"at the last run (or all if none failed)")
group.addoption(
'--ff', '--failed-first', action='store_true', dest="failedfirst",
help="run all tests but run the last failures first. "
"This may re-order tests and thus lead to "
"repeated fixture setup/teardown")
group.addoption(
'--cache-show', action='store_true', dest="cacheshow",
help="show cache contents, don't perform collection or tests")
group.addoption(
'--cache-clear', action='store_true', dest="cacheclear",
help="remove all cache contents at start of test run.")
def pytest_cmdline_main(config):
if config.option.cacheshow:
from _pytest.main import wrap_session
return wrap_session(config, cacheshow)
@pytest.hookimpl(tryfirst=True)
def pytest_configure(config):
config.cache = Cache(config)
config.pluginmanager.register(LFPlugin(config), "lfplugin")
@pytest.fixture
def cache(request):
"""
Return a cache object that can persist state between testing sessions.
cache.get(key, default)
cache.set(key, value)
Keys must be a ``/`` separated value, where the first part is usually the
name of your plugin or application to avoid clashes with other cache users.
Values can be any object handled by the json stdlib module.
"""
return request.config.cache
def pytest_report_header(config):
if config.option.verbose:
relpath = py.path.local().bestrelpath(config.cache._cachedir)
return "cachedir: %s" % relpath
def cacheshow(config, session):
from pprint import pprint
tw = py.io.TerminalWriter()
tw.line("cachedir: " + str(config.cache._cachedir))
if not config.cache._cachedir.check():
tw.line("cache is empty")
return 0
dummy = object()
basedir = config.cache._cachedir
vdir = basedir.join("v")
tw.sep("-", "cache values")
for valpath in vdir.visit(lambda x: x.isfile()):
key = valpath.relto(vdir).replace(valpath.sep, "/")
val = config.cache.get(key, dummy)
if val is dummy:
tw.line("%s contains unreadable content, "
"will be ignored" % key)
else:
tw.line("%s contains:" % key)
stream = py.io.TextIO()
pprint(val, stream=stream)
for line in stream.getvalue().splitlines():
tw.line(" " + line)
ddir = basedir.join("d")
if ddir.isdir() and ddir.listdir():
tw.sep("-", "cache directories")
for p in basedir.join("d").visit():
#if p.check(dir=1):
# print("%s/" % p.relto(basedir))
if p.isfile():
key = p.relto(basedir)
tw.line("%s is a file of length %d" % (
key, p.size()))
return 0

View File

@@ -4,6 +4,7 @@ per-test stdout/stderr capturing mechanism.
"""
from __future__ import with_statement
import contextlib
import sys
import os
from tempfile import TemporaryFile
@@ -29,21 +30,22 @@ def pytest_addoption(parser):
help="shortcut for --capture=no.")
@pytest.mark.hookwrapper
@pytest.hookimpl(hookwrapper=True)
def pytest_load_initial_conftests(early_config, parser, args):
_readline_workaround()
ns = early_config.known_args_namespace
pluginmanager = early_config.pluginmanager
capman = CaptureManager(ns.capture)
pluginmanager.register(capman, "capturemanager")
# make sure that capturemanager is properly reset at final shutdown
pluginmanager.add_shutdown(capman.reset_capturings)
early_config.add_cleanup(capman.reset_capturings)
# make sure logging does not raise exceptions at the end
def silence_logging_at_shutdown():
if "logging" in sys.modules:
sys.modules["logging"].raiseExceptions = False
pluginmanager.add_shutdown(silence_logging_at_shutdown)
early_config.add_cleanup(silence_logging_at_shutdown)
# finally trigger conftest loading but while capturing (issue93)
capman.init_capturings()
@@ -86,8 +88,10 @@ class CaptureManager:
self.deactivate_funcargs()
cap = getattr(self, "_capturing", None)
if cap is not None:
outerr = cap.readouterr()
cap.suspend_capturing(in_=in_)
try:
outerr = cap.readouterr()
finally:
cap.suspend_capturing(in_=in_)
return outerr
def activate_funcargs(self, pyfuncitem):
@@ -101,7 +105,7 @@ class CaptureManager:
if capfuncarg is not None:
capfuncarg.close()
@pytest.mark.hookwrapper
@pytest.hookimpl(hookwrapper=True)
def pytest_make_collect_report(self, collector):
if isinstance(collector, pytest.File):
self.resumecapture()
@@ -115,13 +119,13 @@ class CaptureManager:
else:
yield
@pytest.mark.hookwrapper
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_setup(self, item):
self.resumecapture()
yield
self.suspendcapture_item(item, "setup")
@pytest.mark.hookwrapper
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_call(self, item):
self.resumecapture()
self.activate_funcargs(item)
@@ -129,60 +133,61 @@ class CaptureManager:
#self.deactivate_funcargs() called from suspendcapture()
self.suspendcapture_item(item, "call")
@pytest.mark.hookwrapper
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_teardown(self, item):
self.resumecapture()
yield
self.suspendcapture_item(item, "teardown")
@pytest.mark.tryfirst
@pytest.hookimpl(tryfirst=True)
def pytest_keyboard_interrupt(self, excinfo):
self.reset_capturings()
@pytest.mark.tryfirst
@pytest.hookimpl(tryfirst=True)
def pytest_internalerror(self, excinfo):
self.reset_capturings()
def suspendcapture_item(self, item, when):
out, err = self.suspendcapture()
item.add_report_section(when, "out", out)
item.add_report_section(when, "err", err)
def suspendcapture_item(self, item, when, in_=False):
out, err = self.suspendcapture(in_=in_)
item.add_report_section(when, "stdout", out)
item.add_report_section(when, "stderr", err)
error_capsysfderror = "cannot use capsys and capfd at the same time"
@pytest.fixture
def capsys(request):
"""enables capturing of writes to sys.stdout/sys.stderr and makes
"""Enable capturing of writes to sys.stdout/sys.stderr and make
captured output available via ``capsys.readouterr()`` method calls
which return a ``(out, err)`` tuple.
"""
if "capfd" in request._funcargs:
if "capfd" in request.fixturenames:
raise request.raiseerror(error_capsysfderror)
request.node._capfuncarg = c = CaptureFixture(SysCapture)
request.node._capfuncarg = c = CaptureFixture(SysCapture, request)
return c
@pytest.fixture
def capfd(request):
"""enables capturing of writes to file descriptors 1 and 2 and makes
"""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.
"""
if "capsys" in request._funcargs:
if "capsys" in request.fixturenames:
request.raiseerror(error_capsysfderror)
if not hasattr(os, 'dup'):
pytest.skip("capfd funcarg needs os.dup")
request.node._capfuncarg = c = CaptureFixture(FDCapture)
request.node._capfuncarg = c = CaptureFixture(FDCapture, request)
return c
class CaptureFixture:
def __init__(self, captureclass):
def __init__(self, captureclass, request):
self.captureclass = captureclass
self.request = request
def _start(self):
self._capture = MultiCapture(out=True, err=True, in_=False,
Capture=self.captureclass)
Capture=self.captureclass)
self._capture.start_capturing()
def close(self):
@@ -197,6 +202,15 @@ class CaptureFixture:
except AttributeError:
return self._outerr
@contextlib.contextmanager
def disabled(self):
capmanager = self.request.config.pluginmanager.getplugin('capturemanager')
capmanager.suspendcapture_item(self.request.node, "call", in_=True)
try:
yield
finally:
capmanager.resumecapture()
def safe_text_dupfile(f, mode, default_encoding="UTF8"):
""" return a open text file object that's a duplicate of f on the
@@ -440,3 +454,37 @@ class DontReadFromInput:
def close(self):
pass
@property
def buffer(self):
if sys.version_info >= (3,0):
return self
else:
raise AttributeError('redirected stdin has no attribute buffer')
def _readline_workaround():
"""
Ensure readline is imported so that it attaches to the correct stdio
handles on Windows.
Pdb uses readline support where available--when not running from the Python
prompt, the readline module is not imported until running the pdb REPL. If
running pytest with the --pdb option this means the readline module is not
imported until after I/O capture has been started.
This is a problem for pyreadline, which is often used to implement readline
support on Windows, as it does not attach to the correct handles for stdout
and/or stdin if they have been redirected by the FDCapture mechanism. This
workaround ensures that readline is imported before I/O capture is setup so
that it can attach to the actual stdin/out for the console.
See https://github.com/pytest-dev/pytest/pull/1281
"""
if not sys.platform.startswith('win32'):
return
try:
import readline # noqa
except ImportError:
pass

216
_pytest/compat.py Normal file
View File

@@ -0,0 +1,216 @@
"""
python version compatibility code
"""
import sys
import inspect
import types
import re
import functools
import py
import _pytest
try:
import enum
except ImportError: # pragma: no cover
# Only available in Python 3.4+ or as a backport
enum = None
_PY3 = sys.version_info > (3, 0)
_PY2 = not _PY3
NoneType = type(None)
NOTSET = object()
if hasattr(inspect, 'signature'):
def _format_args(func):
return str(inspect.signature(func))
else:
def _format_args(func):
return inspect.formatargspec(*inspect.getargspec(func))
isfunction = inspect.isfunction
isclass = inspect.isclass
# used to work around a python2 exception info leak
exc_clear = getattr(sys, 'exc_clear', lambda: None)
# The type of re.compile objects is not exposed in Python.
REGEX_TYPE = type(re.compile(''))
def is_generator(func):
try:
return _pytest._code.getrawcode(func).co_flags & 32 # generator function
except AttributeError: # builtin functions have no bytecode
# assume them to not be generators
return False
def getlocation(function, curdir):
import inspect
fn = py.path.local(inspect.getfile(function))
lineno = py.builtin._getcode(function).co_firstlineno
if fn.relto(curdir):
fn = fn.relto(curdir)
return "%s:%d" %(fn, lineno+1)
def num_mock_patch_args(function):
""" return number of arguments used up by mock arguments (if any) """
patchings = getattr(function, "patchings", None)
if not patchings:
return 0
mock = sys.modules.get("mock", sys.modules.get("unittest.mock", None))
if mock is not None:
return len([p for p in patchings
if not p.attribute_name and p.new is mock.DEFAULT])
return len(patchings)
def getfuncargnames(function, startindex=None):
# XXX merge with main.py's varnames
#assert not isclass(function)
realfunction = function
while hasattr(realfunction, "__wrapped__"):
realfunction = realfunction.__wrapped__
if startindex is None:
startindex = inspect.ismethod(function) and 1 or 0
if realfunction != function:
startindex += num_mock_patch_args(function)
function = realfunction
if isinstance(function, functools.partial):
argnames = inspect.getargs(_pytest._code.getrawcode(function.func))[0]
partial = function
argnames = argnames[len(partial.args):]
if partial.keywords:
for kw in partial.keywords:
argnames.remove(kw)
else:
argnames = inspect.getargs(_pytest._code.getrawcode(function))[0]
defaults = getattr(function, 'func_defaults',
getattr(function, '__defaults__', None)) or ()
numdefaults = len(defaults)
if numdefaults:
return tuple(argnames[startindex:-numdefaults])
return tuple(argnames[startindex:])
if sys.version_info[:2] == (2, 6):
def isclass(object):
""" Return true if the object is a class. Overrides inspect.isclass for
python 2.6 because it will return True for objects which always return
something on __getattr__ calls (see #1035).
Backport of https://hg.python.org/cpython/rev/35bf8f7a8edc
"""
return isinstance(object, (type, types.ClassType))
if _PY3:
import codecs
STRING_TYPES = bytes, str
def _escape_strings(val):
"""If val is pure ascii, returns it as a str(). Otherwise, escapes
bytes objects into a sequence of escaped bytes:
b'\xc3\xb4\xc5\xd6' -> u'\\xc3\\xb4\\xc5\\xd6'
and escapes unicode objects into a sequence of escaped unicode
ids, e.g.:
'4\\nV\\U00043efa\\x0eMXWB\\x1e\\u3028\\u15fd\\xcd\\U0007d944'
note:
the obvious "v.decode('unicode-escape')" will return
valid utf-8 unicode if it finds them in bytes, but we
want to return escaped bytes for any byte, even if they match
a utf-8 string.
"""
if isinstance(val, bytes):
if val:
# source: http://goo.gl/bGsnwC
encoded_bytes, _ = codecs.escape_encode(val)
return encoded_bytes.decode('ascii')
else:
# empty bytes crashes codecs.escape_encode (#1087)
return ''
else:
return val.encode('unicode_escape').decode('ascii')
else:
STRING_TYPES = bytes, str, unicode
def _escape_strings(val):
"""In py2 bytes and str are the same type, so return if it's a bytes
object, return it unchanged if it is a full ascii string,
otherwise escape it into its binary form.
If it's a unicode string, change the unicode characters into
unicode escapes.
"""
if isinstance(val, bytes):
try:
return val.encode('ascii')
except UnicodeDecodeError:
return val.encode('string-escape')
else:
return val.encode('unicode-escape')
def get_real_func(obj):
""" gets the real function object of the (possibly) wrapped object by
functools.wraps or functools.partial.
"""
while hasattr(obj, "__wrapped__"):
obj = obj.__wrapped__
if isinstance(obj, functools.partial):
obj = obj.func
return obj
def getfslineno(obj):
# xxx let decorators etc specify a sane ordering
obj = get_real_func(obj)
if hasattr(obj, 'place_as'):
obj = obj.place_as
fslineno = _pytest._code.getfslineno(obj)
assert isinstance(fslineno[1], int), obj
return fslineno
def getimfunc(func):
try:
return func.__func__
except AttributeError:
try:
return func.im_func
except AttributeError:
return func
def safe_getattr(object, name, default):
""" Like getattr but return default upon any Exception.
Attribute access can potentially fail for 'evil' Python objects.
See issue214
"""
try:
return getattr(object, name, default)
except Exception:
return default
def _is_unittest_unexpected_success_a_failure():
"""Return if the test suite should fail if a @expectedFailure unittest test PASSES.
From https://docs.python.org/3/library/unittest.html?highlight=unittest#unittest.TestResult.wasSuccessful:
Changed in version 3.4: Returns False if there were any
unexpectedSuccesses from tests marked with the expectedFailure() decorator.
"""
return sys.version_info >= (3, 4)

File diff suppressed because it is too large Load Diff

View File

@@ -1,543 +0,0 @@
"""
pytest PluginManager, basic initialization and tracing.
"""
import os
import sys
import inspect
import py
# don't import pytest to avoid circular imports
assert py.__version__.split(".")[:2] >= ['1', '4'], ("installation problem: "
"%s is too old, remove or upgrade 'py'" % (py.__version__))
py3 = sys.version_info > (3,0)
class TagTracer:
def __init__(self):
self._tag2proc = {}
self.writer = None
self.indent = 0
def get(self, name):
return TagTracerSub(self, (name,))
def format_message(self, tags, args):
if isinstance(args[-1], dict):
extra = args[-1]
args = args[:-1]
else:
extra = {}
content = " ".join(map(str, args))
indent = " " * self.indent
lines = [
"%s%s [%s]\n" %(indent, content, ":".join(tags))
]
for name, value in extra.items():
lines.append("%s %s: %s\n" % (indent, name, value))
return lines
def processmessage(self, tags, args):
if self.writer is not None and args:
lines = self.format_message(tags, args)
self.writer(''.join(lines))
try:
self._tag2proc[tags](tags, args)
except KeyError:
pass
def setwriter(self, writer):
self.writer = writer
def setprocessor(self, tags, processor):
if isinstance(tags, str):
tags = tuple(tags.split(":"))
else:
assert isinstance(tags, tuple)
self._tag2proc[tags] = processor
class TagTracerSub:
def __init__(self, root, tags):
self.root = root
self.tags = tags
def __call__(self, *args):
self.root.processmessage(self.tags, args)
def setmyprocessor(self, processor):
self.root.setprocessor(self.tags, processor)
def get(self, name):
return self.__class__(self.root, self.tags + (name,))
def add_method_wrapper(cls, wrapper_func):
""" Substitute the function named "wrapperfunc.__name__" at class
"cls" with a function that wraps the call to the original function.
Return an undo function which can be called to reset the class to use
the old method again.
wrapper_func is called with the same arguments as the method
it wraps and its result is used as a wrap_controller for
calling the original function.
"""
name = wrapper_func.__name__
oldcall = getattr(cls, name)
def wrap_exec(*args, **kwargs):
gen = wrapper_func(*args, **kwargs)
return wrapped_call(gen, lambda: oldcall(*args, **kwargs))
setattr(cls, name, wrap_exec)
return lambda: setattr(cls, name, oldcall)
def raise_wrapfail(wrap_controller, msg):
co = wrap_controller.gi_code
raise RuntimeError("wrap_controller at %r %s:%d %s" %
(co.co_name, co.co_filename, co.co_firstlineno, msg))
def wrapped_call(wrap_controller, func):
""" Wrap calling to a function with a generator which needs to yield
exactly once. The yield point will trigger calling the wrapped function
and return its CallOutcome to the yield point. The generator then needs
to finish (raise StopIteration) in order for the wrapped call to complete.
"""
try:
next(wrap_controller) # first yield
except StopIteration:
raise_wrapfail(wrap_controller, "did not yield")
call_outcome = CallOutcome(func)
try:
wrap_controller.send(call_outcome)
raise_wrapfail(wrap_controller, "has second yield")
except StopIteration:
pass
return call_outcome.get_result()
class CallOutcome:
""" Outcome of a function call, either an exception or a proper result.
Calling the ``get_result`` method will return the result or reraise
the exception raised when the function was called. """
excinfo = None
def __init__(self, func):
try:
self.result = func()
except BaseException:
self.excinfo = sys.exc_info()
def force_result(self, result):
self.result = result
self.excinfo = None
def get_result(self):
if self.excinfo is None:
return self.result
else:
ex = self.excinfo
if py3:
raise ex[1].with_traceback(ex[2])
py.builtin._reraise(*ex)
class PluginManager(object):
def __init__(self, hookspecs=None, prefix="pytest_"):
self._name2plugin = {}
self._plugins = []
self._conftestplugins = []
self._plugin2hookcallers = {}
self._warnings = []
self.trace = TagTracer().get("pluginmanage")
self._plugin_distinfo = []
self._shutdown = []
self.hook = HookRelay(hookspecs or [], pm=self, prefix=prefix)
def set_tracing(self, writer):
self.trace.root.setwriter(writer)
# reconfigure HookCalling to perform tracing
assert not hasattr(self, "_wrapping")
self._wrapping = True
def _docall(self, methods, kwargs):
trace = self.hookrelay.trace
trace.root.indent += 1
trace(self.name, kwargs)
box = yield
if box.excinfo is None:
trace("finish", self.name, "-->", box.result)
trace.root.indent -= 1
undo = add_method_wrapper(HookCaller, _docall)
self.add_shutdown(undo)
def do_configure(self, config):
# backward compatibility
config.do_configure()
def set_register_callback(self, callback):
assert not hasattr(self, "_registercallback")
self._registercallback = callback
def register(self, plugin, name=None, prepend=False, conftest=False):
if self._name2plugin.get(name, None) == -1:
return
name = name or getattr(plugin, '__name__', str(id(plugin)))
if self.isregistered(plugin, name):
raise ValueError("Plugin already registered: %s=%s\n%s" %(
name, plugin, self._name2plugin))
#self.trace("registering", name, plugin)
reg = getattr(self, "_registercallback", None)
if reg is not None:
reg(plugin, name) # may call addhooks
hookcallers = list(self.hook._scan_plugin(plugin))
self._plugin2hookcallers[plugin] = hookcallers
self._name2plugin[name] = plugin
if conftest:
self._conftestplugins.append(plugin)
else:
if not prepend:
self._plugins.append(plugin)
else:
self._plugins.insert(0, plugin)
# finally make sure that the methods of the new plugin take part
for hookcaller in hookcallers:
hookcaller.scan_methods()
return True
def unregister(self, plugin):
try:
self._plugins.remove(plugin)
except KeyError:
self._conftestplugins.remove(plugin)
for name, value in list(self._name2plugin.items()):
if value == plugin:
del self._name2plugin[name]
hookcallers = self._plugin2hookcallers.pop(plugin)
for hookcaller in hookcallers:
hookcaller.scan_methods()
def add_shutdown(self, func):
self._shutdown.append(func)
def ensure_shutdown(self):
while self._shutdown:
func = self._shutdown.pop()
func()
self._plugins = self._conftestplugins = []
self._name2plugin.clear()
def isregistered(self, plugin, name=None):
if self.getplugin(name) is not None:
return True
return plugin in self._plugins or plugin in self._conftestplugins
def addhooks(self, spec, prefix="pytest_"):
self.hook._addhooks(spec, prefix=prefix)
def getplugins(self):
return self._plugins + self._conftestplugins
def skipifmissing(self, name):
if not self.hasplugin(name):
import pytest
pytest.skip("plugin %r is missing" % name)
def hasplugin(self, name):
return bool(self.getplugin(name))
def getplugin(self, name):
if name is None:
return None
try:
return self._name2plugin[name]
except KeyError:
return self._name2plugin.get("_pytest." + name, None)
# API for bootstrapping
#
def _envlist(self, varname):
val = os.environ.get(varname, None)
if val is not None:
return val.split(',')
return ()
def consider_env(self):
for spec in self._envlist("PYTEST_PLUGINS"):
self.import_plugin(spec)
def consider_setuptools_entrypoints(self):
try:
from pkg_resources import iter_entry_points, DistributionNotFound
except ImportError:
return # XXX issue a warning
for ep in iter_entry_points('pytest11'):
name = ep.name
if name.startswith("pytest_"):
name = name[7:]
if ep.name in self._name2plugin or name in self._name2plugin:
continue
try:
plugin = ep.load()
except DistributionNotFound:
continue
self._plugin_distinfo.append((ep.dist, plugin))
self.register(plugin, name=name)
def consider_preparse(self, args):
for opt1,opt2 in zip(args, args[1:]):
if opt1 == "-p":
self.consider_pluginarg(opt2)
def consider_pluginarg(self, arg):
if arg.startswith("no:"):
name = arg[3:]
plugin = self.getplugin(name)
if plugin is not None:
self.unregister(plugin)
self._name2plugin[name] = -1
else:
if self.getplugin(arg) is None:
self.import_plugin(arg)
def consider_conftest(self, conftestmodule):
if self.register(conftestmodule, name=conftestmodule.__file__,
conftest=True):
self.consider_module(conftestmodule)
def consider_module(self, mod):
attr = getattr(mod, "pytest_plugins", ())
if attr:
if not isinstance(attr, (list, tuple)):
attr = (attr,)
for spec in attr:
self.import_plugin(spec)
def import_plugin(self, modname):
assert isinstance(modname, str)
if self.getplugin(modname) is not None:
return
try:
mod = importplugin(modname)
except KeyboardInterrupt:
raise
except ImportError:
if modname.startswith("pytest_"):
return self.import_plugin(modname[7:])
raise
except:
e = sys.exc_info()[1]
import pytest
if not hasattr(pytest, 'skip') or not isinstance(e, pytest.skip.Exception):
raise
self._warnings.append("skipped plugin %r: %s" %((modname, e.msg)))
else:
self.register(mod, modname)
self.consider_module(mod)
def listattr(self, attrname, plugins=None):
if plugins is None:
plugins = self._plugins + self._conftestplugins
l = []
last = []
wrappers = []
for plugin in plugins:
try:
meth = getattr(plugin, attrname)
except AttributeError:
continue
if hasattr(meth, 'hookwrapper'):
wrappers.append(meth)
elif hasattr(meth, 'tryfirst'):
last.append(meth)
elif hasattr(meth, 'trylast'):
l.insert(0, meth)
else:
l.append(meth)
l.extend(last)
l.extend(wrappers)
return l
def call_plugin(self, plugin, methname, kwargs):
return MultiCall(methods=self.listattr(methname, plugins=[plugin]),
kwargs=kwargs, firstresult=True).execute()
def importplugin(importspec):
name = importspec
try:
mod = "_pytest." + name
__import__(mod)
return sys.modules[mod]
except ImportError:
__import__(importspec)
return sys.modules[importspec]
class MultiCall:
""" execute a call into multiple python functions/methods. """
def __init__(self, methods, kwargs, firstresult=False):
self.methods = list(methods)
self.kwargs = kwargs
self.kwargs["__multicall__"] = self
self.results = []
self.firstresult = firstresult
def __repr__(self):
status = "%d results, %d meths" % (len(self.results), len(self.methods))
return "<MultiCall %s, kwargs=%r>" %(status, self.kwargs)
def execute(self):
all_kwargs = self.kwargs
while self.methods:
method = self.methods.pop()
args = [all_kwargs[argname] for argname in varnames(method)]
if hasattr(method, "hookwrapper"):
return wrapped_call(method(*args), self.execute)
res = method(*args)
if res is not None:
self.results.append(res)
if self.firstresult:
return res
if not self.firstresult:
return self.results
def varnames(func, startindex=None):
""" return argument name tuple for a function, method, class or callable.
In case of a class, its "__init__" method is considered.
For methods the "self" parameter is not included unless you are passing
an unbound method with Python3 (which has no supports for unbound methods)
"""
cache = getattr(func, "__dict__", {})
try:
return cache["_varnames"]
except KeyError:
pass
if inspect.isclass(func):
try:
func = func.__init__
except AttributeError:
return ()
startindex = 1
else:
if not inspect.isfunction(func) and not inspect.ismethod(func):
func = getattr(func, '__call__', func)
if startindex is None:
startindex = int(inspect.ismethod(func))
rawcode = py.code.getrawcode(func)
try:
x = rawcode.co_varnames[startindex:rawcode.co_argcount]
except AttributeError:
x = ()
else:
defaults = func.__defaults__
if defaults:
x = x[:-len(defaults)]
try:
cache["_varnames"] = x
except TypeError:
pass
return x
class HookRelay:
def __init__(self, hookspecs, pm, prefix="pytest_"):
if not isinstance(hookspecs, list):
hookspecs = [hookspecs]
self._pm = pm
self.trace = pm.trace.root.get("hook")
self.prefix = prefix
for hookspec in hookspecs:
self._addhooks(hookspec, prefix)
def _addhooks(self, hookspec, prefix):
added = False
isclass = int(inspect.isclass(hookspec))
for name, method in vars(hookspec).items():
if name.startswith(prefix):
firstresult = getattr(method, 'firstresult', False)
hc = HookCaller(self, name, firstresult=firstresult,
argnames=varnames(method, startindex=isclass))
setattr(self, name, hc)
added = True
#print ("setting new hook", name)
if not added:
raise ValueError("did not find new %r hooks in %r" %(
prefix, hookspec,))
def _getcaller(self, name, plugins):
caller = getattr(self, name)
methods = self._pm.listattr(name, plugins=plugins)
if methods:
return caller.new_cached_caller(methods)
return caller
def _scan_plugin(self, plugin):
def fail(msg, *args):
name = getattr(plugin, '__name__', plugin)
raise PluginValidationError("plugin %r\n%s" %(name, msg % args))
for name in dir(plugin):
if not name.startswith(self.prefix):
continue
hook = getattr(self, name, None)
method = getattr(plugin, name)
if hook is None:
is_optional = getattr(method, 'optionalhook', False)
if not isgenerichook(name) and not is_optional:
fail("found unknown hook: %r", name)
continue
for arg in varnames(method):
if arg not in hook.argnames:
fail("argument %r not available\n"
"actual definition: %s\n"
"available hookargs: %s",
arg, formatdef(method),
", ".join(hook.argnames))
yield hook
class HookCaller:
def __init__(self, hookrelay, name, firstresult, argnames, methods=()):
self.hookrelay = hookrelay
self.name = name
self.firstresult = firstresult
self.argnames = ["__multicall__"]
self.argnames.extend(argnames)
assert "self" not in argnames # sanity check
self.methods = methods
def new_cached_caller(self, methods):
return HookCaller(self.hookrelay, self.name, self.firstresult,
argnames=self.argnames, methods=methods)
def __repr__(self):
return "<HookCaller %r>" %(self.name,)
def scan_methods(self):
self.methods = self.hookrelay._pm.listattr(self.name)
def __call__(self, **kwargs):
return self._docall(self.methods, kwargs)
def callextra(self, methods, **kwargs):
return self._docall(self.methods + methods, kwargs)
def _docall(self, methods, kwargs):
return MultiCall(methods, kwargs,
firstresult=self.firstresult).execute()
class PluginValidationError(Exception):
""" plugin failed validation. """
def isgenerichook(name):
return name == "pytest_plugins" or \
name.startswith("pytest_funcarg__")
def formatdef(func):
return "%s%s" % (
func.__name__,
inspect.formatargspec(*inspect.getargspec(func))
)

View File

@@ -8,21 +8,33 @@ import pytest
def pytest_addoption(parser):
group = parser.getgroup("general")
group._addoption('--pdb',
action="store_true", dest="usepdb", default=False,
help="start the interactive Python debugger on errors.")
group._addoption(
'--pdb', dest="usepdb", action="store_true",
help="start the interactive Python debugger on errors.")
group._addoption(
'--pdbcls', dest="usepdb_cls", metavar="modulename:classname",
help="start a custom interactive Python debugger on errors. "
"For example: --pdbcls=IPython.terminal.debugger:TerminalPdb")
def pytest_namespace():
return {'set_trace': pytestPDB().set_trace}
def pytest_configure(config):
if config.getvalue("usepdb"):
if config.getvalue("usepdb") or config.getvalue("usepdb_cls"):
config.pluginmanager.register(PdbInvoke(), 'pdbinvoke')
if config.getvalue("usepdb_cls"):
modname, classname = config.getvalue("usepdb_cls").split(":")
__import__(modname)
pdb_cls = getattr(sys.modules[modname], classname)
else:
pdb_cls = pdb.Pdb
pytestPDB._pdb_cls = pdb_cls
old = (pdb.set_trace, pytestPDB._pluginmanager)
def fin():
pdb.set_trace, pytestPDB._pluginmanager = old
pytestPDB._config = None
pytestPDB._pdb_cls = pdb.Pdb
pdb.set_trace = pytest.set_trace
pytestPDB._pluginmanager = config.pluginmanager
pytestPDB._config = config
@@ -32,12 +44,12 @@ class pytestPDB:
""" Pseudo PDB that defers to the real pdb. """
_pluginmanager = None
_config = None
_pdb_cls = pdb.Pdb
def set_trace(self):
""" invoke PDB set_trace debugging, dropping any IO capturing. """
import _pytest.config
frame = sys._getframe().f_back
capman = None
if self._pluginmanager is not None:
capman = self._pluginmanager.getplugin("capturemanager")
if capman:
@@ -45,15 +57,17 @@ class pytestPDB:
tw = _pytest.config.create_terminal_writer(self._config)
tw.line()
tw.sep(">", "PDB set_trace (IO-capturing turned off)")
self._pluginmanager.hook.pytest_enter_pdb()
pdb.Pdb().set_trace(frame)
self._pluginmanager.hook.pytest_enter_pdb(config=self._config)
self._pdb_cls().set_trace(frame)
class PdbInvoke:
def pytest_exception_interact(self, node, call, report):
capman = node.config.pluginmanager.getplugin("capturemanager")
if capman:
capman.suspendcapture(in_=True)
out, err = capman.suspendcapture(in_=True)
sys.stdout.write(out)
sys.stdout.write(err)
_enter_pdb(node, call.excinfo, report)
def pytest_internalerror(self, excrepr, excinfo):
@@ -97,7 +111,7 @@ def _find_last_non_hidden_frame(stack):
def post_mortem(t):
class Pdb(pdb.Pdb):
class Pdb(pytestPDB._pdb_cls):
def get_stack(self, f, t):
stack, i = pdb.Pdb.get_stack(self, f, t)
if f is None:

24
_pytest/deprecated.py Normal file
View File

@@ -0,0 +1,24 @@
"""
This module contains deprecation messages and bits of code used elsewhere in the codebase
that is planned to be removed in the next pytest release.
Keeping it in a central location makes it easy to track what is deprecated and should
be removed when the time comes.
"""
MAIN_STR_ARGS = 'passing a string to pytest.main() is deprecated, ' \
'pass a list of arguments instead.'
YIELD_TESTS = 'yield tests are deprecated, and scheduled to be removed in pytest 4.0'
FUNCARG_PREFIX = (
'{name}: declaring fixtures using "pytest_funcarg__" prefix is deprecated '
'and scheduled to be removed in pytest 4.0. '
'Please remove the prefix and use the @pytest.fixture decorator instead.')
SETUP_CFG_PYTEST = '[pytest] section in setup.cfg files is deprecated, use [tool:pytest] instead.'
GETFUNCARGVALUE = "use of getfuncargvalue is deprecated, use getfixturevalue"
RESULT_LOG = '--result-log is deprecated and scheduled for removal in pytest 4.0'

View File

@@ -1,9 +1,26 @@
""" discover and run doctests in modules and test files."""
from __future__ import absolute_import
import traceback
import pytest, py
from _pytest.python import FixtureRequest, FuncFixtureInfo
from py._code.code import TerminalRepr, ReprFileLocation
import pytest
from _pytest._code.code import ExceptionInfo, ReprFileLocation, TerminalRepr
from _pytest.fixtures import FixtureRequest
DOCTEST_REPORT_CHOICE_NONE = 'none'
DOCTEST_REPORT_CHOICE_CDIFF = 'cdiff'
DOCTEST_REPORT_CHOICE_NDIFF = 'ndiff'
DOCTEST_REPORT_CHOICE_UDIFF = 'udiff'
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE = 'only_first_failure'
DOCTEST_REPORT_CHOICES = (
DOCTEST_REPORT_CHOICE_NONE,
DOCTEST_REPORT_CHOICE_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF,
DOCTEST_REPORT_CHOICE_UDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE,
)
def pytest_addoption(parser):
parser.addini('doctest_optionflags', 'option flags for doctests',
@@ -13,8 +30,13 @@ def pytest_addoption(parser):
action="store_true", default=False,
help="run doctests in all .py modules",
dest="doctestmodules")
group.addoption("--doctest-report",
type=str.lower, default="udiff",
help="choose another output format for diffs on doctest failure",
choices=DOCTEST_REPORT_CHOICES,
dest="doctestreport")
group.addoption("--doctest-glob",
action="store", default="test*.txt", metavar="pat",
action="append", default=[], metavar="pat",
help="doctests file matching pattern, default: test*.txt",
dest="doctestglob")
group.addoption("--doctest-ignore-import-errors",
@@ -22,31 +44,56 @@ def pytest_addoption(parser):
help="ignore doctest ImportErrors",
dest="doctest_ignore_import_errors")
def pytest_collect_file(path, parent):
config = parent.config
if path.ext == ".py":
if config.option.doctestmodules:
return DoctestModule(path, parent)
elif (path.ext in ('.txt', '.rst') and parent.session.isinitpath(path)) or \
path.check(fnmatch=config.getvalue("doctestglob")):
elif _is_doctest(config, path, parent):
return DoctestTextfile(path, parent)
def _is_doctest(config, path, parent):
if path.ext in ('.txt', '.rst') and parent.session.isinitpath(path):
return True
globs = config.getoption("doctestglob") or ['test*.txt']
for glob in globs:
if path.check(fnmatch=glob):
return True
return False
class ReprFailDoctest(TerminalRepr):
def __init__(self, reprlocation, lines):
self.reprlocation = reprlocation
self.lines = lines
def toterminal(self, tw):
for line in self.lines:
tw.line(line)
self.reprlocation.toterminal(tw)
class DoctestItem(pytest.Item):
def __init__(self, name, parent, runner=None, dtest=None):
super(DoctestItem, self).__init__(name, parent)
self.runner = runner
self.dtest = dtest
self.obj = None
self.fixture_request = None
def setup(self):
if self.dtest is not None:
self.fixture_request = _setup_fixtures(self)
globs = dict(getfixture=self.fixture_request.getfixturevalue)
for name, value in self.fixture_request.getfixturevalue('doctest_namespace').items():
globs[name] = value
self.dtest.globs.update(globs)
def runtest(self):
_check_all_skipped(self.dtest)
self.runner.run(self.dtest)
def repr_failure(self, excinfo):
@@ -63,26 +110,26 @@ class DoctestItem(pytest.Item):
lineno = test.lineno + example.lineno + 1
message = excinfo.type.__name__
reprlocation = ReprFileLocation(filename, lineno, message)
checker = doctest.OutputChecker()
REPORT_UDIFF = doctest.REPORT_UDIFF
filelines = py.path.local(filename).readlines(cr=0)
lines = []
checker = _get_checker()
report_choice = _get_report_choice(self.config.getoption("doctestreport"))
if lineno is not None:
i = max(test.lineno, max(0, lineno - 10)) # XXX?
for line in filelines[i:lineno]:
lines.append("%03d %s" % (i+1, line))
i += 1
lines = doctestfailure.test.docstring.splitlines(False)
# add line numbers to the left of the error message
lines = ["%03d %s" % (i + test.lineno + 1, x)
for (i, x) in enumerate(lines)]
# trim docstring error lines to 10
lines = lines[example.lineno - 9:example.lineno + 1]
else:
lines.append('EXAMPLE LOCATION UNKNOWN, not showing all tests of that example')
lines = ['EXAMPLE LOCATION UNKNOWN, not showing all tests of that example']
indent = '>>>'
for line in example.source.splitlines():
lines.append('??? %s %s' % (indent, line))
indent = '...'
if excinfo.errisinstance(doctest.DocTestFailure):
lines += checker.output_difference(example,
doctestfailure.got, REPORT_UDIFF).split("\n")
doctestfailure.got, report_choice).split("\n")
else:
inner_excinfo = py.code.ExceptionInfo(excinfo.value.exc_info)
inner_excinfo = ExceptionInfo(excinfo.value.exc_info)
lines += ["UNEXPECTED EXCEPTION: %s" %
repr(inner_excinfo.value)]
lines += traceback.format_exception(*excinfo.value.exc_info)
@@ -93,6 +140,7 @@ class DoctestItem(pytest.Item):
def reportinfo(self):
return self.fspath, None, "[doctest] %s" % self.name
def _get_flag_lookup():
import doctest
return dict(DONT_ACCEPT_TRUE_FOR_1=doctest.DONT_ACCEPT_TRUE_FOR_1,
@@ -100,7 +148,11 @@ def _get_flag_lookup():
NORMALIZE_WHITESPACE=doctest.NORMALIZE_WHITESPACE,
ELLIPSIS=doctest.ELLIPSIS,
IGNORE_EXCEPTION_DETAIL=doctest.IGNORE_EXCEPTION_DETAIL,
COMPARISON_FLAGS=doctest.COMPARISON_FLAGS)
COMPARISON_FLAGS=doctest.COMPARISON_FLAGS,
ALLOW_UNICODE=_get_allow_unicode_flag(),
ALLOW_BYTES=_get_allow_bytes_flag(),
)
def get_optionflags(parent):
optionflags_str = parent.config.getini("doctest_optionflags")
@@ -110,29 +162,46 @@ def get_optionflags(parent):
flag_acc |= flag_lookup_table[flag]
return flag_acc
class DoctestTextfile(DoctestItem, pytest.File):
def runtest(self):
import doctest
# satisfy `FixtureRequest` constructor...
self.funcargs = {}
fm = self.session._fixturemanager
def func():
pass
self._fixtureinfo = fm.getfixtureinfo(node=self, func=func,
cls=None, funcargs=False)
fixture_request = FixtureRequest(self)
fixture_request._fillfixtures()
failed, tot = doctest.testfile(
str(self.fspath), module_relative=False,
optionflags=get_optionflags(self),
extraglobs=dict(getfixture=fixture_request.getfuncargvalue),
raise_on_error=True, verbose=0)
class DoctestModule(pytest.File):
class DoctestTextfile(pytest.Module):
obj = None
def collect(self):
import doctest
# inspired by doctest.testfile; ideally we would use it directly,
# but it doesn't support passing a custom checker
text = self.fspath.read()
filename = str(self.fspath)
name = self.fspath.basename
globs = {'__name__': '__main__'}
optionflags = get_optionflags(self)
runner = doctest.DebugRunner(verbose=0, optionflags=optionflags,
checker=_get_checker())
parser = doctest.DocTestParser()
test = parser.get_doctest(text, globs, name, filename, 0)
if test.examples:
yield DoctestItem(test.name, self, runner, test)
def _check_all_skipped(test):
"""raises pytest.skip() if all examples in the given DocTest have the SKIP
option set.
"""
import doctest
all_skipped = all(x.options.get(doctest.SKIP, False) for x in test.examples)
if all_skipped:
pytest.skip('all tests skipped by +SKIP option')
class DoctestModule(pytest.Module):
def collect(self):
import doctest
if self.fspath.basename == "conftest.py":
module = self.config._conftest.importconftest(self.fspath)
module = self.config.pluginmanager._importconftest(self.fspath)
else:
try:
module = self.fspath.pyimport()
@@ -141,16 +210,122 @@ class DoctestModule(pytest.File):
pytest.skip('unable to import module %r' % self.fspath)
else:
raise
# satisfy `FixtureRequest` constructor...
self.funcargs = {}
self._fixtureinfo = FuncFixtureInfo((), [], {})
fixture_request = FixtureRequest(self)
doctest_globals = dict(getfixture=fixture_request.getfuncargvalue)
# uses internal doctest module parsing mechanism
finder = doctest.DocTestFinder()
optionflags = get_optionflags(self)
runner = doctest.DebugRunner(verbose=0, optionflags=optionflags)
for test in finder.find(module, module.__name__,
extraglobs=doctest_globals):
runner = doctest.DebugRunner(verbose=0, optionflags=optionflags,
checker=_get_checker())
for test in finder.find(module, module.__name__):
if test.examples: # skip empty doctests
yield DoctestItem(test.name, self, runner, test)
def _setup_fixtures(doctest_item):
"""
Used by DoctestTextfile and DoctestItem to setup fixture information.
"""
def func():
pass
doctest_item.funcargs = {}
fm = doctest_item.session._fixturemanager
doctest_item._fixtureinfo = fm.getfixtureinfo(node=doctest_item, func=func,
cls=None, funcargs=False)
fixture_request = FixtureRequest(doctest_item)
fixture_request._fillfixtures()
return fixture_request
def _get_checker():
"""
Returns a doctest.OutputChecker subclass that takes in account the
ALLOW_UNICODE option to ignore u'' prefixes in strings and ALLOW_BYTES
to strip b'' prefixes.
Useful when the same doctest should run in Python 2 and Python 3.
An inner class is used to avoid importing "doctest" at the module
level.
"""
if hasattr(_get_checker, 'LiteralsOutputChecker'):
return _get_checker.LiteralsOutputChecker()
import doctest
import re
class LiteralsOutputChecker(doctest.OutputChecker):
"""
Copied from doctest_nose_plugin.py from the nltk project:
https://github.com/nltk/nltk
Further extended to also support byte literals.
"""
_unicode_literal_re = re.compile(r"(\W|^)[uU]([rR]?[\'\"])", re.UNICODE)
_bytes_literal_re = re.compile(r"(\W|^)[bB]([rR]?[\'\"])", re.UNICODE)
def check_output(self, want, got, optionflags):
res = doctest.OutputChecker.check_output(self, want, got,
optionflags)
if res:
return True
allow_unicode = optionflags & _get_allow_unicode_flag()
allow_bytes = optionflags & _get_allow_bytes_flag()
if not allow_unicode and not allow_bytes:
return False
else: # pragma: no cover
def remove_prefixes(regex, txt):
return re.sub(regex, r'\1\2', txt)
if allow_unicode:
want = remove_prefixes(self._unicode_literal_re, want)
got = remove_prefixes(self._unicode_literal_re, got)
if allow_bytes:
want = remove_prefixes(self._bytes_literal_re, want)
got = remove_prefixes(self._bytes_literal_re, got)
res = doctest.OutputChecker.check_output(self, want, got,
optionflags)
return res
_get_checker.LiteralsOutputChecker = LiteralsOutputChecker
return _get_checker.LiteralsOutputChecker()
def _get_allow_unicode_flag():
"""
Registers and returns the ALLOW_UNICODE flag.
"""
import doctest
return doctest.register_optionflag('ALLOW_UNICODE')
def _get_allow_bytes_flag():
"""
Registers and returns the ALLOW_BYTES flag.
"""
import doctest
return doctest.register_optionflag('ALLOW_BYTES')
def _get_report_choice(key):
"""
This function returns the actual `doctest` module flag value, we want to do it as late as possible to avoid
importing `doctest` and all its dependencies when parsing options, as it adds overhead and breaks tests.
"""
import doctest
return {
DOCTEST_REPORT_CHOICE_UDIFF: doctest.REPORT_UDIFF,
DOCTEST_REPORT_CHOICE_CDIFF: doctest.REPORT_CDIFF,
DOCTEST_REPORT_CHOICE_NDIFF: doctest.REPORT_NDIFF,
DOCTEST_REPORT_CHOICE_ONLY_FIRST_FAILURE: doctest.REPORT_ONLY_FIRST_FAILURE,
DOCTEST_REPORT_CHOICE_NONE: 0,
}[key]
@pytest.fixture(scope='session')
def doctest_namespace():
"""
Inject names into the doctest namespace.
"""
return dict()

1110
_pytest/fixtures.py Normal file

File diff suppressed because it is too large Load Diff

45
_pytest/freeze_support.py Normal file
View File

@@ -0,0 +1,45 @@
"""
Provides a function to report all internal modules for using freezing tools
pytest
"""
def pytest_namespace():
return {'freeze_includes': freeze_includes}
def freeze_includes():
"""
Returns a list of module names used by py.test that should be
included by cx_freeze.
"""
import py
import _pytest
result = list(_iter_all_modules(py))
result += list(_iter_all_modules(_pytest))
return result
def _iter_all_modules(package, prefix=''):
"""
Iterates over the names of all modules that can be found in the given
package, recursively.
Example:
_iter_all_modules(_pytest) ->
['_pytest.assertion.newinterpret',
'_pytest.capture',
'_pytest.core',
...
]
"""
import os
import pkgutil
if type(package) is not str:
path, prefix = package.__path__[0], package.__name__ + '.'
else:
path = package
for _, name, is_package in pkgutil.iter_modules([path]):
if is_package:
for m in _iter_all_modules(os.path.join(path, name), prefix=name + '.'):
yield prefix + m
else:
yield prefix + name

View File

@@ -1,128 +0,0 @@
""" generate a single-file self-contained version of pytest """
import os
import sys
import pkgutil
import py
import _pytest
def find_toplevel(name):
for syspath in sys.path:
base = py.path.local(syspath)
lib = base/name
if lib.check(dir=1):
return lib
mod = base.join("%s.py" % name)
if mod.check(file=1):
return mod
raise LookupError(name)
def pkgname(toplevel, rootpath, path):
parts = path.parts()[len(rootpath.parts()):]
return '.'.join([toplevel] + [x.purebasename for x in parts])
def pkg_to_mapping(name):
toplevel = find_toplevel(name)
name2src = {}
if toplevel.check(file=1): # module
name2src[toplevel.purebasename] = toplevel.read()
else: # package
for pyfile in toplevel.visit('*.py'):
pkg = pkgname(name, toplevel, pyfile)
name2src[pkg] = pyfile.read()
return name2src
def compress_mapping(mapping):
import base64, pickle, zlib
data = pickle.dumps(mapping, 2)
data = zlib.compress(data, 9)
data = base64.encodestring(data)
data = data.decode('ascii')
return data
def compress_packages(names):
mapping = {}
for name in names:
mapping.update(pkg_to_mapping(name))
return compress_mapping(mapping)
def generate_script(entry, packages):
data = compress_packages(packages)
tmpl = py.path.local(__file__).dirpath().join('standalonetemplate.py')
exe = tmpl.read()
exe = exe.replace('@SOURCES@', data)
exe = exe.replace('@ENTRY@', entry)
return exe
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption("--genscript", action="store", default=None,
dest="genscript", metavar="path",
help="create standalone pytest script at given target path.")
def pytest_cmdline_main(config):
import _pytest.config
genscript = config.getvalue("genscript")
if genscript:
tw = _pytest.config.create_terminal_writer(config)
deps = ['py', '_pytest', 'pytest']
if sys.version_info < (2,7):
deps.append("argparse")
tw.line("generated script will run on python2.6-python3.3++")
else:
tw.line("WARNING: generated script will not run on python2.6 "
"due to 'argparse' dependency. Use python2.6 "
"to generate a python2.6 compatible script", red=True)
script = generate_script(
'import pytest; raise SystemExit(pytest.cmdline.main())',
deps,
)
genscript = py.path.local(genscript)
genscript.write(script)
tw.line("generated pytest standalone script: %s" % genscript,
bold=True)
return 0
def pytest_namespace():
return {'freeze_includes': freeze_includes}
def freeze_includes():
"""
Returns a list of module names used by py.test that should be
included by cx_freeze.
"""
result = list(_iter_all_modules(py))
result += list(_iter_all_modules(_pytest))
return result
def _iter_all_modules(package, prefix=''):
"""
Iterates over the names of all modules that can be found in the given
package, recursively.
Example:
_iter_all_modules(_pytest) ->
['_pytest.assertion.newinterpret',
'_pytest.capture',
'_pytest.core',
...
]
"""
if type(package) is not str:
path, prefix = package.__path__[0], package.__name__ + '.'
else:
path = package
for _, name, is_package in pkgutil.iter_modules([path]):
if is_package:
for m in _iter_all_modules(os.path.join(path, name), prefix=name + '.'):
yield prefix + m
else:
yield prefix + name

View File

@@ -20,32 +20,34 @@ def pytest_addoption(parser):
group.addoption('--debug',
action="store_true", dest="debug", default=False,
help="store internal tracing debug information in 'pytestdebug.log'.")
group._addoption(
'-o', '--override-ini', nargs='*', dest="override_ini",
action="append",
help="override config option, e.g. `-o xfail_strict=True`.")
@pytest.mark.hookwrapper
@pytest.hookimpl(hookwrapper=True)
def pytest_cmdline_parse():
outcome = yield
config = outcome.get_result()
if config.option.debug:
path = os.path.abspath("pytestdebug.log")
f = open(path, 'w')
config._debugfile = f
f.write("versions pytest-%s, py-%s, "
debugfile = open(path, 'w')
debugfile.write("versions pytest-%s, py-%s, "
"python-%s\ncwd=%s\nargs=%s\n\n" %(
pytest.__version__, py.__version__,
".".join(map(str, sys.version_info)),
os.getcwd(), config._origargs))
config.pluginmanager.set_tracing(f.write)
config.trace.root.setwriter(debugfile.write)
undo_tracing = config.pluginmanager.enable_tracing()
sys.stderr.write("writing pytestdebug information to %s\n" % path)
@pytest.mark.trylast
def pytest_unconfigure(config):
if hasattr(config, '_debugfile'):
config._debugfile.close()
sys.stderr.write("wrote pytestdebug information to %s\n" %
config._debugfile.name)
config.trace.root.setwriter(None)
def unset_tracing():
debugfile.close()
sys.stderr.write("wrote pytestdebug information to %s\n" %
debugfile.name)
config.trace.root.setwriter(None)
undo_tracing()
config.add_cleanup(unset_tracing)
def pytest_cmdline_main(config):
if config.option.version:
@@ -58,18 +60,17 @@ def pytest_cmdline_main(config):
sys.stderr.write(line + "\n")
return 0
elif config.option.help:
config.do_configure()
config._do_configure()
showhelp(config)
config.do_unconfigure()
config._ensure_unconfigure()
return 0
def showhelp(config):
import _pytest.config
tw = _pytest.config.create_terminal_writer(config)
reporter = config.pluginmanager.get_plugin('terminalreporter')
tw = reporter._tw
tw.write(config._parser.optparser.format_help())
tw.line()
tw.line()
#tw.sep( "=", "config file settings")
tw.line("[pytest] ini-options in the next "
"pytest.ini|tox.ini|setup.cfg file:")
tw.line()
@@ -82,14 +83,25 @@ def showhelp(config):
line = " %-24s %s" %(spec, help)
tw.line(line[:tw.fullwidth])
tw.line() ; tw.line()
#tw.sep("=")
tw.line("to see available markers type: py.test --markers")
tw.line("to see available fixtures type: py.test --fixtures")
tw.line()
tw.line("environment variables:")
vars = [
("PYTEST_ADDOPTS", "extra command line options"),
("PYTEST_PLUGINS", "comma-separated plugins to load during startup"),
("PYTEST_DEBUG", "set to enable debug tracing of pytest's internals")
]
for name, help in vars:
tw.line(" %-24s %s" % (name, help))
tw.line()
tw.line()
tw.line("to see available markers type: pytest --markers")
tw.line("to see available fixtures type: pytest --fixtures")
tw.line("(shown according to specified file_or_dir or current dir "
"if not specified)")
for warning in config.pluginmanager._warnings:
tw.line("warning: %s" % (warning,), red=True)
for warningreport in reporter.stats.get('warnings', []):
tw.line("warning : " + warningreport.message, red=True)
return
@@ -99,10 +111,10 @@ conftest_options = [
def getpluginversioninfo(config):
lines = []
plugininfo = config.pluginmanager._plugin_distinfo
plugininfo = config.pluginmanager.list_plugin_distinfo()
if plugininfo:
lines.append("setuptools registered plugins:")
for dist, plugin in plugininfo:
for plugin, dist in plugininfo:
loc = getattr(plugin, '__file__', repr(plugin))
content = "%s-%s at %s" % (dist.project_name, dist.version, loc)
lines.append(" " + content)
@@ -120,7 +132,7 @@ def pytest_report_header(config):
if config.option.traceconfig:
lines.append("active plugins:")
items = config.pluginmanager._name2plugin.items()
items = config.pluginmanager.list_name_plugin()
for name, plugin in items:
if hasattr(plugin, '__file__'):
r = plugin.__file__
@@ -128,5 +140,3 @@ def pytest_report_header(config):
r = repr(plugin)
lines.append(" %-20s: %s" %(name, r))
return lines

View File

@@ -1,33 +1,42 @@
""" hook specifications for pytest plugins, invoked from main.py and builtin plugins. """
from _pytest._pluggy import HookspecMarker
hookspec = HookspecMarker("pytest")
# -------------------------------------------------------------------------
# Initialization
# Initialization hooks called for every plugin
# -------------------------------------------------------------------------
@hookspec(historic=True)
def pytest_addhooks(pluginmanager):
"""called at plugin load time to allow adding new hooks via a call to
pluginmanager.registerhooks(module)."""
"""called at plugin registration time to allow adding new hooks via a call to
pluginmanager.add_hookspecs(module_or_class, prefix)."""
@hookspec(historic=True)
def pytest_namespace():
"""return dict of name->object to be made globally available in
the pytest namespace. This hook is called before command line options
are parsed.
the pytest namespace. This hook is called at plugin registration
time.
"""
def pytest_cmdline_parse(pluginmanager, args):
"""return initialized config object, parsing the specified args. """
pytest_cmdline_parse.firstresult = True
@hookspec(historic=True)
def pytest_plugin_registered(plugin, manager):
""" a new pytest plugin got registered. """
def pytest_cmdline_preparse(config, args):
"""(deprecated) modify command line arguments before option parsing. """
@hookspec(historic=True)
def pytest_addoption(parser):
"""register argparse-style options and ini-style config values.
This function must be implemented in a :ref:`plugin <pluginorder>` and is
"""register argparse-style options and ini-style config values,
called once at the beginning of a test run.
.. note::
This function should be implemented only in plugins or ``conftest.py``
files situated at the tests root directory due to how pytest
:ref:`discovers plugins during startup <pluginorder>`.
:arg parser: To add command line options, call
:py:func:`parser.addoption(...) <_pytest.config.Parser.addoption>`.
To add ini-file values call :py:func:`parser.addini(...)
@@ -47,35 +56,43 @@ def pytest_addoption(parser):
via (deprecated) ``pytest.config``.
"""
@hookspec(historic=True)
def pytest_configure(config):
""" called after command line options have been parsed
and all plugins and initial conftest files been loaded.
This hook is called for every plugin.
"""
# -------------------------------------------------------------------------
# Bootstrapping hooks called for plugins registered early enough:
# internal and 3rd party plugins as well as directly
# discoverable conftest.py local plugins.
# -------------------------------------------------------------------------
@hookspec(firstresult=True)
def pytest_cmdline_parse(pluginmanager, args):
"""return initialized config object, parsing the specified args. """
def pytest_cmdline_preparse(config, args):
"""(deprecated) modify command line arguments before option parsing. """
@hookspec(firstresult=True)
def pytest_cmdline_main(config):
""" called for performing the main command line action. The default
implementation will invoke the configure hooks and runtest_mainloop. """
pytest_cmdline_main.firstresult = True
def pytest_load_initial_conftests(args, early_config, parser):
def pytest_load_initial_conftests(early_config, parser, args):
""" implements the loading of initial conftest files ahead
of command line option parsing. """
def pytest_configure(config):
""" called after command line options have been parsed
and all plugins and initial conftest files been loaded.
"""
def pytest_unconfigure(config):
""" called before test process is exited. """
def pytest_runtestloop(session):
""" called for performing the main runtest loop
(after collection finished). """
pytest_runtestloop.firstresult = True
# -------------------------------------------------------------------------
# collection hooks
# -------------------------------------------------------------------------
@hookspec(firstresult=True)
def pytest_collection(session):
""" perform the collection protocol for the given session. """
pytest_collection.firstresult = True
def pytest_collection_modifyitems(session, config, items):
""" called after collection has been performed, may filter or re-order
@@ -84,16 +101,16 @@ def pytest_collection_modifyitems(session, config, items):
def pytest_collection_finish(session):
""" called after collection has been performed and modified. """
@hookspec(firstresult=True)
def pytest_ignore_collect(path, config):
""" return True to prevent considering this path for collection.
This hook is consulted for all files and directories prior to calling
more specific hooks.
"""
pytest_ignore_collect.firstresult = True
@hookspec(firstresult=True)
def pytest_collect_directory(path, parent):
""" called before traversing a directory for collection files. """
pytest_collect_directory.firstresult = True
def pytest_collect_file(path, parent):
""" return collection Node or None for the given path. Any new node
@@ -112,39 +129,52 @@ def pytest_collectreport(report):
def pytest_deselected(items):
""" called for test items deselected by keyword. """
@hookspec(firstresult=True)
def pytest_make_collect_report(collector):
""" perform ``collector.collect()`` and return a CollectReport. """
pytest_make_collect_report.firstresult = True
# -------------------------------------------------------------------------
# Python test function related hooks
# -------------------------------------------------------------------------
@hookspec(firstresult=True)
def pytest_pycollect_makemodule(path, parent):
""" return a Module collector or None for the given path.
This hook will be called for each matching test module path.
The pytest_collect_file hook needs to be used if you want to
create test modules for files that do not match as a test module.
"""
pytest_pycollect_makemodule.firstresult = True
@hookspec(firstresult=True)
def pytest_pycollect_makeitem(collector, name, obj):
""" return custom item/collector for a python object in a module, or None. """
pytest_pycollect_makeitem.firstresult = True
@hookspec(firstresult=True)
def pytest_pyfunc_call(pyfuncitem):
""" call underlying test function. """
pytest_pyfunc_call.firstresult = True
def pytest_generate_tests(metafunc):
""" generate (multiple) parametrized calls to a test function."""
@hookspec(firstresult=True)
def pytest_make_parametrize_id(config, val):
"""Return a user-friendly string representation of the given ``val`` that will be used
by @pytest.mark.parametrize calls. Return None if the hook doesn't know about ``val``.
"""
# -------------------------------------------------------------------------
# generic runtest related hooks
# -------------------------------------------------------------------------
@hookspec(firstresult=True)
def pytest_runtestloop(session):
""" called for performing the main runtest loop
(after collection finished). """
def pytest_itemstart(item, node):
""" (deprecated, use pytest_runtest_logstart). """
@hookspec(firstresult=True)
def pytest_runtest_protocol(item, nextitem):
""" implements the runtest_setup/call/teardown protocol for
the given test item, including capturing exceptions and calling
@@ -158,7 +188,6 @@ def pytest_runtest_protocol(item, nextitem):
:return boolean: True if no further hook implementations should be invoked.
"""
pytest_runtest_protocol.firstresult = True
def pytest_runtest_logstart(nodeid, location):
""" signal the start of running a single test item. """
@@ -178,17 +207,30 @@ def pytest_runtest_teardown(item, nextitem):
so that nextitem only needs to call setup-functions.
"""
@hookspec(firstresult=True)
def pytest_runtest_makereport(item, call):
""" return a :py:class:`_pytest.runner.TestReport` object
for the given :py:class:`pytest.Item` and
:py:class:`_pytest.runner.CallInfo`.
"""
pytest_runtest_makereport.firstresult = True
def pytest_runtest_logreport(report):
""" process a test setup/call/teardown report relating to
the respective phase of executing a test. """
# -------------------------------------------------------------------------
# Fixture related hooks
# -------------------------------------------------------------------------
@hookspec(firstresult=True)
def pytest_fixture_setup(fixturedef, request):
""" performs fixture setup execution. """
def pytest_fixture_post_finalizer(fixturedef):
""" called after fixture teardown, but before the cache is cleared so
the fixture result cache ``fixturedef.cached_result`` can
still be accessed."""
# -------------------------------------------------------------------------
# test session related hooks
# -------------------------------------------------------------------------
@@ -199,6 +241,9 @@ def pytest_sessionstart(session):
def pytest_sessionfinish(session, exitstatus):
""" whole test run finishes. """
def pytest_unconfigure(config):
""" called before test process is exited. """
# -------------------------------------------------------------------------
# hooks for customising the assert methods
@@ -220,13 +265,15 @@ def pytest_assertrepr_compare(config, op, left, right):
def pytest_report_header(config, startdir):
""" return a string to be displayed as header info for terminal reporting."""
@hookspec(firstresult=True)
def pytest_report_teststatus(report):
""" return result-category, shortletter and verbose word for reporting."""
pytest_report_teststatus.firstresult = True
def pytest_terminal_summary(terminalreporter):
def pytest_terminal_summary(terminalreporter, exitstatus):
""" add additional section in terminal summary reporting. """
@hookspec(historic=True)
def pytest_logwarning(message, code, nodeid, fslocation):
""" process a warning specified by a message, a code string,
a nodeid and fslocation (both of which may be None
@@ -236,17 +283,14 @@ def pytest_logwarning(message, code, nodeid, fslocation):
# doctest hooks
# -------------------------------------------------------------------------
@hookspec(firstresult=True)
def pytest_doctest_prepare_content(content):
""" return processed content for a given doctest"""
pytest_doctest_prepare_content.firstresult = True
# -------------------------------------------------------------------------
# error handling and internal debugging hooks
# -------------------------------------------------------------------------
def pytest_plugin_registered(plugin, manager):
""" a new pytest plugin got registered. """
def pytest_internalerror(excrepr, excinfo):
""" called for internal errors. """
@@ -254,13 +298,17 @@ def pytest_keyboard_interrupt(excinfo):
""" called for keyboard interrupt. """
def pytest_exception_interact(node, call, report):
""" (experimental, new in 2.4) called when
an exception was raised which can potentially be
"""called when an exception was raised which can potentially be
interactively handled.
This hook is only called if an exception was raised
that is not an internal exception like "skip.Exception".
that is not an internal exception like ``skip.Exception``.
"""
def pytest_enter_pdb():
""" called upon pdb.set_trace()"""
def pytest_enter_pdb(config):
""" called upon pdb.set_trace(), can be used by plugins to take special
action just before the python debugger enters in interactive mode.
:arg config: pytest config object
:type config: _pytest.config.Config
"""

View File

@@ -1,12 +1,19 @@
""" report test results in JUnit-XML format, for use with Hudson and build integration servers.
"""
report test results in JUnit-XML format,
for use with Jenkins and build integration servers.
Based on initial code from Ross Lawley.
"""
# Output conforms to https://github.com/jenkinsci/xunit-plugin/blob/master/
# src/main/resources/org/jenkinsci/plugins/xunit/types/model/xsd/junit-10.xsd
import py
import os
import re
import sys
import time
import pytest
# Python 2.X and 3.X compatibility
if sys.version_info[0] < 3:
@@ -16,10 +23,10 @@ else:
unicode = str
long = int
class Junit(py.xml.Namespace):
pass
# We need to get the subset of the invalid unicode ranges according to
# XML 1.0 which are valid in this python build. Hence we calculate
# this dynamically instead of hardcoding it. The spec range of valid
@@ -27,21 +34,21 @@ class Junit(py.xml.Namespace):
# | [#x10000-#x10FFFF]
_legal_chars = (0x09, 0x0A, 0x0d)
_legal_ranges = (
(0x20, 0x7E),
(0x80, 0xD7FF),
(0xE000, 0xFFFD),
(0x10000, 0x10FFFF),
(0x20, 0x7E), (0x80, 0xD7FF), (0xE000, 0xFFFD), (0x10000, 0x10FFFF),
)
_legal_xml_re = [unicode("%s-%s") % (unichr(low), unichr(high))
for (low, high) in _legal_ranges
if low < sys.maxunicode]
_legal_xml_re = [
unicode("%s-%s") % (unichr(low), unichr(high))
for (low, high) in _legal_ranges if low < sys.maxunicode
]
_legal_xml_re = [unichr(x) for x in _legal_chars] + _legal_xml_re
illegal_xml_re = re.compile(unicode('[^%s]') %
unicode('').join(_legal_xml_re))
illegal_xml_re = re.compile(unicode('[^%s]') % unicode('').join(_legal_xml_re))
del _legal_chars
del _legal_ranges
del _legal_xml_re
_py_ext_re = re.compile(r"\.py$")
def bin_xml_escape(arg):
def repl(matchobj):
i = ord(matchobj.group())
@@ -49,79 +56,83 @@ def bin_xml_escape(arg):
return unicode('#x%02X') % i
else:
return unicode('#x%04X') % i
return py.xml.raw(illegal_xml_re.sub(repl, py.xml.escape(arg)))
def pytest_addoption(parser):
group = parser.getgroup("terminal reporting")
group.addoption('--junitxml', '--junit-xml', action="store",
dest="xmlpath", metavar="path", default=None,
help="create junit-xml style report file at given path.")
group.addoption('--junitprefix', '--junit-prefix', action="store",
metavar="str", default=None,
help="prepend prefix to classnames in junit-xml output")
def pytest_configure(config):
xmlpath = config.option.xmlpath
# prevent opening xmllog on slave nodes (xdist)
if xmlpath and not hasattr(config, 'slaveinput'):
config._xml = LogXML(xmlpath, config.option.junitprefix)
config.pluginmanager.register(config._xml)
class _NodeReporter(object):
def __init__(self, nodeid, xml):
def pytest_unconfigure(config):
xml = getattr(config, '_xml', None)
if xml:
del config._xml
config.pluginmanager.unregister(xml)
self.id = nodeid
self.xml = xml
self.add_stats = self.xml.add_stats
self.duration = 0
self.properties = []
self.nodes = []
self.testcase = None
self.attrs = {}
def append(self, node):
self.xml.add_stats(type(node).__name__)
self.nodes.append(node)
def mangle_testnames(names):
names = [x.replace(".py", "") for x in names if x != '()']
names[0] = names[0].replace("/", '.')
return names
def add_property(self, name, value):
self.properties.append((str(name), bin_xml_escape(value)))
class LogXML(object):
def __init__(self, logfile, prefix):
logfile = os.path.expanduser(os.path.expandvars(logfile))
self.logfile = os.path.normpath(os.path.abspath(logfile))
self.prefix = prefix
self.tests = []
self.passed = self.skipped = 0
self.failed = self.errors = 0
def make_properties_node(self):
"""Return a Junit node containing custom properties, if any.
"""
if self.properties:
return Junit.properties([
Junit.property(name=name, value=value)
for name, value in self.properties
])
return ''
def _opentestcase(self, report):
names = mangle_testnames(report.nodeid.split("::"))
def record_testreport(self, testreport):
assert not self.testcase
names = mangle_test_address(testreport.nodeid)
classnames = names[:-1]
if self.prefix:
classnames.insert(0, self.prefix)
self.tests.append(Junit.testcase(
classname=".".join(classnames),
name=bin_xml_escape(names[-1]),
time=getattr(report, 'duration', 0)
))
if self.xml.prefix:
classnames.insert(0, self.xml.prefix)
attrs = {
"classname": ".".join(classnames),
"name": bin_xml_escape(names[-1]),
"file": testreport.location[0],
}
if testreport.location[1] is not None:
attrs["line"] = testreport.location[1]
self.attrs = attrs
def to_xml(self):
testcase = Junit.testcase(time=self.duration, **self.attrs)
testcase.append(self.make_properties_node())
for node in self.nodes:
testcase.append(node)
return testcase
def _add_simple(self, kind, message, data=None):
data = bin_xml_escape(data)
node = kind(data, message=message)
self.append(node)
def _write_captured_output(self, report):
for capname in ('out', 'err'):
allcontent = ""
for name, content in report.get_sections("Captured std%s" %
capname):
allcontent += content
if allcontent:
tag = getattr(Junit, 'system-'+capname)
self.append(tag(bin_xml_escape(allcontent)))
def append(self, obj):
self.tests[-1].append(obj)
content = getattr(report, 'capstd' + capname)
if content:
tag = getattr(Junit, 'system-' + capname)
self.append(tag(bin_xml_escape(content)))
def append_pass(self, report):
self.passed += 1
self.add_stats('passed')
self._write_captured_output(report)
def append_failure(self, report):
#msg = str(report.longrepr.reprtraceback.extraline)
# msg = str(report.longrepr.reprtraceback.extraline)
if hasattr(report, "wasxfail"):
self.append(
Junit.skipped(message="xfail-marked test passes unexpectedly"))
self.skipped += 1
self._add_simple(
Junit.skipped,
"xfail-marked test passes unexpectedly")
else:
if hasattr(report.longrepr, "reprcrash"):
message = report.longrepr.reprcrash.message
@@ -133,30 +144,27 @@ class LogXML(object):
fail = Junit.failure(message=message)
fail.append(bin_xml_escape(report.longrepr))
self.append(fail)
self.failed += 1
self._write_captured_output(report)
def append_collect_error(self, report):
#msg = str(report.longrepr.reprtraceback.extraline)
# msg = str(report.longrepr.reprtraceback.extraline)
self.append(Junit.error(bin_xml_escape(report.longrepr),
message="collection failure"))
self.errors += 1
def append_collect_skipped(self, report):
#msg = str(report.longrepr.reprtraceback.extraline)
self.append(Junit.skipped(bin_xml_escape(report.longrepr),
message="collection skipped"))
self.skipped += 1
self._add_simple(
Junit.skipped, "collection skipped", report.longrepr)
def append_error(self, report):
self.append(Junit.error(bin_xml_escape(report.longrepr),
message="test setup failure"))
self.errors += 1
self._add_simple(
Junit.error, "test setup failure", report.longrepr)
self._write_captured_output(report)
def append_skipped(self, report):
if hasattr(report, "wasxfail"):
self.append(Junit.skipped(bin_xml_escape(report.wasxfail),
message="expected test failure"))
self._add_simple(
Junit.skipped, "expected test failure", report.wasxfail
)
else:
filename, lineno, skipreason = report.longrepr
if skipreason.startswith("Skipped: "):
@@ -164,42 +172,192 @@ class LogXML(object):
self.append(
Junit.skipped("%s:%s: %s" % (filename, lineno, skipreason),
type="pytest.skip",
message=skipreason
))
self.skipped += 1
message=skipreason))
self._write_captured_output(report)
def finalize(self):
data = self.to_xml().unicode(indent=0)
self.__dict__.clear()
self.to_xml = lambda: py.xml.raw(data)
@pytest.fixture
def record_xml_property(request):
"""Add extra xml properties to the tag for the calling test.
The fixture is callable with ``(name, value)``, with value being automatically
xml-encoded.
"""
request.node.warn(
code='C3',
message='record_xml_property is an experimental feature',
)
xml = getattr(request.config, "_xml", None)
if xml is not None:
node_reporter = xml.node_reporter(request.node.nodeid)
return node_reporter.add_property
else:
def add_property_noop(name, value):
pass
return add_property_noop
def pytest_addoption(parser):
group = parser.getgroup("terminal reporting")
group.addoption(
'--junitxml', '--junit-xml',
action="store",
dest="xmlpath",
metavar="path",
default=None,
help="create junit-xml style report file at given path.")
group.addoption(
'--junitprefix', '--junit-prefix',
action="store",
metavar="str",
default=None,
help="prepend prefix to classnames in junit-xml output")
def pytest_configure(config):
xmlpath = config.option.xmlpath
# prevent opening xmllog on slave nodes (xdist)
if xmlpath and not hasattr(config, 'slaveinput'):
config._xml = LogXML(xmlpath, config.option.junitprefix)
config.pluginmanager.register(config._xml)
def pytest_unconfigure(config):
xml = getattr(config, '_xml', None)
if xml:
del config._xml
config.pluginmanager.unregister(xml)
def mangle_test_address(address):
path, possible_open_bracket, params = address.partition('[')
names = path.split("::")
try:
names.remove('()')
except ValueError:
pass
# convert file path to dotted path
names[0] = names[0].replace("/", '.')
names[0] = _py_ext_re.sub("", names[0])
# put any params back
names[-1] += possible_open_bracket + params
return names
class LogXML(object):
def __init__(self, logfile, prefix):
logfile = os.path.expanduser(os.path.expandvars(logfile))
self.logfile = os.path.normpath(os.path.abspath(logfile))
self.prefix = prefix
self.stats = dict.fromkeys([
'error',
'passed',
'failure',
'skipped',
], 0)
self.node_reporters = {} # nodeid -> _NodeReporter
self.node_reporters_ordered = []
self.global_properties = []
def finalize(self, report):
nodeid = getattr(report, 'nodeid', report)
# local hack to handle xdist report order
slavenode = getattr(report, 'node', None)
reporter = self.node_reporters.pop((nodeid, slavenode))
if reporter is not None:
reporter.finalize()
def node_reporter(self, report):
nodeid = getattr(report, 'nodeid', report)
# local hack to handle xdist report order
slavenode = getattr(report, 'node', None)
key = nodeid, slavenode
if key in self.node_reporters:
# TODO: breasks for --dist=each
return self.node_reporters[key]
reporter = _NodeReporter(nodeid, self)
self.node_reporters[key] = reporter
self.node_reporters_ordered.append(reporter)
return reporter
def add_stats(self, key):
if key in self.stats:
self.stats[key] += 1
def _opentestcase(self, report):
reporter = self.node_reporter(report)
reporter.record_testreport(report)
return reporter
def pytest_runtest_logreport(self, report):
"""handle a setup/call/teardown report, generating the appropriate
xml tags as necessary.
note: due to plugins like xdist, this hook may be called in interlaced
order with reports from other nodes. for example:
usual call order:
-> setup node1
-> call node1
-> teardown node1
-> setup node2
-> call node2
-> teardown node2
possible call order in xdist:
-> setup node1
-> call node1
-> setup node2
-> call node2
-> teardown node2
-> teardown node1
"""
if report.passed:
if report.when == "call": # ignore setup/teardown
self._opentestcase(report)
self.append_pass(report)
if report.when == "call": # ignore setup/teardown
reporter = self._opentestcase(report)
reporter.append_pass(report)
elif report.failed:
self._opentestcase(report)
if report.when != "call":
self.append_error(report)
reporter = self._opentestcase(report)
if report.when == "call":
reporter.append_failure(report)
else:
self.append_failure(report)
reporter.append_error(report)
elif report.skipped:
self._opentestcase(report)
self.append_skipped(report)
reporter = self._opentestcase(report)
reporter.append_skipped(report)
self.update_testcase_duration(report)
if report.when == "teardown":
self.finalize(report)
def update_testcase_duration(self, report):
"""accumulates total duration for nodeid from given report and updates
the Junit.testcase with the new total if already created.
"""
reporter = self.node_reporter(report)
reporter.duration += getattr(report, 'duration', 0.0)
def pytest_collectreport(self, report):
if not report.passed:
self._opentestcase(report)
reporter = self._opentestcase(report)
if report.failed:
self.append_collect_error(report)
reporter.append_collect_error(report)
else:
self.append_collect_skipped(report)
reporter.append_collect_skipped(report)
def pytest_internalerror(self, excrepr):
self.errors += 1
data = bin_xml_escape(excrepr)
self.tests.append(
Junit.testcase(
Junit.error(data, message="internal error"),
classname="pytest",
name="internal"))
reporter = self.node_reporter('internal')
reporter.attrs.update(classname="pytest", name='internal')
reporter._add_simple(Junit.error, 'internal error', excrepr)
def pytest_sessionstart(self):
self.suite_start_time = time.time()
@@ -211,19 +369,37 @@ class LogXML(object):
logfile = open(self.logfile, 'w', encoding='utf-8')
suite_stop_time = time.time()
suite_time_delta = suite_stop_time - self.suite_start_time
numtests = self.passed + self.failed
numtests = self.stats['passed'] + self.stats['failure'] + self.stats['skipped'] + self.stats['error']
logfile.write('<?xml version="1.0" encoding="utf-8"?>')
logfile.write(Junit.testsuite(
self.tests,
self._get_global_properties_node(),
[x.to_xml() for x in self.node_reporters_ordered],
name="pytest",
errors=self.errors,
failures=self.failed,
skips=self.skipped,
errors=self.stats['error'],
failures=self.stats['failure'],
skips=self.stats['skipped'],
tests=numtests,
time="%.3f" % suite_time_delta,
).unicode(indent=0))
time="%.3f" % suite_time_delta, ).unicode(indent=0))
logfile.close()
def pytest_terminal_summary(self, terminalreporter):
terminalreporter.write_sep("-", "generated xml file: %s" % (self.logfile))
terminalreporter.write_sep("-",
"generated xml file: %s" % (self.logfile))
def add_global_property(self, name, value):
self.global_properties.append((str(name), bin_xml_escape(value)))
def _get_global_properties_node(self):
"""Return a Junit node containing custom properties, if any.
"""
if self.global_properties:
return Junit.properties(
[
Junit.property(name=name, value=value)
for name, value in self.global_properties
]
)
return ''

View File

@@ -1,9 +1,11 @@
""" core implementation of testing process: init, session, runtest loop. """
import re
import os
import sys
import _pytest
import _pytest._code
import py
import pytest, _pytest
import os, sys, imp
import pytest
try:
from collections import MutableMapping as MappingMixin
except ImportError:
@@ -19,20 +21,21 @@ EXIT_TESTSFAILED = 1
EXIT_INTERRUPTED = 2
EXIT_INTERNALERROR = 3
EXIT_USAGEERROR = 4
name_re = re.compile("^[a-zA-Z_]\w*$")
EXIT_NOTESTSCOLLECTED = 5
def pytest_addoption(parser):
parser.addini("norecursedirs", "directory patterns to avoid for recursion",
type="args", default=['.*', 'CVS', '_darcs', '{arch}', '*.egg'])
type="args", default=['.*', 'build', 'dist', 'CVS', '_darcs', '{arch}', '*.egg'])
parser.addini("testpaths", "directories to search for tests when no files or directories are given in the command line.",
type="args", default=[])
#parser.addini("dirpatterns",
# "patterns specifying possible locations of test files",
# type="linelist", default=["**/test_*.txt",
# "**/test_*.py", "**/*_test.py"]
#)
group = parser.getgroup("general", "running and selection options")
group._addoption('-x', '--exitfirst', action="store_true", default=False,
dest="exitfirst",
group._addoption('-x', '--exitfirst', action="store_const",
dest="maxfail", const=1,
help="exit instantly on first error or failed test."),
group._addoption('--maxfail', metavar="num",
action="store", type=int, dest="maxfail", default=0,
@@ -41,6 +44,9 @@ def pytest_addoption(parser):
help="run pytest in strict mode, warnings become errors.")
group._addoption("-c", metavar="file", type=str, dest="inifilename",
help="load configuration from `file` instead of trying to locate one of the implicit configuration files.")
group._addoption("--continue-on-collection-errors", action="store_true",
default=False, dest="continue_on_collection_errors",
help="Force test execution even if collection errors occur.")
group = parser.getgroup("collect", "collection")
group.addoption('--collectonly', '--collect-only', action="store_true",
@@ -54,6 +60,12 @@ def pytest_addoption(parser):
group.addoption('--confcutdir', dest="confcutdir", default=None,
metavar="dir",
help="only load conftest.py's relative to specified dir.")
group.addoption('--noconftest', action="store_true",
dest="noconftest", default=False,
help="Don't load any conftest.py files.")
group.addoption('--keepduplicates', '--keep-duplicates', action="store_true",
dest="keepduplicates", default=False,
help="Keep duplicate tests.")
group = parser.getgroup("debugconfig",
"test session debugging and configuration")
@@ -65,10 +77,10 @@ def pytest_namespace():
collect = dict(Item=Item, Collector=Collector, File=File, Session=Session)
return dict(collect=collect)
def pytest_configure(config):
pytest.config = config # compatibiltiy
if config.option.exitfirst:
config.option.maxfail = 1
def wrap_session(config, doit):
"""Skeleton command line program"""
@@ -77,29 +89,28 @@ def wrap_session(config, doit):
initstate = 0
try:
try:
config.do_configure()
config._do_configure()
initstate = 1
config.hook.pytest_sessionstart(session=session)
initstate = 2
doit(config, session)
session.exitstatus = doit(config, session) or 0
except pytest.UsageError:
args = sys.exc_info()[1].args
for msg in args:
sys.stderr.write("ERROR: %s\n" %(msg,))
session.exitstatus = EXIT_USAGEERROR
raise
except KeyboardInterrupt:
excinfo = py.code.ExceptionInfo()
excinfo = _pytest._code.ExceptionInfo()
if initstate < 2 and isinstance(
excinfo.value, pytest.exit.Exception):
sys.stderr.write('{0}: {1}\n'.format(
excinfo.typename, excinfo.value.msg))
config.hook.pytest_keyboard_interrupt(excinfo=excinfo)
session.exitstatus = EXIT_INTERRUPTED
except:
excinfo = py.code.ExceptionInfo()
excinfo = _pytest._code.ExceptionInfo()
config.notify_exception(excinfo, config.option)
session.exitstatus = EXIT_INTERNALERROR
if excinfo.errisinstance(SystemExit):
sys.stderr.write("mainloop: caught Spurious SystemExit!\n")
else:
if session._testsfailed:
session.exitstatus = EXIT_TESTSFAILED
finally:
excinfo = None # Explicitly break reference cycle.
session.startdir.chdir()
@@ -107,9 +118,7 @@ def wrap_session(config, doit):
config.hook.pytest_sessionfinish(
session=session,
exitstatus=session.exitstatus)
if initstate >= 1:
config.do_unconfigure()
config.pluginmanager.ensure_shutdown()
config._ensure_unconfigure()
return session.exitstatus
def pytest_cmdline_main(config):
@@ -121,24 +130,25 @@ def _main(config, session):
config.hook.pytest_collection(session=session)
config.hook.pytest_runtestloop(session=session)
if session.testsfailed:
return EXIT_TESTSFAILED
elif session.testscollected == 0:
return EXIT_NOTESTSCOLLECTED
def pytest_collection(session):
return session.perform_collect()
def pytest_runtestloop(session):
if (session.testsfailed and
not session.config.option.continue_on_collection_errors):
raise session.Interrupted(
"%d errors during collection" % session.testsfailed)
if session.config.option.collectonly:
return True
def getnextitem(i):
# this is a function to avoid python2
# keeping sys.exc_info set when calling into a test
# python2 keeps sys.exc_info till the frame is left
try:
return session.items[i+1]
except IndexError:
return None
for i, item in enumerate(session.items):
nextitem = getnextitem(i)
nextitem = session.items[i+1] if i+1 < len(session.items) else None
item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
if session.shouldstop:
raise session.Interrupted(session.shouldstop)
@@ -151,20 +161,33 @@ def pytest_ignore_collect(path, config):
excludeopt = config.getoption("ignore")
if excludeopt:
ignore_paths.extend([py.path.local(x) for x in excludeopt])
return path in ignore_paths
class FSHookProxy(object):
def __init__(self, fspath, config):
if path in ignore_paths:
return True
# Skip duplicate paths.
keepduplicates = config.getoption("keepduplicates")
duplicate_paths = config.pluginmanager._duplicatepaths
if not keepduplicates:
if path in duplicate_paths:
return True
else:
duplicate_paths.add(path)
return False
class FSHookProxy:
def __init__(self, fspath, pm, remove_mods):
self.fspath = fspath
self.config = config
self.pm = pm
self.remove_mods = remove_mods
def __getattr__(self, name):
plugins = self.config._getmatchingplugins(self.fspath)
x = self.config.hook._getcaller(name, plugins)
x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods)
self.__dict__[name] = x
return x
def compatproperty(name):
def fget(self):
# deprecated - use pytest.name
@@ -237,17 +260,11 @@ class Node(object):
# used for storing artificial fixturedefs for direct parametrization
self._name2pseudofixturedef = {}
#self.extrainit()
@property
def ihook(self):
""" fspath sensitive hook proxy used to call pytest hooks"""
return self.session.gethookproxy(self.fspath)
#def extrainit(self):
# """"extra initialization after Node is initialized. Implemented
# by some subclasses. """
Module = compatproperty("Module")
Class = compatproperty("Class")
Instance = compatproperty("Instance")
@@ -275,11 +292,11 @@ class Node(object):
if fslocation is None:
fslocation = getattr(self, "fspath", None)
else:
fslocation = "%s:%s" % fslocation[:2]
fslocation = "%s:%s" % (fslocation[0], fslocation[1] + 1)
self.ihook.pytest_logwarning(code=code, message=message,
nodeid=self.nodeid,
fslocation=fslocation)
self.ihook.pytest_logwarning.call_historic(kwargs=dict(
code=code, message=message,
nodeid=self.nodeid, fslocation=fslocation))
# methods for ordering nodes
@property
@@ -364,9 +381,6 @@ class Node(object):
def listnames(self):
return [x.name for x in self.listchain()]
def getplugins(self):
return self.config._getmatchingplugins(self.fspath)
def addfinalizer(self, fin):
""" register a function to be called when this node is finalized.
@@ -394,7 +408,10 @@ class Node(object):
if self.config.option.fulltrace:
style="long"
else:
tb = _pytest._code.Traceback([excinfo.traceback[-1]])
self._prunetraceback(excinfo)
if len(excinfo.traceback) == 0:
excinfo.traceback = tb
tbfilter = False # prunetraceback already does it
if style == "auto":
style = "long"
@@ -405,7 +422,13 @@ class Node(object):
else:
style = "long"
return excinfo.getrepr(funcargs=True,
try:
os.getcwd()
abspath = False
except OSError:
abspath = True
return excinfo.getrepr(funcargs=True, abspath=abspath,
showlocals=self.config.option.showlocals,
style=style, tbfilter=tbfilter)
@@ -512,28 +535,31 @@ class Session(FSCollector):
def __init__(self, config):
FSCollector.__init__(self, config.rootdir, parent=None,
config=config, session=self)
self.config.pluginmanager.register(self, name="session", prepend=True)
self._testsfailed = 0
self._fs2hookproxy = {}
self.testsfailed = 0
self.testscollected = 0
self.shouldstop = False
self.trace = config.trace.root.get("collection")
self._norecursepatterns = config.getini("norecursedirs")
self.startdir = py.path.local()
self._fs2hookproxy = {}
self.config.pluginmanager.register(self, name="session")
def _makeid(self):
return ""
@pytest.hookimpl(tryfirst=True)
def pytest_collectstart(self):
if self.shouldstop:
raise self.Interrupted(self.shouldstop)
@pytest.hookimpl(tryfirst=True)
def pytest_runtest_logreport(self, report):
if report.failed and not hasattr(report, 'wasxfail'):
self._testsfailed += 1
self.testsfailed += 1
maxfail = self.config.getvalue("maxfail")
if maxfail and self._testsfailed >= maxfail:
if maxfail and self.testsfailed >= maxfail:
self.shouldstop = "stopping after %d failures" % (
self._testsfailed)
self.testsfailed)
pytest_collectreport = pytest_runtest_logreport
def isinitpath(self, path):
@@ -543,8 +569,20 @@ class Session(FSCollector):
try:
return self._fs2hookproxy[fspath]
except KeyError:
self._fs2hookproxy[fspath] = x = FSHookProxy(fspath, self.config)
return x
# check if we have the common case of running
# hooks with all conftest.py filesall conftest.py
pm = self.config.pluginmanager
my_conftestmodules = pm._getconftestmodules(fspath)
remove_mods = pm._conftest_plugins.difference(my_conftestmodules)
if remove_mods:
# one or more conftests are not in use at this fspath
proxy = FSHookProxy(fspath, pm, remove_mods)
else:
# all plugis are active for this fspath
proxy = self.config.hook
self._fs2hookproxy[fspath] = proxy
return proxy
def perform_collect(self, args=None, genitems=True):
hook = self.config.hook
@@ -554,6 +592,7 @@ class Session(FSCollector):
config=self.config, items=items)
finally:
hook.pytest_collection_finish(session=self)
self.testscollected = len(items)
return items
def _perform_collect(self, args, genitems):
@@ -635,36 +674,32 @@ class Session(FSCollector):
return True
def _tryconvertpyarg(self, x):
mod = None
path = [os.path.abspath('.')] + sys.path
for name in x.split('.'):
# ignore anything that's not a proper name here
# else something like --pyargs will mess up '.'
# since imp.find_module will actually sometimes work for it
# but it's supposed to be considered a filesystem path
# not a package
if name_re.match(name) is None:
return x
try:
fd, mod, type_ = imp.find_module(name, path)
except ImportError:
return x
else:
if fd is not None:
fd.close()
"""Convert a dotted module name to path.
if type_[2] != imp.PKG_DIRECTORY:
path = [os.path.dirname(mod)]
else:
path = [mod]
return mod
"""
import pkgutil
try:
loader = pkgutil.find_loader(x)
except ImportError:
return x
if loader is None:
return x
# This method is sometimes invoked when AssertionRewritingHook, which
# does not define a get_filename method, is already in place:
try:
path = loader.get_filename(x)
except AttributeError:
# Retrieve path from AssertionRewritingHook:
path = loader.modules[x][0].co_filename
if loader.is_package(x):
path = os.path.dirname(path)
return path
def _parsearg(self, arg):
""" return (fspath, names) tuple after checking the file exists. """
arg = str(arg)
if self.config.option.pyargs:
arg = self._tryconvertpyarg(arg)
parts = str(arg).split("::")
if self.config.option.pyargs:
parts[0] = self._tryconvertpyarg(parts[0])
relpath = parts[0].replace("/", os.sep)
path = self.config.invocation_dir.join(relpath, abs=True)
if not path.check():
@@ -704,7 +739,8 @@ class Session(FSCollector):
if rep.passed:
has_matched = False
for x in rep.result:
if x.name == name:
# TODO: remove parametrized workaround once collection structure contains parametrization
if x.name == name or x.name.split("[")[0] == name:
resultnodes.extend(self.matchnodes([x], nextnames))
has_matched = True
# XXX accept IDs that don't have "()" for class instances
@@ -727,5 +763,3 @@ class Session(FSCollector):
for x in self.genitems(subnode):
yield x
node.ihook.pytest_collectreport(report=rep)

View File

@@ -45,20 +45,20 @@ def pytest_addoption(parser):
def pytest_cmdline_main(config):
import _pytest.config
if config.option.markers:
config.do_configure()
config._do_configure()
tw = _pytest.config.create_terminal_writer(config)
for line in config.getini("markers"):
name, rest = line.split(":", 1)
tw.write("@pytest.mark.%s:" % name, bold=True)
tw.line(rest)
tw.line()
config.do_unconfigure()
config._ensure_unconfigure()
return 0
pytest_cmdline_main.tryfirst = True
def pytest_collection_modifyitems(items, config):
keywordexpr = config.option.keyword
keywordexpr = config.option.keyword.lstrip()
matchexpr = config.option.markexpr
if not keywordexpr and not matchexpr:
return
@@ -169,7 +169,7 @@ class MarkGenerator:
""" Factory for :class:`MarkDecorator` objects - exposed as
a ``pytest.mark`` singleton instance. Example::
import py
import pytest
@pytest.mark.slowtest
def test_function():
pass
@@ -283,6 +283,21 @@ class MarkDecorator:
return self.__class__(self.name, args=args, kwargs=kw)
def extract_argvalue(maybe_marked_args):
# TODO: incorrect mark data, the old code wanst able to collect lists
# individual parametrized argument sets can be wrapped in a series
# of markers in which case we unwrap the values and apply the mark
# at Function init
newmarks = {}
argval = maybe_marked_args
while isinstance(argval, MarkDecorator):
newmark = MarkDecorator(argval.markname,
argval.args[:-1], argval.kwargs)
newmarks[newmark.markname] = newmark
argval = argval.args[-1]
return argval, newmarks
class MarkInfo:
""" Marking object created by :class:`MarkDecorator` instances. """
def __init__(self, name, args, kwargs):
@@ -291,7 +306,7 @@ class MarkInfo:
#: positional argument list, empty if none specified
self.args = args
#: keyword argument dictionary, empty if nothing specified
self.kwargs = kwargs
self.kwargs = kwargs.copy()
self._arglist = [(args, kwargs.copy())]
def __repr__(self):

View File

@@ -1,10 +1,18 @@
""" monkeypatching and mocking functionality. """
import os, sys
import re
from py.builtin import _basestring
def pytest_funcarg__monkeypatch(request):
"""The returned ``monkeypatch`` funcarg provides these
import pytest
RE_IMPORT_ERROR_NAME = re.compile("^No module named (.*)$")
@pytest.fixture
def monkeypatch(request):
"""The returned ``monkeypatch`` fixture provides these
helper methods to modify objects, dictionaries or os.environ::
monkeypatch.setattr(obj, name, value, raising=True)
@@ -17,60 +25,86 @@ def pytest_funcarg__monkeypatch(request):
monkeypatch.chdir(path)
All modifications will be undone after the requesting
test function has finished. The ``raising``
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.
"""
mpatch = monkeypatch()
mpatch = MonkeyPatch()
request.addfinalizer(mpatch.undo)
return mpatch
def resolve(name):
# simplified from zope.dottedname
parts = name.split('.')
def derive_importpath(import_path):
import pytest
used = parts.pop(0)
found = __import__(used)
for part in parts:
used += '.' + part
try:
found = getattr(found, part)
except AttributeError:
pass
else:
continue
# we use explicit un-nesting of the handling block in order
# to avoid nested exceptions on python 3
try:
__import__(used)
except ImportError as ex:
# str is used for py2 vs py3
expected = str(ex).split()[-1]
if expected == used:
raise
else:
raise ImportError(
'import error in %s: %s' % (used, ex)
)
found = annotated_getattr(found, part, used)
return found
def annotated_getattr(obj, name, ann):
try:
obj = getattr(obj, name)
except AttributeError:
raise AttributeError(
'%r object at %s has no attribute %r' % (
type(obj).__name__, ann, name
)
)
return obj
def derive_importpath(import_path, raising):
if not isinstance(import_path, _basestring) or "." not in import_path:
raise TypeError("must be absolute import path string, not %r" %
(import_path,))
rest = []
target = import_path
while target:
try:
obj = __import__(target, None, None, "__doc__")
except ImportError:
if "." not in target:
__tracebackhide__ = True
pytest.fail("could not import any sub part: %s" %
import_path)
target, name = target.rsplit(".", 1)
rest.append(name)
else:
assert rest
try:
while len(rest) > 1:
attr = rest.pop()
obj = getattr(obj, attr)
attr = rest[0]
getattr(obj, attr)
except AttributeError:
__tracebackhide__ = True
pytest.fail("object %r has no attribute %r" % (obj, attr))
return attr, obj
module, attr = import_path.rsplit('.', 1)
target = resolve(module)
if raising:
annotated_getattr(target, attr, ann=module)
return attr, target
class Notset:
def __repr__(self):
return "<notset>"
notset = Notset()
class monkeypatch:
""" Object keeping a record of setattr/item/env/syspath changes. """
class MonkeyPatch:
""" Object returned by the ``monkeypatch`` fixture keeping a record of setattr/item/env/syspath changes.
"""
def __init__(self):
self._setattr = []
self._setitem = []
self._cwd = None
self._savesyspath = None
def setattr(self, target, name, value=notset, raising=True):
""" Set attribute value on target, memorizing the old value.
@@ -92,19 +126,19 @@ class monkeypatch:
if value is notset:
if not isinstance(target, _basestring):
raise TypeError("use setattr(target, name, value) or "
"setattr(target, value) with target being a dotted "
"import string")
"setattr(target, value) with target being a dotted "
"import string")
value = name
name, target = derive_importpath(target)
name, target = derive_importpath(target, raising)
oldval = getattr(target, name, notset)
if raising and oldval is notset:
raise AttributeError("%r has no attribute %r" %(target, name))
raise AttributeError("%r has no attribute %r" % (target, name))
# avoid class descriptors like staticmethod/classmethod
if inspect.isclass(target):
oldval = target.__dict__.get(name, notset)
self._setattr.insert(0, (target, name, oldval))
self._setattr.append((target, name, oldval))
setattr(target, name, value)
def delattr(self, target, name=notset, raising=True):
@@ -124,19 +158,18 @@ class monkeypatch:
raise TypeError("use delattr(target, name) or "
"delattr(target) with target being a dotted "
"import string")
name, target = derive_importpath(target)
name, target = derive_importpath(target, raising)
if not hasattr(target, name):
if raising:
raise AttributeError(name)
else:
self._setattr.insert(0, (target, name,
getattr(target, name, notset)))
self._setattr.append((target, name, getattr(target, name, notset)))
delattr(target, name)
def setitem(self, dic, name, value):
""" Set dictionary entry ``name`` to value. """
self._setitem.insert(0, (dic, name, dic.get(name, notset)))
self._setitem.append((dic, name, dic.get(name, notset)))
dic[name] = value
def delitem(self, dic, name, raising=True):
@@ -149,7 +182,7 @@ class monkeypatch:
if raising:
raise KeyError(name)
else:
self._setitem.insert(0, (dic, name, dic.get(name, notset)))
self._setitem.append((dic, name, dic.get(name, notset)))
del dic[name]
def setenv(self, name, value, prepend=None):
@@ -172,13 +205,13 @@ class monkeypatch:
def syspath_prepend(self, path):
""" Prepend ``path`` to ``sys.path`` list of import locations. """
if not hasattr(self, '_savesyspath'):
if self._savesyspath is None:
self._savesyspath = sys.path[:]
sys.path.insert(0, str(path))
def chdir(self, path):
""" Change the current working directory to the specified path
path can be a string or a py.path.local object
""" Change the current working directory to the specified path.
Path can be a string or a py.path.local object.
"""
if self._cwd is None:
self._cwd = os.getcwd()
@@ -190,25 +223,35 @@ class monkeypatch:
def undo(self):
""" Undo previous changes. This call consumes the
undo stack. Calling it a second time has no effect unless
you do more monkeypatching after the undo call."""
for obj, name, value in self._setattr:
you do more monkeypatching after the undo call.
There is generally no need to call `undo()`, since it is
called automatically during tear-down.
Note that the same `monkeypatch` fixture is used across a
single test function invocation. If `monkeypatch` is used both by
the test function itself and one of the test fixtures,
calling `undo()` will undo all of the changes made in
both functions.
"""
for obj, name, value in reversed(self._setattr):
if value is not notset:
setattr(obj, name, value)
else:
delattr(obj, name)
self._setattr[:] = []
for dictionary, name, value in self._setitem:
for dictionary, name, value in reversed(self._setitem):
if value is notset:
try:
del dictionary[name]
except KeyError:
pass # was already deleted, so we have the desired state
pass # was already deleted, so we have the desired state
else:
dictionary[name] = value
self._setitem[:] = []
if hasattr(self, '_savesyspath'):
if self._savesyspath is not None:
sys.path[:] = self._savesyspath
del self._savesyspath
self._savesyspath = None
if self._cwd is not None:
os.chdir(self._cwd)

View File

@@ -24,7 +24,7 @@ def pytest_runtest_makereport(item, call):
call.excinfo = call2.excinfo
@pytest.mark.trylast
@pytest.hookimpl(trylast=True)
def pytest_runtest_setup(item):
if is_potential_nosetest(item):
if isinstance(item.parent, pytest.Generator):

View File

@@ -11,19 +11,23 @@ def pytest_addoption(parser):
choices=['failed', 'all'],
help="send failed|all info to bpaste.net pastebin service.")
@pytest.mark.trylast
@pytest.hookimpl(trylast=True)
def pytest_configure(config):
import py
if config.option.pastebin == "all":
tr = config.pluginmanager.getplugin('terminalreporter')
# if no terminal reporter plugin is present, nothing we can do here;
# this can happen when this function executes in a slave node
# when using pytest-xdist, for example
if tr is not None:
config._pastebinfile = tempfile.TemporaryFile('w+')
# pastebin file will be utf-8 encoded binary file
config._pastebinfile = tempfile.TemporaryFile('w+b')
oldwrite = tr._tw.write
def tee_write(s, **kwargs):
oldwrite(s, **kwargs)
config._pastebinfile.write(str(s))
if py.builtin._istext(s):
s = s.encode('utf-8')
config._pastebinfile.write(s)
tr._tw.write = tee_write
def pytest_unconfigure(config):
@@ -45,7 +49,7 @@ def create_new_paste(contents):
"""
Creates a new paste using bpaste.net service.
:contents: paste contents
:contents: paste contents as utf-8 encoded bytes
:returns: url to the pasted contents
"""
import re
@@ -61,8 +65,8 @@ def create_new_paste(contents):
'expiry': '1week',
}
url = 'https://bpaste.net'
response = urlopen(url, data=urlencode(params)).read()
m = re.search(r'href="/raw/(\w+)"', response)
response = urlopen(url, data=urlencode(params).encode('ascii')).read()
m = re.search(r'href="/raw/(\w+)"', response.decode('utf-8'))
if m:
return '%s/show/%s' % (url, m.group(1))
else:

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,16 @@
""" recording warnings during test function execution. """
import inspect
import _pytest._code
import py
import sys
import warnings
import pytest
def pytest_funcarg__recwarn(request):
@pytest.yield_fixture
def recwarn(request):
"""Return a WarningsRecorder instance that provides these methods:
* ``pop(category=None)``: return last warning matching the category.
@@ -13,83 +19,203 @@ def pytest_funcarg__recwarn(request):
See http://docs.python.org/library/warnings.html for information
on warning categories.
"""
if sys.version_info >= (2,7):
oldfilters = warnings.filters[:]
warnings.simplefilter('default')
def reset_filters():
warnings.filters[:] = oldfilters
request.addfinalizer(reset_filters)
wrec = WarningsRecorder()
request.addfinalizer(wrec.finalize)
return wrec
with wrec:
warnings.simplefilter('default')
yield wrec
def pytest_namespace():
return {'deprecated_call': deprecated_call}
return {'deprecated_call': deprecated_call,
'warns': warns}
def deprecated_call(func, *args, **kwargs):
""" assert that calling ``func(*args, **kwargs)``
triggers a DeprecationWarning.
def deprecated_call(func=None, *args, **kwargs):
""" assert that calling ``func(*args, **kwargs)`` triggers a
``DeprecationWarning`` or ``PendingDeprecationWarning``.
This function can be used as a context manager::
>>> with deprecated_call():
... myobject.deprecated_method()
Note: we cannot use WarningsRecorder here because it is still subject
to the mechanism that prevents warnings of the same type from being
triggered twice for the same module. See #1190.
"""
l = []
oldwarn_explicit = getattr(warnings, 'warn_explicit')
def warn_explicit(*args, **kwargs):
l.append(args)
oldwarn_explicit(*args, **kwargs)
oldwarn = getattr(warnings, 'warn')
def warn(*args, **kwargs):
l.append(args)
oldwarn(*args, **kwargs)
if not func:
return WarningsChecker(expected_warning=DeprecationWarning)
categories = []
def warn_explicit(message, category, *args, **kwargs):
categories.append(category)
old_warn_explicit(message, category, *args, **kwargs)
def warn(message, category=None, *args, **kwargs):
if isinstance(message, Warning):
categories.append(message.__class__)
else:
categories.append(category)
old_warn(message, category, *args, **kwargs)
old_warn = warnings.warn
old_warn_explicit = warnings.warn_explicit
warnings.warn_explicit = warn_explicit
warnings.warn = warn
try:
ret = func(*args, **kwargs)
finally:
warnings.warn_explicit = oldwarn_explicit
warnings.warn = oldwarn
if not l:
warnings.warn_explicit = old_warn_explicit
warnings.warn = old_warn
deprecation_categories = (DeprecationWarning, PendingDeprecationWarning)
if not any(issubclass(c, deprecation_categories) for c in categories):
__tracebackhide__ = True
raise AssertionError("%r did not produce DeprecationWarning" %(func,))
raise AssertionError("%r did not produce DeprecationWarning" % (func,))
return ret
class RecordedWarning:
def __init__(self, message, category, filename, lineno, line):
def warns(expected_warning, *args, **kwargs):
"""Assert that code raises a particular class of warning.
Specifically, the input @expected_warning can be a warning class or
tuple of warning classes, and the code must return that warning
(if a single class) or one of those warnings (if a tuple).
This helper produces a list of ``warnings.WarningMessage`` objects,
one for each warning raised.
This function can be used as a context manager, or any of the other ways
``pytest.raises`` can be used::
>>> with warns(RuntimeWarning):
... warnings.warn("my warning", RuntimeWarning)
"""
wcheck = WarningsChecker(expected_warning)
if not args:
return wcheck
elif isinstance(args[0], str):
code, = args
assert isinstance(code, str)
frame = sys._getframe(1)
loc = frame.f_locals.copy()
loc.update(kwargs)
with wcheck:
code = _pytest._code.Source(code).compile()
py.builtin.exec_(code, frame.f_globals, loc)
else:
func = args[0]
with wcheck:
return func(*args[1:], **kwargs)
class RecordedWarning(object):
def __init__(self, message, category, filename, lineno, file, line):
self.message = message
self.category = category
self.filename = filename
self.lineno = lineno
self.file = file
self.line = line
class WarningsRecorder:
def __init__(self):
self.list = []
def showwarning(message, category, filename, lineno, line=0):
self.list.append(RecordedWarning(
message, category, filename, lineno, line))
try:
self.old_showwarning(message, category,
filename, lineno, line=line)
except TypeError:
# < python2.6
self.old_showwarning(message, category, filename, lineno)
self.old_showwarning = warnings.showwarning
warnings.showwarning = showwarning
class WarningsRecorder(object):
"""A context manager to record raised warnings.
Adapted from `warnings.catch_warnings`.
"""
def __init__(self, module=None):
self._module = sys.modules['warnings'] if module is None else module
self._entered = False
self._list = []
@property
def list(self):
"""The list of recorded warnings."""
return self._list
def __getitem__(self, i):
"""Get a recorded warning by index."""
return self._list[i]
def __iter__(self):
"""Iterate through the recorded warnings."""
return iter(self._list)
def __len__(self):
"""The number of recorded warnings."""
return len(self._list)
def pop(self, cls=Warning):
""" pop the first recorded warning, raise exception if not exists."""
for i, w in enumerate(self.list):
"""Pop the first recorded warning, raise exception if not exists."""
for i, w in enumerate(self._list):
if issubclass(w.category, cls):
return self.list.pop(i)
return self._list.pop(i)
__tracebackhide__ = True
assert 0, "%r not found in %r" %(cls, self.list)
#def resetregistry(self):
# warnings.onceregistry.clear()
# warnings.__warningregistry__.clear()
raise AssertionError("%r not found in warning list" % cls)
def clear(self):
self.list[:] = []
"""Clear the list of recorded warnings."""
self._list[:] = []
def finalize(self):
warnings.showwarning = self.old_showwarning
def __enter__(self):
if self._entered:
__tracebackhide__ = True
raise RuntimeError("Cannot enter %r twice" % self)
self._entered = True
self._filters = self._module.filters
self._module.filters = self._filters[:]
self._showwarning = self._module.showwarning
def showwarning(message, category, filename, lineno,
file=None, line=None):
self._list.append(RecordedWarning(
message, category, filename, lineno, file, line))
# still perform old showwarning functionality
self._showwarning(
message, category, filename, lineno, file=file, line=line)
self._module.showwarning = showwarning
# allow the same warning to be raised more than once
self._module.simplefilter('always')
return self
def __exit__(self, *exc_info):
if not self._entered:
__tracebackhide__ = True
raise RuntimeError("Cannot exit %r without entering first" % self)
self._module.filters = self._filters
self._module.showwarning = self._showwarning
class WarningsChecker(WarningsRecorder):
def __init__(self, expected_warning=None, module=None):
super(WarningsChecker, self).__init__(module=module)
msg = ("exceptions must be old-style classes or "
"derived from Warning, not %s")
if isinstance(expected_warning, tuple):
for exc in expected_warning:
if not inspect.isclass(exc):
raise TypeError(msg % type(exc))
elif inspect.isclass(expected_warning):
expected_warning = (expected_warning,)
elif expected_warning is not None:
raise TypeError(msg % type(expected_warning))
self.expected_warning = expected_warning
def __exit__(self, *exc_info):
super(WarningsChecker, self).__exit__(*exc_info)
# only check if we're not currently handling an exception
if all(a is None for a in exc_info):
if self.expected_warning is not None:
if not any(r.category in self.expected_warning for r in self):
__tracebackhide__ = True
pytest.fail("DID NOT WARN")

View File

@@ -9,7 +9,7 @@ def pytest_addoption(parser):
group = parser.getgroup("terminal reporting", "resultlog plugin options")
group.addoption('--resultlog', '--result-log', action="store",
metavar="path", default=None,
help="path for machine-readable result log.")
help="DEPRECATED path for machine-readable result log.")
def pytest_configure(config):
resultlog = config.option.resultlog
@@ -22,6 +22,9 @@ def pytest_configure(config):
config._resultlog = ResultLog(config, logfile)
config.pluginmanager.register(config._resultlog)
from _pytest.deprecated import RESULT_LOG
config.warn('C1', RESULT_LOG)
def pytest_unconfigure(config):
resultlog = getattr(config, '_resultlog', None)
if resultlog:

View File

@@ -5,7 +5,8 @@ from time import time
import py
import pytest
from py._code.code import TerminalRepr
from _pytest._code.code import TerminalRepr, ExceptionInfo
def pytest_namespace():
return {
@@ -72,7 +73,10 @@ def runtestprotocol(item, log=True, nextitem=None):
rep = call_and_report(item, "setup", log)
reports = [rep]
if rep.passed:
reports.append(call_and_report(item, "call", log))
if item.config.option.setupshow:
show_test_item(item)
if not item.config.option.setuponly:
reports.append(call_and_report(item, "call", log))
reports.append(call_and_report(item, "teardown", log,
nextitem=nextitem))
# after all teardown hooks have been called
@@ -82,6 +86,16 @@ def runtestprotocol(item, log=True, nextitem=None):
item.funcargs = None
return reports
def show_test_item(item):
"""Show test function, parameters and the fixtures of the test item."""
tw = item.config.get_terminal_writer()
tw.line()
tw.write(' ' * 8)
tw.write(item._nodeid)
used_fixtures = sorted(item._fixtureinfo.name2fixturedefs.keys())
if used_fixtures:
tw.write(' (fixtures used: {0})'.format(', '.join(used_fixtures)))
def pytest_runtest_setup(item):
item.session._setupstate.prepare(item)
@@ -151,7 +165,7 @@ class CallInfo:
self.stop = time()
raise
except:
self.excinfo = py.code.ExceptionInfo()
self.excinfo = ExceptionInfo()
self.stop = time()
def __repr__(self):
@@ -177,9 +191,13 @@ class BaseReport(object):
self.__dict__.update(kw)
def toterminal(self, out):
longrepr = self.longrepr
if hasattr(self, 'node'):
out.line(getslaveinfoline(self.node))
longrepr = self.longrepr
if longrepr is None:
return
if hasattr(longrepr, 'toterminal'):
longrepr.toterminal(out)
else:
@@ -193,6 +211,36 @@ class BaseReport(object):
if name.startswith(prefix):
yield prefix, content
@property
def longreprtext(self):
"""
Read-only property that returns the full string representation
of ``longrepr``.
.. versionadded:: 3.0
"""
tw = py.io.TerminalWriter(stringio=True)
tw.hasmarkup = False
self.toterminal(tw)
exc = tw.stringio.getvalue()
return exc.strip()
@property
def capstdout(self):
"""Return captured text from stdout, if capturing is enabled
.. versionadded:: 3.0
"""
return ''.join(content for (prefix, content) in self.get_sections('Captured stdout'))
@property
def capstderr(self):
"""Return captured text from stderr, if capturing is enabled
.. versionadded:: 3.0
"""
return ''.join(content for (prefix, content) in self.get_sections('Captured stderr'))
passed = property(lambda x: x.outcome == "passed")
failed = property(lambda x: x.outcome == "failed")
skipped = property(lambda x: x.outcome == "skipped")
@@ -211,7 +259,7 @@ def pytest_runtest_makereport(item, call):
outcome = "passed"
longrepr = None
else:
if not isinstance(excinfo, py.code.ExceptionInfo):
if not isinstance(excinfo, ExceptionInfo):
outcome = "failed"
longrepr = excinfo
elif excinfo.errisinstance(pytest.skip.Exception):
@@ -226,7 +274,7 @@ def pytest_runtest_makereport(item, call):
longrepr = item._repr_failure_py(excinfo,
style=item.config.option.tbstyle)
for rwhen, key, content in item._report_sections:
sections.append(("Captured std%s %s" %(key, rwhen), content))
sections.append(("Captured %s %s" %(key, rwhen), content))
return TestReport(item.nodeid, item.location,
keywords, outcome, longrepr, when,
sections, duration)
@@ -258,8 +306,10 @@ class TestReport(BaseReport):
#: one of 'setup', 'call', 'teardown' to indicate runtest phase.
self.when = when
#: list of (secname, data) extra information which needs to
#: marshallable
#: list of pairs ``(str, str)`` of extra information which needs to
#: marshallable. Used by pytest to add captured text
#: from ``stdout`` and ``stderr``, but may be used by other plugins
#: to add arbitrary information to reports.
self.sections = list(sections)
#: time it took to run just the test
@@ -430,7 +480,10 @@ class OutcomeException(Exception):
def __repr__(self):
if self.msg:
return str(self.msg)
val = self.msg
if isinstance(val, bytes):
val = py._builtin._totext(val, errors='replace')
return val
return "<%s instance>" %(self.__class__.__name__,)
__str__ = __repr__
@@ -439,10 +492,16 @@ class Skipped(OutcomeException):
# in order to have Skipped exception printing shorter/nicer
__module__ = 'builtins'
def __init__(self, msg=None, pytrace=True, allow_module_level=False):
OutcomeException.__init__(self, msg=msg, pytrace=pytrace)
self.allow_module_level = allow_module_level
class Failed(OutcomeException):
""" raised from an explicit call to pytest.fail() """
__module__ = 'builtins'
class Exit(KeyboardInterrupt):
""" raised for immediate program exits (no tracebacks/summaries)"""
def __init__(self, msg="unknown reason"):
@@ -469,7 +528,7 @@ def skip(msg=""):
skip.Exception = Skipped
def fail(msg="", pytrace=True):
""" explicitely fail an currently-executing test with the given Message.
""" explicitly fail an currently-executing test with the given Message.
:arg pytrace: if false the msg represents the full failure information
and no python traceback will be reported.
@@ -486,10 +545,14 @@ def importorskip(modname, minversion=None):
"""
__tracebackhide__ = True
compile(modname, '', 'eval') # to catch syntaxerrors
should_skip = False
try:
__import__(modname)
except ImportError:
skip("could not import %r" %(modname,))
# Do not raise chained exception here(#1485)
should_skip = True
if should_skip:
raise Skipped("could not import %r" %(modname,), allow_module_level=True)
mod = sys.modules[modname]
if minversion is None:
return mod
@@ -498,10 +561,11 @@ def importorskip(modname, minversion=None):
try:
from pkg_resources import parse_version as pv
except ImportError:
skip("we have a required version for %r but can not import "
"no pkg_resources to parse version strings." %(modname,))
raise Skipped("we have a required version for %r but can not import "
"pkg_resources to parse version strings." % (modname,),
allow_module_level=True)
if verattr is None or pv(verattr) < pv(minversion):
skip("module %r has __version__ %r, required is: %r" %(
modname, verattr, minversion))
raise Skipped("module %r has __version__ %r, required is: %r" %(
modname, verattr, minversion), allow_module_level=True)
return mod

72
_pytest/setuponly.py Normal file
View File

@@ -0,0 +1,72 @@
import pytest
import sys
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--setuponly', '--setup-only', action="store_true",
help="only setup fixtures, don't execute the tests.")
group.addoption('--setupshow', '--setup-show', action="store_true",
help="show setup fixtures while executing the tests.")
@pytest.hookimpl(hookwrapper=True)
def pytest_fixture_setup(fixturedef, request):
yield
config = request.config
if config.option.setupshow:
if hasattr(request, 'param'):
# Save the fixture parameter so ._show_fixture_action() can
# display it now and during the teardown (in .finish()).
if fixturedef.ids:
if callable(fixturedef.ids):
fixturedef.cached_param = fixturedef.ids(request.param)
else:
fixturedef.cached_param = fixturedef.ids[
request.param_index]
else:
fixturedef.cached_param = request.param
_show_fixture_action(fixturedef, 'SETUP')
def pytest_fixture_post_finalizer(fixturedef):
if hasattr(fixturedef, "cached_result"):
config = fixturedef._fixturemanager.config
if config.option.setupshow:
_show_fixture_action(fixturedef, 'TEARDOWN')
if hasattr(fixturedef, "cached_param"):
del fixturedef.cached_param
def _show_fixture_action(fixturedef, msg):
config = fixturedef._fixturemanager.config
capman = config.pluginmanager.getplugin('capturemanager')
if capman:
out, err = capman.suspendcapture()
tw = config.get_terminal_writer()
tw.line()
tw.write(' ' * 2 * fixturedef.scopenum)
tw.write('{step} {scope} {fixture}'.format(
step=msg.ljust(8), # align the output to TEARDOWN
scope=fixturedef.scope[0].upper(),
fixture=fixturedef.argname))
if msg == 'SETUP':
deps = sorted(arg for arg in fixturedef.argnames if arg != 'request')
if deps:
tw.write(' (fixtures used: {0})'.format(', '.join(deps)))
if hasattr(fixturedef, 'cached_param'):
tw.write('[{0}]'.format(fixturedef.cached_param))
if capman:
capman.resumecapture()
sys.stdout.write(out)
sys.stderr.write(err)
@pytest.hookimpl(tryfirst=True)
def pytest_cmdline_main(config):
if config.option.setuponly:
config.option.setupshow = True

23
_pytest/setupplan.py Normal file
View File

@@ -0,0 +1,23 @@
import pytest
def pytest_addoption(parser):
group = parser.getgroup("debugconfig")
group.addoption('--setupplan', '--setup-plan', action="store_true",
help="show what fixtures and tests would be executed but "
"don't execute anything.")
@pytest.hookimpl(tryfirst=True)
def pytest_fixture_setup(fixturedef, request):
# Will return a dummy fixture if the setuponly option is provided.
if request.config.option.setupplan:
fixturedef.cached_result = (None, None, None)
return fixturedef.cached_result
@pytest.hookimpl(tryfirst=True)
def pytest_cmdline_main(config):
if config.option.setupplan:
config.option.setuponly = True
config.option.setupshow = True

View File

@@ -5,6 +5,8 @@ import traceback
import py
import pytest
from _pytest.mark import MarkInfo, MarkDecorator
def pytest_addoption(parser):
group = parser.getgroup("general")
@@ -12,6 +14,13 @@ def pytest_addoption(parser):
action="store_true", dest="runxfail", default=False,
help="run tests even if they are marked xfail")
parser.addini("xfail_strict", "default for the strict parameter of xfail "
"markers when not given explicitly (default: "
"False)",
default=False,
type="bool")
def pytest_configure(config):
if config.option.runxfail:
old = pytest.xfail
@@ -21,6 +30,11 @@ def pytest_configure(config):
nop.Exception = XFailed
setattr(pytest, "xfail", nop)
config.addinivalue_line("markers",
"skip(reason=None): skip the given test function with an optional reason. "
"Example: skip(reason=\"no way of currently testing this\") skips the "
"test."
)
config.addinivalue_line("markers",
"skipif(condition): skip the given test function if eval(condition) "
"results in a True value. Evaluation happens within the "
@@ -29,27 +43,31 @@ def pytest_configure(config):
"http://pytest.org/latest/skipping.html"
)
config.addinivalue_line("markers",
"xfail(condition, reason=None, run=True, raises=None): mark the the test function "
"as an expected failure if eval(condition) has a True value. "
"Optionally specify a reason for better reporting and run=False if "
"you don't even want to execute the test function. If only specific "
"exception(s) are expected, you can list them in raises, and if the test fails "
"in other ways, it will be reported as a true failure. "
"See http://pytest.org/latest/skipping.html"
"xfail(condition, reason=None, run=True, raises=None, strict=False): "
"mark the the test function as an expected failure if eval(condition) "
"has a True value. Optionally specify a reason for better reporting "
"and run=False if you don't even want to execute the test function. "
"If only specific exception(s) are expected, you can list them in "
"raises, and if the test fails in other ways, it will be reported as "
"a true failure. See http://pytest.org/latest/skipping.html"
)
def pytest_namespace():
return dict(xfail=xfail)
class XFailed(pytest.fail.Exception):
""" raised from an explicit call to pytest.xfail() """
def xfail(reason=""):
""" xfail an executing test or setup functions with the given reason."""
__tracebackhide__ = True
raise XFailed(reason)
xfail.Exception = XFailed
class MarkEvaluator:
def __init__(self, item, name):
self.item = item
@@ -90,11 +108,7 @@ class MarkEvaluator:
def _getglobals(self):
d = {'os': os, 'sys': sys, 'config': self.item.config}
func = self.item.obj
try:
d.update(func.__globals__)
except AttributeError:
d.update(func.func_globals)
d.update(self.item.obj.__globals__)
return d
def _istrue(self):
@@ -102,7 +116,7 @@ class MarkEvaluator:
return self.result
if self.holder:
d = self._getglobals()
if self.holder.args:
if self.holder.args or 'condition' in self.holder.kwargs:
self.result = False
# "holder" might be a MarkInfo or a MarkDecorator; only
# MarkInfo keeps track of all parameters it received in an
@@ -112,6 +126,8 @@ class MarkEvaluator:
else:
arglist = [(self.holder.args, self.holder.kwargs)]
for args, kwargs in arglist:
if 'condition' in kwargs:
args = (kwargs['condition'],)
for expr in args:
self.expr = expr
if isinstance(expr, py.builtin._basestring):
@@ -145,26 +161,62 @@ class MarkEvaluator:
return expl
@pytest.mark.tryfirst
@pytest.hookimpl(tryfirst=True)
def pytest_runtest_setup(item):
evalskip = MarkEvaluator(item, 'skipif')
if evalskip.istrue():
item._evalskip = evalskip
pytest.skip(evalskip.getexplanation())
# Check if skip or skipif are specified as pytest marks
skipif_info = item.keywords.get('skipif')
if isinstance(skipif_info, (MarkInfo, MarkDecorator)):
eval_skipif = MarkEvaluator(item, 'skipif')
if eval_skipif.istrue():
item._evalskip = eval_skipif
pytest.skip(eval_skipif.getexplanation())
skip_info = item.keywords.get('skip')
if isinstance(skip_info, (MarkInfo, MarkDecorator)):
item._evalskip = True
if 'reason' in skip_info.kwargs:
pytest.skip(skip_info.kwargs['reason'])
elif skip_info.args:
pytest.skip(skip_info.args[0])
else:
pytest.skip("unconditional skip")
item._evalxfail = MarkEvaluator(item, 'xfail')
check_xfail_no_run(item)
@pytest.mark.hookwrapper
def pytest_pyfunc_call(pyfuncitem):
check_xfail_no_run(pyfuncitem)
outcome = yield
passed = outcome.excinfo is None
if passed:
check_strict_xfail(pyfuncitem)
def check_xfail_no_run(item):
"""check xfail(run=False)"""
if not item.config.option.runxfail:
evalxfail = item._evalxfail
if evalxfail.istrue():
if not evalxfail.get('run', True):
pytest.xfail("[NOTRUN] " + evalxfail.getexplanation())
@pytest.mark.hookwrapper
def check_strict_xfail(pyfuncitem):
"""check xfail(strict=True) for the given PASSING test"""
evalxfail = pyfuncitem._evalxfail
if evalxfail.istrue():
strict_default = pyfuncitem.config.getini('xfail_strict')
is_strict_xfail = evalxfail.get('strict', strict_default)
if is_strict_xfail:
del pyfuncitem._evalxfail
explanation = evalxfail.getexplanation()
pytest.fail('[XPASS(strict)] ' + explanation, pytrace=False)
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
@@ -172,9 +224,16 @@ def pytest_runtest_makereport(item, call):
evalskip = getattr(item, '_evalskip', None)
# unitttest special case, see setting of _unexpectedsuccess
if hasattr(item, '_unexpectedsuccess') and rep.when == "call":
# we need to translate into how pytest encodes xpass
rep.wasxfail = "reason: " + repr(item._unexpectedsuccess)
rep.outcome = "failed"
from _pytest.compat import _is_unittest_unexpected_success_a_failure
if item._unexpectedsuccess:
rep.longrepr = "Unexpected success: {0}".format(item._unexpectedsuccess)
else:
rep.longrepr = "Unexpected success"
if _is_unittest_unexpected_success_a_failure():
rep.outcome = "failed"
else:
rep.outcome = "passed"
rep.wasxfail = rep.longrepr
elif item.config.option.runxfail:
pass # don't interefere
elif call.excinfo and call.excinfo.errisinstance(pytest.xfail.Exception):
@@ -189,8 +248,15 @@ def pytest_runtest_makereport(item, call):
rep.outcome = "skipped"
rep.wasxfail = evalxfail.getexplanation()
elif call.when == "call":
rep.outcome = "failed" # xpass outcome
rep.wasxfail = evalxfail.getexplanation()
strict_default = item.config.getini('xfail_strict')
is_strict_xfail = evalxfail.get('strict', strict_default)
explanation = evalxfail.getexplanation()
if is_strict_xfail:
rep.outcome = "failed"
rep.longrepr = "[XPASS(strict)] {0}".format(explanation)
else:
rep.outcome = "passed"
rep.wasxfail = explanation
elif evalskip is not None and rep.skipped and type(rep.longrepr) is tuple:
# skipped by mark.skipif; change the location of the failure
# to point to the item definition, otherwise it will display
@@ -204,7 +270,7 @@ def pytest_report_teststatus(report):
if hasattr(report, "wasxfail"):
if report.skipped:
return "xfailed", "x", "xfail"
elif report.failed:
elif report.passed:
return "xpassed", "X", ("XPASS", {'yellow': True})
# called by the terminalreporter instance/plugin
@@ -230,6 +296,9 @@ def pytest_terminal_summary(terminalreporter):
show_skipped(terminalreporter, lines)
elif char == "E":
show_simple(terminalreporter, lines, 'error', "ERROR %s")
elif char == 'p':
show_simple(terminalreporter, lines, 'passed', "PASSED %s")
if lines:
tr._tw.sep("=", "short test summary info")
for line in lines:
@@ -266,9 +335,8 @@ def cached_eval(config, expr, d):
try:
return config._evalcache[expr]
except KeyError:
#import sys
#print >>sys.stderr, ("cache-miss: %r" % expr)
exprcode = py.code.compile(expr, mode="eval")
import _pytest._code
exprcode = _pytest._code.compile(expr, mode="eval")
config._evalcache[expr] = x = eval(exprcode, d)
return x

View File

@@ -1,85 +0,0 @@
#! /usr/bin/env python
# Hi There!
# You may be wondering what this giant blob of binary data here is, you might
# even be worried that we're up to something nefarious (good for you for being
# paranoid!). This is a base64 encoding of a zip file, this zip file contains
# a fully functional basic pytest script.
#
# Pytest is a thing that tests packages, pytest itself is a package that some-
# one might want to install, especially if they're looking to run tests inside
# some package they want to install. Pytest has a lot of code to collect and
# execute tests, and other such sort of "tribal knowledge" that has been en-
# coded in its code base. Because of this we basically include a basic copy
# of pytest inside this blob. We do this because it let's you as a maintainer
# or application developer who wants people who don't deal with python much to
# easily run tests without installing the complete pytest package.
#
# If you're wondering how this is created: you can create it yourself if you
# have a complete pytest installation by using this command on the command-
# line: ``py.test --genscript=runtests.py``.
sources = """
@SOURCES@"""
import sys
import base64
import zlib
class DictImporter(object):
def __init__(self, sources):
self.sources = sources
def find_module(self, fullname, path=None):
if fullname == "argparse" and sys.version_info >= (2,7):
# we were generated with <python2.7 (which pulls in argparse)
# but we are running now on a stdlib which has it, so use that.
return None
if fullname in self.sources:
return self
if fullname + '.__init__' in self.sources:
return self
return None
def load_module(self, fullname):
# print "load_module:", fullname
from types import ModuleType
try:
s = self.sources[fullname]
is_pkg = False
except KeyError:
s = self.sources[fullname + '.__init__']
is_pkg = True
co = compile(s, fullname, 'exec')
module = sys.modules.setdefault(fullname, ModuleType(fullname))
module.__file__ = "%s/%s" % (__file__, fullname)
module.__loader__ = self
if is_pkg:
module.__path__ = [fullname]
do_exec(co, module.__dict__) # noqa
return sys.modules[fullname]
def get_source(self, name):
res = self.sources.get(name)
if res is None:
res = self.sources.get(name + '.__init__')
return res
if __name__ == "__main__":
if sys.version_info >= (3, 0):
exec("def do_exec(co, loc): exec(co, loc)\n")
import pickle
sources = sources.encode("ascii") # ensure bytes
sources = pickle.loads(zlib.decompress(base64.decodebytes(sources)))
else:
import cPickle as pickle
exec("def do_exec(co, loc): exec co in loc\n")
sources = pickle.loads(zlib.decompress(base64.decodestring(sources)))
importer = DictImporter(sources)
sys.meta_path.insert(0, importer)
entry = "@ENTRY@"
do_exec(entry, locals()) # noqa

View File

@@ -2,10 +2,15 @@
This is a good source for looking at the various reporting hooks.
"""
from _pytest.main import EXIT_OK, EXIT_TESTSFAILED, EXIT_INTERRUPTED, \
EXIT_USAGEERROR, EXIT_NOTESTSCOLLECTED
import pytest
import py
import sys
import time
import platform
import _pytest._pluggy as pluggy
def pytest_addoption(parser):
@@ -15,15 +20,18 @@ def pytest_addoption(parser):
group._addoption('-q', '--quiet', action="count",
dest="quiet", default=0, help="decrease verbosity."),
group._addoption('-r',
action="store", dest="reportchars", default=None, metavar="chars",
action="store", dest="reportchars", default='', metavar="chars",
help="show extra test summary info as specified by chars (f)ailed, "
"(E)error, (s)skipped, (x)failed, (X)passed (w)warnings.")
"(E)error, (s)skipped, (x)failed, (X)passed, "
"(p)passed, (P)passed with output, (a)all except pP. "
"The pytest warnings are displayed at all times except when "
"--disable-pytest-warnings is set")
group._addoption('--disable-pytest-warnings', default=False,
dest='disablepytestwarnings', action='store_true',
help='disable warnings summary, overrides -r w flag')
group._addoption('-l', '--showlocals',
action="store_true", dest="showlocals", default=False,
help="show locals in tracebacks (disabled by default).")
group._addoption('--report',
action="store", dest="report", default=None, metavar="opts",
help="(deprecated, use -r)")
group._addoption('--tb', metavar="style",
action="store", dest="tbstyle", default='auto',
choices=['auto', 'long', 'short', 'no', 'line', 'native'],
@@ -48,22 +56,17 @@ def pytest_configure(config):
def getreportopt(config):
reportopts = ""
optvalue = config.option.report
if optvalue:
py.builtin.print_("DEPRECATED: use -r instead of --report option.",
file=sys.stderr)
if optvalue:
for setting in optvalue.split(","):
setting = setting.strip()
if setting == "skipped":
reportopts += "s"
elif setting == "xfailed":
reportopts += "x"
reportchars = config.option.reportchars
if not config.option.disablepytestwarnings and 'w' not in reportchars:
reportchars += 'w'
elif config.option.disablepytestwarnings and 'w' in reportchars:
reportchars = reportchars.replace('w', '')
if reportchars:
for char in reportchars:
if char not in reportopts:
if char not in reportopts and char != 'a':
reportopts += char
elif char == 'a':
reportopts = 'fEsxXw'
return reportopts
def pytest_report_teststatus(report):
@@ -104,6 +107,7 @@ class TerminalReporter:
self.currentfspath = None
self.reportchars = getreportopt(config)
self.hasmarkup = self._tw.hasmarkup
self.isatty = file.isatty()
def hasopt(self, char):
char = {'xfailed': 'x', 'skipped': 's'}.get(char, char)
@@ -162,6 +166,8 @@ class TerminalReporter:
def pytest_logwarning(self, code, fslocation, message, nodeid):
warnings = self.stats.setdefault("warnings", [])
if isinstance(fslocation, tuple):
fslocation = "%s:%d" % fslocation
warning = WarningReport(code=code, fslocation=fslocation,
message=message, nodeid=nodeid)
warnings.append(warning)
@@ -224,7 +230,7 @@ class TerminalReporter:
self.currentfspath = -2
def pytest_collection(self):
if not self.hasmarkup and self.config.option.verbose >= 1:
if not self.isatty and self.config.option.verbose >= 1:
self.write("collecting ... ", bold=True)
def pytest_collectreport(self, report):
@@ -234,7 +240,7 @@ class TerminalReporter:
self.stats.setdefault("skipped", []).append(report)
items = [x for x in report.result if isinstance(x, pytest.Item)]
self._numcollected += len(items)
if self.hasmarkup:
if self.isatty:
#self.write_fspath_result(report.nodeid, 'E')
self.report_collect()
@@ -253,7 +259,7 @@ class TerminalReporter:
line += " / %d errors" % errors
if skipped:
line += " / %d skipped" % skipped
if self.hasmarkup:
if self.isatty:
if final:
line += " \n"
self.rewrite(line, bold=True)
@@ -263,18 +269,19 @@ class TerminalReporter:
def pytest_collection_modifyitems(self):
self.report_collect(True)
@pytest.mark.trylast
@pytest.hookimpl(trylast=True)
def pytest_sessionstart(self, session):
self._sessionstarttime = time.time()
if not self.showheader:
return
self.write_sep("=", "test session starts", bold=True)
verinfo = ".".join(map(str, sys.version_info[:3]))
verinfo = platform.python_version()
msg = "platform %s -- Python %s" % (sys.platform, verinfo)
if hasattr(sys, 'pypy_version_info'):
verinfo = ".".join(map(str, sys.pypy_version_info[:3]))
msg += "[pypy-%s-%s]" % (verinfo, sys.pypy_version_info[3])
msg += " -- py-%s -- pytest-%s" % (py.__version__, pytest.__version__)
msg += ", pytest-%s, py-%s, pluggy-%s" % (
pytest.__version__, py.__version__, pluggy.__version__)
if self.verbosity > 0 or self.config.option.debug or \
getattr(self.config.option, 'pastebin', None):
msg += " -- " + str(sys.executable)
@@ -290,15 +297,12 @@ class TerminalReporter:
if config.inifile:
inifile = config.rootdir.bestrelpath(config.inifile)
lines = ["rootdir: %s, inifile: %s" %(config.rootdir, inifile)]
plugininfo = config.pluginmanager._plugin_distinfo
plugininfo = config.pluginmanager.list_plugin_distinfo()
if plugininfo:
l = []
for dist, plugin in plugininfo:
name = dist.project_name
if name.startswith("pytest-"):
name = name[7:]
l.append(name)
lines.append("plugins: %s" % ", ".join(l))
lines.append(
"plugins: %s" % ", ".join(_plugin_nameversions(plugininfo)))
return lines
def pytest_collection_finish(self, session):
@@ -348,17 +352,22 @@ class TerminalReporter:
indent = (len(stack) - 1) * " "
self._tw.line("%s%s" % (indent, col))
@pytest.mark.hookwrapper
@pytest.hookimpl(hookwrapper=True)
def pytest_sessionfinish(self, exitstatus):
outcome = yield
outcome.get_result()
self._tw.line("")
if exitstatus in (0, 1, 2, 4):
summary_exit_codes = (
EXIT_OK, EXIT_TESTSFAILED, EXIT_INTERRUPTED, EXIT_USAGEERROR,
EXIT_NOTESTSCOLLECTED)
if exitstatus in summary_exit_codes:
self.config.hook.pytest_terminal_summary(terminalreporter=self,
exitstatus=exitstatus)
self.summary_errors()
self.summary_failures()
self.summary_warnings()
self.config.hook.pytest_terminal_summary(terminalreporter=self)
if exitstatus == 2:
self.summary_passes()
if exitstatus == EXIT_INTERRUPTED:
self._report_keyboardinterrupt()
del self._keyboardinterrupt_memo
self.summary_deselected()
@@ -379,6 +388,7 @@ class TerminalReporter:
if self.config.option.fulltrace:
excrepr.toterminal(self._tw)
else:
self._tw.line("to show a full traceback on KeyboardInterrupt use --fulltrace", yellow=True)
excrepr.reprcrash.toterminal(self._tw)
def _locationline(self, nodeid, fspath, lineno, domain):
@@ -431,11 +441,23 @@ class TerminalReporter:
warnings = self.stats.get("warnings")
if not warnings:
return
self.write_sep("=", "warning summary")
self.write_sep("=", "pytest-warning summary")
for w in warnings:
self._tw.line("W%s %s %s" % (w.code,
w.fslocation, w.message))
def summary_passes(self):
if self.config.option.tbstyle != "no":
if self.hasopt("P"):
reports = self.getreports('passed')
if not reports:
return
self.write_sep("=", "PASSES")
for rep in reports:
msg = self._getfailureheadline(rep)
self.write_sep("_", msg)
self._outrep_summary(rep)
def summary_failures(self):
if self.config.option.tbstyle != "no":
reports = self.getreports('failed')
@@ -448,7 +470,8 @@ class TerminalReporter:
self.write_line(line)
else:
msg = self._getfailureheadline(rep)
self.write_sep("_", msg)
markup = {'red': True, 'bold': True}
self.write_sep("_", msg, **markup)
self._outrep_summary(rep)
def summary_errors(self):
@@ -479,26 +502,9 @@ class TerminalReporter:
def summary_stats(self):
session_duration = time.time() - self._sessionstarttime
keys = ("failed passed skipped deselected "
"xfailed xpassed warnings").split()
for key in self.stats.keys():
if key not in keys:
keys.append(key)
parts = []
for key in keys:
if key: # setup/teardown reports have an empty key, ignore them
val = self.stats.get(key, None)
if val:
parts.append("%d %s" % (len(val), key))
line = ", ".join(parts)
(line, color) = build_summary_stats_line(self.stats)
msg = "%s in %.2f seconds" % (line, session_duration)
markup = {'bold': True}
if 'failed' in self.stats or 'error' in self.stats:
markup = {'red': True, 'bold': True}
else:
markup = {'green': True, 'bold': True}
markup = {color: True, 'bold': True}
if self.verbosity >= 0:
self.write_sep("=", msg, **markup)
@@ -507,16 +513,8 @@ class TerminalReporter:
def summary_deselected(self):
if 'deselected' in self.stats:
l = []
k = self.config.option.keyword
if k:
l.append("-k%s" % k)
m = self.config.option.markexpr
if m:
l.append("-m %r" % m)
if l:
self.write_sep("=", "%d tests deselected by %r" % (
len(self.stats['deselected']), " ".join(l)), bold=True)
self.write_sep("=", "%d tests deselected" % (
len(self.stats['deselected'])), bold=True)
def repr_pythonversion(v=None):
if v is None:
@@ -534,3 +532,50 @@ def flatten(l):
else:
yield x
def build_summary_stats_line(stats):
keys = ("failed passed skipped deselected "
"xfailed xpassed warnings error").split()
key_translation = {'warnings': 'pytest-warnings'}
unknown_key_seen = False
for key in stats.keys():
if key not in keys:
if key: # setup/teardown reports have an empty key, ignore them
keys.append(key)
unknown_key_seen = True
parts = []
for key in keys:
val = stats.get(key, None)
if val:
key_name = key_translation.get(key, key)
parts.append("%d %s" % (len(val), key_name))
if parts:
line = ", ".join(parts)
else:
line = "no tests ran"
if 'failed' in stats or 'error' in stats:
color = 'red'
elif 'warnings' in stats or unknown_key_seen:
color = 'yellow'
elif 'passed' in stats:
color = 'green'
else:
color = 'yellow'
return (line, color)
def _plugin_nameversions(plugininfo):
l = []
for plugin, dist in plugininfo:
# gets us name and version!
name = '{dist.project_name}-{dist.version}'.format(dist=dist)
# questionable convenience, but it keeps things short
if name.startswith("pytest-"):
name = name[7:]
# we decided to print python package names
# they can have more than one plugin
if name not in l:
l.append(name)
return l

View File

@@ -3,10 +3,15 @@ import re
import pytest
import py
from _pytest.monkeypatch import monkeypatch
from _pytest.monkeypatch import MonkeyPatch
class TempdirHandler:
class TempdirFactory:
"""Factory for temporary directories under the common base temp directory.
The base directory can be configured using the ``--basetemp`` option.
"""
def __init__(self, config):
self.config = config
self.trace = config.trace.get("tmpdir")
@@ -22,6 +27,10 @@ class TempdirHandler:
return self.getbasetemp().ensure(string, dir=dir)
def mktemp(self, basename, numbered=True):
"""Create a subdirectory of the base temporary directory and return it.
If ``numbered``, ensure the directory is unique by adding a number
prefix greater than any existing one.
"""
basetemp = self.getbasetemp()
if not numbered:
p = basetemp.mkdir(basename)
@@ -43,11 +52,14 @@ class TempdirHandler:
basetemp.remove()
basetemp.mkdir()
else:
# use a sub-directory in the temproot to speed-up
# make_numbered_dir() call
import getpass
temproot = py.path.local.get_temproot()
rootdir = temproot.join('pytest-%s' % getpass.getuser())
user = get_user()
if user:
# use a sub-directory in the temproot to speed-up
# make_numbered_dir() call
rootdir = temproot.join('pytest-of-%s' % user)
else:
rootdir = temproot
rootdir.ensure(dir=1)
basetemp = py.path.local.make_numbered_dir(prefix='pytest-',
rootdir=rootdir)
@@ -58,16 +70,45 @@ class TempdirHandler:
def finish(self):
self.trace("finish")
def get_user():
"""Return the current user name, or None if getuser() does not work
in the current environment (see #1010).
"""
import getpass
try:
return getpass.getuser()
except (ImportError, KeyError):
return None
# backward compatibility
TempdirHandler = TempdirFactory
def pytest_configure(config):
mp = monkeypatch()
t = TempdirHandler(config)
"""Create a TempdirFactory and attach it to the config object.
This is to comply with existing plugins which expect the handler to be
available at pytest_configure time, but ideally should be moved entirely
to the tmpdir_factory session fixture.
"""
mp = MonkeyPatch()
t = TempdirFactory(config)
config._cleanup.extend([mp.undo, t.finish])
mp.setattr(config, '_tmpdirhandler', t, raising=False)
mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)
@pytest.fixture(scope='session')
def tmpdir_factory(request):
"""Return a TempdirFactory instance for the test session.
"""
return request.config._tmpdirhandler
@pytest.fixture
def tmpdir(request):
"""return a temporary directory path object
def tmpdir(request, tmpdir_factory):
"""Return a temporary directory path object
which is unique to each test function invocation,
created as a sub directory of the base temporary
directory. The returned object is a `py.path.local`_
@@ -78,5 +119,5 @@ def tmpdir(request):
MAXVAL = 30
if len(name) > MAXVAL:
name = name[:MAXVAL]
x = request.config._tmpdirhandler.mktemp(name, numbered=True)
x = tmpdir_factory.mktemp(name, numbered=True)
return x

View File

@@ -1,13 +1,12 @@
""" discovery and running of std-library "unittest" style tests. """
from __future__ import absolute_import
import traceback
import sys
import traceback
import pytest
import py
# for transfering markers
import _pytest._code
from _pytest.python import transfer_markers
from _pytest.skipping import MarkEvaluator
@@ -24,9 +23,10 @@ def pytest_pycollect_makeitem(collector, name, obj):
class UnitTestCase(pytest.Class):
nofuncargs = True # marker for fixturemanger.getfixtureinfo()
# to declare that our children do not support funcargs
#
# marker for fixturemanger.getfixtureinfo()
# to declare that our children do not support funcargs
nofuncargs = True
def setup(self):
cls = self.obj
if getattr(cls, '__unittest_skip__', False):
@@ -50,6 +50,8 @@ class UnitTestCase(pytest.Class):
foundsomething = False
for name in loader.getTestCaseNames(self.obj):
x = getattr(self.obj, name)
if not getattr(x, '__test__', True):
continue
funcobj = getattr(x, 'im_func', x)
transfer_markers(funcobj, cls, module)
yield TestCaseFunction(name, parent=self)
@@ -69,12 +71,26 @@ class TestCaseFunction(pytest.Function):
def setup(self):
self._testcase = self.parent.obj(self.name)
self._fix_unittest_skip_decorator()
self._obj = getattr(self._testcase, self.name)
if hasattr(self._testcase, 'setup_method'):
self._testcase.setup_method(self._obj)
if hasattr(self, "_request"):
self._request._fillfixtures()
def _fix_unittest_skip_decorator(self):
"""
The @unittest.skip decorator calls functools.wraps(self._testcase)
The call to functools.wraps() fails unless self._testcase
has a __name__ attribute. This is usually automatically supplied
if the test is a function or method, but we need to add manually
here.
See issue #1169
"""
if sys.version_info[0] == 2:
setattr(self._testcase, "__name__", self.name)
def teardown(self):
if hasattr(self._testcase, 'teardown_method'):
self._testcase.teardown_method(self._obj)
@@ -86,7 +102,7 @@ class TestCaseFunction(pytest.Function):
# unwrap potential exception info (see twisted trial support below)
rawexcinfo = getattr(rawexcinfo, '_rawexcinfo', rawexcinfo)
try:
excinfo = py.code.ExceptionInfo(rawexcinfo)
excinfo = _pytest._code.ExceptionInfo(rawexcinfo)
except TypeError:
try:
try:
@@ -102,7 +118,7 @@ class TestCaseFunction(pytest.Function):
except KeyboardInterrupt:
raise
except pytest.fail.Exception:
excinfo = py.code.ExceptionInfo()
excinfo = _pytest._code.ExceptionInfo()
self.__dict__.setdefault('_excinfo', []).append(excinfo)
def addError(self, testcase, rawexcinfo):
@@ -134,7 +150,12 @@ class TestCaseFunction(pytest.Function):
pass
def runtest(self):
self._testcase(result=self)
if self.config.pluginmanager.get_plugin("pdbinvoke") is None:
self._testcase(result=self)
else:
# disables tearDown and cleanups for post mortem debugging (see #1890)
self._testcase.debug()
def _prunetraceback(self, excinfo):
pytest.Function._prunetraceback(self, excinfo)
@@ -143,7 +164,7 @@ class TestCaseFunction(pytest.Function):
if traceback:
excinfo.traceback = traceback
@pytest.mark.tryfirst
@pytest.hookimpl(tryfirst=True)
def pytest_runtest_makereport(item, call):
if isinstance(item, TestCaseFunction):
if item._excinfo:
@@ -155,7 +176,7 @@ def pytest_runtest_makereport(item, call):
# twisted trial support
@pytest.mark.hookwrapper
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_protocol(item):
if isinstance(item, TestCaseFunction) and \
'twisted.trial.unittest' in sys.modules:

View File

@@ -0,0 +1,13 @@
This directory vendors the `pluggy` module.
For a more detailed discussion for the reasons to vendoring this
package, please see [this issue](https://github.com/pytest-dev/pytest/issues/944).
To update the current version, execute:
```
$ pip install -U pluggy==<version> --no-compile --target=_pytest/vendored_packages
```
And commit the modified files. The `pluggy-<version>.dist-info` directory
created by `pip` should be ignored.

View File

View File

@@ -0,0 +1,10 @@
Plugin registration and hook calling for Python
===============================================
This is the plugin manager as used by pytest but stripped
of pytest specific details.
During the 0.x series this plugin does not have much documentation
except extensive docstrings in the pluggy.py module.

View File

@@ -0,0 +1,39 @@
Metadata-Version: 2.0
Name: pluggy
Version: 0.3.1
Summary: plugin and hook calling mechanisms for python
Home-page: UNKNOWN
Author: Holger Krekel
Author-email: holger at merlinux.eu
License: MIT license
Platform: unix
Platform: linux
Platform: osx
Platform: win32
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: Utilities
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Plugin registration and hook calling for Python
===============================================
This is the plugin manager as used by pytest but stripped
of pytest specific details.
During the 0.x series this plugin does not have much documentation
except extensive docstrings in the pluggy.py module.

View File

@@ -0,0 +1,8 @@
pluggy.py,sha256=v_RfWzyW6DPU1cJu_EFoL_OHq3t13qloVdR6UaMCXQA,29862
pluggy-0.3.1.dist-info/top_level.txt,sha256=xKSCRhai-v9MckvMuWqNz16c1tbsmOggoMSwTgcpYHE,7
pluggy-0.3.1.dist-info/pbr.json,sha256=xX3s6__wOcAyF-AZJX1sdZyW6PUXT-FkfBlM69EEUCg,47
pluggy-0.3.1.dist-info/RECORD,,
pluggy-0.3.1.dist-info/metadata.json,sha256=nLKltOT78dMV-00uXD6Aeemp4xNsz2q59j6ORSDeLjw,1027
pluggy-0.3.1.dist-info/METADATA,sha256=1b85Ho2u4iK30M099k7axMzcDDhLcIMb-A82JUJZnSo,1334
pluggy-0.3.1.dist-info/WHEEL,sha256=AvR0WeTpDaxT645bl5FQxUK6NPsTls2ttpcGJg3j1Xg,110
pluggy-0.3.1.dist-info/DESCRIPTION.rst,sha256=P5Akh1EdIBR6CeqtV2P8ZwpGSpZiTKPw0NyS7jEiD-g,306

View File

@@ -0,0 +1,6 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.24.0)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any

View File

@@ -0,0 +1 @@
{"license": "MIT license", "name": "pluggy", "metadata_version": "2.0", "generator": "bdist_wheel (0.24.0)", "summary": "plugin and hook calling mechanisms for python", "platform": "unix", "version": "0.3.1", "extensions": {"python.details": {"document_names": {"description": "DESCRIPTION.rst"}, "contacts": [{"role": "author", "email": "holger at merlinux.eu", "name": "Holger Krekel"}]}}, "classifiers": ["Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Operating System :: Microsoft :: Windows", "Operating System :: MacOS :: MacOS X", "Topic :: Software Development :: Testing", "Topic :: Software Development :: Libraries", "Topic :: Utilities", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5"]}

View File

@@ -0,0 +1 @@
{"is_release": false, "git_version": "7d4c9cd"}

View File

@@ -0,0 +1 @@
pluggy

View File

@@ -0,0 +1,777 @@
"""
PluginManager, basic initialization and tracing.
pluggy is the cristallized core of plugin management as used
by some 150 plugins for pytest.
Pluggy uses semantic versioning. Breaking changes are only foreseen for
Major releases (incremented X in "X.Y.Z"). If you want to use pluggy in
your project you should thus use a dependency restriction like
"pluggy>=0.1.0,<1.0" to avoid surprises.
pluggy is concerned with hook specification, hook implementations and hook
calling. For any given hook specification a hook call invokes up to N implementations.
A hook implementation can influence its position and type of execution:
if attributed "tryfirst" or "trylast" it will be tried to execute
first or last. However, if attributed "hookwrapper" an implementation
can wrap all calls to non-hookwrapper implementations. A hookwrapper
can thus execute some code ahead and after the execution of other hooks.
Hook specification is done by way of a regular python function where
both the function name and the names of all its arguments are significant.
Each hook implementation function is verified against the original specification
function, including the names of all its arguments. To allow for hook specifications
to evolve over the livetime of a project, hook implementations can
accept less arguments. One can thus add new arguments and semantics to
a hook specification by adding another argument typically without breaking
existing hook implementations.
The chosen approach is meant to let a hook designer think carefuly about
which objects are needed by an extension writer. By contrast, subclass-based
extension mechanisms often expose a lot more state and behaviour than needed,
thus restricting future developments.
Pluggy currently consists of functionality for:
- a way to register new hook specifications. Without a hook
specification no hook calling can be performed.
- a registry of plugins which contain hook implementation functions. It
is possible to register plugins for which a hook specification is not yet
known and validate all hooks when the system is in a more referentially
consistent state. Setting an "optionalhook" attribution to a hook
implementation will avoid PluginValidationError's if a specification
is missing. This allows to have optional integration between plugins.
- a "hook" relay object from which you can launch 1:N calls to
registered hook implementation functions
- a mechanism for ordering hook implementation functions
- mechanisms for two different type of 1:N calls: "firstresult" for when
the call should stop when the first implementation returns a non-None result.
And the other (default) way of guaranteeing that all hook implementations
will be called and their non-None result collected.
- mechanisms for "historic" extension points such that all newly
registered functions will receive all hook calls that happened
before their registration.
- a mechanism for discovering plugin objects which are based on
setuptools based entry points.
- a simple tracing mechanism, including tracing of plugin calls and
their arguments.
"""
import sys
import inspect
__version__ = '0.3.1'
__all__ = ["PluginManager", "PluginValidationError",
"HookspecMarker", "HookimplMarker"]
_py3 = sys.version_info > (3, 0)
class HookspecMarker:
""" Decorator helper class for marking functions as hook specifications.
You can instantiate it with a project_name to get a decorator.
Calling PluginManager.add_hookspecs later will discover all marked functions
if the PluginManager uses the same project_name.
"""
def __init__(self, project_name):
self.project_name = project_name
def __call__(self, function=None, firstresult=False, historic=False):
""" if passed a function, directly sets attributes on the function
which will make it discoverable to add_hookspecs(). If passed no
function, returns a decorator which can be applied to a function
later using the attributes supplied.
If firstresult is True the 1:N hook call (N being the number of registered
hook implementation functions) will stop at I<=N when the I'th function
returns a non-None result.
If historic is True calls to a hook will be memorized and replayed
on later registered plugins.
"""
def setattr_hookspec_opts(func):
if historic and firstresult:
raise ValueError("cannot have a historic firstresult hook")
setattr(func, self.project_name + "_spec",
dict(firstresult=firstresult, historic=historic))
return func
if function is not None:
return setattr_hookspec_opts(function)
else:
return setattr_hookspec_opts
class HookimplMarker:
""" Decorator helper class for marking functions as hook implementations.
You can instantiate with a project_name to get a decorator.
Calling PluginManager.register later will discover all marked functions
if the PluginManager uses the same project_name.
"""
def __init__(self, project_name):
self.project_name = project_name
def __call__(self, function=None, hookwrapper=False, optionalhook=False,
tryfirst=False, trylast=False):
""" if passed a function, directly sets attributes on the function
which will make it discoverable to register(). If passed no function,
returns a decorator which can be applied to a function later using
the attributes supplied.
If optionalhook is True a missing matching hook specification will not result
in an error (by default it is an error if no matching spec is found).
If tryfirst is True this hook implementation will run as early as possible
in the chain of N hook implementations for a specfication.
If trylast is True this hook implementation will run as late as possible
in the chain of N hook implementations.
If hookwrapper is True the hook implementations needs to execute exactly
one "yield". The code before the yield is run early before any non-hookwrapper
function is run. The code after the yield is run after all non-hookwrapper
function have run. The yield receives an ``_CallOutcome`` object representing
the exception or result outcome of the inner calls (including other hookwrapper
calls).
"""
def setattr_hookimpl_opts(func):
setattr(func, self.project_name + "_impl",
dict(hookwrapper=hookwrapper, optionalhook=optionalhook,
tryfirst=tryfirst, trylast=trylast))
return func
if function is None:
return setattr_hookimpl_opts
else:
return setattr_hookimpl_opts(function)
def normalize_hookimpl_opts(opts):
opts.setdefault("tryfirst", False)
opts.setdefault("trylast", False)
opts.setdefault("hookwrapper", False)
opts.setdefault("optionalhook", False)
class _TagTracer:
def __init__(self):
self._tag2proc = {}
self.writer = None
self.indent = 0
def get(self, name):
return _TagTracerSub(self, (name,))
def format_message(self, tags, args):
if isinstance(args[-1], dict):
extra = args[-1]
args = args[:-1]
else:
extra = {}
content = " ".join(map(str, args))
indent = " " * self.indent
lines = [
"%s%s [%s]\n" % (indent, content, ":".join(tags))
]
for name, value in extra.items():
lines.append("%s %s: %s\n" % (indent, name, value))
return lines
def processmessage(self, tags, args):
if self.writer is not None and args:
lines = self.format_message(tags, args)
self.writer(''.join(lines))
try:
self._tag2proc[tags](tags, args)
except KeyError:
pass
def setwriter(self, writer):
self.writer = writer
def setprocessor(self, tags, processor):
if isinstance(tags, str):
tags = tuple(tags.split(":"))
else:
assert isinstance(tags, tuple)
self._tag2proc[tags] = processor
class _TagTracerSub:
def __init__(self, root, tags):
self.root = root
self.tags = tags
def __call__(self, *args):
self.root.processmessage(self.tags, args)
def setmyprocessor(self, processor):
self.root.setprocessor(self.tags, processor)
def get(self, name):
return self.__class__(self.root, self.tags + (name,))
def _raise_wrapfail(wrap_controller, msg):
co = wrap_controller.gi_code
raise RuntimeError("wrap_controller at %r %s:%d %s" %
(co.co_name, co.co_filename, co.co_firstlineno, msg))
def _wrapped_call(wrap_controller, func):
""" Wrap calling to a function with a generator which needs to yield
exactly once. The yield point will trigger calling the wrapped function
and return its _CallOutcome to the yield point. The generator then needs
to finish (raise StopIteration) in order for the wrapped call to complete.
"""
try:
next(wrap_controller) # first yield
except StopIteration:
_raise_wrapfail(wrap_controller, "did not yield")
call_outcome = _CallOutcome(func)
try:
wrap_controller.send(call_outcome)
_raise_wrapfail(wrap_controller, "has second yield")
except StopIteration:
pass
return call_outcome.get_result()
class _CallOutcome:
""" Outcome of a function call, either an exception or a proper result.
Calling the ``get_result`` method will return the result or reraise
the exception raised when the function was called. """
excinfo = None
def __init__(self, func):
try:
self.result = func()
except BaseException:
self.excinfo = sys.exc_info()
def force_result(self, result):
self.result = result
self.excinfo = None
def get_result(self):
if self.excinfo is None:
return self.result
else:
ex = self.excinfo
if _py3:
raise ex[1].with_traceback(ex[2])
_reraise(*ex) # noqa
if not _py3:
exec("""
def _reraise(cls, val, tb):
raise cls, val, tb
""")
class _TracedHookExecution:
def __init__(self, pluginmanager, before, after):
self.pluginmanager = pluginmanager
self.before = before
self.after = after
self.oldcall = pluginmanager._inner_hookexec
assert not isinstance(self.oldcall, _TracedHookExecution)
self.pluginmanager._inner_hookexec = self
def __call__(self, hook, hook_impls, kwargs):
self.before(hook.name, hook_impls, kwargs)
outcome = _CallOutcome(lambda: self.oldcall(hook, hook_impls, kwargs))
self.after(outcome, hook.name, hook_impls, kwargs)
return outcome.get_result()
def undo(self):
self.pluginmanager._inner_hookexec = self.oldcall
class PluginManager(object):
""" Core Pluginmanager class which manages registration
of plugin objects and 1:N hook calling.
You can register new hooks by calling ``addhooks(module_or_class)``.
You can register plugin objects (which contain hooks) by calling
``register(plugin)``. The Pluginmanager is initialized with a
prefix that is searched for in the names of the dict of registered
plugin objects. An optional excludefunc allows to blacklist names which
are not considered as hooks despite a matching prefix.
For debugging purposes you can call ``enable_tracing()``
which will subsequently send debug information to the trace helper.
"""
def __init__(self, project_name, implprefix=None):
""" if implprefix is given implementation functions
will be recognized if their name matches the implprefix. """
self.project_name = project_name
self._name2plugin = {}
self._plugin2hookcallers = {}
self._plugin_distinfo = []
self.trace = _TagTracer().get("pluginmanage")
self.hook = _HookRelay(self.trace.root.get("hook"))
self._implprefix = implprefix
self._inner_hookexec = lambda hook, methods, kwargs: \
_MultiCall(methods, kwargs, hook.spec_opts).execute()
def _hookexec(self, hook, methods, kwargs):
# called from all hookcaller instances.
# enable_tracing will set its own wrapping function at self._inner_hookexec
return self._inner_hookexec(hook, methods, kwargs)
def register(self, plugin, name=None):
""" Register a plugin and return its canonical name or None if the name
is blocked from registering. Raise a ValueError if the plugin is already
registered. """
plugin_name = name or self.get_canonical_name(plugin)
if plugin_name in self._name2plugin or plugin in self._plugin2hookcallers:
if self._name2plugin.get(plugin_name, -1) is None:
return # blocked plugin, return None to indicate no registration
raise ValueError("Plugin already registered: %s=%s\n%s" %
(plugin_name, plugin, self._name2plugin))
# XXX if an error happens we should make sure no state has been
# changed at point of return
self._name2plugin[plugin_name] = plugin
# register matching hook implementations of the plugin
self._plugin2hookcallers[plugin] = hookcallers = []
for name in dir(plugin):
hookimpl_opts = self.parse_hookimpl_opts(plugin, name)
if hookimpl_opts is not None:
normalize_hookimpl_opts(hookimpl_opts)
method = getattr(plugin, name)
hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts)
hook = getattr(self.hook, name, None)
if hook is None:
hook = _HookCaller(name, self._hookexec)
setattr(self.hook, name, hook)
elif hook.has_spec():
self._verify_hook(hook, hookimpl)
hook._maybe_apply_history(hookimpl)
hook._add_hookimpl(hookimpl)
hookcallers.append(hook)
return plugin_name
def parse_hookimpl_opts(self, plugin, name):
method = getattr(plugin, name)
res = getattr(method, self.project_name + "_impl", None)
if res is not None and not isinstance(res, dict):
# false positive
res = None
elif res is None and self._implprefix and name.startswith(self._implprefix):
res = {}
return res
def unregister(self, plugin=None, name=None):
""" unregister a plugin object and all its contained hook implementations
from internal data structures. """
if name is None:
assert plugin is not None, "one of name or plugin needs to be specified"
name = self.get_name(plugin)
if plugin is None:
plugin = self.get_plugin(name)
# if self._name2plugin[name] == None registration was blocked: ignore
if self._name2plugin.get(name):
del self._name2plugin[name]
for hookcaller in self._plugin2hookcallers.pop(plugin, []):
hookcaller._remove_plugin(plugin)
return plugin
def set_blocked(self, name):
""" block registrations of the given name, unregister if already registered. """
self.unregister(name=name)
self._name2plugin[name] = None
def is_blocked(self, name):
""" return True if the name blogs registering plugins of that name. """
return name in self._name2plugin and self._name2plugin[name] is None
def add_hookspecs(self, module_or_class):
""" add new hook specifications defined in the given module_or_class.
Functions are recognized if they have been decorated accordingly. """
names = []
for name in dir(module_or_class):
spec_opts = self.parse_hookspec_opts(module_or_class, name)
if spec_opts is not None:
hc = getattr(self.hook, name, None)
if hc is None:
hc = _HookCaller(name, self._hookexec, module_or_class, spec_opts)
setattr(self.hook, name, hc)
else:
# plugins registered this hook without knowing the spec
hc.set_specification(module_or_class, spec_opts)
for hookfunction in (hc._wrappers + hc._nonwrappers):
self._verify_hook(hc, hookfunction)
names.append(name)
if not names:
raise ValueError("did not find any %r hooks in %r" %
(self.project_name, module_or_class))
def parse_hookspec_opts(self, module_or_class, name):
method = getattr(module_or_class, name)
return getattr(method, self.project_name + "_spec", None)
def get_plugins(self):
""" return the set of registered plugins. """
return set(self._plugin2hookcallers)
def is_registered(self, plugin):
""" Return True if the plugin is already registered. """
return plugin in self._plugin2hookcallers
def get_canonical_name(self, plugin):
""" Return canonical name for a plugin object. Note that a plugin
may be registered under a different name which was specified
by the caller of register(plugin, name). To obtain the name
of an registered plugin use ``get_name(plugin)`` instead."""
return getattr(plugin, "__name__", None) or str(id(plugin))
def get_plugin(self, name):
""" Return a plugin or None for the given name. """
return self._name2plugin.get(name)
def get_name(self, plugin):
""" Return name for registered plugin or None if not registered. """
for name, val in self._name2plugin.items():
if plugin == val:
return name
def _verify_hook(self, hook, hookimpl):
if hook.is_historic() and hookimpl.hookwrapper:
raise PluginValidationError(
"Plugin %r\nhook %r\nhistoric incompatible to hookwrapper" %
(hookimpl.plugin_name, hook.name))
for arg in hookimpl.argnames:
if arg not in hook.argnames:
raise PluginValidationError(
"Plugin %r\nhook %r\nargument %r not available\n"
"plugin definition: %s\n"
"available hookargs: %s" %
(hookimpl.plugin_name, hook.name, arg,
_formatdef(hookimpl.function), ", ".join(hook.argnames)))
def check_pending(self):
""" Verify that all hooks which have not been verified against
a hook specification are optional, otherwise raise PluginValidationError"""
for name in self.hook.__dict__:
if name[0] != "_":
hook = getattr(self.hook, name)
if not hook.has_spec():
for hookimpl in (hook._wrappers + hook._nonwrappers):
if not hookimpl.optionalhook:
raise PluginValidationError(
"unknown hook %r in plugin %r" %
(name, hookimpl.plugin))
def load_setuptools_entrypoints(self, entrypoint_name):
""" Load modules from querying the specified setuptools entrypoint name.
Return the number of loaded plugins. """
from pkg_resources import iter_entry_points, DistributionNotFound
for ep in iter_entry_points(entrypoint_name):
# is the plugin registered or blocked?
if self.get_plugin(ep.name) or self.is_blocked(ep.name):
continue
try:
plugin = ep.load()
except DistributionNotFound:
continue
self.register(plugin, name=ep.name)
self._plugin_distinfo.append((plugin, ep.dist))
return len(self._plugin_distinfo)
def list_plugin_distinfo(self):
""" return list of distinfo/plugin tuples for all setuptools registered
plugins. """
return list(self._plugin_distinfo)
def list_name_plugin(self):
""" return list of name/plugin pairs. """
return list(self._name2plugin.items())
def get_hookcallers(self, plugin):
""" get all hook callers for the specified plugin. """
return self._plugin2hookcallers.get(plugin)
def add_hookcall_monitoring(self, before, after):
""" add before/after tracing functions for all hooks
and return an undo function which, when called,
will remove the added tracers.
``before(hook_name, hook_impls, kwargs)`` will be called ahead
of all hook calls and receive a hookcaller instance, a list
of HookImpl instances and the keyword arguments for the hook call.
``after(outcome, hook_name, hook_impls, kwargs)`` receives the
same arguments as ``before`` but also a :py:class:`_CallOutcome`` object
which represents the result of the overall hook call.
"""
return _TracedHookExecution(self, before, after).undo
def enable_tracing(self):
""" enable tracing of hook calls and return an undo function. """
hooktrace = self.hook._trace
def before(hook_name, methods, kwargs):
hooktrace.root.indent += 1
hooktrace(hook_name, kwargs)
def after(outcome, hook_name, methods, kwargs):
if outcome.excinfo is None:
hooktrace("finish", hook_name, "-->", outcome.result)
hooktrace.root.indent -= 1
return self.add_hookcall_monitoring(before, after)
def subset_hook_caller(self, name, remove_plugins):
""" Return a new _HookCaller instance for the named method
which manages calls to all registered plugins except the
ones from remove_plugins. """
orig = getattr(self.hook, name)
plugins_to_remove = [plug for plug in remove_plugins if hasattr(plug, name)]
if plugins_to_remove:
hc = _HookCaller(orig.name, orig._hookexec, orig._specmodule_or_class,
orig.spec_opts)
for hookimpl in (orig._wrappers + orig._nonwrappers):
plugin = hookimpl.plugin
if plugin not in plugins_to_remove:
hc._add_hookimpl(hookimpl)
# we also keep track of this hook caller so it
# gets properly removed on plugin unregistration
self._plugin2hookcallers.setdefault(plugin, []).append(hc)
return hc
return orig
class _MultiCall:
""" execute a call into multiple python functions/methods. """
# XXX note that the __multicall__ argument is supported only
# for pytest compatibility reasons. It was never officially
# supported there and is explicitly deprecated since 2.8
# so we can remove it soon, allowing to avoid the below recursion
# in execute() and simplify/speed up the execute loop.
def __init__(self, hook_impls, kwargs, specopts={}):
self.hook_impls = hook_impls
self.kwargs = kwargs
self.kwargs["__multicall__"] = self
self.specopts = specopts
def execute(self):
all_kwargs = self.kwargs
self.results = results = []
firstresult = self.specopts.get("firstresult")
while self.hook_impls:
hook_impl = self.hook_impls.pop()
args = [all_kwargs[argname] for argname in hook_impl.argnames]
if hook_impl.hookwrapper:
return _wrapped_call(hook_impl.function(*args), self.execute)
res = hook_impl.function(*args)
if res is not None:
if firstresult:
return res
results.append(res)
if not firstresult:
return results
def __repr__(self):
status = "%d meths" % (len(self.hook_impls),)
if hasattr(self, "results"):
status = ("%d results, " % len(self.results)) + status
return "<_MultiCall %s, kwargs=%r>" % (status, self.kwargs)
def varnames(func, startindex=None):
""" return argument name tuple for a function, method, class or callable.
In case of a class, its "__init__" method is considered.
For methods the "self" parameter is not included unless you are passing
an unbound method with Python3 (which has no supports for unbound methods)
"""
cache = getattr(func, "__dict__", {})
try:
return cache["_varnames"]
except KeyError:
pass
if inspect.isclass(func):
try:
func = func.__init__
except AttributeError:
return ()
startindex = 1
else:
if not inspect.isfunction(func) and not inspect.ismethod(func):
func = getattr(func, '__call__', func)
if startindex is None:
startindex = int(inspect.ismethod(func))
try:
rawcode = func.__code__
except AttributeError:
return ()
try:
x = rawcode.co_varnames[startindex:rawcode.co_argcount]
except AttributeError:
x = ()
else:
defaults = func.__defaults__
if defaults:
x = x[:-len(defaults)]
try:
cache["_varnames"] = x
except TypeError:
pass
return x
class _HookRelay:
""" hook holder object for performing 1:N hook calls where N is the number
of registered plugins.
"""
def __init__(self, trace):
self._trace = trace
class _HookCaller(object):
def __init__(self, name, hook_execute, specmodule_or_class=None, spec_opts=None):
self.name = name
self._wrappers = []
self._nonwrappers = []
self._hookexec = hook_execute
if specmodule_or_class is not None:
assert spec_opts is not None
self.set_specification(specmodule_or_class, spec_opts)
def has_spec(self):
return hasattr(self, "_specmodule_or_class")
def set_specification(self, specmodule_or_class, spec_opts):
assert not self.has_spec()
self._specmodule_or_class = specmodule_or_class
specfunc = getattr(specmodule_or_class, self.name)
argnames = varnames(specfunc, startindex=inspect.isclass(specmodule_or_class))
assert "self" not in argnames # sanity check
self.argnames = ["__multicall__"] + list(argnames)
self.spec_opts = spec_opts
if spec_opts.get("historic"):
self._call_history = []
def is_historic(self):
return hasattr(self, "_call_history")
def _remove_plugin(self, plugin):
def remove(wrappers):
for i, method in enumerate(wrappers):
if method.plugin == plugin:
del wrappers[i]
return True
if remove(self._wrappers) is None:
if remove(self._nonwrappers) is None:
raise ValueError("plugin %r not found" % (plugin,))
def _add_hookimpl(self, hookimpl):
if hookimpl.hookwrapper:
methods = self._wrappers
else:
methods = self._nonwrappers
if hookimpl.trylast:
methods.insert(0, hookimpl)
elif hookimpl.tryfirst:
methods.append(hookimpl)
else:
# find last non-tryfirst method
i = len(methods) - 1
while i >= 0 and methods[i].tryfirst:
i -= 1
methods.insert(i + 1, hookimpl)
def __repr__(self):
return "<_HookCaller %r>" % (self.name,)
def __call__(self, **kwargs):
assert not self.is_historic()
return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
def call_historic(self, proc=None, kwargs=None):
self._call_history.append((kwargs or {}, proc))
# historizing hooks don't return results
self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
def call_extra(self, methods, kwargs):
""" Call the hook with some additional temporarily participating
methods using the specified kwargs as call parameters. """
old = list(self._nonwrappers), list(self._wrappers)
for method in methods:
opts = dict(hookwrapper=False, trylast=False, tryfirst=False)
hookimpl = HookImpl(None, "<temp>", method, opts)
self._add_hookimpl(hookimpl)
try:
return self(**kwargs)
finally:
self._nonwrappers, self._wrappers = old
def _maybe_apply_history(self, method):
if self.is_historic():
for kwargs, proc in self._call_history:
res = self._hookexec(self, [method], kwargs)
if res and proc is not None:
proc(res[0])
class HookImpl:
def __init__(self, plugin, plugin_name, function, hook_impl_opts):
self.function = function
self.argnames = varnames(self.function)
self.plugin = plugin
self.opts = hook_impl_opts
self.plugin_name = plugin_name
self.__dict__.update(hook_impl_opts)
class PluginValidationError(Exception):
""" plugin failed validation. """
if hasattr(inspect, 'signature'):
def _formatdef(func):
return "%s%s" % (
func.__name__,
str(inspect.signature(func))
)
else:
def _formatdef(func):
return "%s%s" % (
func.__name__,
inspect.formatargspec(*inspect.getargspec(func))
)

View File

@@ -1,82 +1,35 @@
environment:
global:
# SDK v7.0 MSVC Express 2008's SetEnv.cmd script will fail if the
# /E:ON and /V:ON options are not enabled in the batch script intepreter
# See: http://stackoverflow.com/a/13751649/163740
CMD_IN_ENV: "cmd /E:ON /V:ON /C .\\appveyor\\run_with_env.cmd"
COVERALLS_REPO_TOKEN:
secure: 2NJ5Ct55cHJ9WEg3xbSqCuv0rdgzzb6pnzOIG5OkMbTndw3wOBrXntWFoQrXiMFi
# this is pytest's token in coveralls.io, encrypted
# using pytestbot account as detailed here:
# https://www.appveyor.com/docs/build-configuration#secure-variables
matrix:
# Pre-installed Python versions, which Appveyor may upgrade to
# a later point release.
- PYTHON: "C:\\Python27"
PYTHON_VERSION: "2.7.x" # currently 2.7.9
PYTHON_ARCH: "32"
TESTENV: "py27"
- PYTHON: "C:\\Python27-x64"
PYTHON_VERSION: "2.7.x" # currently 2.7.9
PYTHON_ARCH: "64"
TESTENV: "py27"
- PYTHON: "C:\\Python33"
PYTHON_VERSION: "3.3.x" # currently 3.3.5
PYTHON_ARCH: "32"
TESTENV: "py33"
- PYTHON: "C:\\Python33-x64"
PYTHON_VERSION: "3.3.x" # currently 3.3.5
PYTHON_ARCH: "64"
TESTENV: "py33"
- PYTHON: "C:\\Python34"
PYTHON_VERSION: "3.4.x" # currently 3.4.3
PYTHON_ARCH: "32"
TESTENV: "py34"
- PYTHON: "C:\\Python34-x64"
PYTHON_VERSION: "3.4.x" # currently 3.4.3
PYTHON_ARCH: "64"
TESTENV: "py34"
# Also test a Python version not pre-installed
# See: https://github.com/ogrisel/python-appveyor-demo/issues/10
- PYTHON: "C:\\Python266"
PYTHON_VERSION: "2.6.6"
PYTHON_ARCH: "32"
TESTENV: "py26"
# create multiple jobs to execute a set of tox runs on each; this is to workaround having
# builds timing out in AppVeyor
- TOXENV: "linting,py26,py27,py33,py34,py35,pypy"
- TOXENV: "py27-pexpect,py27-xdist,py27-trial,py35-pexpect,py35-xdist,py35-trial"
- TOXENV: "py27-nobyte,doctesting,freeze,docs"
install:
- ECHO "Filesystem root:"
- ps: "ls \"C:/\""
- echo Installed Pythons
- dir c:\Python*
- ECHO "Installed SDKs:"
- ps: "ls \"C:/Program Files/Microsoft SDKs/Windows\""
# install pypy using choco (redirect to a file and write to console in case
# choco install returns non-zero, because choco install python.pypy is too
# noisy)
- choco install python.pypy > pypy-inst.log 2>&1 || (type pypy-inst.log & exit /b 1)
- set PATH=C:\tools\pypy\pypy;%PATH% # so tox can find pypy
- echo PyPy installed
- pypy --version
# Install Python (from the official .msi of http://python.org) and pip when
# not already installed.
- ps: if (-not(Test-Path($env:PYTHON))) { & appveyor\install.ps1 }
# Prepend newly installed Python to the PATH of this build (this cannot be
# done from inside the powershell script as it would require to restart
# the parent CMD process).
- "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
# Check that we have the expected version and architecture for Python
- "python --version"
- "python -c \"import struct; print(struct.calcsize('P') * 8)\""
# Install the build dependencies of the project. If some dependencies contain
# compiled extensions and are not provided as pre-built wheel packages,
# pip will build them from source using the MSVC compiler matching the
# target Python version and architecture
- "%CMD_IN_ENV% pip install tox"
- C:\Python35\python -m pip install tox
build: false # Not a C# project, build stuff at the test step instead.
test_script:
# Build the compiled extension and run the project tests
- "%CMD_IN_ENV% tox -e %TESTENV%"
- C:\Python35\python -m tox
# coveralls is not in tox's envlist, plus for PRs the secure variable
# is not defined so we have to check for it
- if defined COVERALLS_REPO_TOKEN C:\Python35\python -m tox -e coveralls

View File

@@ -1,180 +0,0 @@
# Sample script to install Python and pip under Windows
# Authors: Olivier Grisel, Jonathan Helmus and Kyle Kastner
# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/
$MINICONDA_URL = "http://repo.continuum.io/miniconda/"
$BASE_URL = "https://www.python.org/ftp/python/"
$GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
$GET_PIP_PATH = "C:\get-pip.py"
function DownloadPython ($python_version, $platform_suffix) {
$webclient = New-Object System.Net.WebClient
$filename = "python-" + $python_version + $platform_suffix + ".msi"
$url = $BASE_URL + $python_version + "/" + $filename
$basedir = $pwd.Path + "\"
$filepath = $basedir + $filename
if (Test-Path $filename) {
Write-Host "Reusing" $filepath
return $filepath
}
# Download and retry up to 3 times in case of network transient errors.
Write-Host "Downloading" $filename "from" $url
$retry_attempts = 2
for($i=0; $i -lt $retry_attempts; $i++){
try {
$webclient.DownloadFile($url, $filepath)
break
}
Catch [Exception]{
Start-Sleep 1
}
}
if (Test-Path $filepath) {
Write-Host "File saved at" $filepath
} else {
# Retry once to get the error message if any at the last try
$webclient.DownloadFile($url, $filepath)
}
return $filepath
}
function InstallPython ($python_version, $architecture, $python_home) {
Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home
if (Test-Path $python_home) {
Write-Host $python_home "already exists, skipping."
return $false
}
if ($architecture -eq "32") {
$platform_suffix = ""
} else {
$platform_suffix = ".amd64"
}
$msipath = DownloadPython $python_version $platform_suffix
Write-Host "Installing" $msipath "to" $python_home
$install_log = $python_home + ".log"
$install_args = "/qn /log $install_log /i $msipath TARGETDIR=$python_home"
$uninstall_args = "/qn /x $msipath"
RunCommand "msiexec.exe" $install_args
if (-not(Test-Path $python_home)) {
Write-Host "Python seems to be installed else-where, reinstalling."
RunCommand "msiexec.exe" $uninstall_args
RunCommand "msiexec.exe" $install_args
}
if (Test-Path $python_home) {
Write-Host "Python $python_version ($architecture) installation complete"
} else {
Write-Host "Failed to install Python in $python_home"
Get-Content -Path $install_log
Exit 1
}
}
function RunCommand ($command, $command_args) {
Write-Host $command $command_args
Start-Process -FilePath $command -ArgumentList $command_args -Wait -Passthru
}
function InstallPip ($python_home) {
$pip_path = $python_home + "\Scripts\pip.exe"
$python_path = $python_home + "\python.exe"
if (-not(Test-Path $pip_path)) {
Write-Host "Installing pip..."
$webclient = New-Object System.Net.WebClient
$webclient.DownloadFile($GET_PIP_URL, $GET_PIP_PATH)
Write-Host "Executing:" $python_path $GET_PIP_PATH
Start-Process -FilePath "$python_path" -ArgumentList "$GET_PIP_PATH" -Wait -Passthru
} else {
Write-Host "pip already installed."
}
}
function DownloadMiniconda ($python_version, $platform_suffix) {
$webclient = New-Object System.Net.WebClient
if ($python_version -eq "3.4") {
$filename = "Miniconda3-3.5.5-Windows-" + $platform_suffix + ".exe"
} else {
$filename = "Miniconda-3.5.5-Windows-" + $platform_suffix + ".exe"
}
$url = $MINICONDA_URL + $filename
$basedir = $pwd.Path + "\"
$filepath = $basedir + $filename
if (Test-Path $filename) {
Write-Host "Reusing" $filepath
return $filepath
}
# Download and retry up to 3 times in case of network transient errors.
Write-Host "Downloading" $filename "from" $url
$retry_attempts = 2
for($i=0; $i -lt $retry_attempts; $i++){
try {
$webclient.DownloadFile($url, $filepath)
break
}
Catch [Exception]{
Start-Sleep 1
}
}
if (Test-Path $filepath) {
Write-Host "File saved at" $filepath
} else {
# Retry once to get the error message if any at the last try
$webclient.DownloadFile($url, $filepath)
}
return $filepath
}
function InstallMiniconda ($python_version, $architecture, $python_home) {
Write-Host "Installing Python" $python_version "for" $architecture "bit architecture to" $python_home
if (Test-Path $python_home) {
Write-Host $python_home "already exists, skipping."
return $false
}
if ($architecture -eq "32") {
$platform_suffix = "x86"
} else {
$platform_suffix = "x86_64"
}
$filepath = DownloadMiniconda $python_version $platform_suffix
Write-Host "Installing" $filepath "to" $python_home
$install_log = $python_home + ".log"
$args = "/S /D=$python_home"
Write-Host $filepath $args
Start-Process -FilePath $filepath -ArgumentList $args -Wait -Passthru
if (Test-Path $python_home) {
Write-Host "Python $python_version ($architecture) installation complete"
} else {
Write-Host "Failed to install Python in $python_home"
Get-Content -Path $install_log
Exit 1
}
}
function InstallMinicondaPip ($python_home) {
$pip_path = $python_home + "\Scripts\pip.exe"
$conda_path = $python_home + "\Scripts\conda.exe"
if (-not(Test-Path $pip_path)) {
Write-Host "Installing pip..."
$args = "install --yes pip"
Write-Host $conda_path $args
Start-Process -FilePath "$conda_path" -ArgumentList $args -Wait -Passthru
} else {
Write-Host "pip already installed."
}
}
function main () {
InstallPython $env:PYTHON_VERSION $env:PYTHON_ARCH $env:PYTHON
InstallPip $env:PYTHON
}
main

View File

@@ -1,47 +0,0 @@
:: To build extensions for 64 bit Python 3, we need to configure environment
:: variables to use the MSVC 2010 C++ compilers from GRMSDKX_EN_DVD.iso of:
:: MS Windows SDK for Windows 7 and .NET Framework 4 (SDK v7.1)
::
:: To build extensions for 64 bit Python 2, we need to configure environment
:: variables to use the MSVC 2008 C++ compilers from GRMSDKX_EN_DVD.iso of:
:: MS Windows SDK for Windows 7 and .NET Framework 3.5 (SDK v7.0)
::
:: 32 bit builds do not require specific environment configurations.
::
:: Note: this script needs to be run with the /E:ON and /V:ON flags for the
:: cmd interpreter, at least for (SDK v7.0)
::
:: More details at:
:: https://github.com/cython/cython/wiki/64BitCythonExtensionsOnWindows
:: http://stackoverflow.com/a/13751649/163740
::
:: Author: Olivier Grisel
:: License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/
@ECHO OFF
SET COMMAND_TO_RUN=%*
SET WIN_SDK_ROOT=C:\Program Files\Microsoft SDKs\Windows
SET MAJOR_PYTHON_VERSION="%PYTHON_VERSION:~0,1%"
IF %MAJOR_PYTHON_VERSION% == "2" (
SET WINDOWS_SDK_VERSION="v7.0"
) ELSE IF %MAJOR_PYTHON_VERSION% == "3" (
SET WINDOWS_SDK_VERSION="v7.1"
) ELSE (
ECHO Unsupported Python version: "%MAJOR_PYTHON_VERSION%"
EXIT 1
)
IF "%PYTHON_ARCH%"=="64" (
ECHO Configuring Windows SDK %WINDOWS_SDK_VERSION% for Python %MAJOR_PYTHON_VERSION% on a 64 bit architecture
SET DISTUTILS_USE_SDK=1
SET MSSdk=1
"%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Setup\WindowsSdkVer.exe" -q -version:%WINDOWS_SDK_VERSION%
"%WIN_SDK_ROOT%\%WINDOWS_SDK_VERSION%\Bin\SetEnv.cmd" /x64 /release
ECHO Executing: %COMMAND_TO_RUN%
call %COMMAND_TO_RUN% || EXIT 1
) ELSE (
ECHO Using default MSVC build environment for 32 bit architecture
ECHO Executing: %COMMAND_TO_RUN%
call %COMMAND_TO_RUN% || EXIT 1
)

View File

@@ -12,6 +12,13 @@ PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
REGENDOC_ARGS := \
--normalize "/={8,} (.*) ={8,}/======= \1 ========/" \
--normalize "/_{8,} (.*) _{8,}/_______ \1 ________/" \
--normalize "/in \d+.\d+ seconds/in 0.12 seconds/" \
--normalize "@/tmp/pytest-of-.*/pytest-\d+@PYTEST_TMPDIR@" \
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
@@ -46,7 +53,7 @@ installall: clean install installpdf
@echo "done"
regen:
PYTHONDONTWRITEBYTECODE=1 COLUMNS=76 regendoc --update *.txt */*.txt
PYTHONDONTWRITEBYTECODE=1 COLUMNS=76 regendoc --update *.rst */*.rst ${REGENDOC_ARGS}
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html

View File

@@ -6,7 +6,7 @@ def get_version_string():
fn = py.path.local(__file__).join("..", "..", "..",
"_pytest", "__init__.py")
for line in fn.readlines():
if "version" in line:
if "version" in line and not line.strip().startswith('#'):
return eval(line.split("=")[-1])
def get_minor_version_string():

View File

@@ -9,6 +9,7 @@
<li><a href="{{ pathto('contact') }}">Contact</a></li>
<li><a href="{{ pathto('talks') }}">Talks/Posts</a></li>
<li><a href="{{ pathto('changelog') }}">Changelog</a></li>
<li><a href="{{ pathto('license') }}">License</a></li>
</ul>
{%- if display_toc %}

View File

@@ -1,5 +1,7 @@
{% extends "!layout.html" %}
{% block header %}
{{super()}}
{% endblock %}
{% block footer %}
{{ super() }}
<script type="text/javascript">

View File

@@ -4,7 +4,7 @@
<li><a href="{{ pathto('contributing') }}">Contribution Guide</a></li>
<li><a href="https://pypi.python.org/pypi/pytest">pytest @ PyPI</a></li>
<li><a href="https://github.com/pytest-dev/pytest/">pytest @ GitHub</a></li>
<li><a href="http://pytest.org/latest/plugins_index/index.html">3rd party plugins</a></li>
<li><a href="http://plugincompat.herokuapp.com/">3rd party plugins</a></li>
<li><a href="https://github.com/pytest-dev/pytest/issues">Issue Tracker</a></li>
<li><a href="http://pytest.org/latest/pytest.pdf">PDF Documentation</a>
</ul>

View File

@@ -1,3 +1,7 @@
:orphan:
.. warnings about this file not being included in any toctree will be suppressed by :orphan:
April 2015 is "adopt pytest month"
=============================================
@@ -9,7 +13,7 @@ We will pair experienced pytest users with open source projects, for a month's e
In 2015 we are trying this for the first time. In February and March 2015 we will gather volunteers on both sides, in April we will do the work, and in May we will evaluate how it went. This effort is being coordinated by Brianna Laugher. If you have any questions or comments, you can raise them on the `@pytestdotorg twitter account <https://twitter.com/pytestdotorg>`_ the `issue tracker`_ or the `pytest-dev mailing list`_.
.. _`issue tracker`: https://bitbucket.org/pytest-dev/pytest/issue/676/adopt-pytest-month-2015
.. _`issue tracker`: https://github.com/pytest-dev/pytest/issues/676
.. _`pytest-dev mailing list`: https://mail.python.org/mailman/listinfo/pytest-dev

View File

@@ -5,6 +5,21 @@ Release announcements
.. toctree::
:maxdepth: 2
release-3.0.2
release-3.0.1
release-3.0.0
sprint2016
release-2.9.2
release-2.9.1
release-2.9.0
release-2.8.7
release-2.8.6
release-2.8.5
release-2.8.4
release-2.8.3
release-2.8.2
release-2.7.2
release-2.7.1
release-2.7.0
release-2.6.3
@@ -35,4 +50,3 @@ Release announcements
release-2.0.2
release-2.0.1
release-2.0.0

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